diff options
author | Kristian Monsen <kristianm@google.com> | 2011-05-11 20:53:37 +0100 |
---|---|---|
committer | Kristian Monsen <kristianm@google.com> | 2011-05-16 13:54:48 +0100 |
commit | 21d179b334e59e9a3bfcaed4c4430bef1bc5759d (patch) | |
tree | 64e2bb6da27af6a5c93ca34f6051584aafbfcb9e /webkit | |
parent | 0c63f00edd6ed0482fd5cbcea937ca088baf7858 (diff) | |
download | external_chromium-21d179b334e59e9a3bfcaed4c4430bef1bc5759d.zip external_chromium-21d179b334e59e9a3bfcaed4c4430bef1bc5759d.tar.gz external_chromium-21d179b334e59e9a3bfcaed4c4430bef1bc5759d.tar.bz2 |
Merge Chromium at 10.0.621.0: Initial merge by git.
Change-Id: I070cc91c608dfa4a968a5a54c173260765ac8097
Diffstat (limited to 'webkit')
290 files changed, 2276 insertions, 36392 deletions
diff --git a/webkit/glue/bookmarklet_unittest.cc b/webkit/glue/bookmarklet_unittest.cc index 5d8a364..d7fada5 100644 --- a/webkit/glue/bookmarklet_unittest.cc +++ b/webkit/glue/bookmarklet_unittest.cc @@ -26,8 +26,8 @@ TEST_F(BookmarkletTest, Redirect) { test_shell_->LoadURL( GURL("javascript:location.href='data:text/plain,SUCCESS'")); test_shell_->WaitTestFinished(); - std::wstring text = test_shell_->GetDocumentText(); - EXPECT_EQ(L"SUCCESS", text); + string16 text = test_shell_->GetDocumentText(); + EXPECT_EQ("SUCCESS", UTF16ToASCII(text)); } TEST_F(BookmarkletTest, RedirectVoided) { @@ -38,12 +38,12 @@ TEST_F(BookmarkletTest, RedirectVoided) { test_shell_->LoadURL( GURL("javascript:void(location.href='data:text/plain,SUCCESS')")); test_shell_->WaitTestFinished(); - std::wstring text = test_shell_->GetDocumentText(); - EXPECT_EQ(L"SUCCESS", text); + string16 text = test_shell_->GetDocumentText(); + EXPECT_EQ("SUCCESS", UTF16ToASCII(text)); } TEST_F(BookmarkletTest, NonEmptyResult) { - std::wstring text; + string16 text; // TODO(darin): This test fails in a JSC build. WebCore+JSC does not really // need to support this usage until WebCore supports javascript: URLs that @@ -54,13 +54,13 @@ TEST_F(BookmarkletTest, NonEmptyResult) { test_shell_->LoadURL(L"javascript:false"); MessageLoop::current()->RunAllPending(); text = test_shell_->GetDocumentText(); - EXPECT_EQ(L"false", text); + EXPECT_EQ("false", UTF16ToASCII(text)); #endif test_shell_->LoadURL(GURL("javascript:'hello world'")); MessageLoop::current()->RunAllPending(); text = test_shell_->GetDocumentText(); - EXPECT_EQ(L"hello world", text); + EXPECT_EQ("hello world", UTF16ToASCII(text)); } TEST_F(BookmarkletTest, DocumentWrite) { @@ -69,8 +69,8 @@ TEST_F(BookmarkletTest, DocumentWrite) { "document.write('hello world');" "document.close()")); MessageLoop::current()->RunAllPending(); - std::wstring text = test_shell_->GetDocumentText(); - EXPECT_EQ(L"hello world", text); + string16 text = test_shell_->GetDocumentText(); + EXPECT_EQ("hello world", UTF16ToASCII(text)); } } // namespace diff --git a/webkit/glue/context_menu.cc b/webkit/glue/context_menu.cc index 390d740..bdfe790 100644 --- a/webkit/glue/context_menu.cc +++ b/webkit/glue/context_menu.cc @@ -18,7 +18,7 @@ ContextMenuParams::ContextMenuParams(const WebKit::WebContextMenuData& data) page_url(data.pageURL), frame_url(data.frameURL), media_flags(data.mediaFlags), - selection_text(UTF16ToWideHack(data.selectedText)), + selection_text(data.selectedText), misspelled_word(data.misspelledWord), spellcheck_enabled(data.isSpellCheckingEnabled), is_editable(data.isEditable), diff --git a/webkit/glue/context_menu.h b/webkit/glue/context_menu.h index b681a38..c87de41 100644 --- a/webkit/glue/context_menu.h +++ b/webkit/glue/context_menu.h @@ -8,7 +8,7 @@ #include <vector> #include "base/basictypes.h" -#include "base/utf_string_conversions.h" +#include "base/string16.h" #include "googleurl/src/gurl.h" #include "webkit/glue/webmenuitem.h" @@ -57,7 +57,7 @@ struct ContextMenuParams { int media_flags; // This is the text of the selection that the context menu was invoked on. - std::wstring selection_text; + string16 selection_text; // The misspelled word under the cursor, if any. Used to generate the // |dictionary_suggestions| list. diff --git a/webkit/glue/cpp_bound_class.cc b/webkit/glue/cpp_bound_class.cc index d58fc4e..c5d15b6 100644 --- a/webkit/glue/cpp_bound_class.cc +++ b/webkit/glue/cpp_bound_class.cc @@ -319,7 +319,7 @@ CppVariant* CppBoundClass::GetAsCppVariant() { } void CppBoundClass::BindToJavascript(WebFrame* frame, - const std::wstring& classname) { + const std::string& classname) { #if WEBKIT_USING_JSC #error "This is not going to work anymore...but it's not clear what the solution is...or if it's still necessary." JSC::JSLock lock(false); @@ -328,7 +328,7 @@ void CppBoundClass::BindToJavascript(WebFrame* frame, // BindToWindowObject will take its own reference to the NPObject, and clean // up after itself. It will also (indirectly) register the object with V8, // so we must remember this so we can unregister it when we're destroyed. - frame->bindToWindowObject(WideToUTF16Hack(classname), + frame->bindToWindowObject(ASCIIToUTF16(classname), NPVARIANT_TO_OBJECT(*GetAsCppVariant())); bound_to_frame_ = true; } diff --git a/webkit/glue/cpp_bound_class.h b/webkit/glue/cpp_bound_class.h index a446386..06662ce 100644 --- a/webkit/glue/cpp_bound_class.h +++ b/webkit/glue/cpp_bound_class.h @@ -65,8 +65,7 @@ class CppBoundClass { // as window.<classname>. The owner of the CppBoundObject is responsible for // keeping the object around while the frame is alive, and for destroying it // afterwards. - void BindToJavascript( - WebKit::WebFrame* frame, const std::wstring& classname); + void BindToJavascript(WebKit::WebFrame* frame, const std::string& classname); // The type of callbacks. typedef Callback2<const CppArgumentList&, CppVariant*>::Type Callback; diff --git a/webkit/glue/cpp_bound_class_unittest.cc b/webkit/glue/cpp_bound_class_unittest.cc index f40b66b..54581ad 100644 --- a/webkit/glue/cpp_bound_class_unittest.cc +++ b/webkit/glue/cpp_bound_class_unittest.cc @@ -9,6 +9,7 @@ #include <vector> #include "base/message_loop.h" +#include "base/string_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebData.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" @@ -63,7 +64,7 @@ class ExampleTestShell : public TestShell { // When called by WebViewDelegate::WindowObjectCleared method, this binds a // CppExampleObject to window.example. virtual void BindJSObjectsToWindow(WebFrame* frame) { - example_bound_class_.BindToJavascript(frame, L"example"); + example_bound_class_.BindToJavascript(frame, "example"); // We use the layoutTestController binding for notifyDone. TestShell::BindJSObjectsToWindow(frame); } @@ -113,14 +114,15 @@ class CppBoundClassTest : public TestShellTest { // document text is exactly "SUCCESS". void CheckJavaScriptSuccess(const std::string& javascript) { ExecuteJavaScript(javascript); - EXPECT_EQ(L"SUCCESS", webkit_glue::DumpDocumentText(webframe_)); + EXPECT_EQ("SUCCESS", + UTF16ToASCII(webkit_glue::DumpDocumentText(webframe_))); } // Executes the specified JavaScript and checks that the resulting document // text is empty. void CheckJavaScriptFailure(const std::string& javascript) { ExecuteJavaScript(javascript); - EXPECT_EQ(L"", webkit_glue::DumpDocumentText(webframe_)); + EXPECT_EQ("", UTF16ToASCII(webkit_glue::DumpDocumentText(webframe_))); } // Constructs a JavaScript snippet that evaluates and compares the left and @@ -238,8 +240,7 @@ TEST_F(CppBoundClassTest, InvokeMethods) { "example.echoValue()", "null", // Too few arguments "example.echoType(false)", "true", - // Re-enable after merging r72243. - //"example.echoType(19)", "3.14159", + "example.echoType(19)", "3.14159", "example.echoType(9.876)", "3.14159", "example.echoType('test string')", "'Success!'", "example.echoType()", "null", // Too few arguments diff --git a/webkit/glue/cpp_variant.cc b/webkit/glue/cpp_variant.cc index 8545bc1..0d16cdd 100644 --- a/webkit/glue/cpp_variant.cc +++ b/webkit/glue/cpp_variant.cc @@ -211,10 +211,9 @@ bool CppVariant::ToBoolean() const { return value.boolValue; } -std::vector<std::wstring> CppVariant::ToStringVector() const { - +std::vector<std::string> CppVariant::ToStringVector() const { DCHECK(isObject()); - std::vector<std::wstring> wstring_vector; + std::vector<std::string> string_vector; NPObject* np_value = value.objectValue; NPIdentifier length_id = WebBindings::getStringIdentifier("length"); @@ -242,7 +241,7 @@ std::vector<std::wstring> CppVariant::ToStringVector() const { std::string string( NPVARIANT_TO_STRING(index_value).UTF8Characters, NPVARIANT_TO_STRING(index_value).UTF8Length); - wstring_vector.push_back(UTF8ToWide(string)); + string_vector.push_back(string); } WebBindings::releaseVariantValue(&index_value); } @@ -250,7 +249,7 @@ std::vector<std::wstring> CppVariant::ToStringVector() const { } } } - return wstring_vector; + return string_vector; } bool CppVariant::Invoke(const std::string& method, const CppVariant* args, diff --git a/webkit/glue/cpp_variant.h b/webkit/glue/cpp_variant.h index 71b3166..34f843a 100644 --- a/webkit/glue/cpp_variant.h +++ b/webkit/glue/cpp_variant.h @@ -96,7 +96,7 @@ class CppVariant : public NPVariant { bool ToBoolean() const; // Returns a vector of strings for the specified argument. This is useful // for converting a JavaScript array of strings into a vector of strings. - std::vector<std::wstring> ToStringVector() const; + std::vector<std::string> ToStringVector() const; // Invoke method of the given name on an object with the supplied arguments. // The first argument should be the object on which the method is to be diff --git a/webkit/glue/glue_serialize.cc b/webkit/glue/glue_serialize.cc index 835ae78..5b76784 100644 --- a/webkit/glue/glue_serialize.cc +++ b/webkit/glue/glue_serialize.cc @@ -343,7 +343,9 @@ static void WriteHistoryItem( // Creates a new HistoryItem tree based on the serialized string. // Assumes the data is in the format returned by WriteHistoryItem. static WebHistoryItem ReadHistoryItem( - const SerializeObject* obj, bool include_form_data) { + const SerializeObject* obj, + bool include_form_data, + bool include_scroll_offset) { // See note in WriteHistoryItem. on this. obj->version = ReadInteger(obj); @@ -368,9 +370,12 @@ static WebHistoryItem ReadHistoryItem( item.setTitle(ReadString(obj)); item.setAlternateTitle(ReadString(obj)); item.setLastVisitedTime(ReadReal(obj)); + int x = ReadInteger(obj); int y = ReadInteger(obj); - item.setScrollOffset(WebPoint(x, y)); + if (include_scroll_offset) + item.setScrollOffset(WebPoint(x, y)); + item.setIsTargetItem(ReadBoolean(obj)); item.setVisitCount(ReadInteger(obj)); item.setReferrer(ReadString(obj)); @@ -401,7 +406,9 @@ static WebHistoryItem ReadHistoryItem( // Subitems int num_children = ReadInteger(obj); for (int i = 0; i < num_children; ++i) - item.appendToChildren(ReadHistoryItem(obj, include_form_data)); + item.appendToChildren(ReadHistoryItem(obj, + include_form_data, + include_scroll_offset)); return item; } @@ -420,20 +427,22 @@ std::string HistoryItemToString(const WebHistoryItem& item) { // This assumes that the given serialized string has all the required key,value // pairs, and does minimal error checking. If |include_form_data| is true, // the form data from a post is restored, otherwise the form data is empty. +// If |include_scroll_offset| is true, the scroll offset is restored. static WebHistoryItem HistoryItemFromString( const std::string& serialized_item, - bool include_form_data) { + bool include_form_data, + bool include_scroll_offset) { if (serialized_item.empty()) return WebHistoryItem(); SerializeObject obj(serialized_item.data(), static_cast<int>(serialized_item.length())); - return ReadHistoryItem(&obj, include_form_data); + return ReadHistoryItem(&obj, include_form_data, include_scroll_offset); } WebHistoryItem HistoryItemFromString( const std::string& serialized_item) { - return HistoryItemFromString(serialized_item, true); + return HistoryItemFromString(serialized_item, true, true); } // For testing purposes only. @@ -470,7 +479,22 @@ std::string CreateHistoryStateForURL(const GURL& url) { std::string RemoveFormDataFromHistoryState(const std::string& content_state) { // TODO(darin): We should avoid using the WebKit API here, so that we do not // need to have WebKit initialized before calling this method. - const WebHistoryItem& item = HistoryItemFromString(content_state, false); + const WebHistoryItem& item = + HistoryItemFromString(content_state, false, true); + if (item.isNull()) { + // Couldn't parse the string, return an empty string. + return std::string(); + } + + return HistoryItemToString(item); +} + +std::string RemoveScrollOffsetFromHistoryState( + const std::string& content_state) { + // TODO(darin): We should avoid using the WebKit API here, so that we do not + // need to have WebKit initialized before calling this method. + const WebHistoryItem& item = + HistoryItemFromString(content_state, true, false); if (item.isNull()) { // Couldn't parse the string, return an empty string. return std::string(); diff --git a/webkit/glue/media/audio_decoder.cc b/webkit/glue/media/audio_decoder.cc new file mode 100644 index 0000000..3fc05c9 --- /dev/null +++ b/webkit/glue/media/audio_decoder.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 "webkit/glue/media/audio_decoder.h" + +#include <vector> +#include "base/basictypes.h" +#include "base/string_util.h" +#include "base/time.h" +#include "media/filters/audio_file_reader.h" +#include "third_party/WebKit/WebKit/chromium/public/WebAudioBus.h" + +using media::AudioFileReader; +using media::InMemoryDataReader; +using std::vector; +using WebKit::WebAudioBus; + +namespace webkit_glue { + +// Decode in-memory audio file data. +bool DecodeAudioFileData( + WebKit::WebAudioBus* destination_bus, + const char* data, size_t data_size, double sample_rate) { + DCHECK(destination_bus); + if (!destination_bus) + return false; + + // Uses the FFmpeg library for audio file reading. + InMemoryDataReader data_reader(data, data_size); + AudioFileReader reader(&data_reader); + + if (!reader.Open()) + return false; + + size_t number_of_channels = reader.channels(); + double file_sample_rate = reader.sample_rate(); + double duration = reader.duration().InSecondsF(); + size_t number_of_frames = static_cast<size_t>(reader.number_of_frames()); + + // TODO(crogers) : do sample-rate conversion with FFmpeg. + // For now, we're ignoring the requested 'sample_rate' and returning + // the WebAudioBus at the file's sample-rate. + // double destination_sample_rate = + // (sample_rate != 0.0) ? sample_rate : file_sample_rate; + double destination_sample_rate = file_sample_rate; + + DLOG(INFO) << "Decoding file data -" + << " data: " << data + << " data size: " << data_size + << " duration: " << duration + << " number of frames: " << number_of_frames + << " sample rate: " << file_sample_rate + << " number of channels: " << number_of_channels; + + // Change to destination sample-rate. + number_of_frames = static_cast<size_t>(number_of_frames * + (destination_sample_rate / file_sample_rate)); + + // Allocate and configure the output audio channel data. + destination_bus->initialize(number_of_channels, + number_of_frames, + destination_sample_rate); + + // Wrap the channel pointers which will receive the decoded PCM audio. + vector<float*> audio_data; + audio_data.reserve(number_of_channels); + for (size_t i = 0; i < number_of_channels; ++i) { + audio_data.push_back(destination_bus->channelData(i)); + } + + // Decode the audio file data. + return reader.Read(audio_data, number_of_frames); +} + +} // namespace webkit_glue diff --git a/webkit/glue/media/audio_decoder.h b/webkit/glue/media/audio_decoder.h new file mode 100644 index 0000000..57cc90b --- /dev/null +++ b/webkit/glue/media/audio_decoder.h @@ -0,0 +1,20 @@ +// 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 WEBKIT_GLUE_MEDIA_AUDIO_DECODER_H_ +#define WEBKIT_GLUE_MEDIA_AUDIO_DECODER_H_ + +#include "base/basictypes.h" + +namespace WebKit { class WebAudioBus; } + +namespace webkit_glue { + +// Decode in-memory audio file data. +bool DecodeAudioFileData(WebKit::WebAudioBus* destination_bus, const char* data, + size_t data_size, double sample_rate); + +} // namespace webkit_glue + +#endif // WEBKIT_GLUE_MEDIA_AUDIO_DECODER_H_ diff --git a/webkit/glue/media/buffered_data_source.cc b/webkit/glue/media/buffered_data_source.cc index 29c86ac..b6efa16 100644 --- a/webkit/glue/media/buffered_data_source.cc +++ b/webkit/glue/media/buffered_data_source.cc @@ -2,46 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/message_loop.h" -#include "base/process_util.h" -#include "base/stl_util-inl.h" -#include "base/string_util.h" +#include "webkit/glue/media/buffered_data_source.h" + #include "media/base/filter_host.h" -#include "media/base/media_format.h" -#include "net/base/load_flags.h" #include "net/base/net_errors.h" -#include "net/http/http_response_headers.h" -#include "webkit/glue/media/buffered_data_source.h" #include "webkit/glue/webkit_glue.h" -#include "webkit/glue/webmediaplayer_impl.h" - -namespace { -const char kHttpScheme[] = "http"; -const char kHttpsScheme[] = "https"; -const char kDataScheme[] = "data"; -const int64 kPositionNotSpecified = -1; -const int kHttpOK = 200; -const int kHttpPartialContent = 206; +using WebKit::WebFrame; -// Define the number of bytes in a megabyte. -const size_t kMegabyte = 1024 * 1024; - -// Backward capacity of the buffer, by default 2MB. -const size_t kBackwardCapcity = 2 * kMegabyte; - -// Forward capacity of the buffer, by default 10MB. -const size_t kForwardCapacity = 10 * kMegabyte; - -// The threshold of bytes that we should wait until the data arrives in the -// future instead of restarting a new connection. This number is defined in the -// number of bytes, we should determine this value from typical connection speed -// and amount of time for a suitable wait. Now I just make a guess for this -// number to be 2MB. -// TODO(hclam): determine a better value for this. -const int kForwardWaitThreshold = 2 * kMegabyte; +namespace { // Defines how long we should wait for more data before we declare a connection // timeout and start a new request. @@ -58,479 +27,18 @@ const int kReadTrials = 3; // of FFmpeg. const int kInitialReadBufferSize = 32768; -// Returns true if |url| operates on HTTP protocol. -bool IsHttpProtocol(const GURL& url) { - return url.SchemeIs(kHttpScheme) || url.SchemeIs(kHttpsScheme); -} - -bool IsDataProtocol(const GURL& url) { - return url.SchemeIs(kDataScheme); -} - -} // namespace +} // namespace namespace webkit_glue { -///////////////////////////////////////////////////////////////////////////// -// BufferedResourceLoader -BufferedResourceLoader::BufferedResourceLoader( - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory, - const GURL& url, - int64 first_byte_position, - int64 last_byte_position) - : buffer_(new media::SeekableBuffer(kBackwardCapcity, kForwardCapacity)), - deferred_(false), - defer_allowed_(true), - completed_(false), - range_requested_(false), - partial_response_(false), - bridge_factory_(bridge_factory), - url_(url), - first_byte_position_(first_byte_position), - last_byte_position_(last_byte_position), - start_callback_(NULL), - bridge_(NULL), - offset_(0), - content_length_(kPositionNotSpecified), - instance_size_(kPositionNotSpecified), - read_callback_(NULL), - read_position_(0), - read_size_(0), - read_buffer_(NULL), - first_offset_(0), - last_offset_(0) { -} - -BufferedResourceLoader::~BufferedResourceLoader() { -} - -void BufferedResourceLoader::Start(net::CompletionCallback* start_callback, - NetworkEventCallback* event_callback) { - // Make sure we have not started. - DCHECK(!bridge_.get()); - DCHECK(!start_callback_.get()); - DCHECK(!event_callback_.get()); - DCHECK(start_callback); - DCHECK(event_callback); - - start_callback_.reset(start_callback); - event_callback_.reset(event_callback); - - if (first_byte_position_ != kPositionNotSpecified) { - range_requested_ = true; - // TODO(hclam): server may not support range request so |offset_| may not - // equal to |first_byte_position_|. - offset_ = first_byte_position_; - } - - // Creates the bridge on render thread since we can only access - // ResourceDispatcher on this thread. - bridge_.reset( - bridge_factory_->CreateBridge( - url_, - net::LOAD_NORMAL, - first_byte_position_, - last_byte_position_)); - - // Increment the reference count right before we start the request. This - // reference will be release when this request has ended. - AddRef(); - - // And start the resource loading. - bridge_->Start(this); -} - -void BufferedResourceLoader::Stop() { - // Reset callbacks. - start_callback_.reset(); - event_callback_.reset(); - read_callback_.reset(); - - // Use the internal buffer to signal that we have been stopped. - // TODO(hclam): Not so pretty to do this. - if (!buffer_.get()) - return; - - // Destroy internal buffer. - buffer_.reset(); - - if (bridge_.get()) { - // Cancel the request. This method call will cancel the request - // asynchronously. We may still get data or messages until we receive - // a response completed message. - if (deferred_) - bridge_->SetDefersLoading(false); - deferred_ = false; - bridge_->Cancel(); - } -} - -void BufferedResourceLoader::Read(int64 position, - int read_size, - uint8* buffer, - net::CompletionCallback* read_callback) { - DCHECK(!read_callback_.get()); - DCHECK(buffer_.get()); - DCHECK(read_callback); - DCHECK(buffer); - - // Save the parameter of reading. - read_callback_.reset(read_callback); - read_position_ = position; - read_size_ = read_size; - read_buffer_ = buffer; - // If read position is beyond the instance size, we cannot read there. - if (instance_size_ != kPositionNotSpecified && - instance_size_ <= read_position_) { - DoneRead(0); - return; - } - - // Make sure |offset_| and |read_position_| does not differ by a large - // amount. - if (read_position_ > offset_ + kint32max || - read_position_ < offset_ + kint32min) { - DoneRead(net::ERR_CACHE_MISS); - return; - } - - // Prepare the parameters. - first_offset_ = static_cast<int>(read_position_ - offset_); - last_offset_ = first_offset_ + read_size_; - - // If we can serve the request now, do the actual read. - if (CanFulfillRead()) { - ReadInternal(); - DisableDeferIfNeeded(); - return; - } - - // If we expected the read request to be fulfilled later, returns - // immediately and let more data to flow in. - if (WillFulfillRead()) - return; - - // Make a callback to report failure. - DoneRead(net::ERR_CACHE_MISS); -} - -int64 BufferedResourceLoader::GetBufferedFirstBytePosition() { - if (buffer_.get()) - return offset_ - static_cast<int>(buffer_->backward_bytes()); - return kPositionNotSpecified; -} - -int64 BufferedResourceLoader::GetBufferedLastBytePosition() { - if (buffer_.get()) - return offset_ + static_cast<int>(buffer_->forward_bytes()) - 1; - return kPositionNotSpecified; -} - -void BufferedResourceLoader::SetAllowDefer(bool is_allowed) { - defer_allowed_ = is_allowed; - DisableDeferIfNeeded(); -} - -///////////////////////////////////////////////////////////////////////////// -// BufferedResourceLoader, -// webkit_glue::ResourceLoaderBridge::Peer implementations -bool BufferedResourceLoader::OnReceivedRedirect( - const GURL& new_url, - const webkit_glue::ResourceResponseInfo& info, - bool* has_new_first_party_for_cookies, - GURL* new_first_party_for_cookies) { - DCHECK(bridge_.get()); - - // Save the new URL. - url_ = new_url; - // TODO(wtc): should we return a new first party for cookies URL? - *has_new_first_party_for_cookies = false; - - // The load may have been stopped and |start_callback| is destroyed. - // In this case we shouldn't do anything. - if (!start_callback_.get()) - return true; - - if (!IsProtocolSupportedForMedia(new_url)) { - DoneStart(net::ERR_ADDRESS_INVALID); - Stop(); - return false; - } - return true; -} - -void BufferedResourceLoader::OnReceivedResponse( - const webkit_glue::ResourceResponseInfo& info, - bool content_filtered) { - DCHECK(bridge_.get()); - - // The loader may have been stopped and |start_callback| is destroyed. - // In this case we shouldn't do anything. - if (!start_callback_.get()) - return; - - // We make a strong assumption that when we reach here we have either - // received a response from HTTP/HTTPS protocol or the request was - // successful (in particular range request). So we only verify the partial - // response for HTTP and HTTPS protocol. - if (IsHttpProtocol(url_)) { - int error = net::OK; - if (!info.headers) { - // We expect to receive headers because this is a HTTP or HTTPS protocol, - // if not report failure. - error = net::ERR_INVALID_RESPONSE; - } else { - if (info.headers->response_code() == kHttpPartialContent) - partial_response_ = true; - - if (range_requested_ && partial_response_) { - // If we have verified the partial response and it is correct, we will - // return net::OK. - if (!VerifyPartialResponse(info)) - error = net::ERR_INVALID_RESPONSE; - } else if (info.headers->response_code() != kHttpOK) { - // We didn't request a range but server didn't reply with "200 OK". - error = net::ERR_FAILED; - } - } - - if (error != net::OK) { - DoneStart(error); - Stop(); - return; - } - } else { - // For any protocol other than HTTP and HTTPS, assume range request is - // always fulfilled. - partial_response_ = range_requested_; - } - - // |info.content_length| can be -1, in that case |content_length_| is - // not specified and this is a streaming response. - content_length_ = info.content_length; - - // If we have not requested a range, then the size of the instance is equal - // to the content length. - if (!partial_response_) - instance_size_ = content_length_; - - // Calls with a successful response. - DoneStart(net::OK); -} - -void BufferedResourceLoader::OnReceivedData(const char* data, int len) { - DCHECK(bridge_.get()); - - // If this loader has been stopped, |buffer_| would be destroyed. - // In this case we shouldn't do anything. - if (!buffer_.get()) - return; - - // Writes more data to |buffer_|. - buffer_->Append(reinterpret_cast<const uint8*>(data), len); - - // If there is an active read request, try to fulfill the request. - if (HasPendingRead() && CanFulfillRead()) { - ReadInternal(); - } else if (!defer_allowed_) { - // If we're not allowed to defer, slide the buffer window forward instead - // of deferring. - if (buffer_->forward_bytes() > buffer_->forward_capacity()) { - size_t excess = buffer_->forward_bytes() - buffer_->forward_capacity(); - bool success = buffer_->Seek(excess); - DCHECK(success); - offset_ += first_offset_ + excess; - } - } - - // At last see if the buffer is full and we need to defer the downloading. - EnableDeferIfNeeded(); - - // Notify that we have received some data. - NotifyNetworkEvent(); -} - -void BufferedResourceLoader::OnCompletedRequest( - const URLRequestStatus& status, - const std::string& security_info, - const base::Time& completion_time) { - DCHECK(bridge_.get()); - - // Saves the information that the request has completed. - completed_ = true; - - // If there is a start callback, calls it. - if (start_callback_.get()) { - DoneStart(status.os_error()); - } - - // If there is a pending read but the request has ended, returns with what - // we have. - if (HasPendingRead()) { - // Make sure we have a valid buffer before we satisfy a read request. - DCHECK(buffer_.get()); - - if (status.is_success()) { - // Try to fulfill with what is in the buffer. - if (CanFulfillRead()) - ReadInternal(); - else - DoneRead(net::ERR_CACHE_MISS); - } else { - // If the request has failed, then fail the read. - DoneRead(net::ERR_FAILED); - } - } - - // There must not be any outstanding read request. - DCHECK(!HasPendingRead()); - - // Notify that network response is completed. - NotifyNetworkEvent(); - - // We incremented the reference count when the loader was started. We balance - // that reference here so that we get destroyed. This is also the only safe - // place to destroy the ResourceLoaderBridge. - bridge_.reset(); - Release(); -} - -///////////////////////////////////////////////////////////////////////////// -// BufferedResourceLoader, private -void BufferedResourceLoader::EnableDeferIfNeeded() { - if (!defer_allowed_) - return; - - if (!deferred_ && - buffer_->forward_bytes() >= buffer_->forward_capacity()) { - deferred_ = true; - - if (bridge_.get()) - bridge_->SetDefersLoading(true); - - NotifyNetworkEvent(); - } -} - -void BufferedResourceLoader::DisableDeferIfNeeded() { - if (deferred_ && - (!defer_allowed_ || - buffer_->forward_bytes() < buffer_->forward_capacity() / 2)) { - deferred_ = false; - - if (bridge_.get()) - bridge_->SetDefersLoading(false); - - NotifyNetworkEvent(); - } -} - -bool BufferedResourceLoader::CanFulfillRead() { - // If we are reading too far in the backward direction. - if (first_offset_ < 0 && - first_offset_ + static_cast<int>(buffer_->backward_bytes()) < 0) - return false; - - // If the start offset is too far ahead. - if (first_offset_ >= static_cast<int>(buffer_->forward_bytes())) - return false; - - // At the point, we verified that first byte requested is within the buffer. - // If the request has completed, then just returns with what we have now. - if (completed_) - return true; - - // If the resource request is still active, make sure the whole requested - // range is covered. - if (last_offset_ > static_cast<int>(buffer_->forward_bytes())) - return false; - - return true; -} - -bool BufferedResourceLoader::WillFulfillRead() { - // Reading too far in the backward direction. - if (first_offset_ < 0 && - first_offset_ + static_cast<int>(buffer_->backward_bytes()) < 0) - return false; - - // Try to read too far ahead. - if (last_offset_ > kForwardWaitThreshold) - return false; - - // The resource request has completed, there's no way we can fulfill the - // read request. - if (completed_) - return false; - - return true; -} - -void BufferedResourceLoader::ReadInternal() { - // Seek to the first byte requested. - bool ret = buffer_->Seek(first_offset_); - DCHECK(ret); - - // Then do the read. - int read = static_cast<int>(buffer_->Read(read_buffer_, read_size_)); - offset_ += first_offset_ + read; - - // And report with what we have read. - DoneRead(read); -} - -bool BufferedResourceLoader::VerifyPartialResponse( - const ResourceResponseInfo& info) { - int64 first_byte_position, last_byte_position, instance_size; - if (!info.headers->GetContentRange(&first_byte_position, - &last_byte_position, - &instance_size)) { - return false; - } - - if (instance_size != kPositionNotSpecified) - instance_size_ = instance_size; - - if (first_byte_position_ != -1 && - first_byte_position_ != first_byte_position) { - return false; - } - - // TODO(hclam): I should also check |last_byte_position|, but since - // we will never make such a request that it is ok to leave it unimplemented. - return true; -} - -void BufferedResourceLoader::DoneRead(int error) { - read_callback_->RunWithParams(Tuple1<int>(error)); - read_callback_.reset(); - read_position_ = 0; - read_size_ = 0; - read_buffer_ = NULL; - first_offset_ = 0; - last_offset_ = 0; -} - -void BufferedResourceLoader::DoneStart(int error) { - start_callback_->RunWithParams(Tuple1<int>(error)); - start_callback_.reset(); -} - -void BufferedResourceLoader::NotifyNetworkEvent() { - if (event_callback_.get()) - event_callback_->Run(); -} - -///////////////////////////////////////////////////////////////////////////// -// BufferedDataSource BufferedDataSource::BufferedDataSource( MessageLoop* render_loop, - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory) + WebFrame* frame) : total_bytes_(kPositionNotSpecified), loaded_(false), streaming_(false), + frame_(frame), single_origin_(true), - bridge_factory_(bridge_factory), loader_(NULL), network_activity_(false), initialize_callback_(NULL), @@ -558,7 +66,7 @@ BufferedResourceLoader* BufferedDataSource::CreateResourceLoader( int64 first_byte_position, int64 last_byte_position) { DCHECK(MessageLoop::current() == render_loop_); - return new BufferedResourceLoader(bridge_factory_.get(), url_, + return new BufferedResourceLoader(url_, first_byte_position, last_byte_position); } @@ -571,7 +79,7 @@ base::TimeDelta BufferedDataSource::GetTimeoutMilliseconds() { } ///////////////////////////////////////////////////////////////////////////// -// BufferedDataSource, media::MediaFilter implementation +// media::Filter implementation. void BufferedDataSource::Initialize(const std::string& url, media::FilterCallback* callback) { // Saves the url. @@ -602,7 +110,7 @@ bool BufferedDataSource::IsUrlSupported(const std::string& url) { GURL gurl(url); // This data source doesn't support data:// protocol so reject it. - return IsProtocolSupportedForMedia(gurl) && !IsDataProtocol(gurl); + return IsProtocolSupportedForMedia(gurl) && !gurl.SchemeIs(kDataScheme); } void BufferedDataSource::Stop(media::FilterCallback* callback) { @@ -626,7 +134,7 @@ void BufferedDataSource::SetPlaybackRate(float playback_rate) { } ///////////////////////////////////////////////////////////////////////////// -// BufferedDataSource, media::DataSource implementation +// media::DataSource implementation. void BufferedDataSource::Read(int64 position, size_t size, uint8* data, media::DataSource::ReadCallback* read_callback) { render_loop_->PostTask(FROM_HERE, @@ -658,20 +166,21 @@ void BufferedDataSource::Abort() { // If we are told to abort, immediately return from any pending read // with an error. if (read_callback_.get()) { - { AutoLock auto_lock(lock_); DoneRead_Locked(net::ERR_FAILED); - } - CleanupTask(); } + + CleanupTask(); + frame_ = NULL; } ///////////////////////////////////////////////////////////////////////////// -// BufferedDataSource, render thread tasks +// Render thread tasks. void BufferedDataSource::InitializeTask() { DCHECK(MessageLoop::current() == render_loop_); DCHECK(!loader_.get()); - DCHECK(!stopped_on_render_loop_); + if (stopped_on_render_loop_) + return; // Kick starts the watch dog task that will handle connection timeout. // We run the watch dog 2 times faster the actual timeout so as to catch @@ -681,24 +190,24 @@ void BufferedDataSource::InitializeTask() { this, &BufferedDataSource::WatchDogTask); - if (IsHttpProtocol(url_)) { - // Fetch only first 1024 bytes as this usually covers the header portion - // of a media file that gives enough information about the codecs, etc. - // This also serve as a probe to determine server capability to serve - // range request. - // TODO(hclam): Do some experiments for the best approach. - loader_ = CreateResourceLoader(0, 1024); + if (url_.SchemeIs(kHttpScheme) || url_.SchemeIs(kHttpsScheme)) { + // Do an unbounded range request starting at the beginning. If the server + // responds with 200 instead of 206 we'll fall back into a streaming mode. + loader_ = CreateResourceLoader(0, kPositionNotSpecified); loader_->Start( NewCallback(this, &BufferedDataSource::HttpInitialStartCallback), - NewCallback(this, &BufferedDataSource::NetworkEventCallback)); + NewCallback(this, &BufferedDataSource::NetworkEventCallback), + frame_); } else { // For all other protocols, assume they support range request. We fetch // the full range of the resource to obtain the instance size because // we won't be served HTTP headers. - loader_ = CreateResourceLoader(-1, -1); + loader_ = CreateResourceLoader(kPositionNotSpecified, + kPositionNotSpecified); loader_->Start( NewCallback(this, &BufferedDataSource::NonHttpInitialStartCallback), - NewCallback(this, &BufferedDataSource::NetworkEventCallback)); + NewCallback(this, &BufferedDataSource::NetworkEventCallback), + frame_); } } @@ -706,11 +215,6 @@ void BufferedDataSource::ReadTask( int64 position, int read_size, uint8* buffer, media::DataSource::ReadCallback* read_callback) { DCHECK(MessageLoop::current() == render_loop_); - - // If CleanupTask() was executed we should return immediately. We check this - // variable to prevent doing any actual work after clean up was done. We do - // not check |stop_signal_received_| because anything use of it has to be - // within |lock_| which is not desirable. if (stopped_on_render_loop_) return; @@ -731,8 +235,6 @@ void BufferedDataSource::ReadTask( void BufferedDataSource::CleanupTask() { DCHECK(MessageLoop::current() == render_loop_); - - // If we have already stopped, do nothing. if (stopped_on_render_loop_) return; @@ -757,13 +259,6 @@ void BufferedDataSource::CleanupTask() { void BufferedDataSource::RestartLoadingTask() { DCHECK(MessageLoop::current() == render_loop_); - - // This variable is set in CleanupTask(). We check this and do an early - // return. The sequence of actions which enable this conditions is: - // 1. Stop() is called from the pipeline. - // 2. ReadCallback() is called from the resource loader. - // 3. CleanupTask() is executed. - // 4. RestartLoadingTask() is executed. if (stopped_on_render_loop_) return; @@ -771,16 +266,18 @@ void BufferedDataSource::RestartLoadingTask() { if (!read_callback_.get()) return; - loader_ = CreateResourceLoader(read_position_, -1); + loader_ = CreateResourceLoader(read_position_, kPositionNotSpecified); loader_->SetAllowDefer(!media_is_paused_); loader_->Start( NewCallback(this, &BufferedDataSource::PartialReadStartCallback), - NewCallback(this, &BufferedDataSource::NetworkEventCallback)); + NewCallback(this, &BufferedDataSource::NetworkEventCallback), + frame_); } void BufferedDataSource::WatchDogTask() { DCHECK(MessageLoop::current() == render_loop_); - DCHECK(!stopped_on_render_loop_); + if (stopped_on_render_loop_) + return; // We only care if there is an active read request. if (!read_callback_.get()) @@ -802,11 +299,12 @@ void BufferedDataSource::WatchDogTask() { // Stops the current loader and creates a new resource loader and // retry the request. loader_->Stop(); - loader_ = CreateResourceLoader(read_position_, -1); + loader_ = CreateResourceLoader(read_position_, kPositionNotSpecified); loader_->SetAllowDefer(!media_is_paused_); loader_->Start( NewCallback(this, &BufferedDataSource::PartialReadStartCallback), - NewCallback(this, &BufferedDataSource::NetworkEventCallback)); + NewCallback(this, &BufferedDataSource::NetworkEventCallback), + frame_); } void BufferedDataSource::SetPlaybackRateTask(float playback_rate) { @@ -829,7 +327,7 @@ void BufferedDataSource::SetPlaybackRateTask(float playback_rate) { // prior to make this method call. void BufferedDataSource::ReadInternal() { DCHECK(MessageLoop::current() == render_loop_); - DCHECK(loader_.get()); + DCHECK(loader_); // First we prepare the intermediate read buffer for BufferedResourceLoader // to write to. @@ -872,9 +370,7 @@ void BufferedDataSource::DoneInitialization_Locked() { } ///////////////////////////////////////////////////////////////////////////// -// BufferedDataSource, callback methods. -// These methods are called on the render thread for the events reported by -// BufferedResourceLoader. +// BufferedResourceLoader callback methods. void BufferedDataSource::HttpInitialStartCallback(int error) { DCHECK(MessageLoop::current() == render_loop_); DCHECK(loader_.get()); @@ -901,10 +397,12 @@ void BufferedDataSource::HttpInitialStartCallback(int error) { // Assuming that the Range header was causing the problem. Retry without // the Range header. using_range_request_ = false; - loader_ = CreateResourceLoader(-1, -1); + loader_ = CreateResourceLoader(kPositionNotSpecified, + kPositionNotSpecified); loader_->Start( NewCallback(this, &BufferedDataSource::HttpInitialStartCallback), - NewCallback(this, &BufferedDataSource::NetworkEventCallback)); + NewCallback(this, &BufferedDataSource::NetworkEventCallback), + frame_); return; } @@ -1058,10 +556,10 @@ void BufferedDataSource::NetworkEventCallback() { return; bool network_activity = loader_->network_activity(); - int64 buffered_last_byte_position = loader_->GetBufferedLastBytePosition(); + int64 buffered_position = loader_->GetBufferedPosition(); // If we get an unspecified value, return immediately. - if (buffered_last_byte_position == kPositionNotSpecified) + if (buffered_position == kPositionNotSpecified) return; // We need to prevent calling to filter host and running the callback if @@ -1080,7 +578,7 @@ void BufferedDataSource::NetworkEventCallback() { network_activity_ = network_activity; host()->SetNetworkActivity(network_activity); } - host()->SetBufferedBytes(buffered_last_byte_position + 1); + host()->SetBufferedBytes(buffered_position + 1); } } // namespace webkit_glue diff --git a/webkit/glue/media/buffered_data_source.h b/webkit/glue/media/buffered_data_source.h index 2af9e84..1c4e3fa 100644 --- a/webkit/glue/media/buffered_data_source.h +++ b/webkit/glue/media/buffered_data_source.h @@ -10,220 +10,18 @@ #include "base/callback.h" #include "base/lock.h" #include "base/scoped_ptr.h" -#include "base/timer.h" -#include "base/condition_variable.h" -#include "googleurl/src/gurl.h" -#include "media/base/filters.h" -#include "media/base/media_format.h" -#include "media/base/pipeline.h" -#include "media/base/seekable_buffer.h" -#include "net/base/completion_callback.h" -#include "net/base/file_stream.h" -#include "webkit/glue/media/media_resource_loader_bridge_factory.h" -#include "webkit/glue/media/web_data_source.h" -#include "webkit/glue/webmediaplayer_impl.h" +#include "webkit/glue/media/buffered_resource_loader.h" namespace webkit_glue { -///////////////////////////////////////////////////////////////////////////// -// BufferedResourceLoader -// This class works inside demuxer thread and render thread. It contains a -// resource loader bridge and does the actual resource loading. This object -// does buffering internally, it defers the resource loading if buffer is -// full and un-defers the resource loading if it is under buffered. -class BufferedResourceLoader : - public base::RefCountedThreadSafe<BufferedResourceLoader>, - public webkit_glue::ResourceLoaderBridge::Peer { - public: - typedef Callback0::Type NetworkEventCallback; - - // |bridge_factory| - Factory to create a ResourceLoaderBridge. - // |url| - URL for the resource to be loaded. - // |first_byte_position| - First byte to start loading from, -1 for not - // specified. - // |last_byte_position| - Last byte to be loaded, -1 for not specified. - BufferedResourceLoader( - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory, - const GURL& url, - int64 first_byte_position, - int64 last_byte_position); - - // Start the resource loading with the specified URL and range. - // This method operates in asynchronous mode. Once there's a response from the - // server, success or fail |callback| is called with the result. - // |callback| is called with the following values: - // - net::OK - // The request has started successfully. - // - net::ERR_FAILED - // The request has failed because of an error with the network. - // - net::ERR_INVALID_RESPONSE - // An invalid response is received from the server. - // - (Anything else) - // An error code that indicates the request has failed. - // |event_callback| is called when the response is completed, data is - // received, the request is suspended or resumed. - virtual void Start(net::CompletionCallback* callback, - NetworkEventCallback* event_callback); - - // Stop this loader, cancels and request and release internal buffer. - virtual void Stop(); - - // Reads the specified |read_size| from |position| into |buffer| and when - // the operation is done invoke |callback| with number of bytes read or an - // error code. - // |callback| is called with the following values: - // - (Anything greater than or equal 0) - // Read was successful with the indicated number of bytes read. - // - net::ERR_FAILED - // The read has failed because of an error with the network. - // - net::ERR_CACHE_MISS - // The read was made too far away from the current buffered position. - virtual void Read(int64 position, int read_size, - uint8* buffer, net::CompletionCallback* callback); - - // Returns the position of the first byte buffered. Returns -1 if such value - // is not available. - virtual int64 GetBufferedFirstBytePosition(); - - // Returns the position of the last byte buffered. Returns -1 if such value - // is not available. - virtual int64 GetBufferedLastBytePosition(); - - // Sets whether deferring data is allowed or disallowed. - virtual void SetAllowDefer(bool is_allowed); - - // Gets the content length in bytes of the instance after this loader has been - // started. If this value is -1, then content length is unknown. - virtual int64 content_length() { return content_length_; } - - // Gets the original size of the file requested. If this value is -1, then - // the size is unknown. - virtual int64 instance_size() { return instance_size_; } - - // Returns true if the response for this loader is a partial response. - // It means a 206 response in HTTP/HTTPS protocol. - virtual bool partial_response() { return partial_response_; } - - // Returns true if network is currently active. - virtual bool network_activity() { return !completed_ && !deferred_; } - - // Returns resulting URL. - virtual const GURL& url() { return url_; } - - ///////////////////////////////////////////////////////////////////////////// - // webkit_glue::ResourceLoaderBridge::Peer implementations. - virtual void OnUploadProgress(uint64 position, uint64 size) {} - virtual bool OnReceivedRedirect( - const GURL& new_url, - const webkit_glue::ResourceResponseInfo& info, - bool* has_new_first_party_for_cookies, - GURL* new_first_party_for_cookies); - virtual void OnReceivedResponse( - const webkit_glue::ResourceResponseInfo& info, - bool content_filtered); - virtual void OnDownloadedData(int len) {} - virtual void OnReceivedData(const char* data, int len); - virtual void OnCompletedRequest( - const URLRequestStatus& status, - const std::string& security_info, - const base::Time& completion_time); - - protected: - friend class base::RefCountedThreadSafe<BufferedResourceLoader>; - - virtual ~BufferedResourceLoader(); - - private: - friend class BufferedResourceLoaderTest; - - // Defer the resource loading if the buffer is full. - void EnableDeferIfNeeded(); - - // Disable defer loading if we are under-buffered. - void DisableDeferIfNeeded(); - - // Returns true if the current read request can be fulfilled by what is in - // the buffer. - bool CanFulfillRead(); - - // Returns true if the current read request will be fulfilled in the future. - bool WillFulfillRead(); - - // Method that does the actual read and calls the |read_callbac_|, assuming - // the request range is in |buffer_|. - void ReadInternal(); - - // If we have made a range request, verify the response from the server. - bool VerifyPartialResponse(const ResourceResponseInfo& info); - - // Done with read. Invokes the read callback and reset parameters for the - // read request. - void DoneRead(int error); - - // Done with start. Invokes the start callback and reset it. - void DoneStart(int error); - - // Calls |event_callback_| in terms of a network event. - void NotifyNetworkEvent(); - - bool HasPendingRead() { return read_callback_.get() != NULL; } - - // A sliding window of buffer. - scoped_ptr<media::SeekableBuffer> buffer_; - - // True if resource loading was deferred. - bool deferred_; - - // True if resource loader is allowed to defer, false otherwise. - bool defer_allowed_; - - // True if resource loading has completed. - bool completed_; - - // True if a range request was made. - bool range_requested_; - - // True if response data received is a partial range. - bool partial_response_; - - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory_; - GURL url_; - int64 first_byte_position_; - int64 last_byte_position_; - - // Callback method that listens to network events. - scoped_ptr<NetworkEventCallback> event_callback_; - - // Members used during request start. - scoped_ptr<net::CompletionCallback> start_callback_; - scoped_ptr<webkit_glue::ResourceLoaderBridge> bridge_; - int64 offset_; - int64 content_length_; - int64 instance_size_; - - // Members used during a read operation. They should be reset after each - // read has completed or failed. - scoped_ptr<net::CompletionCallback> read_callback_; - int64 read_position_; - int read_size_; - uint8* read_buffer_; - - // Offsets of the requested first byte and last byte in |buffer_|. They are - // written by VerifyRead(). - int first_offset_; - int last_offset_; - - DISALLOW_COPY_AND_ASSIGN(BufferedResourceLoader); -}; class BufferedDataSource : public WebDataSource { public: - BufferedDataSource( - MessageLoop* render_loop, - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory); + BufferedDataSource(MessageLoop* render_loop, + WebKit::WebFrame* frame); virtual ~BufferedDataSource(); - // media::MediaFilter implementation. + // media::Filter implementation. virtual void Initialize(const std::string& url, media::FilterCallback* callback); virtual bool IsUrlSupported(const std::string& url); @@ -247,7 +45,6 @@ class BufferedDataSource : public WebDataSource { virtual void Abort(); protected: - // A factory method to create a BufferedResourceLoader based on the read // parameters. We can override this file to object a mock // BufferedResourceLoader for testing. @@ -338,12 +135,12 @@ class BufferedDataSource : public WebDataSource { // i.e. range request is not supported. bool streaming_; + // A webframe for loading. + WebKit::WebFrame* frame_; + // True if the media resource has a single origin. bool single_origin_; - // A factory object to produce ResourceLoaderBridge. - scoped_ptr<webkit_glue::MediaResourceLoaderBridgeFactory> bridge_factory_; - // A resource loader for the media resource. scoped_refptr<BufferedResourceLoader> loader_; @@ -385,7 +182,7 @@ class BufferedDataSource : public WebDataSource { bool stop_signal_received_; // This variable is set by CleanupTask() that indicates this object is stopped - // on the render thread. + // on the render thread and work should no longer progress. bool stopped_on_render_loop_; // This variable is true when we are in a paused state and false when we diff --git a/webkit/glue/media/buffered_data_source_unittest.cc b/webkit/glue/media/buffered_data_source_unittest.cc index 81103b2..dcb11ec 100644 --- a/webkit/glue/media/buffered_data_source_unittest.cc +++ b/webkit/glue/media/buffered_data_source_unittest.cc @@ -4,22 +4,18 @@ #include <algorithm> -#include "base/callback.h" -#include "base/format_macros.h" -#include "base/message_loop.h" -#include "base/string_util.h" -#include "base/stringprintf.h" -#include "media/base/filters.h" +#include "base/test/test_timeouts.h" #include "media/base/mock_filter_host.h" #include "media/base/mock_filters.h" #include "net/base/net_errors.h" -#include "net/http/http_response_headers.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" #include "webkit/glue/media/buffered_data_source.h" -#include "webkit/glue/media/mock_media_resource_loader_bridge_factory.h" -#include "webkit/glue/mock_resource_loader_bridge.h" +#include "webkit/mocks/mock_webframe.h" using ::testing::_; using ::testing::Assign; +using ::testing::AtLeast; using ::testing::DeleteArg; using ::testing::DoAll; using ::testing::InSequence; @@ -49,476 +45,36 @@ enum NetworkState { namespace webkit_glue { -// Submit a request completed event to the resource loader due to request -// being canceled. Pretending the event is from external. -ACTION_P(RequestCanceled, loader) { - URLRequestStatus status; - status.set_status(URLRequestStatus::CANCELED); - status.set_os_error(net::ERR_ABORTED); - loader->OnCompletedRequest(status, "", base::Time()); -} - -class BufferedResourceLoaderTest : public testing::Test { +// A mock BufferedDataSource to inject mock BufferedResourceLoader through +// CreateResourceLoader() method. +class MockBufferedDataSource : public BufferedDataSource { public: - BufferedResourceLoaderTest() { - bridge_.reset(new StrictMock<MockResourceLoaderBridge>()); - - for (int i = 0; i < kDataSize; ++i) - data_[i] = i; - } - - ~BufferedResourceLoaderTest() { - if (bridge_.get()) - EXPECT_CALL(*bridge_, OnDestroy()); - EXPECT_CALL(bridge_factory_, OnDestroy()); - } - - void Initialize(const char* url, int first_position, int last_position) { - gurl_ = GURL(url); - first_position_ = first_position; - last_position_ = last_position; - - loader_ = new BufferedResourceLoader(&bridge_factory_, gurl_, - first_position_, last_position_); - } - - void SetLoaderBuffer(size_t forward_capacity, size_t backward_capacity) { - loader_->buffer_.reset( - new media::SeekableBuffer(backward_capacity, forward_capacity)); - } - - void Start() { - InSequence s; - EXPECT_CALL(bridge_factory_, - CreateBridge(gurl_, _, first_position_, last_position_)) - .WillOnce(Return(bridge_.get())); - EXPECT_CALL(*bridge_, Start(loader_.get())); - loader_->Start( - NewCallback(this, &BufferedResourceLoaderTest::StartCallback), - NewCallback(this, &BufferedResourceLoaderTest::NetworkCallback)); - } - - void FullResponse(int64 instance_size) { - EXPECT_CALL(*this, StartCallback(net::OK)); - ResourceResponseInfo info; - std::string header = base::StringPrintf("HTTP/1.1 200 OK\n" - "Content-Length: %" PRId64, - instance_size); - replace(header.begin(), header.end(), '\n', '\0'); - info.headers = new net::HttpResponseHeaders(header); - info.content_length = instance_size; - loader_->OnReceivedResponse(info, false); - EXPECT_EQ(instance_size, loader_->content_length()); - EXPECT_EQ(instance_size, loader_->instance_size()); - EXPECT_FALSE(loader_->partial_response()); - } - - void PartialResponse(int64 first_position, int64 last_position, - int64 instance_size) { - EXPECT_CALL(*this, StartCallback(net::OK)); - int64 content_length = last_position - first_position + 1; - ResourceResponseInfo info; - std::string header = base::StringPrintf("HTTP/1.1 206 Partial Content\n" - "Content-Range: bytes " - "%" PRId64 "-%" PRId64 "/%" PRId64, - first_position, - last_position, - instance_size); - replace(header.begin(), header.end(), '\n', '\0'); - info.headers = new net::HttpResponseHeaders(header); - info.content_length = content_length; - loader_->OnReceivedResponse(info, false); - EXPECT_EQ(content_length, loader_->content_length()); - EXPECT_EQ(instance_size, loader_->instance_size()); - EXPECT_TRUE(loader_->partial_response()); - } - - void StopWhenLoad() { - InSequence s; - EXPECT_CALL(*bridge_, Cancel()) - .WillOnce(RequestCanceled(loader_)); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &BufferedResourceLoaderTest::ReleaseBridge)); - loader_->Stop(); - } - - void ReleaseBridge() { - ignore_result(bridge_.release()); - } - - // Helper method to write to |loader_| from |data_|. - void WriteLoader(int position, int size) { - EXPECT_CALL(*this, NetworkCallback()) - .RetiresOnSaturation(); - loader_->OnReceivedData(reinterpret_cast<char*>(data_ + position), size); - } - - // Helper method to read from |loader_|. - void ReadLoader(int64 position, int size, uint8* buffer) { - loader_->Read(position, size, buffer, - NewCallback(this, &BufferedResourceLoaderTest::ReadCallback)); - } - - // Verifis that data in buffer[0...size] is equal to data_[pos...pos+size]. - void VerifyBuffer(uint8* buffer, int pos, int size) { - EXPECT_EQ(0, memcmp(buffer, data_ + pos, size)); - } - - // Helper method to disallow deferring in |loader_|. - void DisallowLoaderDefer() { - if (loader_->deferred_) { - EXPECT_CALL(*bridge_, SetDefersLoading(false)); - EXPECT_CALL(*this, NetworkCallback()); - } - loader_->SetAllowDefer(false); + MockBufferedDataSource( + MessageLoop* message_loop, WebFrame* frame) + : BufferedDataSource(message_loop, frame) { } - // Helper method to allow deferring in |loader_|. - void AllowLoaderDefer() { - loader_->SetAllowDefer(true); + virtual base::TimeDelta GetTimeoutMilliseconds() { + return base::TimeDelta::FromMilliseconds( + TestTimeouts::tiny_timeout_ms()); } - MOCK_METHOD1(StartCallback, void(int error)); - MOCK_METHOD1(ReadCallback, void(int error)); - MOCK_METHOD0(NetworkCallback, void()); - - protected: - GURL gurl_; - int64 first_position_; - int64 last_position_; - - scoped_refptr<BufferedResourceLoader> loader_; - StrictMock<MockMediaResourceLoaderBridgeFactory> bridge_factory_; - scoped_ptr<StrictMock<MockResourceLoaderBridge> > bridge_; - - uint8 data_[kDataSize]; + MOCK_METHOD2(CreateResourceLoader, + BufferedResourceLoader*(int64 first_position, + int64 last_position)); private: - DISALLOW_COPY_AND_ASSIGN(BufferedResourceLoaderTest); + DISALLOW_COPY_AND_ASSIGN(MockBufferedDataSource); }; -TEST_F(BufferedResourceLoaderTest, StartStop) { - Initialize(kHttpUrl, -1, -1); - Start(); - StopWhenLoad(); -} - -// Tests that HTTP header is missing in the response. -TEST_F(BufferedResourceLoaderTest, MissingHttpHeader) { - Initialize(kHttpUrl, -1, -1); - Start(); - - EXPECT_CALL(*this, StartCallback(net::ERR_INVALID_RESPONSE)); - EXPECT_CALL(*bridge_, Cancel()) - .WillOnce(RequestCanceled(loader_)); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &BufferedResourceLoaderTest::ReleaseBridge)); - - ResourceResponseInfo info; - loader_->OnReceivedResponse(info, false); -} - -// Tests that a bad HTTP response is recived, e.g. file not found. -TEST_F(BufferedResourceLoaderTest, BadHttpResponse) { - Initialize(kHttpUrl, -1, -1); - Start(); - - EXPECT_CALL(*this, StartCallback(net::ERR_FAILED)); - EXPECT_CALL(*bridge_, Cancel()) - .WillOnce(RequestCanceled(loader_)); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &BufferedResourceLoaderTest::ReleaseBridge)); - - ResourceResponseInfo info; - info.headers = new net::HttpResponseHeaders("HTTP/1.1 404 Not Found\n"); - loader_->OnReceivedResponse(info, false); -} - -// Tests that partial content is requested but not fulfilled. -TEST_F(BufferedResourceLoaderTest, NotPartialResponse) { - Initialize(kHttpUrl, 100, -1); - Start(); - FullResponse(1024); - StopWhenLoad(); -} - -// Tests that a 200 response is received. -TEST_F(BufferedResourceLoaderTest, FullResponse) { - Initialize(kHttpUrl, -1, -1); - Start(); - FullResponse(1024); - StopWhenLoad(); -} - -// Tests that a partial content response is received. -TEST_F(BufferedResourceLoaderTest, PartialResponse) { - Initialize(kHttpUrl, 100, 200); - Start(); - PartialResponse(100, 200, 1024); - StopWhenLoad(); -} - -// Tests that an invalid partial response is received. -TEST_F(BufferedResourceLoaderTest, InvalidPartialResponse) { - Initialize(kHttpUrl, 0, 10); - Start(); - - EXPECT_CALL(*this, StartCallback(net::ERR_INVALID_RESPONSE)); - EXPECT_CALL(*bridge_, Cancel()) - .WillOnce(RequestCanceled(loader_)); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &BufferedResourceLoaderTest::ReleaseBridge)); - - ResourceResponseInfo info; - std::string header = base::StringPrintf("HTTP/1.1 206 Partial Content\n" - "Content-Range: bytes %d-%d/%d", - 1, 10, 1024); - replace(header.begin(), header.end(), '\n', '\0'); - info.headers = new net::HttpResponseHeaders(header); - info.content_length = 10; - loader_->OnReceivedResponse(info, false); -} - -// Tests the logic of sliding window for data buffering and reading. -TEST_F(BufferedResourceLoaderTest, BufferAndRead) { - Initialize(kHttpUrl, 10, 29); - Start(); - PartialResponse(10, 29, 30); - - uint8 buffer[10]; - InSequence s; - - // Writes 10 bytes and read them back. - WriteLoader(10, 10); - EXPECT_CALL(*this, ReadCallback(10)); - ReadLoader(10, 10, buffer); - VerifyBuffer(buffer, 10, 10); - - // Writes 10 bytes and read 2 times. - WriteLoader(20, 10); - EXPECT_CALL(*this, ReadCallback(5)); - ReadLoader(20, 5, buffer); - VerifyBuffer(buffer, 20, 5); - EXPECT_CALL(*this, ReadCallback(5)); - ReadLoader(25, 5, buffer); - VerifyBuffer(buffer, 25, 5); - - // Read backward within buffer. - EXPECT_CALL(*this, ReadCallback(10)); - ReadLoader(10, 10, buffer); - VerifyBuffer(buffer, 10, 10); - - // Read backward outside buffer. - EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); - ReadLoader(9, 10, buffer); - - // Response has completed. - EXPECT_CALL(*this, NetworkCallback()); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &BufferedResourceLoaderTest::ReleaseBridge)); - URLRequestStatus status; - status.set_status(URLRequestStatus::SUCCESS); - loader_->OnCompletedRequest(status, "", base::Time()); - - // Try to read 10 from position 25 will just return with 5 bytes. - EXPECT_CALL(*this, ReadCallback(5)); - ReadLoader(25, 10, buffer); - VerifyBuffer(buffer, 25, 5); - - // Try to read outside buffered range after request has completed. - EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); - ReadLoader(5, 10, buffer); - - // Try to read beyond the instance size. - EXPECT_CALL(*this, ReadCallback(0)); - ReadLoader(30, 10, buffer); -} - -TEST_F(BufferedResourceLoaderTest, ReadOutsideBuffer) { - Initialize(kHttpUrl, 10, 0x00FFFFFF); - Start(); - PartialResponse(10, 0x00FFFFFF, 0x01000000); - - uint8 buffer[10]; - InSequence s; - - // Read very far aheard will get a cache miss. - EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); - ReadLoader(0x00FFFFFF, 1, buffer); - - // The following call will not call ReadCallback() because it is waiting for - // data to arrive. - ReadLoader(10, 10, buffer); - - // Writing to loader will fulfill the read request. - EXPECT_CALL(*this, ReadCallback(10)); - WriteLoader(10, 20); - VerifyBuffer(buffer, 10, 10); - - // The following call cannot be fulfilled now. - ReadLoader(25, 10, buffer); - - EXPECT_CALL(*this, ReadCallback(5)); - EXPECT_CALL(*this, NetworkCallback()); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &BufferedResourceLoaderTest::ReleaseBridge)); - URLRequestStatus status; - status.set_status(URLRequestStatus::SUCCESS); - loader_->OnCompletedRequest(status, "", base::Time()); -} - -TEST_F(BufferedResourceLoaderTest, RequestFailedWhenRead) { - Initialize(kHttpUrl, 10, 29); - Start(); - PartialResponse(10, 29, 30); - - uint8 buffer[10]; - InSequence s; - - ReadLoader(10, 10, buffer); - EXPECT_CALL(*this, ReadCallback(net::ERR_FAILED)); - EXPECT_CALL(*this, NetworkCallback()); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &BufferedResourceLoaderTest::ReleaseBridge)); - URLRequestStatus status; - status.set_status(URLRequestStatus::FAILED); - loader_->OnCompletedRequest(status, "", base::Time()); -} - -// Tests the logic of caching data to disk when media is paused. -TEST_F(BufferedResourceLoaderTest, AllowDefer_NoDataReceived) { - Initialize(kHttpUrl, 10, 99); - SetLoaderBuffer(10, 20); - Start(); - PartialResponse(10, 99, 100); - - // Start in undeferred state, then disallow defer, then allow defer - // without receiving data in between. - DisallowLoaderDefer(); - AllowLoaderDefer(); - StopWhenLoad(); -} - -TEST_F(BufferedResourceLoaderTest, AllowDefer_ReadSameWindow) { - Initialize(kHttpUrl, 10, 99); - SetLoaderBuffer(10, 20); - Start(); - PartialResponse(10, 99, 100); - - uint8 buffer[10]; - - // Start in undeferred state, disallow defer, receive data but don't shift - // buffer window, then allow defer and read. - DisallowLoaderDefer(); - WriteLoader(10, 10); - AllowLoaderDefer(); - - EXPECT_CALL(*this, ReadCallback(10)); - ReadLoader(10, 10, buffer); - VerifyBuffer(buffer, 10, 10); - StopWhenLoad(); -} - -TEST_F(BufferedResourceLoaderTest, AllowDefer_ReadPastWindow) { - Initialize(kHttpUrl, 10, 99); - SetLoaderBuffer(10, 20); - Start(); - PartialResponse(10, 99, 100); - - uint8 buffer[10]; - - // Not deferred, disallow defer, received data and shift buffer window, - // allow defer, then read in area outside of buffer window. - DisallowLoaderDefer(); - WriteLoader(10, 10); - WriteLoader(20, 50); - AllowLoaderDefer(); - - EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); - ReadLoader(10, 10, buffer); - StopWhenLoad(); -} - -TEST_F(BufferedResourceLoaderTest, AllowDefer_DeferredNoDataReceived) { - Initialize(kHttpUrl, 10, 99); - SetLoaderBuffer(10, 20); - Start(); - PartialResponse(10, 99, 100); - - uint8 buffer[10]; - - // Start in deferred state, then disallow defer, receive no data, and - // allow defer and read. - EXPECT_CALL(*bridge_, SetDefersLoading(true)); - EXPECT_CALL(*this, NetworkCallback()); - WriteLoader(10, 40); - - DisallowLoaderDefer(); - AllowLoaderDefer(); - - EXPECT_CALL(*this, ReadCallback(10)); - ReadLoader(20, 10, buffer); - VerifyBuffer(buffer, 20, 10); - StopWhenLoad(); -} - -TEST_F(BufferedResourceLoaderTest, AllowDefer_DeferredReadSameWindow) { - Initialize(kHttpUrl, 10, 99); - SetLoaderBuffer(10, 20); - Start(); - PartialResponse(10, 99, 100); - - uint8 buffer[10]; - - // Start in deferred state, disallow defer, receive data and shift buffer - // window, allow defer, and read in a place that's still in the window. - EXPECT_CALL(*bridge_, SetDefersLoading(true)); - EXPECT_CALL(*this, NetworkCallback()); - WriteLoader(10, 30); - - DisallowLoaderDefer(); - WriteLoader(40, 5); - AllowLoaderDefer(); - - EXPECT_CALL(*this, ReadCallback(10)); - ReadLoader(20, 10, buffer); - VerifyBuffer(buffer, 20, 10); - StopWhenLoad(); -} - -TEST_F(BufferedResourceLoaderTest, AllowDefer_DeferredReadPastWindow) { - Initialize(kHttpUrl, 10, 99); - SetLoaderBuffer(10, 20); - Start(); - PartialResponse(10, 99, 100); - - uint8 buffer[10]; - - // Start in deferred state, disallow defer, receive data and shift buffer - // window, allow defer, and read outside of the buffer window. - EXPECT_CALL(*bridge_, SetDefersLoading(true)); - EXPECT_CALL(*this, NetworkCallback()); - WriteLoader(10, 40); - - DisallowLoaderDefer(); - WriteLoader(50, 20); - WriteLoader(70, 40); - AllowLoaderDefer(); - - EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); - ReadLoader(20, 5, buffer); - StopWhenLoad(); -} - -// TODO(hclam): add unit test for defer loading. - class MockBufferedResourceLoader : public BufferedResourceLoader { public: - MockBufferedResourceLoader() : BufferedResourceLoader(NULL, GURL(), 0, 0) { + MockBufferedResourceLoader() : BufferedResourceLoader(GURL(), 0, 0) { } - MOCK_METHOD2(Start, void(net::CompletionCallback* read_callback, - NetworkEventCallback* network_callback)); + MOCK_METHOD3(Start, void(net::CompletionCallback* read_callback, + NetworkEventCallback* network_callback, + WebFrame* frame)); MOCK_METHOD0(Stop, void()); MOCK_METHOD4(Read, void(int64 position, int read_size, uint8* buffer, net::CompletionCallback* callback)); @@ -536,33 +92,10 @@ class MockBufferedResourceLoader : public BufferedResourceLoader { DISALLOW_COPY_AND_ASSIGN(MockBufferedResourceLoader); }; -// A mock BufferedDataSource to inject mock BufferedResourceLoader through -// CreateResourceLoader() method. -class MockBufferedDataSource : public BufferedDataSource { - public: - MockBufferedDataSource( - MessageLoop* message_loop, MediaResourceLoaderBridgeFactory* factory) - : BufferedDataSource(message_loop, factory) { - } - - virtual base::TimeDelta GetTimeoutMilliseconds() { - // It is 100 ms because we don't want the test to run too long. - return base::TimeDelta::FromMilliseconds(100); - } - - MOCK_METHOD2(CreateResourceLoader, BufferedResourceLoader*( - int64 first_position, int64 last_position)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockBufferedDataSource); -}; - class BufferedDataSourceTest : public testing::Test { public: BufferedDataSourceTest() { message_loop_ = MessageLoop::current(); - bridge_factory_.reset( - new StrictMock<MockMediaResourceLoaderBridgeFactory>()); // Prepare test data. for (size_t i = 0; i < sizeof(data_); ++i) { @@ -571,20 +104,14 @@ class BufferedDataSourceTest : public testing::Test { } virtual ~BufferedDataSourceTest() { - if (data_source_) { - // Release the bridge factory because we don't own it. - // Expects bridge factory to be destroyed along with data source. - EXPECT_CALL(*bridge_factory_, OnDestroy()) - .WillOnce(Invoke(this, - &BufferedDataSourceTest::ReleaseBridgeFactory)); - } + ignore_result(frame_.release()); } void ExpectCreateAndStartResourceLoader(int start_error) { EXPECT_CALL(*data_source_, CreateResourceLoader(_, _)) .WillOnce(Return(loader_.get())); - EXPECT_CALL(*loader_, Start(NotNull(), NotNull())) + EXPECT_CALL(*loader_, Start(NotNull(), NotNull(), NotNull())) .WillOnce( DoAll(Assign(&error_, start_error), Invoke(this, @@ -597,15 +124,10 @@ class BufferedDataSourceTest : public testing::Test { // Saves the url first. gurl_ = GURL(url); - media::MediaFormat url_format; - url_format.SetAsString(media::MediaFormat::kMimeType, - media::mime_type::kURL); - url_format.SetAsString(media::MediaFormat::kURL, url); - data_source_ = new MockBufferedDataSource(MessageLoop::current(), - bridge_factory_.get()); - CHECK(data_source_); + frame_.reset(new NiceMock<MockWebFrame>()); - // There is no need to provide a message loop to data source. + data_source_ = new MockBufferedDataSource(MessageLoop::current(), + frame_.get()); data_source_->set_host(&host_); scoped_refptr<NiceMock<MockBufferedResourceLoader> > first_loader( @@ -631,7 +153,7 @@ class BufferedDataSourceTest : public testing::Test { // Replace loader_ with a new instance. loader_ = new NiceMock<MockBufferedResourceLoader>(); - // Create and start Make sure Start() is called the new loader. + // Create and start. Make sure Start() is called on the new loader. ExpectCreateAndStartResourceLoader(net::OK); // Update initialization variable since we know the second loader will @@ -705,13 +227,10 @@ class BufferedDataSourceTest : public testing::Test { message_loop_->RunAllPending(); } - void ReleaseBridgeFactory() { - ignore_result(bridge_factory_.release()); - } - void InvokeStartCallback( net::CompletionCallback* callback, - BufferedResourceLoader::NetworkEventCallback* network_callback) { + BufferedResourceLoader::NetworkEventCallback* network_callback, + WebFrame* frame) { callback->RunWithParams(Tuple1<int>(error_)); delete callback; // TODO(hclam): Save this callback. @@ -790,7 +309,7 @@ class BufferedDataSourceTest : public testing::Test { .WillOnce(Return(new_loader)); // 3. Then the new loader will be started. - EXPECT_CALL(*new_loader, Start(NotNull(), NotNull())) + EXPECT_CALL(*new_loader, Start(NotNull(), NotNull(), NotNull())) .WillOnce(DoAll(Assign(&error_, net::OK), Invoke(this, &BufferedDataSourceTest::InvokeStartCallback))); @@ -856,7 +375,7 @@ class BufferedDataSourceTest : public testing::Test { // 3. Then the new loader will be started and respond to queries about // whether this is a partial response using the value of the previous // loader. - EXPECT_CALL(*new_loader, Start(NotNull(), NotNull())) + EXPECT_CALL(*new_loader, Start(NotNull(), NotNull(), NotNull())) .WillOnce(DoAll(Assign(&error_, net::OK), Invoke(this, &BufferedDataSourceTest::InvokeStartCallback))); @@ -889,10 +408,9 @@ class BufferedDataSourceTest : public testing::Test { MOCK_METHOD1(ReadCallback, void(size_t size)); - scoped_ptr<StrictMock<MockMediaResourceLoaderBridgeFactory> > - bridge_factory_; scoped_refptr<NiceMock<MockBufferedResourceLoader> > loader_; scoped_refptr<MockBufferedDataSource> data_source_; + scoped_ptr<NiceMock<MockWebFrame> > frame_; StrictMock<media::MockFilterHost> host_; GURL gurl_; diff --git a/webkit/glue/media/buffered_resource_loader.cc b/webkit/glue/media/buffered_resource_loader.cc new file mode 100644 index 0000000..61aac72 --- /dev/null +++ b/webkit/glue/media/buffered_resource_loader.cc @@ -0,0 +1,578 @@ +// 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 "webkit/glue/media/buffered_resource_loader.h" + +#include "base/format_macros.h" +#include "base/string_util.h" +#include "net/base/net_errors.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKitClient.h" +#include "third_party/WebKit/WebKit/chromium/public/WebString.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h" +#include "webkit/glue/multipart_response_delegate.h" +#include "webkit/glue/webkit_glue.h" + +using WebKit::WebFrame; +using WebKit::WebString; +using WebKit::WebURLError; +using WebKit::WebURLLoader; +using WebKit::WebURLRequest; +using WebKit::WebURLResponse; +using webkit_glue::MultipartResponseDelegate; + +namespace { + +const int kHttpOK = 200; +const int kHttpPartialContent = 206; + +// Define the number of bytes in a megabyte. +const size_t kMegabyte = 1024 * 1024; + +// Backward capacity of the buffer, by default 2MB. +const size_t kBackwardCapcity = 2 * kMegabyte; + +// Forward capacity of the buffer, by default 10MB. +const size_t kForwardCapacity = 10 * kMegabyte; + +// The threshold of bytes that we should wait until the data arrives in the +// future instead of restarting a new connection. This number is defined in the +// number of bytes, we should determine this value from typical connection speed +// and amount of time for a suitable wait. Now I just make a guess for this +// number to be 2MB. +// TODO(hclam): determine a better value for this. +const int kForwardWaitThreshold = 2 * kMegabyte; + +} // namespace + +namespace webkit_glue { + +BufferedResourceLoader::BufferedResourceLoader( + const GURL& url, + int64 first_byte_position, + int64 last_byte_position) + : buffer_(new media::SeekableBuffer(kBackwardCapcity, kForwardCapacity)), + deferred_(false), + defer_allowed_(true), + completed_(false), + range_requested_(false), + partial_response_(false), + url_(url), + first_byte_position_(first_byte_position), + last_byte_position_(last_byte_position), + start_callback_(NULL), + offset_(0), + content_length_(kPositionNotSpecified), + instance_size_(kPositionNotSpecified), + read_callback_(NULL), + read_position_(0), + read_size_(0), + read_buffer_(NULL), + first_offset_(0), + last_offset_(0), + keep_test_loader_(false) { +} + +BufferedResourceLoader::~BufferedResourceLoader() { + if (!completed_ && url_loader_.get()) + url_loader_->cancel(); +} + +void BufferedResourceLoader::Start(net::CompletionCallback* start_callback, + NetworkEventCallback* event_callback, + WebFrame* frame) { + // Make sure we have not started. + DCHECK(!start_callback_.get()); + DCHECK(!event_callback_.get()); + DCHECK(start_callback); + DCHECK(event_callback); + CHECK(frame); + + start_callback_.reset(start_callback); + event_callback_.reset(event_callback); + + if (first_byte_position_ != kPositionNotSpecified) { + range_requested_ = true; + // TODO(hclam): server may not support range request so |offset_| may not + // equal to |first_byte_position_|. + offset_ = first_byte_position_; + } + + // Increment the reference count right before we start the request. This + // reference will be release when this request has ended. + AddRef(); + + // Prepare the request. + WebURLRequest request(url_); + request.setTargetType(WebURLRequest::TargetIsMedia); + request.setHTTPHeaderField(WebString::fromUTF8("Range"), + WebString::fromUTF8(GenerateHeaders( + first_byte_position_, + last_byte_position_))); + frame->setReferrerForRequest(request, WebKit::WebURL()); + + // This flag is for unittests as we don't want to reset |url_loader| + if (!keep_test_loader_) + url_loader_.reset(frame->createAssociatedURLLoader()); + + // Start the resource loading. + url_loader_->loadAsynchronously(request, this); +} + +void BufferedResourceLoader::Stop() { + // Reset callbacks. + start_callback_.reset(); + event_callback_.reset(); + read_callback_.reset(); + + // Use the internal buffer to signal that we have been stopped. + // TODO(hclam): Not so pretty to do this. + if (!buffer_.get()) + return; + + // Destroy internal buffer. + buffer_.reset(); + + if (url_loader_.get()) { + if (deferred_) + url_loader_->setDefersLoading(false); + deferred_ = false; + + if (!completed_) { + url_loader_->cancel(); + completed_ = true; + } + } +} + +void BufferedResourceLoader::Read(int64 position, + int read_size, + uint8* buffer, + net::CompletionCallback* read_callback) { + DCHECK(!read_callback_.get()); + DCHECK(buffer_.get()); + DCHECK(read_callback); + DCHECK(buffer); + + // Save the parameter of reading. + read_callback_.reset(read_callback); + read_position_ = position; + read_size_ = read_size; + read_buffer_ = buffer; + + // If read position is beyond the instance size, we cannot read there. + if (instance_size_ != kPositionNotSpecified && + instance_size_ <= read_position_) { + DoneRead(0); + return; + } + + // Make sure |offset_| and |read_position_| does not differ by a large + // amount. + if (read_position_ > offset_ + kint32max || + read_position_ < offset_ + kint32min) { + DoneRead(net::ERR_CACHE_MISS); + return; + } + + // Prepare the parameters. + first_offset_ = static_cast<int>(read_position_ - offset_); + last_offset_ = first_offset_ + read_size_; + + // If we can serve the request now, do the actual read. + if (CanFulfillRead()) { + ReadInternal(); + DisableDeferIfNeeded(); + return; + } + + // If we expected the read request to be fulfilled later, returns + // immediately and let more data to flow in. + if (WillFulfillRead()) + return; + + // Make a callback to report failure. + DoneRead(net::ERR_CACHE_MISS); +} + +int64 BufferedResourceLoader::GetBufferedPosition() { + if (buffer_.get()) + return offset_ + static_cast<int>(buffer_->forward_bytes()) - 1; + return kPositionNotSpecified; +} + +void BufferedResourceLoader::SetAllowDefer(bool is_allowed) { + defer_allowed_ = is_allowed; + DisableDeferIfNeeded(); +} + +int64 BufferedResourceLoader::content_length() { + return content_length_; +} + +int64 BufferedResourceLoader::instance_size() { + return instance_size_; +} + +bool BufferedResourceLoader::partial_response() { + return partial_response_; +} + +bool BufferedResourceLoader::network_activity() { + return !completed_ && !deferred_; +} + +const GURL& BufferedResourceLoader::url() { + return url_; +} + +void BufferedResourceLoader::SetURLLoaderForTest(WebURLLoader* mock_loader) { + url_loader_.reset(mock_loader); + keep_test_loader_ = true; +} + +///////////////////////////////////////////////////////////////////////////// +// WebKit::WebURLLoaderClient implementation. +void BufferedResourceLoader::willSendRequest( + WebURLLoader* loader, + WebURLRequest& newRequest, + const WebURLResponse& redirectResponse) { + + // The load may have been stopped and |start_callback| is destroyed. + // In this case we shouldn't do anything. + if (!start_callback_.get()) { + // Set the url in the request to an invalid value (empty url). + newRequest.setURL(WebKit::WebURL()); + return; + } + + if (!IsProtocolSupportedForMedia(newRequest.url())) { + // Set the url in the request to an invalid value (empty url). + newRequest.setURL(WebKit::WebURL()); + DoneStart(net::ERR_ADDRESS_INVALID); + Stop(); + return; + } + + url_ = newRequest.url(); +} + +void BufferedResourceLoader::didSendData( + WebURLLoader* loader, + unsigned long long bytes_sent, + unsigned long long total_bytes_to_be_sent) { + NOTIMPLEMENTED(); +} + +void BufferedResourceLoader::didReceiveResponse( + WebURLLoader* loader, + const WebURLResponse& response) { + + // The loader may have been stopped and |start_callback| is destroyed. + // In this case we shouldn't do anything. + if (!start_callback_.get()) + return; + + // We make a strong assumption that when we reach here we have either + // received a response from HTTP/HTTPS protocol or the request was + // successful (in particular range request). So we only verify the partial + // response for HTTP and HTTPS protocol. + if (url_.SchemeIs(kHttpScheme) || url_.SchemeIs(kHttpsScheme)) { + int error = net::OK; + + if (response.httpStatusCode() == kHttpPartialContent) + partial_response_ = true; + + if (range_requested_ && partial_response_) { + // If we have verified the partial response and it is correct, we will + // return net::OK. + if (!VerifyPartialResponse(response)) + error = net::ERR_INVALID_RESPONSE; + } else if (response.httpStatusCode() != kHttpOK) { + // We didn't request a range but server didn't reply with "200 OK". + error = net::ERR_FAILED; + } + + if (error != net::OK) { + DoneStart(error); + Stop(); + return; + } + } else { + // For any protocol other than HTTP and HTTPS, assume range request is + // always fulfilled. + partial_response_ = range_requested_; + } + + // Expected content length can be |kPositionNotSpecified|, in that case + // |content_length_| is not specified and this is a streaming response. + content_length_ = response.expectedContentLength(); + + // If we have not requested a range, then the size of the instance is equal + // to the content length. + if (!partial_response_) + instance_size_ = content_length_; + + // Calls with a successful response. + DoneStart(net::OK); +} + +void BufferedResourceLoader::didReceiveData( + WebURLLoader* loader, + const char* data, + int data_length) { + DCHECK(!completed_); + DCHECK_GT(data_length, 0); + + // If this loader has been stopped, |buffer_| would be destroyed. + // In this case we shouldn't do anything. + if (!buffer_.get()) + return; + + // Writes more data to |buffer_|. + buffer_->Append(reinterpret_cast<const uint8*>(data), data_length); + + // If there is an active read request, try to fulfill the request. + if (HasPendingRead() && CanFulfillRead()) { + ReadInternal(); + } else if (!defer_allowed_) { + // If we're not allowed to defer, slide the buffer window forward instead + // of deferring. + if (buffer_->forward_bytes() > buffer_->forward_capacity()) { + size_t excess = buffer_->forward_bytes() - buffer_->forward_capacity(); + bool success = buffer_->Seek(excess); + DCHECK(success); + offset_ += first_offset_ + excess; + } + } + + // At last see if the buffer is full and we need to defer the downloading. + EnableDeferIfNeeded(); + + // Notify that we have received some data. + NotifyNetworkEvent(); +} + +void BufferedResourceLoader::didDownloadData( + WebKit::WebURLLoader* loader, + int dataLength) { + NOTIMPLEMENTED(); +} + +void BufferedResourceLoader::didReceiveCachedMetadata( + WebURLLoader* loader, + const char* data, + int data_length) { + NOTIMPLEMENTED(); +} + +void BufferedResourceLoader::didFinishLoading( + WebURLLoader* loader, + double finishTime) { + DCHECK(!completed_); + completed_ = true; + + // If there is a start callback, calls it. + if (start_callback_.get()) { + DoneStart(net::OK); + } + + // If there is a pending read but the request has ended, returns with what + // we have. + if (HasPendingRead()) { + // Make sure we have a valid buffer before we satisfy a read request. + DCHECK(buffer_.get()); + + // Try to fulfill with what is in the buffer. + if (CanFulfillRead()) + ReadInternal(); + else + DoneRead(net::ERR_CACHE_MISS); + } + + // There must not be any outstanding read request. + DCHECK(!HasPendingRead()); + + // Notify that network response is completed. + NotifyNetworkEvent(); + + url_loader_.reset(); + Release(); +} + +void BufferedResourceLoader::didFail( + WebURLLoader* loader, + const WebURLError& error) { + DCHECK(!completed_); + completed_ = true; + + // If there is a start callback, calls it. + if (start_callback_.get()) { + DoneStart(error.reason); + } + + // If there is a pending read but the request failed, return with the + // reason for the error. + if (HasPendingRead()) { + DoneRead(error.reason); + } + + // Notify that network response is completed. + NotifyNetworkEvent(); + + url_loader_.reset(); + Release(); +} + +///////////////////////////////////////////////////////////////////////////// +// Helper methods. +void BufferedResourceLoader::EnableDeferIfNeeded() { + if (!defer_allowed_) + return; + + if (!deferred_ && + buffer_->forward_bytes() >= buffer_->forward_capacity()) { + deferred_ = true; + + if (url_loader_.get()) + url_loader_->setDefersLoading(true); + + NotifyNetworkEvent(); + } +} + +void BufferedResourceLoader::DisableDeferIfNeeded() { + if (deferred_ && + (!defer_allowed_ || + buffer_->forward_bytes() < buffer_->forward_capacity() / 2)) { + deferred_ = false; + + if (url_loader_.get()) + url_loader_->setDefersLoading(false); + + NotifyNetworkEvent(); + } +} + +bool BufferedResourceLoader::CanFulfillRead() { + // If we are reading too far in the backward direction. + if (first_offset_ < 0 && + first_offset_ + static_cast<int>(buffer_->backward_bytes()) < 0) + return false; + + // If the start offset is too far ahead. + if (first_offset_ >= static_cast<int>(buffer_->forward_bytes())) + return false; + + // At the point, we verified that first byte requested is within the buffer. + // If the request has completed, then just returns with what we have now. + if (completed_) + return true; + + // If the resource request is still active, make sure the whole requested + // range is covered. + if (last_offset_ > static_cast<int>(buffer_->forward_bytes())) + return false; + + return true; +} + +bool BufferedResourceLoader::WillFulfillRead() { + // Reading too far in the backward direction. + if (first_offset_ < 0 && + first_offset_ + static_cast<int>(buffer_->backward_bytes()) < 0) + return false; + + // Try to read too far ahead. + if (last_offset_ > kForwardWaitThreshold) + return false; + + // The resource request has completed, there's no way we can fulfill the + // read request. + if (completed_) + return false; + + return true; +} + +void BufferedResourceLoader::ReadInternal() { + // Seek to the first byte requested. + bool ret = buffer_->Seek(first_offset_); + DCHECK(ret); + + // Then do the read. + int read = static_cast<int>(buffer_->Read(read_buffer_, read_size_)); + offset_ += first_offset_ + read; + + // And report with what we have read. + DoneRead(read); +} + +bool BufferedResourceLoader::VerifyPartialResponse( + const WebURLResponse& response) { + int first_byte_position, last_byte_position, instance_size; + + if (!MultipartResponseDelegate::ReadContentRanges(response, + &first_byte_position, + &last_byte_position, + &instance_size)) { + return false; + } + + if (instance_size != kPositionNotSpecified) { + instance_size_ = instance_size; + } + + if (first_byte_position_ != kPositionNotSpecified && + first_byte_position_ != first_byte_position) { + return false; + } + + // TODO(hclam): I should also check |last_byte_position|, but since + // we will never make such a request that it is ok to leave it unimplemented. + return true; +} + +std::string BufferedResourceLoader::GenerateHeaders( + int64 first_byte_position, + int64 last_byte_position) { + // Construct the value for the range header. + std::string header; + if (first_byte_position > kPositionNotSpecified && + last_byte_position > kPositionNotSpecified) { + if (first_byte_position <= last_byte_position) { + header = base::StringPrintf("bytes=%" PRId64 "-%" PRId64, + first_byte_position, + last_byte_position); + } + } else if (first_byte_position > kPositionNotSpecified) { + header = base::StringPrintf("bytes=%" PRId64 "-", + first_byte_position); + } else if (last_byte_position > kPositionNotSpecified) { + NOTIMPLEMENTED() << "Suffix range not implemented"; + } + return header; +} + +void BufferedResourceLoader::DoneRead(int error) { + read_callback_->RunWithParams(Tuple1<int>(error)); + read_callback_.reset(); + read_position_ = 0; + read_size_ = 0; + read_buffer_ = NULL; + first_offset_ = 0; + last_offset_ = 0; +} + +void BufferedResourceLoader::DoneStart(int error) { + start_callback_->RunWithParams(Tuple1<int>(error)); + start_callback_.reset(); +} + +void BufferedResourceLoader::NotifyNetworkEvent() { + if (event_callback_.get()) + event_callback_->Run(); +} + +} // namespace webkit_glue diff --git a/webkit/glue/media/buffered_resource_loader.h b/webkit/glue/media/buffered_resource_loader.h new file mode 100644 index 0000000..09b05e6 --- /dev/null +++ b/webkit/glue/media/buffered_resource_loader.h @@ -0,0 +1,246 @@ +// 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 WEBKIT_GLUE_MEDIA_BUFFERED_RESOURCE_LOADER_H_ +#define WEBKIT_GLUE_MEDIA_BUFFERED_RESOURCE_LOADER_H_ + +#include <string> + +#include "base/callback.h" +#include "base/lock.h" +#include "base/scoped_ptr.h" +#include "base/timer.h" +#include "googleurl/src/gurl.h" +#include "media/base/seekable_buffer.h" +#include "net/base/file_stream.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLLoader.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" +#include "webkit/glue/media/web_data_source.h" +#include "webkit/glue/webmediaplayer_impl.h" + +namespace webkit_glue { + +const int64 kPositionNotSpecified = -1; + +const char kHttpScheme[] = "http"; +const char kHttpsScheme[] = "https"; +const char kDataScheme[] = "data"; + +// This class works inside demuxer thread and render thread. It contains a +// WebURLLoader and does the actual resource loading. This object does +// buffering internally, it defers the resource loading if buffer is full +// and un-defers the resource loading if it is under buffered. +class BufferedResourceLoader : + public base::RefCountedThreadSafe<BufferedResourceLoader>, + public WebKit::WebURLLoaderClient { + public: + typedef Callback0::Type NetworkEventCallback; + + // |url| - URL for the resource to be loaded. + // |first_byte_position| - First byte to start loading from, + // |kPositionNotSpecified| for not specified. + // |last_byte_position| - Last byte to be loaded, + // |kPositionNotSpecified| for not specified. + BufferedResourceLoader(const GURL& url, + int64 first_byte_position, + int64 last_byte_position); + + // Start the resource loading with the specified URL and range. + // This method operates in asynchronous mode. Once there's a response from the + // server, success or fail |callback| is called with the result. + // |callback| is called with the following values: + // - net::OK + // The request has started successfully. + // - net::ERR_FAILED + // The request has failed because of an error with the network. + // - net::ERR_INVALID_RESPONSE + // An invalid response is received from the server. + // - (Anything else) + // An error code that indicates the request has failed. + // |event_callback| is called when the response is completed, data is + // received, the request is suspended or resumed. + virtual void Start(net::CompletionCallback* callback, + NetworkEventCallback* event_callback, + WebKit::WebFrame* frame); + + // Stop this loader, cancels and request and release internal buffer. + virtual void Stop(); + + // Reads the specified |read_size| from |position| into |buffer| and when + // the operation is done invoke |callback| with number of bytes read or an + // error code. + // |callback| is called with the following values: + // - (Anything greater than or equal 0) + // Read was successful with the indicated number of bytes read. + // - net::ERR_FAILED + // The read has failed because of an error with the network. + // - net::ERR_CACHE_MISS + // The read was made too far away from the current buffered position. + virtual void Read(int64 position, int read_size, + uint8* buffer, net::CompletionCallback* callback); + + // Returns the position of the last byte buffered. Returns + // |kPositionNotSpecified| if such value is not available. + virtual int64 GetBufferedPosition(); + + // Sets whether deferring data is allowed or disallowed. + virtual void SetAllowDefer(bool is_allowed); + + // Gets the content length in bytes of the instance after this loader has been + // started. If this value is |kPositionNotSpecified|, then content length is + // unknown. + virtual int64 content_length(); + + // Gets the original size of the file requested. If this value is + // |kPositionNotSpecified|, then the size is unknown. + virtual int64 instance_size(); + + // Returns true if the response for this loader is a partial response. + // It means a 206 response in HTTP/HTTPS protocol. + virtual bool partial_response(); + + // Returns true if network is currently active. + virtual bool network_activity(); + + // Returns resulting URL. + virtual const GURL& url(); + + // Used to inject a mock used for unittests. + virtual void SetURLLoaderForTest(WebKit::WebURLLoader* mock_loader); + + // WebKit::WebURLLoaderClient implementation. + virtual void willSendRequest( + WebKit::WebURLLoader* loader, + WebKit::WebURLRequest& newRequest, + const WebKit::WebURLResponse& redirectResponse); + virtual void didSendData( + WebKit::WebURLLoader* loader, + unsigned long long bytesSent, + unsigned long long totalBytesToBeSent); + virtual void didReceiveResponse( + WebKit::WebURLLoader* loader, + const WebKit::WebURLResponse& response); + virtual void didDownloadData( + WebKit::WebURLLoader* loader, + int dataLength); + virtual void didReceiveData( + WebKit::WebURLLoader* loader, + const char* data, + int dataLength); + virtual void didReceiveCachedMetadata( + WebKit::WebURLLoader* loader, + const char* data, int dataLength); + virtual void didFinishLoading( + WebKit::WebURLLoader* loader, + double finishTime); + virtual void didFail( + WebKit::WebURLLoader* loader, + const WebKit::WebURLError&); + + protected: + friend class base::RefCountedThreadSafe<BufferedResourceLoader>; + + virtual ~BufferedResourceLoader(); + + private: + friend class BufferedResourceLoaderTest; + + // Defer the resource loading if the buffer is full. + void EnableDeferIfNeeded(); + + // Disable defer loading if we are under-buffered. + void DisableDeferIfNeeded(); + + // Returns true if the current read request can be fulfilled by what is in + // the buffer. + bool CanFulfillRead(); + + // Returns true if the current read request will be fulfilled in the future. + bool WillFulfillRead(); + + // Method that does the actual read and calls the |read_callback_|, assuming + // the request range is in |buffer_|. + void ReadInternal(); + + // If we have made a range request, verify the response from the server. + bool VerifyPartialResponse(const WebKit::WebURLResponse& response); + + // Returns the value for a range request header using parameters + // |first_byte_position| and |last_byte_position|. Negative numbers other + // than |kPositionNotSpecified| are not allowed for |first_byte_position| and + // |last_byte_position|. |first_byte_position| should always be less than or + // equal to |last_byte_position| if they are both not |kPositionNotSpecified|. + // Empty string is returned on invalid parameters. + std::string GenerateHeaders(int64 first_byte_position, + int64 last_byte_position); + + // Done with read. Invokes the read callback and reset parameters for the + // read request. + void DoneRead(int error); + + // Done with start. Invokes the start callback and reset it. + void DoneStart(int error); + + // Calls |event_callback_| in terms of a network event. + void NotifyNetworkEvent(); + + bool HasPendingRead() { return read_callback_.get() != NULL; } + + // A sliding window of buffer. + scoped_ptr<media::SeekableBuffer> buffer_; + + // True if resource loading was deferred. + bool deferred_; + + // True if resource loader is allowed to defer, false otherwise. + bool defer_allowed_; + + // True if resource loading has completed. + bool completed_; + + // True if a range request was made. + bool range_requested_; + + // True if response data received is a partial range. + bool partial_response_; + + // Does the work of loading and sends data back to this client. + scoped_ptr<WebKit::WebURLLoader> url_loader_; + + GURL url_; + int64 first_byte_position_; + int64 last_byte_position_; + + // Callback method that listens to network events. + scoped_ptr<NetworkEventCallback> event_callback_; + + // Members used during request start. + scoped_ptr<net::CompletionCallback> start_callback_; + int64 offset_; + int64 content_length_; + int64 instance_size_; + + // Members used during a read operation. They should be reset after each + // read has completed or failed. + scoped_ptr<net::CompletionCallback> read_callback_; + int64 read_position_; + int read_size_; + uint8* read_buffer_; + + // Offsets of the requested first byte and last byte in |buffer_|. They are + // written by Read(). + int first_offset_; + int last_offset_; + + // Used to ensure mocks for unittests are used instead of reset in Start(). + bool keep_test_loader_; + + DISALLOW_COPY_AND_ASSIGN(BufferedResourceLoader); +}; + +} // namespace webkit_glue + +#endif // WEBKIT_GLUE_MEDIA_BUFFERED_RESOURCE_LOADER_H_ diff --git a/webkit/glue/media/buffered_resource_loader_unittest.cc b/webkit/glue/media/buffered_resource_loader_unittest.cc new file mode 100644 index 0000000..8e64c26 --- /dev/null +++ b/webkit/glue/media/buffered_resource_loader_unittest.cc @@ -0,0 +1,486 @@ +// 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 <algorithm> + +#include "base/format_macros.h" +#include "base/stringprintf.h" +#include "net/base/net_errors.h" +#include "net/http/http_util.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrameClient.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" +#include "webkit/glue/media/buffered_resource_loader.h" +#include "webkit/mocks/mock_webframe.h" +#include "webkit/mocks/mock_weburlloader.h" + +using ::testing::_; +using ::testing::Assign; +using ::testing::AtLeast; +using ::testing::DeleteArg; +using ::testing::DoAll; +using ::testing::InSequence; +using ::testing::Invoke; +using ::testing::InvokeWithoutArgs; +using ::testing::NotNull; +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::SetArgumentPointee; +using ::testing::StrictMock; +using ::testing::NiceMock; +using ::testing::WithArgs; + +using WebKit::WebURLError; +using WebKit::WebFrameClient; +using WebKit::WebURLResponse; +using WebKit::WebView; + +namespace { + +const char* kHttpUrl = "http://test"; +const int kDataSize = 1024; +const int kHttpOK = 200; +const int kHttpPartialContent = 206; + +enum NetworkState { + NONE, + LOADED, + LOADING +}; + +} // namespace + +namespace webkit_glue { + +// Submit a request completed event to the resource loader due to request +// being canceled. Pretending the event is from external. +ACTION_P(RequestCanceled, loader) { + WebURLError error; + error.reason = net::ERR_ABORTED; + error.domain = WebString::fromUTF8(net::kErrorDomain); + loader->didFail(NULL, error); +} + +class BufferedResourceLoaderTest : public testing::Test { + public: + BufferedResourceLoaderTest() { + url_loader_ = new NiceMock<MockWebURLLoader>(); + + for (int i = 0; i < kDataSize; ++i) + data_[i] = i; + } + + virtual ~BufferedResourceLoaderTest() { + ignore_result(frame_.release()); + } + + void Initialize(const char* url, int first_position, int last_position) { + gurl_ = GURL(url); + first_position_ = first_position; + last_position_ = last_position; + + frame_.reset(new NiceMock<MockWebFrame>()); + + loader_ = new BufferedResourceLoader(gurl_, + first_position_, last_position_); + loader_->SetURLLoaderForTest(url_loader_); + } + + void SetLoaderBuffer(size_t forward_capacity, size_t backward_capacity) { + loader_->buffer_.reset( + new media::SeekableBuffer(backward_capacity, forward_capacity)); + } + + void Start() { + InSequence s; + EXPECT_CALL(*url_loader_, loadAsynchronously(_, loader_.get())); + loader_->Start( + NewCallback(this, &BufferedResourceLoaderTest::StartCallback), + NewCallback(this, &BufferedResourceLoaderTest::NetworkCallback), + frame_.get()); + } + + void FullResponse(int64 instance_size) { + EXPECT_CALL(*this, StartCallback(net::OK)); + + WebURLResponse response(gurl_); + response.setHTTPHeaderField(WebString::fromUTF8("Content-Length"), + WebString::fromUTF8(base::StringPrintf("%" + PRId64, instance_size))); + response.setExpectedContentLength(instance_size); + response.setHTTPStatusCode(kHttpOK); + loader_->didReceiveResponse(url_loader_, response); + EXPECT_EQ(instance_size, loader_->content_length()); + EXPECT_EQ(instance_size, loader_->instance_size()); + EXPECT_FALSE(loader_->partial_response()); + } + + void PartialResponse(int64 first_position, int64 last_position, + int64 instance_size) { + EXPECT_CALL(*this, StartCallback(net::OK)); + int64 content_length = last_position - first_position + 1; + + WebURLResponse response(gurl_); + response.setHTTPHeaderField(WebString::fromUTF8("Content-Range"), + WebString::fromUTF8(base::StringPrintf("bytes " + "%" PRId64 "-%" PRId64 "/%" PRId64, + first_position, + last_position, + instance_size))); + response.setExpectedContentLength(content_length); + response.setHTTPStatusCode(kHttpPartialContent); + loader_->didReceiveResponse(url_loader_, response); + EXPECT_EQ(content_length, loader_->content_length()); + EXPECT_EQ(instance_size, loader_->instance_size()); + EXPECT_TRUE(loader_->partial_response()); + } + + void StopWhenLoad() { + InSequence s; + EXPECT_CALL(*url_loader_, cancel()) + .WillOnce(RequestCanceled(loader_)); + loader_->Stop(); + } + + // Helper method to write to |loader_| from |data_|. + void WriteLoader(int position, int size) { + EXPECT_CALL(*this, NetworkCallback()) + .RetiresOnSaturation(); + loader_->didReceiveData(url_loader_, + reinterpret_cast<char*>(data_ + position), size); + } + + // Helper method to read from |loader_|. + void ReadLoader(int64 position, int size, uint8* buffer) { + loader_->Read(position, size, buffer, + NewCallback(this, &BufferedResourceLoaderTest::ReadCallback)); + } + + // Verifis that data in buffer[0...size] is equal to data_[pos...pos+size]. + void VerifyBuffer(uint8* buffer, int pos, int size) { + EXPECT_EQ(0, memcmp(buffer, data_ + pos, size)); + } + + // Helper method to disallow deferring in |loader_|. + void DisallowLoaderDefer() { + if (loader_->deferred_) { + EXPECT_CALL(*url_loader_, setDefersLoading(false)); + EXPECT_CALL(*this, NetworkCallback()); + } + loader_->SetAllowDefer(false); + } + + // Helper method to allow deferring in |loader_|. + void AllowLoaderDefer() { + loader_->SetAllowDefer(true); + } + + MOCK_METHOD1(StartCallback, void(int error)); + MOCK_METHOD1(ReadCallback, void(int error)); + MOCK_METHOD0(NetworkCallback, void()); + + protected: + GURL gurl_; + int64 first_position_; + int64 last_position_; + + scoped_refptr<BufferedResourceLoader> loader_; + NiceMock<MockWebURLLoader>* url_loader_; + scoped_ptr<NiceMock<MockWebFrame> > frame_; + + uint8 data_[kDataSize]; + + private: + DISALLOW_COPY_AND_ASSIGN(BufferedResourceLoaderTest); +}; + +TEST_F(BufferedResourceLoaderTest, StartStop) { + Initialize(kHttpUrl, -1, -1); + Start(); + StopWhenLoad(); +} + +// Tests that a bad HTTP response is recived, e.g. file not found. +TEST_F(BufferedResourceLoaderTest, BadHttpResponse) { + Initialize(kHttpUrl, -1, -1); + Start(); + + EXPECT_CALL(*this, StartCallback(net::ERR_FAILED)); + EXPECT_CALL(*url_loader_, cancel()) + .WillOnce(RequestCanceled(loader_)); + + WebURLResponse response(gurl_); + response.setHTTPStatusCode(404); + response.setHTTPStatusText("Not Found\n"); + loader_->didReceiveResponse(url_loader_, response); +} + +// Tests that partial content is requested but not fulfilled. +TEST_F(BufferedResourceLoaderTest, NotPartialResponse) { + Initialize(kHttpUrl, 100, -1); + Start(); + FullResponse(1024); + StopWhenLoad(); +} + +// Tests that a 200 response is received. +TEST_F(BufferedResourceLoaderTest, FullResponse) { + Initialize(kHttpUrl, -1, -1); + Start(); + FullResponse(1024); + StopWhenLoad(); +} + +// Tests that a partial content response is received. +TEST_F(BufferedResourceLoaderTest, PartialResponse) { + Initialize(kHttpUrl, 100, 200); + Start(); + PartialResponse(100, 200, 1024); + StopWhenLoad(); +} + +// Tests that an invalid partial response is received. +TEST_F(BufferedResourceLoaderTest, InvalidPartialResponse) { + Initialize(kHttpUrl, 0, 10); + Start(); + + EXPECT_CALL(*this, StartCallback(net::ERR_INVALID_RESPONSE)); + EXPECT_CALL(*url_loader_, cancel()) + .WillOnce(RequestCanceled(loader_)); + + WebURLResponse response(gurl_); + response.setHTTPHeaderField(WebString::fromUTF8("Content-Range"), + WebString::fromUTF8(base::StringPrintf("bytes " + "%d-%d/%d", 1, 10, 1024))); + response.setExpectedContentLength(10); + response.setHTTPStatusCode(kHttpPartialContent); + loader_->didReceiveResponse(url_loader_, response); +} + +// Tests the logic of sliding window for data buffering and reading. +TEST_F(BufferedResourceLoaderTest, BufferAndRead) { + Initialize(kHttpUrl, 10, 29); + Start(); + PartialResponse(10, 29, 30); + + uint8 buffer[10]; + InSequence s; + + // Writes 10 bytes and read them back. + WriteLoader(10, 10); + EXPECT_CALL(*this, ReadCallback(10)); + ReadLoader(10, 10, buffer); + VerifyBuffer(buffer, 10, 10); + + // Writes 10 bytes and read 2 times. + WriteLoader(20, 10); + EXPECT_CALL(*this, ReadCallback(5)); + ReadLoader(20, 5, buffer); + VerifyBuffer(buffer, 20, 5); + EXPECT_CALL(*this, ReadCallback(5)); + ReadLoader(25, 5, buffer); + VerifyBuffer(buffer, 25, 5); + + // Read backward within buffer. + EXPECT_CALL(*this, ReadCallback(10)); + ReadLoader(10, 10, buffer); + VerifyBuffer(buffer, 10, 10); + + // Read backward outside buffer. + EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); + ReadLoader(9, 10, buffer); + + // Response has completed. + EXPECT_CALL(*this, NetworkCallback()); + loader_->didFinishLoading(url_loader_, 0); + + // Try to read 10 from position 25 will just return with 5 bytes. + EXPECT_CALL(*this, ReadCallback(5)); + ReadLoader(25, 10, buffer); + VerifyBuffer(buffer, 25, 5); + + // Try to read outside buffered range after request has completed. + EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); + ReadLoader(5, 10, buffer); + + // Try to read beyond the instance size. + EXPECT_CALL(*this, ReadCallback(0)); + ReadLoader(30, 10, buffer); +} + +TEST_F(BufferedResourceLoaderTest, ReadOutsideBuffer) { + Initialize(kHttpUrl, 10, 0x00FFFFFF); + Start(); + PartialResponse(10, 0x00FFFFFF, 0x01000000); + + uint8 buffer[10]; + InSequence s; + + // Read very far aheard will get a cache miss. + EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); + ReadLoader(0x00FFFFFF, 1, buffer); + + // The following call will not call ReadCallback() because it is waiting for + // data to arrive. + ReadLoader(10, 10, buffer); + + // Writing to loader will fulfill the read request. + EXPECT_CALL(*this, ReadCallback(10)); + WriteLoader(10, 20); + VerifyBuffer(buffer, 10, 10); + + // The following call cannot be fulfilled now. + ReadLoader(25, 10, buffer); + + EXPECT_CALL(*this, ReadCallback(5)); + EXPECT_CALL(*this, NetworkCallback()); + loader_->didFinishLoading(url_loader_, 0); +} + +TEST_F(BufferedResourceLoaderTest, RequestFailedWhenRead) { + Initialize(kHttpUrl, 10, 29); + Start(); + PartialResponse(10, 29, 30); + + uint8 buffer[10]; + InSequence s; + + ReadLoader(10, 10, buffer); + EXPECT_CALL(*this, ReadCallback(net::ERR_FAILED)); + EXPECT_CALL(*this, NetworkCallback()); + WebURLError error; + error.reason = net::ERR_FAILED; + loader_->didFail(url_loader_, error); +} + +// Tests the logic of caching data to disk when media is paused. +TEST_F(BufferedResourceLoaderTest, AllowDefer_NoDataReceived) { + Initialize(kHttpUrl, 10, 99); + SetLoaderBuffer(10, 20); + Start(); + PartialResponse(10, 99, 100); + + // Start in undeferred state, then disallow defer, then allow defer + // without receiving data in between. + DisallowLoaderDefer(); + AllowLoaderDefer(); + StopWhenLoad(); +} + +TEST_F(BufferedResourceLoaderTest, AllowDefer_ReadSameWindow) { + Initialize(kHttpUrl, 10, 99); + SetLoaderBuffer(10, 20); + Start(); + PartialResponse(10, 99, 100); + + uint8 buffer[10]; + + // Start in undeferred state, disallow defer, receive data but don't shift + // buffer window, then allow defer and read. + DisallowLoaderDefer(); + WriteLoader(10, 10); + AllowLoaderDefer(); + + EXPECT_CALL(*this, ReadCallback(10)); + ReadLoader(10, 10, buffer); + VerifyBuffer(buffer, 10, 10); + StopWhenLoad(); +} + +TEST_F(BufferedResourceLoaderTest, AllowDefer_ReadPastWindow) { + Initialize(kHttpUrl, 10, 99); + SetLoaderBuffer(10, 20); + Start(); + PartialResponse(10, 99, 100); + + uint8 buffer[10]; + + // Not deferred, disallow defer, received data and shift buffer window, + // allow defer, then read in area outside of buffer window. + DisallowLoaderDefer(); + WriteLoader(10, 10); + WriteLoader(20, 50); + AllowLoaderDefer(); + + EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); + ReadLoader(10, 10, buffer); + StopWhenLoad(); +} + +TEST_F(BufferedResourceLoaderTest, AllowDefer_DeferredNoDataReceived) { + Initialize(kHttpUrl, 10, 99); + SetLoaderBuffer(10, 20); + Start(); + PartialResponse(10, 99, 100); + + uint8 buffer[10]; + + // Start in deferred state, then disallow defer, receive no data, and + // allow defer and read. + EXPECT_CALL(*url_loader_, setDefersLoading(true)); + EXPECT_CALL(*this, NetworkCallback()); + WriteLoader(10, 40); + + DisallowLoaderDefer(); + AllowLoaderDefer(); + + EXPECT_CALL(*this, ReadCallback(10)); + ReadLoader(20, 10, buffer); + VerifyBuffer(buffer, 20, 10); + StopWhenLoad(); +} + +TEST_F(BufferedResourceLoaderTest, AllowDefer_DeferredReadSameWindow) { + Initialize(kHttpUrl, 10, 99); + SetLoaderBuffer(10, 20); + Start(); + PartialResponse(10, 99, 100); + + uint8 buffer[10]; + + // Start in deferred state, disallow defer, receive data and shift buffer + // window, allow defer, and read in a place that's still in the window. + EXPECT_CALL(*url_loader_, setDefersLoading(true)); + EXPECT_CALL(*this, NetworkCallback()); + WriteLoader(10, 30); + + DisallowLoaderDefer(); + WriteLoader(40, 5); + AllowLoaderDefer(); + + EXPECT_CALL(*this, ReadCallback(10)); + ReadLoader(20, 10, buffer); + VerifyBuffer(buffer, 20, 10); + StopWhenLoad(); +} + +TEST_F(BufferedResourceLoaderTest, AllowDefer_DeferredReadPastWindow) { + Initialize(kHttpUrl, 10, 99); + SetLoaderBuffer(10, 20); + Start(); + PartialResponse(10, 99, 100); + + uint8 buffer[10]; + + // Start in deferred state, disallow defer, receive data and shift buffer + // window, allow defer, and read outside of the buffer window. + EXPECT_CALL(*url_loader_, setDefersLoading(true)); + EXPECT_CALL(*this, NetworkCallback()); + WriteLoader(10, 40); + + DisallowLoaderDefer(); + WriteLoader(50, 20); + WriteLoader(70, 40); + AllowLoaderDefer(); + + EXPECT_CALL(*this, ReadCallback(net::ERR_CACHE_MISS)); + ReadLoader(20, 5, buffer); + StopWhenLoad(); +} +// TODO(hclam): add unit test for defer loading. + +} // namespace webkit_glue + diff --git a/webkit/glue/media/media_resource_loader_bridge_factory.cc b/webkit/glue/media/media_resource_loader_bridge_factory.cc deleted file mode 100644 index 3fb9d65..0000000 --- a/webkit/glue/media/media_resource_loader_bridge_factory.cc +++ /dev/null @@ -1,82 +0,0 @@ -// 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 "webkit/glue/media/media_resource_loader_bridge_factory.h" - -#include "base/format_macros.h" -#include "base/string_util.h" -#include "base/stringprintf.h" - -namespace { - -// A constant for an unknown position. -const int64 kPositionNotSpecified = -1; - -} // namespace - -namespace webkit_glue { - -MediaResourceLoaderBridgeFactory::MediaResourceLoaderBridgeFactory( - const GURL& referrer, - const std::string& frame_origin, - const std::string& main_frame_origin, - int origin_pid, - int appcache_host_id, - int32 routing_id) - : referrer_(referrer), - frame_origin_(frame_origin), - main_frame_origin_(main_frame_origin), - origin_pid_(origin_pid), - appcache_host_id_(appcache_host_id), - routing_id_(routing_id) { -} - -MediaResourceLoaderBridgeFactory::~MediaResourceLoaderBridgeFactory() {} - -ResourceLoaderBridge* MediaResourceLoaderBridgeFactory::CreateBridge( - const GURL& url, - int load_flags, - int64 first_byte_position, - int64 last_byte_position) { - webkit_glue::ResourceLoaderBridge::RequestInfo request_info; - request_info.method = "GET"; - request_info.url = url; - request_info.first_party_for_cookies = url; - request_info.referrer = referrer_; - request_info.frame_origin = frame_origin_; - request_info.main_frame_origin = main_frame_origin_; - request_info.headers = GenerateHeaders(first_byte_position, - last_byte_position); - request_info.load_flags = load_flags; - request_info.requestor_pid = origin_pid_; - request_info.request_type = ResourceType::MEDIA; - request_info.appcache_host_id = appcache_host_id_; - request_info.routing_id = routing_id_; - return webkit_glue::ResourceLoaderBridge::Create(request_info); -} - -MediaResourceLoaderBridgeFactory::MediaResourceLoaderBridgeFactory() {} - -// static -const std::string MediaResourceLoaderBridgeFactory::GenerateHeaders ( - int64 first_byte_position, int64 last_byte_position) { - // Construct the range header. - std::string header; - if (first_byte_position > kPositionNotSpecified && - last_byte_position > kPositionNotSpecified) { - if (first_byte_position <= last_byte_position) { - header = base::StringPrintf("Range: bytes=%" PRId64 "-%" PRId64, - first_byte_position, - last_byte_position); - } - } else if (first_byte_position > kPositionNotSpecified) { - header = base::StringPrintf("Range: bytes=%" PRId64 "-", - first_byte_position); - } else if (last_byte_position > kPositionNotSpecified) { - NOTIMPLEMENTED() << "Suffix range not implemented"; - } - return header; -} - -} // namespace webkit_glue diff --git a/webkit/glue/media/media_resource_loader_bridge_factory.h b/webkit/glue/media/media_resource_loader_bridge_factory.h deleted file mode 100644 index ccacdc6..0000000 --- a/webkit/glue/media/media_resource_loader_bridge_factory.h +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_MEDIA_MEDIA_RESOURCE_LOADER_BRIDGE_FACTORY_H_ -#define WEBKIT_GLUE_MEDIA_MEDIA_RESOURCE_LOADER_BRIDGE_FACTORY_H_ - -#include "base/gtest_prod_util.h" -#include "webkit/glue/resource_loader_bridge.h" - -namespace webkit_glue { - -// A factory used to create a ResourceLoaderBridge for the media player. -// This factory is used also for testing. Testing code can use this class and -// override CreateBridge() to inject a mock ResourceLoaderBridge for code that -// interacts with it, e.g. BufferedDataSource. -class MediaResourceLoaderBridgeFactory { - public: - MediaResourceLoaderBridgeFactory( - const GURL& referrer, - const std::string& frame_origin, - const std::string& main_frame_origin, - int origin_pid, - int appcache_host_id, - int32 routing_id); - - virtual ~MediaResourceLoaderBridgeFactory(); - - // Factory method to create a ResourceLoaderBridge with the following - // parameters: - // |url| - URL of the resource to be loaded. - // |load_flags| - Load flags for this loading. - // |first_byte_position| - First byte position for a range request, -1 if not. - // |last_byte_position| - Last byte position for a range request, -1 if not. - virtual ResourceLoaderBridge* CreateBridge( - const GURL& url, - int load_flags, - int64 first_byte_position, - int64 last_byte_position); - - protected: - // An empty constructor only used by inherited classes. - MediaResourceLoaderBridgeFactory(); - - private: - FRIEND_TEST_ALL_PREFIXES(MediaResourceLoaderBridgeFactoryTest, - GenerateHeaders); - - // Returns a range request header using parameters |first_byte_position| and - // |last_byte_position|. - // Negative numbers other than -1 are not allowed for |first_byte_position| - // and |last_byte_position|. |first_byte_position| should always be less than - // or equal to |last_byte_position| if they are both not -1. - // Here's a list of valid parameters: - // |first_byte_position| |last_byte_position| - // 0 1000 - // 4096 4096 - // 0 -1 - // -1 -1 - // Empty string is returned on invalid parameters. - static const std::string GenerateHeaders(int64 first_byte_position, - int64 last_byte_position); - - GURL first_party_for_cookies_; - GURL referrer_; - std::string frame_origin_; - std::string main_frame_origin_; - std::string headers_; - int origin_pid_; - int appcache_host_id_; - int32 routing_id_; -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_MEDIA_MEDIA_RESOURCE_LOADER_BRIDGE_FACTORY_H_ diff --git a/webkit/glue/media/media_resource_loader_bridge_factory_unittest.cc b/webkit/glue/media/media_resource_loader_bridge_factory_unittest.cc deleted file mode 100644 index 4c0126b..0000000 --- a/webkit/glue/media/media_resource_loader_bridge_factory_unittest.cc +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/http/http_util.h" -#include "webkit/glue/media/media_resource_loader_bridge_factory.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace webkit_glue { - -TEST(MediaResourceLoaderBridgeFactoryTest, GenerateHeaders) { - static const struct { - const bool success; - const int64 first_byte_position; - const int64 last_byte_position; - } data[] = { - { false, -1, -1 }, - { false, -5, 0 }, - { false, 100, 0 }, - { true, 0, -1 }, - { true, 0, 0 }, - { true, 100, 100 }, - { true, 50, -1 }, - { true, 10000, -1 }, - { true, 50, 100 }, - }; - - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(data); ++i) { - std::string headers = MediaResourceLoaderBridgeFactory::GenerateHeaders( - data[i].first_byte_position, data[i].last_byte_position); - std::vector<net::HttpByteRange> ranges; - bool ret = net::HttpUtil::ParseRanges(headers, &ranges); - EXPECT_EQ(data[i].success, ret); - if (ret) { - EXPECT_EQ(1u, ranges.size()); - EXPECT_EQ(data[i].first_byte_position, - ranges[0].first_byte_position()); - EXPECT_EQ(data[i].last_byte_position, - ranges[0].last_byte_position()); - } - } -} - -} // namespace webkit_glue diff --git a/webkit/glue/media/mock_media_resource_loader_bridge_factory.h b/webkit/glue/media/mock_media_resource_loader_bridge_factory.h deleted file mode 100644 index 3c0a3ae..0000000 --- a/webkit/glue/media/mock_media_resource_loader_bridge_factory.h +++ /dev/null @@ -1,36 +0,0 @@ -// 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 WEBKIT_GLUE_MEDIA_MOCK_MEDIA_RESOURCE_LOADER_BRIDGE_FACTORY_H_ -#define WEBKIT_GLUE_MEDIA_MOCK_MEDIA_RESOURCE_LOADER_BRIDGE_FACTORY_H_ - -#include "testing/gmock/include/gmock/gmock.h" -#include "webkit/glue/media/media_resource_loader_bridge_factory.h" - -namespace webkit_glue { - -class MockMediaResourceLoaderBridgeFactory - : public webkit_glue::MediaResourceLoaderBridgeFactory { - public: - MockMediaResourceLoaderBridgeFactory() { - } - - virtual ~MockMediaResourceLoaderBridgeFactory() { - OnDestroy(); - } - - MOCK_METHOD4(CreateBridge, - webkit_glue::ResourceLoaderBridge*(const GURL& url, - int load_flags, - int64 first_byte_position, - int64 last_byte_position)); - MOCK_METHOD0(OnDestroy, void()); - - private: - DISALLOW_COPY_AND_ASSIGN(MockMediaResourceLoaderBridgeFactory); -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_MEDIA_MOCK_MEDIA_RESOURCE_LOADER_BRIDGE_FACTORY_H_ diff --git a/webkit/glue/media/simple_data_source.cc b/webkit/glue/media/simple_data_source.cc index 291928e..8869e28 100644 --- a/webkit/glue/media/simple_data_source.cc +++ b/webkit/glue/media/simple_data_source.cc @@ -2,40 +2,35 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "webkit/glue/media/simple_data_source.h" + #include "base/message_loop.h" #include "base/process_util.h" #include "media/base/filter_host.h" -#include "net/base/load_flags.h" #include "net/base/data_url.h" -#include "net/http/http_response_headers.h" +#include "net/base/load_flags.h" #include "net/url_request/url_request_status.h" -#include "webkit/glue/media/simple_data_source.h" -#include "webkit/glue/resource_loader_bridge.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKitClient.h" #include "webkit/glue/webkit_glue.h" namespace { -const char kHttpScheme[] = "http"; -const char kHttpsScheme[] = "https"; const char kDataScheme[] = "data"; -// A helper method that accepts only HTTP, HTTPS and FILE protocol. -bool IsDataProtocol(const GURL& url) { - return url.SchemeIs(kDataScheme); -} - } // namespace namespace webkit_glue { SimpleDataSource::SimpleDataSource( MessageLoop* render_loop, - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory) + WebKit::WebFrame* frame) : render_loop_(render_loop), - bridge_factory_(bridge_factory), + frame_(frame), size_(-1), single_origin_(true), - state_(UNINITIALIZED) { + state_(UNINITIALIZED), + keep_test_loader_(false) { DCHECK(render_loop); } @@ -108,34 +103,59 @@ bool SimpleDataSource::IsStreaming() { return false; } -bool SimpleDataSource::OnReceivedRedirect( - const GURL& new_url, - const webkit_glue::ResourceResponseInfo& info, - bool* has_new_first_party_for_cookies, - GURL* new_first_party_for_cookies) { +void SimpleDataSource::SetURLLoaderForTest(WebKit::WebURLLoader* mock_loader) { + url_loader_.reset(mock_loader); + keep_test_loader_ = true; +} + +void SimpleDataSource::willSendRequest( + WebKit::WebURLLoader* loader, + WebKit::WebURLRequest& newRequest, + const WebKit::WebURLResponse& redirectResponse) { DCHECK(MessageLoop::current() == render_loop_); - single_origin_ = url_.GetOrigin() == new_url.GetOrigin(); + single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin(); - // TODO(wtc): should we return a new first party for cookies URL? - *has_new_first_party_for_cookies = false; - return true; + url_ = newRequest.url(); } -void SimpleDataSource::OnReceivedResponse( - const webkit_glue::ResourceResponseInfo& info, - bool content_filtered) { +void SimpleDataSource::didSendData( + WebKit::WebURLLoader* loader, + unsigned long long bytesSent, + unsigned long long totalBytesToBeSent) { + NOTIMPLEMENTED(); +} + +void SimpleDataSource::didReceiveResponse( + WebKit::WebURLLoader* loader, + const WebKit::WebURLResponse& response) { DCHECK(MessageLoop::current() == render_loop_); - size_ = info.content_length; + size_ = response.expectedContentLength(); +} + +void SimpleDataSource::didDownloadData( + WebKit::WebURLLoader* loader, + int dataLength) { + NOTIMPLEMENTED(); } -void SimpleDataSource::OnReceivedData(const char* data, int len) { +void SimpleDataSource::didReceiveData( + WebKit::WebURLLoader* loader, + const char* data, + int data_length) { DCHECK(MessageLoop::current() == render_loop_); - data_.append(data, len); + data_.append(data, data_length); } -void SimpleDataSource::OnCompletedRequest(const URLRequestStatus& status, - const std::string& security_info, - const base::Time& completion_time) { +void SimpleDataSource::didReceiveCachedMetadata( + WebKit::WebURLLoader* loader, + const char* data, + int dataLength) { + NOTIMPLEMENTED(); +} + +void SimpleDataSource::didFinishLoading( + WebKit::WebURLLoader* loader, + double finishTime) { DCHECK(MessageLoop::current() == render_loop_); AutoLock auto_lock(lock_); // It's possible this gets called after Stop(), in which case |host_| is no @@ -143,10 +163,8 @@ void SimpleDataSource::OnCompletedRequest(const URLRequestStatus& status, if (state_ == STOPPED) return; - // Otherwise we should be initializing and have created a bridge. + // Otherwise we should be initializing and have created a WebURLLoader. DCHECK_EQ(state_, INITIALIZING); - DCHECK(bridge_.get()); - bridge_.reset(); // If we don't get a content length or the request has failed, report it // as a network error. @@ -154,7 +172,29 @@ void SimpleDataSource::OnCompletedRequest(const URLRequestStatus& status, size_ = data_.length(); DCHECK(static_cast<size_t>(size_) == data_.length()); - DoneInitialization_Locked(status.is_success()); + DoneInitialization_Locked(true); +} + +void SimpleDataSource::didFail( + WebKit::WebURLLoader* loader, + const WebKit::WebURLError& error) { + DCHECK(MessageLoop::current() == render_loop_); + AutoLock auto_lock(lock_); + // It's possible this gets called after Stop(), in which case |host_| is no + // longer valid. + if (state_ == STOPPED) + return; + + // Otherwise we should be initializing and have created a WebURLLoader. + DCHECK_EQ(state_, INITIALIZING); + + // If we don't get a content length or the request has failed, report it + // as a network error. + if (size_ == -1) + size_ = data_.length(); + DCHECK(static_cast<size_t>(size_) == data_.length()); + + DoneInitialization_Locked(false); } bool SimpleDataSource::HasSingleOrigin() { @@ -164,7 +204,7 @@ bool SimpleDataSource::HasSingleOrigin() { void SimpleDataSource::Abort() { DCHECK(MessageLoop::current() == render_loop_); - NOTIMPLEMENTED(); + frame_ = NULL; } void SimpleDataSource::SetURL(const GURL& url) { @@ -183,9 +223,11 @@ void SimpleDataSource::StartTask() { if (state_ == STOPPED) return; + CHECK(frame_); + DCHECK_EQ(state_, INITIALIZING); - if (IsDataProtocol(url_)) { + if (url_.SchemeIs(kDataScheme)) { // If this using data protocol, we just need to decode it. std::string mime_type, charset; bool success = net::DataURL::Parse(url_, &mime_type, &charset, &data_); @@ -194,10 +236,18 @@ void SimpleDataSource::StartTask() { size_ = data_.length(); DoneInitialization_Locked(success); } else { - // Create our bridge and start loading the resource. - bridge_.reset(bridge_factory_->CreateBridge( - url_, net::LOAD_BYPASS_CACHE, -1, -1)); - bridge_->Start(this); + // Prepare the request. + WebKit::WebURLRequest request(url_); + request.setTargetType(WebKit::WebURLRequest::TargetIsMedia); + + frame_->setReferrerForRequest(request, WebKit::WebURL()); + + // This flag is for unittests as we don't want to reset |url_loader| + if (!keep_test_loader_) + url_loader_.reset(frame_->createAssociatedURLLoader()); + + // Start the resource loading. + url_loader_->loadAsynchronously(request, this); } } @@ -207,9 +257,9 @@ void SimpleDataSource::CancelTask() { DCHECK_EQ(state_, STOPPED); // Cancel any pending requests. - if (bridge_.get()) { - bridge_->Cancel(); - bridge_.reset(); + if (url_loader_.get()) { + url_loader_->cancel(); + url_loader_.reset(); } } @@ -220,7 +270,7 @@ void SimpleDataSource::DoneInitialization_Locked(bool success) { host()->SetTotalBytes(size_); host()->SetBufferedBytes(size_); // If scheme is file or data, say we are loaded. - host()->SetLoaded(url_.SchemeIsFile() || IsDataProtocol(url_)); + host()->SetLoaded(url_.SchemeIsFile() || url_.SchemeIs(kDataScheme)); } else { host()->SetError(media::PIPELINE_ERROR_NETWORK); } diff --git a/webkit/glue/media/simple_data_source.h b/webkit/glue/media/simple_data_source.h index ff1e247..f4c83e6 100644 --- a/webkit/glue/media/simple_data_source.h +++ b/webkit/glue/media/simple_data_source.h @@ -10,10 +10,17 @@ #ifndef WEBKIT_GLUE_MEDIA_SIMPLE_DATA_SOURCE_H_ #define WEBKIT_GLUE_MEDIA_SIMPLE_DATA_SOURCE_H_ +#include <algorithm> +#include <string> + #include "base/message_loop.h" #include "base/scoped_ptr.h" #include "media/base/filters.h" -#include "webkit/glue/media/media_resource_loader_bridge_factory.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLLoader.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" #include "webkit/glue/media/web_data_source.h" class MessageLoop; @@ -22,17 +29,15 @@ class WebMediaPlayerDelegateImpl; namespace webkit_glue { class SimpleDataSource : public WebDataSource, - public webkit_glue::ResourceLoaderBridge::Peer { + public WebKit::WebURLLoaderClient { public: - SimpleDataSource( - MessageLoop* render_loop, - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory); + SimpleDataSource(MessageLoop* render_loop, WebKit::WebFrame* frame); virtual ~SimpleDataSource(); - // MediaFilter implementation. + // media::Filter implementation. virtual void Stop(media::FilterCallback* callback); - // DataSource implementation. + // media::DataSource implementation. virtual void Initialize(const std::string& url, media::FilterCallback* callback); virtual const media::MediaFormat& media_format(); @@ -41,21 +46,37 @@ class SimpleDataSource : public WebDataSource, virtual bool GetSize(int64* size_out); virtual bool IsStreaming(); - // webkit_glue::ResourceLoaderBridge::Peer implementation. - virtual void OnUploadProgress(uint64 position, uint64 size) {} - virtual bool OnReceivedRedirect( - const GURL& new_url, - const webkit_glue::ResourceResponseInfo& info, - bool* has_new_first_party_for_cookies, - GURL* new_first_party_for_cookies); - virtual void OnReceivedResponse( - const webkit_glue::ResourceResponseInfo& info, - bool content_filtered); - virtual void OnDownloadedData(int len) {} - virtual void OnReceivedData(const char* data, int len); - virtual void OnCompletedRequest(const URLRequestStatus& status, - const std::string& security_info, - const base::Time& completion_time); + // Used to inject a mock used for unittests. + virtual void SetURLLoaderForTest(WebKit::WebURLLoader* mock_loader); + + // WebKit::WebURLLoaderClient implementations. + virtual void willSendRequest( + WebKit::WebURLLoader* loader, + WebKit::WebURLRequest& newRequest, + const WebKit::WebURLResponse& redirectResponse); + virtual void didSendData( + WebKit::WebURLLoader* loader, + unsigned long long bytesSent, + unsigned long long totalBytesToBeSent); + virtual void didReceiveResponse( + WebKit::WebURLLoader* loader, + const WebKit::WebURLResponse& response); + virtual void didDownloadData( + WebKit::WebURLLoader* loader, + int dataLength); + virtual void didReceiveData( + WebKit::WebURLLoader* loader, + const char* data, + int dataLength); + virtual void didReceiveCachedMetadata( + WebKit::WebURLLoader* loader, + const char* data, int dataLength); + virtual void didFinishLoading( + WebKit::WebURLLoader* loader, + double finishTime); + virtual void didFail( + WebKit::WebURLLoader* loader, + const WebKit::WebURLError&); // webkit_glue::WebDataSource implementation. virtual bool HasSingleOrigin(); @@ -77,11 +98,11 @@ class SimpleDataSource : public WebDataSource, // Primarily used for asserting the bridge is loading on the render thread. MessageLoop* render_loop_; - // Factory to create a bridge. - scoped_ptr<webkit_glue::MediaResourceLoaderBridgeFactory> bridge_factory_; + // A webframe for loading. + WebKit::WebFrame* frame_; - // Bridge used to load the media resource. - scoped_ptr<webkit_glue::ResourceLoaderBridge> bridge_; + // Does the work of loading and sends data back to this client. + scoped_ptr<WebKit::WebURLLoader> url_loader_; media::MediaFormat media_format_; GURL url_; @@ -104,6 +125,9 @@ class SimpleDataSource : public WebDataSource, // Filter callbacks. scoped_ptr<media::FilterCallback> initialize_callback_; + // Used to ensure mocks for unittests are used instead of reset in Start(). + bool keep_test_loader_; + DISALLOW_COPY_AND_ASSIGN(SimpleDataSource); }; diff --git a/webkit/glue/media/simple_data_source_unittest.cc b/webkit/glue/media/simple_data_source_unittest.cc index 537798f..55dc913 100644 --- a/webkit/glue/media/simple_data_source_unittest.cc +++ b/webkit/glue/media/simple_data_source_unittest.cc @@ -6,9 +6,15 @@ #include "media/base/filters.h" #include "media/base/mock_filter_host.h" #include "media/base/mock_filters.h" -#include "webkit/glue/media/mock_media_resource_loader_bridge_factory.h" +#include "net/base/net_errors.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLLoader.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" #include "webkit/glue/media/simple_data_source.h" -#include "webkit/glue/mock_resource_loader_bridge.h" +#include "webkit/mocks/mock_webframe.h" +#include "webkit/mocks/mock_weburlloader.h" using ::testing::_; using ::testing::DoAll; @@ -21,6 +27,11 @@ using ::testing::SetArgumentPointee; using ::testing::StrictMock; using ::testing::WithArgs; +using WebKit::WebURLError; +using WebKit::WebURLLoader; +using WebKit::WebURLRequest; +using WebKit::WebURLResponse; + namespace { const int kDataSize = 1024; @@ -39,68 +50,56 @@ namespace webkit_glue { class SimpleDataSourceTest : public testing::Test { public: SimpleDataSourceTest() { - bridge_factory_.reset( - new NiceMock<MockMediaResourceLoaderBridgeFactory>()); - bridge_.reset(new NiceMock<MockResourceLoaderBridge>()); - for (int i = 0; i < kDataSize; ++i) { data_[i] = i; } } virtual ~SimpleDataSourceTest() { - if (bridge_.get()) - EXPECT_CALL(*bridge_, OnDestroy()); - if (bridge_factory_.get()) - EXPECT_CALL(*bridge_factory_, OnDestroy()); + ignore_result(frame_.release()); } void InitializeDataSource(const char* url) { + gurl_ = GURL(url); + + frame_.reset(new NiceMock<MockWebFrame>()); + url_loader_ = new NiceMock<MockWebURLLoader>(); + data_source_ = new SimpleDataSource(MessageLoop::current(), - bridge_factory_.get()); - CHECK(data_source_); + frame_.get()); // There is no need to provide a message loop to data source. data_source_->set_host(&host_); + data_source_->SetURLLoaderForTest(url_loader_); - // First a bridge is created. InSequence s; - EXPECT_CALL(*bridge_factory_, CreateBridge(GURL(url), _, -1, -1)) - .WillOnce(Return(bridge_.get())); - EXPECT_CALL(*bridge_, Start(data_source_.get())) - .WillOnce(Return(true)); data_source_->Initialize(url, callback_.NewCallback()); - MessageLoop::current()->RunAllPending(); } void RequestSucceeded(bool is_loaded) { - ResourceResponseInfo info; - info.content_length = kDataSize; + WebURLResponse response(gurl_); + response.setExpectedContentLength(kDataSize); - data_source_->OnReceivedResponse(info, false); + data_source_->didReceiveResponse(NULL, response); int64 size; EXPECT_TRUE(data_source_->GetSize(&size)); EXPECT_EQ(kDataSize, size); - for (int i = 0; i < kDataSize; ++i) - data_source_->OnReceivedData(data_ + i, 1); + for (int i = 0; i < kDataSize; ++i) { + data_source_->didReceiveData(NULL, data_ + i, 1); + } EXPECT_CALL(host_, SetLoaded(is_loaded)); InSequence s; - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &SimpleDataSourceTest::ReleaseBridge)); EXPECT_CALL(host_, SetTotalBytes(kDataSize)); EXPECT_CALL(host_, SetBufferedBytes(kDataSize)); EXPECT_CALL(callback_, OnFilterCallback()); EXPECT_CALL(callback_, OnCallbackDestroyed()); - URLRequestStatus status; - status.set_status(URLRequestStatus::SUCCESS); - status.set_os_error(0); - data_source_->OnCompletedRequest(status, "", base::Time()); + data_source_->didFinishLoading(NULL, 0); // Let the tasks to be executed. MessageLoop::current()->RunAllPending(); @@ -108,28 +107,23 @@ class SimpleDataSourceTest : public testing::Test { void RequestFailed() { InSequence s; - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &SimpleDataSourceTest::ReleaseBridge)); EXPECT_CALL(host_, SetError(media::PIPELINE_ERROR_NETWORK)); EXPECT_CALL(callback_, OnFilterCallback()); EXPECT_CALL(callback_, OnCallbackDestroyed()); - URLRequestStatus status; - status.set_status(URLRequestStatus::FAILED); - status.set_os_error(100); - data_source_->OnCompletedRequest(status, "", base::Time()); + WebURLError error; + error.reason = net::ERR_FAILED; + data_source_->didFail(NULL, error); // Let the tasks to be executed. MessageLoop::current()->RunAllPending(); } void DestroyDataSource() { - EXPECT_CALL(*bridge_factory_, OnDestroy()) - .WillOnce(Invoke(this, &SimpleDataSourceTest::ReleaseBridgeFactory)); - StrictMock<media::MockFilterCallback> callback; EXPECT_CALL(callback, OnFilterCallback()); EXPECT_CALL(callback, OnCallbackDestroyed()); + data_source_->Stop(callback.NewCallback()); MessageLoop::current()->RunAllPending(); @@ -148,23 +142,17 @@ class SimpleDataSourceTest : public testing::Test { } } - void ReleaseBridge() { - ignore_result(bridge_.release()); - } - - void ReleaseBridgeFactory() { - ignore_result(bridge_factory_.release()); - } - MOCK_METHOD1(ReadCallback, void(size_t size)); protected: + GURL gurl_; scoped_ptr<MessageLoop> message_loop_; - scoped_ptr<NiceMock<MockMediaResourceLoaderBridgeFactory> > bridge_factory_; - scoped_ptr<NiceMock<MockResourceLoaderBridge> > bridge_; + NiceMock<MockWebURLLoader>* url_loader_; scoped_refptr<SimpleDataSource> data_source_; StrictMock<media::MockFilterHost> host_; StrictMock<media::MockFilterCallback> callback_; + scoped_ptr<NiceMock<MockWebFrame> > frame_; + char data_[kDataSize]; DISALLOW_COPY_AND_ASSIGN(SimpleDataSourceTest); @@ -189,13 +177,16 @@ TEST_F(SimpleDataSourceTest, InitializeFile) { } TEST_F(SimpleDataSourceTest, InitializeData) { + frame_.reset(new NiceMock<MockWebFrame>()); + url_loader_ = new NiceMock<MockWebURLLoader>(); + data_source_ = new SimpleDataSource(MessageLoop::current(), - bridge_factory_.get()); + frame_.get()); EXPECT_TRUE(data_source_->IsUrlSupported(kDataUrl)); - CHECK(data_source_); // There is no need to provide a message loop to data source. data_source_->set_host(&host_); + data_source_->SetURLLoaderForTest(url_loader_); EXPECT_CALL(host_, SetLoaded(true)); EXPECT_CALL(host_, SetTotalBytes(sizeof(kDataUrlDecoded))); @@ -218,9 +209,7 @@ TEST_F(SimpleDataSourceTest, RequestFailed) { TEST_F(SimpleDataSourceTest, StopWhenDownloading) { InitializeDataSource(kHttpUrl); - EXPECT_CALL(*bridge_, Cancel()); - EXPECT_CALL(*bridge_, OnDestroy()) - .WillOnce(Invoke(this, &SimpleDataSourceTest::ReleaseBridge)); + EXPECT_CALL(*url_loader_, cancel()); EXPECT_CALL(callback_, OnCallbackDestroyed()); DestroyDataSource(); } diff --git a/webkit/glue/mimetype_unittest.cc b/webkit/glue/mimetype_unittest.cc index 1c2e5f4..3f17e79 100644 --- a/webkit/glue/mimetype_unittest.cc +++ b/webkit/glue/mimetype_unittest.cc @@ -23,12 +23,12 @@ class MimeTypeTests : public TestShellTest { test_shell_->WaitTestFinished(); } - void CheckMimeType(const char* mimetype, const std::wstring& expected) { + void CheckMimeType(const char* mimetype, const std::string& expected) { std::string path("contenttype?"); GURL url(test_server_.GetURL(path + mimetype)); LoadURL(url); WebFrame* frame = test_shell_->webView()->mainFrame(); - EXPECT_EQ(expected, webkit_glue::DumpDocumentText(frame)); + EXPECT_EQ(expected, UTF16ToASCII(webkit_glue::DumpDocumentText(frame))); } UnittestTestServer test_server_; @@ -37,8 +37,8 @@ class MimeTypeTests : public TestShellTest { TEST_F(MimeTypeTests, MimeTypeTests) { ASSERT_TRUE(test_server_.Start()); - std::wstring expected_src(L"<html>\n<body>\n" - L"<p>HTML text</p>\n</body>\n</html>\n"); + std::string expected_src("<html>\n<body>\n" + "<p>HTML text</p>\n</body>\n</html>\n"); // These files should all be displayed as plain text. const char* plain_text[] = { @@ -66,7 +66,7 @@ TEST_F(MimeTypeTests, MimeTypeTests) { "application/xhtml+xml", }; for (size_t i = 0; i < arraysize(html_src); ++i) { - CheckMimeType(html_src[i], L"HTML text"); + CheckMimeType(html_src[i], "HTML text"); } // These shouldn't be rendered as text or HTML, but shouldn't download @@ -78,7 +78,7 @@ TEST_F(MimeTypeTests, MimeTypeTests) { "image/bmp", }; for (size_t i = 0; i < arraysize(not_text); ++i) { - CheckMimeType(not_text[i], L""); + CheckMimeType(not_text[i], ""); test_shell_->webView()->mainFrame()->stopLoading(); } diff --git a/webkit/glue/mock_resource_loader_bridge.h b/webkit/glue/mock_resource_loader_bridge.h deleted file mode 100644 index 49c41ed..0000000 --- a/webkit/glue/mock_resource_loader_bridge.h +++ /dev/null @@ -1,44 +0,0 @@ -// 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 WEBKIT_GLUE_MOCK_RESOURCE_LOADER_BRIDGE_H_ -#define WEBKIT_GLUE_MOCK_RESOURCE_LOADER_BRIDGE_H_ - -#include "testing/gmock/include/gmock/gmock.h" -#include "webkit/glue/resource_loader_bridge.h" - -class FilePath; - -namespace webkit_glue { - -class MockResourceLoaderBridge : public webkit_glue::ResourceLoaderBridge { - public: - MockResourceLoaderBridge() { - } - - virtual ~MockResourceLoaderBridge() { - OnDestroy(); - } - - MOCK_METHOD2(AppendDataToUpload, void(const char* data, int data_len)); - MOCK_METHOD4(AppendFileRangeToUpload, - void(const FilePath& file_path, - uint64 offset, - uint64 length, - const base::Time& expected_modification_time)); - MOCK_METHOD1(AppendBlobToUpload, void(const GURL& blob_url)); - MOCK_METHOD1(SetUploadIdentifier, void(int64 identifier)); - MOCK_METHOD1(Start, bool(ResourceLoaderBridge::Peer* peer)); - MOCK_METHOD0(Cancel, void()); - MOCK_METHOD1(SetDefersLoading, void(bool value)); - MOCK_METHOD1(SyncLoad, void(SyncLoadResponse* response)); - MOCK_METHOD0(OnDestroy, void()); - - private: - DISALLOW_COPY_AND_ASSIGN(MockResourceLoaderBridge); -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_MOCK_RESOURCE_LOADER_BRIDGE_H_ diff --git a/webkit/glue/multipart_response_delegate.cc b/webkit/glue/multipart_response_delegate.cc index 99a9e4c..b8c7758 100644 --- a/webkit/glue/multipart_response_delegate.cc +++ b/webkit/glue/multipart_response_delegate.cc @@ -316,7 +316,8 @@ bool MultipartResponseDelegate::ReadMultipartBoundary( bool MultipartResponseDelegate::ReadContentRanges( const WebURLResponse& response, int* content_range_lower_bound, - int* content_range_upper_bound) { + int* content_range_upper_bound, + int* content_range_instance_size) { std::string content_range = response.httpHeaderField("Content-Range").utf8(); if (content_range.empty()) { @@ -336,12 +337,20 @@ bool MultipartResponseDelegate::ReadContentRanges( // Skip over the initial space. byte_range_lower_bound_start_offset++; + // Find the lower bound. size_t byte_range_lower_bound_end_offset = content_range.find("-", byte_range_lower_bound_start_offset); if (byte_range_lower_bound_end_offset == std::string::npos) { return false; } + size_t byte_range_lower_bound_characters = + byte_range_lower_bound_end_offset - byte_range_lower_bound_start_offset; + std::string byte_range_lower_bound = + content_range.substr(byte_range_lower_bound_start_offset, + byte_range_lower_bound_characters); + + // Find the upper bound. size_t byte_range_upper_bound_start_offset = byte_range_lower_bound_end_offset + 1; @@ -351,16 +360,31 @@ bool MultipartResponseDelegate::ReadContentRanges( return false; } - if (!base::StringToInt( - content_range.begin() + byte_range_lower_bound_start_offset, - content_range.begin() + byte_range_lower_bound_end_offset, - content_range_lower_bound)) - return false; + size_t byte_range_upper_bound_characters = + byte_range_upper_bound_end_offset - byte_range_upper_bound_start_offset; + std::string byte_range_upper_bound = + content_range.substr(byte_range_upper_bound_start_offset, + byte_range_upper_bound_characters); + + // Find the instance size. + size_t byte_range_instance_size_start_offset = + byte_range_upper_bound_end_offset + 1; + + size_t byte_range_instance_size_end_offset = + content_range.length(); - if (!base::StringToInt( - content_range.begin() + byte_range_upper_bound_start_offset, - content_range.begin() + byte_range_upper_bound_end_offset, - content_range_upper_bound)) + size_t byte_range_instance_size_characters = + byte_range_instance_size_end_offset - + byte_range_instance_size_start_offset; + std::string byte_range_instance_size = + content_range.substr(byte_range_instance_size_start_offset, + byte_range_instance_size_characters); + + if (!base::StringToInt(byte_range_lower_bound, content_range_lower_bound)) + return false; + if (!base::StringToInt(byte_range_upper_bound, content_range_upper_bound)) + return false; + if (!base::StringToInt(byte_range_instance_size, content_range_instance_size)) return false; return true; } diff --git a/webkit/glue/multipart_response_delegate.h b/webkit/glue/multipart_response_delegate.h index aded54a..0500983 100644 --- a/webkit/glue/multipart_response_delegate.h +++ b/webkit/glue/multipart_response_delegate.h @@ -92,7 +92,8 @@ class MultipartResponseDelegate { // Returns true on success. static bool ReadContentRanges(const WebKit::WebURLResponse& response, int* content_range_lower_bound, - int* content_range_upper_bound); + int* content_range_upper_bound, + int* content_range_instance_size); private: friend class MultipartResponseDelegateTester; // For unittests. diff --git a/webkit/glue/multipart_response_delegate_unittest.cc b/webkit/glue/multipart_response_delegate_unittest.cc index fab798c..1837cb5 100644 --- a/webkit/glue/multipart_response_delegate_unittest.cc +++ b/webkit/glue/multipart_response_delegate_unittest.cc @@ -550,10 +550,12 @@ TEST(MultipartResponseTest, MultipartContentRangesTest) { int content_range_lower_bound = 0; int content_range_upper_bound = 0; + int content_range_instance_size = 0; bool result = MultipartResponseDelegate::ReadContentRanges( response1, &content_range_lower_bound, - &content_range_upper_bound); + &content_range_upper_bound, + &content_range_instance_size); EXPECT_EQ(result, true); EXPECT_EQ(content_range_lower_bound, 1000); @@ -567,10 +569,12 @@ TEST(MultipartResponseTest, MultipartContentRangesTest) { content_range_lower_bound = 0; content_range_upper_bound = 0; + content_range_instance_size = 0; result = MultipartResponseDelegate::ReadContentRanges( response2, &content_range_lower_bound, - &content_range_upper_bound); + &content_range_upper_bound, + &content_range_instance_size); EXPECT_EQ(result, false); @@ -582,10 +586,12 @@ TEST(MultipartResponseTest, MultipartContentRangesTest) { content_range_lower_bound = 0; content_range_upper_bound = 0; + content_range_instance_size = 0; result = MultipartResponseDelegate::ReadContentRanges( response3, &content_range_lower_bound, - &content_range_upper_bound); + &content_range_upper_bound, + &content_range_instance_size); EXPECT_EQ(result, true); EXPECT_EQ(content_range_lower_bound, 1000); @@ -598,10 +604,12 @@ TEST(MultipartResponseTest, MultipartContentRangesTest) { content_range_lower_bound = 0; content_range_upper_bound = 0; + content_range_instance_size = 0; result = MultipartResponseDelegate::ReadContentRanges( response4, &content_range_lower_bound, - &content_range_upper_bound); + &content_range_upper_bound, + &content_range_instance_size); EXPECT_EQ(result, false); } diff --git a/webkit/glue/plugins/DEPS b/webkit/glue/plugins/DEPS deleted file mode 100644 index cfee702..0000000 --- a/webkit/glue/plugins/DEPS +++ /dev/null @@ -1,4 +0,0 @@ -include_rules = [ - "+ppapi", - "+printing", -] diff --git a/webkit/glue/plugins/carbon_plugin_window_tracker_mac.cc b/webkit/glue/plugins/carbon_plugin_window_tracker_mac.cc deleted file mode 100644 index c4ae72d..0000000 --- a/webkit/glue/plugins/carbon_plugin_window_tracker_mac.cc +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/logging.h" -#include "webkit/glue/plugins/carbon_plugin_window_tracker_mac.h" - -CarbonPluginWindowTracker::CarbonPluginWindowTracker() { -} - -CarbonPluginWindowTracker* CarbonPluginWindowTracker::SharedInstance() { - static CarbonPluginWindowTracker* tracker = new CarbonPluginWindowTracker(); - return tracker; -} - -WindowRef CarbonPluginWindowTracker::CreateDummyWindowForDelegate( - OpaquePluginRef delegate) { - // The real size will be set by the plugin instance, once that size is known. - Rect window_bounds = { 0, 0, 100, 100 }; - WindowRef new_ref = NULL; - if (CreateNewWindow(kDocumentWindowClass, - kWindowNoTitleBarAttribute, - &window_bounds, - &new_ref) == noErr) { - window_to_delegate_map_[new_ref] = delegate; - delegate_to_window_map_[delegate] = new_ref; - } - return new_ref; -} - -OpaquePluginRef CarbonPluginWindowTracker::GetDelegateForDummyWindow( - WindowRef window) const { - WindowToDelegateMap::const_iterator i = window_to_delegate_map_.find(window); - if (i != window_to_delegate_map_.end()) - return i->second; - return NULL; -} - -WindowRef CarbonPluginWindowTracker::GetDummyWindowForDelegate( - OpaquePluginRef delegate) const { - DelegateToWindowMap::const_iterator i = - delegate_to_window_map_.find(delegate); - if (i != delegate_to_window_map_.end()) - return i->second; - return NULL; -} - -void CarbonPluginWindowTracker::DestroyDummyWindowForDelegate( - OpaquePluginRef delegate, WindowRef window) { - DCHECK(GetDelegateForDummyWindow(window) == delegate); - window_to_delegate_map_.erase(window); - delegate_to_window_map_.erase(delegate); - if (window) // Check just in case the initial window creation failed. - DisposeWindow(window); -} diff --git a/webkit/glue/plugins/carbon_plugin_window_tracker_mac.h b/webkit/glue/plugins/carbon_plugin_window_tracker_mac.h deleted file mode 100644 index 90fc318..0000000 --- a/webkit/glue/plugins/carbon_plugin_window_tracker_mac.h +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_CARBON_PLUGIN_WINDOW_TRACKER_MAC_H_ -#define WEBKIT_GLUE_PLUGINS_CARBON_PLUGIN_WINDOW_TRACKER_MAC_H_ - -#include <Carbon/Carbon.h> -#include <map> - -#include "base/basictypes.h" - -// This is really a WebPluginDelegateImpl, but that class is private to the -// framework, and these functions are called from a dylib. -typedef void* OpaquePluginRef; - -// Creates and tracks the invisible windows that are necessary for -// Carbon-event-model plugins. -// -// Serves as a bridge between plugin delegate instances and the Carbon -// interposing library. The Carbon functions we interpose work in terms of -// WindowRefs, and we need to be able to map from those back to the plugin -// delegates that know what we should claim about the state of the window. -class __attribute__((visibility("default"))) CarbonPluginWindowTracker { - public: - CarbonPluginWindowTracker(); - - // Returns the shared window tracker instance. - static CarbonPluginWindowTracker* SharedInstance(); - - // Creates a new carbon window associated with |delegate|. - WindowRef CreateDummyWindowForDelegate(OpaquePluginRef delegate); - - // Returns the WebPluginDelegate associated with the given dummy window. - OpaquePluginRef GetDelegateForDummyWindow(WindowRef window) const; - - // Returns the dummy window associated with |delegate|. - WindowRef GetDummyWindowForDelegate(OpaquePluginRef delegate) const; - - // Destroys the dummy window for |delegate|. - void DestroyDummyWindowForDelegate(OpaquePluginRef delegate, - WindowRef window); - - private: - typedef std::map<WindowRef, OpaquePluginRef> WindowToDelegateMap; - typedef std::map<OpaquePluginRef, WindowRef> DelegateToWindowMap; - WindowToDelegateMap window_to_delegate_map_; - DelegateToWindowMap delegate_to_window_map_; - - DISALLOW_COPY_AND_ASSIGN(CarbonPluginWindowTracker); -}; - -#endif // WEBKIT_GLUE_PLUGINS_CARBON_PLUGIN_WINDOW_TRACKER_MAC_H_ diff --git a/webkit/glue/plugins/coregraphics_private_symbols_mac.h b/webkit/glue/plugins/coregraphics_private_symbols_mac.h deleted file mode 100644 index 0342d6f..0000000 --- a/webkit/glue/plugins/coregraphics_private_symbols_mac.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_COREGRAPHICS_PRIVATE_SYMBOLS_MAC_H_ -#define WEBKIT_GLUE_PLUGINS_COREGRAPHICS_PRIVATE_SYMBOLS_MAC_H_ - -// These are CoreGraphics SPI, verified to exist in both 10.5 and 10.6. - -#ifdef __cplusplus -extern "C" { -#endif - -// Copies the contents of the window with id |wid| into the given rect in the -// given context -OSStatus CGContextCopyWindowCaptureContentsToRect( - CGContextRef, CGRect, int cid, int wid, int unknown); - -// Returns the connection ID we need for the third argument to -// CGContextCopyWindowCaptureContentsToRect -int _CGSDefaultConnection(void); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // WEBKIT_GLUE_PLUGINS_COREGRAPHICS_PRIVATE_SYMBOLS_MAC_H_ diff --git a/webkit/glue/plugins/default_plugin_shared.h b/webkit/glue/plugins/default_plugin_shared.h deleted file mode 100644 index 79d06b3..0000000 --- a/webkit/glue/plugins/default_plugin_shared.h +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Thes file contains stuff that should be shared among projects that do some -// special handling with default plugin - -#ifndef WEBKIT_GLUE_PLUGINS_DEFAULT_PLUGIN_SHARED_H -#define WEBKIT_GLUE_PLUGINS_DEFAULT_PLUGIN_SHARED_H - -namespace default_plugin { - -// We use the NPNGetValue host function to send notification message to host. -// This corresponds to NPNVariable defined in npapi.h, and should be chosen so -// as to not overlap values if NPAPI is updated. - -const int kMissingPluginStatusStart = 5000; - -enum MissingPluginStatus { - MISSING_PLUGIN_AVAILABLE, - MISSING_PLUGIN_USER_STARTED_DOWNLOAD -}; - -#if defined(OS_WIN) -#include <windows.h> -const int kInstallMissingPluginMessage = WM_APP + 117; -#endif - -} // namespace default_plugin - -#endif // WEBKIT_GLUE_PLUGINS_DEFAULT_PLUGIN_SHARED_H diff --git a/webkit/glue/plugins/gtk_plugin_container.cc b/webkit/glue/plugins/gtk_plugin_container.cc deleted file mode 100644 index c80bbf1..0000000 --- a/webkit/glue/plugins/gtk_plugin_container.cc +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/gtk_plugin_container.h" - -#include <gtk/gtk.h> - -#include "base/basictypes.h" - -namespace { - -// NOTE: This class doesn't have constructors/destructors, it is created -// through GLib's object management. -class GtkPluginContainer : public GtkSocket { - public: - // Sets the requested size of the widget. - void set_size(int width, int height) { - width_ = width; - height_ = height; - } - - // Casts a widget into a GtkPluginContainer, after checking the type. - template <class T> - static GtkPluginContainer *CastChecked(T *instance) { - return G_TYPE_CHECK_INSTANCE_CAST(instance, GetType(), GtkPluginContainer); - } - - // Create and register our custom container type with GTK. - static GType GetType() { - static GType type = 0; // We only want to register our type once. - if (!type) { - static const GTypeInfo info = { - sizeof(GtkSocketClass), - NULL, NULL, - static_cast<GClassInitFunc>(&ClassInit), - NULL, NULL, - sizeof(GtkPluginContainer), - 0, &InstanceInit, - }; - type = g_type_register_static(GTK_TYPE_SOCKET, - "GtkPluginContainer", - &info, - static_cast<GTypeFlags>(0)); - } - return type; - } - - // Implementation of the class initializer. - static void ClassInit(gpointer klass, gpointer class_data_unusued) { - GtkWidgetClass* widget_class = reinterpret_cast<GtkWidgetClass*>(klass); - widget_class->size_request = &HandleSizeRequest; - } - - // Implementation of the instance initializer (constructor). - static void InstanceInit(GTypeInstance *instance, gpointer klass) { - GtkPluginContainer *container = CastChecked(instance); - container->set_size(0, 0); - } - - // Report our allocation size during size requisition. - static void HandleSizeRequest(GtkWidget* widget, - GtkRequisition* requisition) { - GtkPluginContainer *container = CastChecked(widget); - requisition->width = container->width_; - requisition->height = container->height_; - } - - int width_; - int height_; - DISALLOW_IMPLICIT_CONSTRUCTORS(GtkPluginContainer); -}; - -} // anonymous namespace - -// Create a new instance of our GTK widget object. -GtkWidget* gtk_plugin_container_new() { - return GTK_WIDGET(g_object_new(GtkPluginContainer::GetType(), NULL)); -} - -void gtk_plugin_container_set_size(GtkWidget *widget, int width, int height) { - GtkPluginContainer::CastChecked(widget)->set_size(width, height); - // Signal the parent that the size request has changed. - gtk_widget_queue_resize_no_redraw(widget); -} diff --git a/webkit/glue/plugins/gtk_plugin_container.h b/webkit/glue/plugins/gtk_plugin_container.h deleted file mode 100644 index eed6b94..0000000 --- a/webkit/glue/plugins/gtk_plugin_container.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_GTK_PLUGIN_CONTAINER_H_ -#define WEBKIT_GLUE_PLUGINS_GTK_PLUGIN_CONTAINER_H_ - -// Windowed plugins are embedded via XEmbed, which is implemented by -// GtkPlug/GtkSocket. But we want to control sizing and positioning -// directly, so we need a subclass of GtkSocket that sidesteps the -// size_request handler. -// -// The custom size_request handler just reports the size set by -// gtk_plugin_container_set_size. - -typedef struct _GtkWidget GtkWidget; - -// Return a new GtkPluginContainer. -// Intentionally GTK-style here since we're creating a custom GTK widget. -// This is a GtkSocket subclass; see its documentation for available methods. -GtkWidget* gtk_plugin_container_new(); - -// Sets the size of the GtkPluginContainer. -void gtk_plugin_container_set_size(GtkWidget *widget, int width, int height); - -#endif // WEBKIT_GLUE_PLUGINS_GTK_PLUGIN_CONTAINER_H_ diff --git a/webkit/glue/plugins/gtk_plugin_container_manager.cc b/webkit/glue/plugins/gtk_plugin_container_manager.cc deleted file mode 100644 index 2f82b24..0000000 --- a/webkit/glue/plugins/gtk_plugin_container_manager.cc +++ /dev/null @@ -1,155 +0,0 @@ -// 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 "webkit/glue/plugins/gtk_plugin_container_manager.h" - -#include <gtk/gtk.h> - -#include "base/logging.h" -#include "gfx/gtk_util.h" -#include "webkit/glue/plugins/gtk_plugin_container.h" -#include "webkit/glue/plugins/webplugin.h" - -GtkPluginContainerManager::GtkPluginContainerManager() : host_widget_(NULL) {} - -GtkPluginContainerManager::~GtkPluginContainerManager() {} - -GtkWidget* GtkPluginContainerManager::CreatePluginContainer( - gfx::PluginWindowHandle id) { - DCHECK(host_widget_); - GtkWidget *widget = gtk_plugin_container_new(); - plugin_window_to_widget_map_.insert(std::make_pair(id, widget)); - - // The Realize callback is responsible for adding the plug into the socket. - // The reason is 2-fold: - // - the plug can't be added until the socket is realized, but this may not - // happen until the socket is attached to a top-level window, which isn't the - // case for background tabs. - // - when dragging tabs, the socket gets unrealized, which breaks the XEMBED - // connection. We need to make it again when the tab is reattached, and the - // socket gets realized again. - // - // Note, the RealizeCallback relies on the plugin_window_to_widget_map_ to - // have the mapping. - g_signal_connect(widget, "realize", - G_CALLBACK(RealizeCallback), this); - - // Don't destroy the widget when the plug is removed. - g_signal_connect(widget, "plug-removed", - G_CALLBACK(gtk_true), NULL); - - gtk_container_add(GTK_CONTAINER(host_widget_), widget); - gtk_widget_show(widget); - - return widget; -} - -void GtkPluginContainerManager::DestroyPluginContainer( - gfx::PluginWindowHandle id) { - DCHECK(host_widget_); - GtkWidget* widget = MapIDToWidget(id); - if (widget) - gtk_widget_destroy(widget); - - plugin_window_to_widget_map_.erase(id); -} - -void GtkPluginContainerManager::MovePluginContainer( - const webkit_glue::WebPluginGeometry& move) { - DCHECK(host_widget_); - GtkWidget *widget = MapIDToWidget(move.window); - if (!widget) - return; - - DCHECK(!GTK_WIDGET_NO_WINDOW(widget)); - - if (!move.visible) { - gtk_widget_hide(widget); - return; - } - - gtk_widget_show(widget); - - if (!move.rects_valid) - return; - - // TODO(piman): if the widget hasn't been realized (e.g. the tab has been - // torn off and the parent gtk widget has been detached from the hierarchy), - // we lose the cutout information. - if (GTK_WIDGET_REALIZED(widget)) { - GdkRectangle clip_rect = move.clip_rect.ToGdkRectangle(); - GdkRegion* clip_region = gdk_region_rectangle(&clip_rect); - gfx::SubtractRectanglesFromRegion(clip_region, move.cutout_rects); - gdk_window_shape_combine_region(widget->window, clip_region, 0, 0); - gdk_region_destroy(clip_region); - } - - // Update the window position. Resizing is handled by WebPluginDelegate. - // TODO(deanm): Verify that we only need to move and not resize. - // TODO(evanm): we should cache the last shape and position and skip all - // of this business in the common case where nothing has changed. - int current_x, current_y; - - // Until the above TODO is resolved, we can grab the last position - // off of the GtkFixed with a bit of hackery. - GValue value = {0}; - g_value_init(&value, G_TYPE_INT); - gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget, - "x", &value); - current_x = g_value_get_int(&value); - gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget, - "y", &value); - current_y = g_value_get_int(&value); - g_value_unset(&value); - - if (move.window_rect.x() != current_x || - move.window_rect.y() != current_y) { - // Calling gtk_fixed_move unnecessarily is a no-no, as it causes the - // parent window to repaint! - gtk_fixed_move(GTK_FIXED(host_widget_), - widget, - move.window_rect.x(), - move.window_rect.y()); - } - - gtk_plugin_container_set_size(widget, - move.window_rect.width(), - move.window_rect.height()); -} - -GtkWidget* GtkPluginContainerManager::MapIDToWidget( - gfx::PluginWindowHandle id) { - PluginWindowToWidgetMap::const_iterator i = - plugin_window_to_widget_map_.find(id); - if (i != plugin_window_to_widget_map_.end()) - return i->second; - - LOG(ERROR) << "Request for widget host for unknown window id " << id; - - return NULL; -} - -gfx::PluginWindowHandle GtkPluginContainerManager::MapWidgetToID( - GtkWidget* widget) { - for (PluginWindowToWidgetMap::const_iterator i = - plugin_window_to_widget_map_.begin(); - i != plugin_window_to_widget_map_.end(); ++i) { - if (i->second == widget) - return i->first; - } - - LOG(ERROR) << "Request for id for unknown widget"; - return 0; -} - -// static -void GtkPluginContainerManager::RealizeCallback(GtkWidget* widget, - void* user_data) { - GtkPluginContainerManager* plugin_container_manager = - static_cast<GtkPluginContainerManager*>(user_data); - - gfx::PluginWindowHandle id = plugin_container_manager->MapWidgetToID(widget); - if (id) - gtk_socket_add_id(GTK_SOCKET(widget), id); -} diff --git a/webkit/glue/plugins/gtk_plugin_container_manager.h b/webkit/glue/plugins/gtk_plugin_container_manager.h deleted file mode 100644 index 7f7db8d..0000000 --- a/webkit/glue/plugins/gtk_plugin_container_manager.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_GTK_PLUGIN_CONTAINER_MANAGER_H_ -#define WEBKIT_GLUE_PLUGINS_GTK_PLUGIN_CONTAINER_MANAGER_H_ - -#include <gtk/gtk.h> -#include <map> - -#include "gfx/native_widget_types.h" - -typedef struct _GtkWidget GtkWidget; - -namespace webkit_glue { -struct WebPluginGeometry; -} - -// Helper class that creates and manages plugin containers (GtkSocket). -class GtkPluginContainerManager { - public: - GtkPluginContainerManager(); - ~GtkPluginContainerManager(); - - // Sets the widget that will host the plugin containers. Must be a GtkFixed. - void set_host_widget(GtkWidget *widget) { host_widget_ = widget; } - - // Creates a new plugin container, for a given plugin XID. - GtkWidget* CreatePluginContainer(gfx::PluginWindowHandle id); - - // Destroys a plugin container, given the plugin XID. - void DestroyPluginContainer(gfx::PluginWindowHandle id); - - // Takes an update from WebKit about a plugin's position and side and moves - // the plugin accordingly. - void MovePluginContainer(const webkit_glue::WebPluginGeometry& move); - - private: - // Maps a plugin XID to the corresponding container widget. - GtkWidget* MapIDToWidget(gfx::PluginWindowHandle id); - - // Maps a container widget to the corresponding plugin XID. - gfx::PluginWindowHandle MapWidgetToID(GtkWidget* widget); - - // Callback for when the plugin container gets realized, at which point it - // plugs the plugin XID. - static void RealizeCallback(GtkWidget *widget, void *user_data); - - // Parent of the plugin containers. - GtkWidget* host_widget_; - - // A map that associates plugin containers to the plugin XID. - typedef std::map<gfx::PluginWindowHandle, GtkWidget*> PluginWindowToWidgetMap; - PluginWindowToWidgetMap plugin_window_to_widget_map_; -}; - -#endif // WEBKIT_GLUE_PLUGINS_GTK_PLUGIN_CONTAINER_MANAGER_H_ diff --git a/webkit/glue/plugins/npapi_extension_thunk.cc b/webkit/glue/plugins/npapi_extension_thunk.cc deleted file mode 100644 index 05a9c5d..0000000 --- a/webkit/glue/plugins/npapi_extension_thunk.cc +++ /dev/null @@ -1,551 +0,0 @@ -// 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 "webkit/glue/plugins/npapi_extension_thunk.h" - -#include "base/logging.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "third_party/npapi/bindings/npapi_extensions.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/webplugin.h" -#include "webkit/glue/plugins/webplugin_delegate.h" -#include "webkit/glue/webkit_glue.h" - -// FindInstance() -// Finds a PluginInstance from an NPP. -// The caller must take a reference if needed. -static NPAPI::PluginInstance* FindInstance(NPP id) { - if (id == NULL) { - NOTREACHED(); - return NULL; - } - return static_cast<NPAPI::PluginInstance*>(id->ndata); -} - -// 2D device API --------------------------------------------------------------- - -static NPError Device2DQueryCapability(NPP id, int32_t capability, - int32_t* value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - plugin->webplugin()->delegate()->Device2DQueryCapability(capability, value); - return NPERR_NO_ERROR; - } else { - return NPERR_GENERIC_ERROR; - } -} - -static NPError Device2DQueryConfig(NPP id, - const NPDeviceConfig* request, - NPDeviceConfig* obtain) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device2DQueryConfig( - static_cast<const NPDeviceContext2DConfig*>(request), - static_cast<NPDeviceContext2DConfig*>(obtain)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DInitializeContext(NPP id, - const NPDeviceConfig* config, - NPDeviceContext* context) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device2DInitializeContext( - static_cast<const NPDeviceContext2DConfig*>(config), - static_cast<NPDeviceContext2D*>(context)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DSetStateContext(NPP id, - NPDeviceContext* context, - int32_t state, - intptr_t value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device2DSetStateContext( - static_cast<NPDeviceContext2D*>(context), state, value); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DGetStateContext(NPP id, - NPDeviceContext* context, - int32_t state, - intptr_t* value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device2DGetStateContext( - static_cast<NPDeviceContext2D*>(context), state, value); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DFlushContext(NPP id, - NPDeviceContext* context, - NPDeviceFlushContextCallbackPtr callback, - void* user_data) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - NPError err = plugin->webplugin()->delegate()->Device2DFlushContext( - id, static_cast<NPDeviceContext2D*>(context), callback, user_data); - - // Invoke the callback to inform the caller the work was done. - // TODO(brettw) this is probably not how we want this to work, this should - // happen when the frame is painted so the plugin knows when it can draw - // the next frame. - if (callback != NULL) - (*callback)(id, context, err, user_data); - - // Return any errors. - return err; - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DDestroyContext(NPP id, - NPDeviceContext* context) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device2DDestroyContext( - static_cast<NPDeviceContext2D*>(context)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DCreateBuffer(NPP id, - NPDeviceContext* context, - size_t size, - int32_t* buffer_id) { - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DDestroyBuffer(NPP id, - NPDeviceContext* context, - int32_t buffer_id) { - return NPERR_GENERIC_ERROR; -} - -static NPError Device2DMapBuffer(NPP id, - NPDeviceContext* context, - int32_t buffer_id, - NPDeviceBuffer* buffer) { - return NPERR_GENERIC_ERROR; -} - -// 3D device API --------------------------------------------------------------- - -static NPError Device3DQueryCapability(NPP id, int32_t capability, - int32_t* value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - plugin->webplugin()->delegate()->Device3DQueryCapability(capability, value); - return NPERR_NO_ERROR; - } else { - return NPERR_GENERIC_ERROR; - } -} - -static NPError Device3DQueryConfig(NPP id, - const NPDeviceConfig* request, - NPDeviceConfig* obtain) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DQueryConfig( - static_cast<const NPDeviceContext3DConfig*>(request), - static_cast<NPDeviceContext3DConfig*>(obtain)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DInitializeContext(NPP id, - const NPDeviceConfig* config, - NPDeviceContext* context) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DInitializeContext( - static_cast<const NPDeviceContext3DConfig*>(config), - static_cast<NPDeviceContext3D*>(context)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DSetStateContext(NPP id, - NPDeviceContext* context, - int32_t state, - intptr_t value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DSetStateContext( - static_cast<NPDeviceContext3D*>(context), state, value); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DGetStateContext(NPP id, - NPDeviceContext* context, - int32_t state, - intptr_t* value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DGetStateContext( - static_cast<NPDeviceContext3D*>(context), state, value); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DFlushContext(NPP id, - NPDeviceContext* context, - NPDeviceFlushContextCallbackPtr callback, - void* user_data) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DFlushContext( - id, static_cast<NPDeviceContext3D*>(context), callback, user_data); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DDestroyContext(NPP id, - NPDeviceContext* context) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DDestroyContext( - static_cast<NPDeviceContext3D*>(context)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DCreateBuffer(NPP id, - NPDeviceContext* context, - size_t size, - int32_t* buffer_id) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DCreateBuffer( - static_cast<NPDeviceContext3D*>(context), size, buffer_id); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DDestroyBuffer(NPP id, - NPDeviceContext* context, - int32_t buffer_id) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DDestroyBuffer( - static_cast<NPDeviceContext3D*>(context), buffer_id); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DMapBuffer(NPP id, - NPDeviceContext* context, - int32_t buffer_id, - NPDeviceBuffer* buffer) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DMapBuffer( - static_cast<NPDeviceContext3D*>(context), buffer_id, buffer); - } - return NPERR_GENERIC_ERROR; -} - -// Experimental 3D device API -------------------------------------------------- - -static NPError Device3DGetNumConfigs(NPP id, int32_t* num_configs) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DGetNumConfigs(num_configs); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DGetConfigAttribs(NPP id, - int32_t config, - int32_t* attrib_list) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DGetConfigAttribs( - config, - attrib_list); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DCreateContext(NPP id, - int32_t config, - const int32_t* attrib_list, - NPDeviceContext** context) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DCreateContext( - config, - attrib_list, - reinterpret_cast<NPDeviceContext3D**>(context)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DSynchronizeContext( - NPP id, - NPDeviceContext* context, - NPDeviceSynchronizationMode mode, - const int32_t* input_attrib_list, - int32_t* output_attrib_list, - NPDeviceSynchronizeContextCallbackPtr callback, - void* callback_data) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DSynchronizeContext( - id, - static_cast<NPDeviceContext3D*>(context), - mode, - input_attrib_list, - output_attrib_list, - callback, - callback_data); - } - return NPERR_GENERIC_ERROR; -} - -static NPError Device3DRegisterCallback( - NPP id, - NPDeviceContext* context, - int32_t callback_type, - NPDeviceGenericCallbackPtr callback, - void* callback_data) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->Device3DRegisterCallback( - id, - static_cast<NPDeviceContext3D*>(context), - callback_type, - callback, - callback_data); - } - return NPERR_GENERIC_ERROR; -} - -// Audio device API ------------------------------------------------------------ - -static NPError DeviceAudioQueryCapability(NPP id, int32_t capability, - int32_t* value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - plugin->webplugin()->delegate()->DeviceAudioQueryCapability(capability, - value); - return NPERR_NO_ERROR; - } else { - return NPERR_GENERIC_ERROR; - } -} - -static NPError DeviceAudioQueryConfig(NPP id, - const NPDeviceConfig* request, - NPDeviceConfig* obtain) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->DeviceAudioQueryConfig( - static_cast<const NPDeviceContextAudioConfig*>(request), - static_cast<NPDeviceContextAudioConfig*>(obtain)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError DeviceAudioInitializeContext(NPP id, - const NPDeviceConfig* config, - NPDeviceContext* context) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->DeviceAudioInitializeContext( - static_cast<const NPDeviceContextAudioConfig*>(config), - static_cast<NPDeviceContextAudio*>(context)); - } - return NPERR_GENERIC_ERROR; -} - -static NPError DeviceAudioSetStateContext(NPP id, - NPDeviceContext* context, - int32_t state, - intptr_t value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - return plugin->webplugin()->delegate()->DeviceAudioSetStateContext( - static_cast<NPDeviceContextAudio*>(context), state, value); - } - return NPERR_GENERIC_ERROR; -} - -static NPError DeviceAudioGetStateContext(NPP id, - NPDeviceContext* context, - int32_t state, - intptr_t* value) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - return plugin->webplugin()->delegate()->DeviceAudioGetStateContext( - static_cast<NPDeviceContextAudio*>(context), state, value); -} - -static NPError DeviceAudioFlushContext(NPP id, - NPDeviceContext* context, - NPDeviceFlushContextCallbackPtr callback, - void* user_data) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - return plugin->webplugin()->delegate()->DeviceAudioFlushContext( - id, static_cast<NPDeviceContextAudio*>(context), callback, user_data); -} - -static NPError DeviceAudioDestroyContext(NPP id, - NPDeviceContext* context) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - return plugin->webplugin()->delegate()->DeviceAudioDestroyContext( - static_cast<NPDeviceContextAudio*>(context)); -} -// ----------------------------------------------------------------------------- - -static NPDevice* AcquireDevice(NPP id, NPDeviceID device_id) { - static NPDevice device_2d = { - Device2DQueryCapability, - Device2DQueryConfig, - Device2DInitializeContext, - Device2DSetStateContext, - Device2DGetStateContext, - Device2DFlushContext, - Device2DDestroyContext, - Device2DCreateBuffer, - Device2DDestroyBuffer, - Device2DMapBuffer, - NULL, - NULL, - NULL, - NULL, - NULL, - }; - static NPDevice device_3d = { - Device3DQueryCapability, - Device3DQueryConfig, - Device3DInitializeContext, - Device3DSetStateContext, - Device3DGetStateContext, - Device3DFlushContext, - Device3DDestroyContext, - Device3DCreateBuffer, - Device3DDestroyBuffer, - Device3DMapBuffer, - Device3DGetNumConfigs, - Device3DGetConfigAttribs, - Device3DCreateContext, - Device3DRegisterCallback, - Device3DSynchronizeContext, - }; - static NPDevice device_audio = { - DeviceAudioQueryCapability, - DeviceAudioQueryConfig, - DeviceAudioInitializeContext, - DeviceAudioSetStateContext, - DeviceAudioGetStateContext, - DeviceAudioFlushContext, - DeviceAudioDestroyContext, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - }; - - switch (device_id) { - case NPPepper2DDevice: - return const_cast<NPDevice*>(&device_2d); - case NPPepper3DDevice: - return const_cast<NPDevice*>(&device_3d); - case NPPepperAudioDevice: - return const_cast<NPDevice*>(&device_audio); - default: - return NULL; - } -} - -static NPError ChooseFile(NPP id, - const char* mime_types, - NPChooseFileMode mode, - NPChooseFileCallback callback, - void* user_data) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin) - return NPERR_GENERIC_ERROR; - - if (!plugin->webplugin()->delegate()->ChooseFile(mime_types, - static_cast<int>(mode), - callback, user_data)) - return NPERR_GENERIC_ERROR; - - return NPERR_NO_ERROR; -} - -static void NumberOfFindResultsChanged(NPP id, int total, bool final_result) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) { - plugin->webplugin()->delegate()->NumberOfFindResultsChanged( - total, final_result); - } -} - -static void SelectedFindResultChanged(NPP id, int index) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) - plugin->webplugin()->delegate()->SelectedFindResultChanged(index); -} - -static NPWidgetExtensions* GetWidgetExtensions(NPP id) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin) - return NULL; - - return plugin->webplugin()->delegate()->GetWidgetExtensions(); -} - -static NPError NPSetCursor(NPP id, NPCursorType type) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin) - return NPERR_GENERIC_ERROR; - - return plugin->webplugin()->delegate()->SetCursor(type) ? - NPERR_NO_ERROR : NPERR_GENERIC_ERROR; -} - -static NPFontExtensions* GetFontExtensions(NPP id) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin) - return NULL; - - return plugin->webplugin()->delegate()->GetFontExtensions(); -} - -namespace NPAPI { - -NPError GetPepperExtensionsFunctions(void* value) { - static const NPNExtensions kExtensions = { - &AcquireDevice, - &NumberOfFindResultsChanged, - &SelectedFindResultChanged, - &ChooseFile, - &GetWidgetExtensions, - &NPSetCursor, - &GetFontExtensions, - }; - - // Return a pointer to the canonical function table. - NPNExtensions* extensions = const_cast<NPNExtensions*>(&kExtensions); - NPNExtensions** exts = reinterpret_cast<NPNExtensions**>(value); - *exts = extensions; - return NPERR_NO_ERROR; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/npapi_extension_thunk.h b/webkit/glue/plugins/npapi_extension_thunk.h deleted file mode 100644 index fada6bc..0000000 --- a/webkit/glue/plugins/npapi_extension_thunk.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_NPAPI_EXTENSION_THUNK_H_ -#define WEBKIT_GLUE_PLUGINS_NPAPI_EXTENSION_THUNK_H_ - -#include "third_party/npapi/bindings/npapi_extensions.h" - -// This file implements forwarding for the NPAPI "Pepper" extensions through to -// the WebPluginDelegate associated with the plugin. - -namespace NPAPI { - -// Implements NPN_GetValue for the case of NPNVPepperExtensions. The function -// pointers in the returned structure implement all the extensions. -NPError GetPepperExtensionsFunctions(void* value); - -} // namespace NPAPI - -#endif // WEBKIT_GLUE_PLUGINS_NPAPI_EXTENSION_THUNK_H_ - - diff --git a/webkit/glue/plugins/pepper_audio.cc b/webkit/glue/plugins/pepper_audio.cc deleted file mode 100644 index 1731d8a..0000000 --- a/webkit/glue/plugins/pepper_audio.cc +++ /dev/null @@ -1,389 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_audio.h" - -#include "base/logging.h" -#include "ppapi/c/dev/ppb_audio_dev.h" -#include "ppapi/c/dev/ppb_audio_trusted_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "webkit/glue/plugins/pepper_common.h" - -namespace pepper { - -namespace { - -// PPB_AudioConfig ------------------------------------------------------------- - -uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count); - -PP_Resource CreateStereo16bit(PP_Module module_id, - PP_AudioSampleRate_Dev sample_rate, - uint32_t sample_frame_count) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - // TODO(brettw): Currently we don't actually check what the hardware - // supports, so just allow sample rates of the "guaranteed working" ones. - if (sample_rate != PP_AUDIOSAMPLERATE_44100 && - sample_rate != PP_AUDIOSAMPLERATE_48000) - return 0; - - // TODO(brettw): Currently we don't actually query to get a value from the - // hardware, so just validate the range. - if (RecommendSampleFrameCount(sample_frame_count) != sample_frame_count) - return 0; - - scoped_refptr<AudioConfig> config(new AudioConfig(module, - sample_rate, - sample_frame_count)); - return config->GetReference(); -} - -uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count) { - // TODO(brettw) Currently we don't actually query to get a value from the - // hardware, so we always return the input for in-range values. - if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT) - return PP_AUDIOMINSAMPLEFRAMECOUNT; - if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT) - return PP_AUDIOMAXSAMPLEFRAMECOUNT; - return requested_sample_frame_count; -} - -PP_Bool IsAudioConfig(PP_Resource resource) { - scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(resource); - return BoolToPPBool(!!config); -} - -PP_AudioSampleRate_Dev GetSampleRate(PP_Resource config_id) { - scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id); - return config ? config->sample_rate() : PP_AUDIOSAMPLERATE_NONE; -} - -uint32_t GetSampleFrameCount(PP_Resource config_id) { - scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id); - return config ? config->sample_frame_count() : 0; -} - -const PPB_AudioConfig_Dev ppb_audioconfig = { - &CreateStereo16bit, - &RecommendSampleFrameCount, - &IsAudioConfig, - &GetSampleRate, - &GetSampleFrameCount -}; - -// PPB_Audio ------------------------------------------------------------------- - -PP_Resource Create(PP_Instance instance_id, PP_Resource config_id, - PPB_Audio_Callback user_callback, void* user_data) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return 0; - if (!user_callback) - return 0; - scoped_refptr<Audio> audio(new Audio(instance->module(), instance_id)); - if (!audio->Init(instance->delegate(), config_id, - user_callback, user_data)) - return 0; - return audio->GetReference(); -} - -PP_Bool IsAudio(PP_Resource resource) { - scoped_refptr<Audio> audio = Resource::GetAs<Audio>(resource); - return BoolToPPBool(!!audio); -} - -PP_Resource GetCurrentConfiguration(PP_Resource audio_id) { - scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id); - return audio ? audio->GetCurrentConfiguration() : 0; -} - -PP_Bool StartPlayback(PP_Resource audio_id) { - scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id); - return audio ? BoolToPPBool(audio->StartPlayback()) : PP_FALSE; -} - -PP_Bool StopPlayback(PP_Resource audio_id) { - scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id); - return audio ? BoolToPPBool(audio->StopPlayback()) : PP_FALSE; -} - -const PPB_Audio_Dev ppb_audio = { - &Create, - &IsAudio, - &GetCurrentConfiguration, - &StartPlayback, - &StopPlayback, -}; - -// PPB_AudioTrusted ------------------------------------------------------------ - -PP_Resource CreateTrusted(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return 0; - scoped_refptr<Audio> audio(new Audio(instance->module(), instance_id)); - return audio->GetReference(); -} - -int32_t Open(PP_Resource audio_id, - PP_Resource config_id, - PP_CompletionCallback created) { - scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id); - if (!audio) - return PP_ERROR_BADRESOURCE; - if (!created.func) - return PP_ERROR_BADARGUMENT; - PP_Instance instance_id = audio->pp_instance(); - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_ERROR_FAILED; - return audio->Open(instance->delegate(), config_id, created); -} - -int32_t GetSyncSocket(PP_Resource audio_id, int* sync_socket) { - scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id); - if (audio) - return audio->GetSyncSocket(sync_socket); - return PP_ERROR_BADRESOURCE; -} - -int32_t GetSharedMemory(PP_Resource audio_id, - int* shm_handle, - int32_t* shm_size) { - scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id); - if (audio) - return audio->GetSharedMemory(shm_handle, shm_size); - return PP_ERROR_BADRESOURCE; -} - -const PPB_AudioTrusted_Dev ppb_audiotrusted = { - &CreateTrusted, - &Open, - &GetSyncSocket, - &GetSharedMemory, -}; - -} // namespace - -// AudioConfig ----------------------------------------------------------------- - -AudioConfig::AudioConfig(PluginModule* module, - PP_AudioSampleRate_Dev sample_rate, - uint32_t sample_frame_count) - : Resource(module), - sample_rate_(sample_rate), - sample_frame_count_(sample_frame_count) { -} - -const PPB_AudioConfig_Dev* AudioConfig::GetInterface() { - return &ppb_audioconfig; -} - -size_t AudioConfig::BufferSize() { - // TODO(audio): as more options become available, we'll need to - // have additional code here to correctly calculate the size in - // bytes of an audio buffer. For now, only support two channel - // int16_t sample buffers. - const int kChannels = 2; - const int kSizeOfSample = sizeof(int16_t); - return static_cast<size_t>(sample_frame_count_ * kSizeOfSample * kChannels); -} - -AudioConfig* AudioConfig::AsAudioConfig() { - return this; -} - -// Audio ----------------------------------------------------------------------- - -Audio::Audio(PluginModule* module, PP_Instance instance_id) - : Resource(module), - playing_(false), - pp_instance_(instance_id), - audio_(NULL), - socket_(NULL), - shared_memory_(NULL), - shared_memory_size_(0), - callback_(NULL), - user_data_(NULL), - create_callback_pending_(false) { - create_callback_ = PP_MakeCompletionCallback(NULL, NULL); -} - -Audio::~Audio() { - // Calling ShutDown() makes sure StreamCreated cannot be called anymore. - audio_->ShutDown(); - audio_ = NULL; - - // Closing the socket causes the thread to exit - wait for it. - socket_->Close(); - if (audio_thread_.get()) { - audio_thread_->Join(); - audio_thread_.reset(); - } - - // If the completion callback hasn't fired yet, do so here - // with an error condition. - if (create_callback_pending_) { - PP_RunCompletionCallback(&create_callback_, PP_ERROR_ABORTED); - create_callback_pending_ = false; - } - // Shared memory destructor will unmap the memory automatically. -} - -const PPB_Audio_Dev* Audio::GetInterface() { - return &ppb_audio; -} - -const PPB_AudioTrusted_Dev* Audio::GetTrustedInterface() { - return &ppb_audiotrusted; -} - -Audio* Audio::AsAudio() { - return this; -} - -bool Audio::Init(PluginDelegate* plugin_delegate, - PP_Resource config_id, - PPB_Audio_Callback callback, void* user_data) { - CHECK(!audio_); - config_ = Resource::GetAs<AudioConfig>(config_id); - if (!config_) - return false; - callback_ = callback; - user_data_ = user_data; - - // When the stream is created, we'll get called back on StreamCreated(). - audio_ = plugin_delegate->CreateAudio(config_->sample_rate(), - config_->sample_frame_count(), - this); - return audio_ != NULL; -} - -int32_t Audio::Open(PluginDelegate* plugin_delegate, - PP_Resource config_id, - PP_CompletionCallback create_callback) { - DCHECK(!audio_); - config_ = Resource::GetAs<AudioConfig>(config_id); - if (!config_) - return PP_ERROR_BADRESOURCE; - - // When the stream is created, we'll get called back on StreamCreated(). - audio_ = plugin_delegate->CreateAudio(config_->sample_rate(), - config_->sample_frame_count(), - this); - if (!audio_) - return PP_ERROR_FAILED; - - // At this point, we are guaranteeing ownership of the completion - // callback. Audio promises to fire the completion callback - // once and only once. - create_callback_ = create_callback; - create_callback_pending_ = true; - return PP_ERROR_WOULDBLOCK; -} - -int32_t Audio::GetSyncSocket(int* sync_socket) { - if (socket_ != NULL) { -#if defined(OS_POSIX) - *sync_socket = socket_->handle(); -#elif defined(OS_WIN) - *sync_socket = reinterpret_cast<int>(socket_->handle()); -#else - #error "Platform not supported." -#endif - return PP_OK; - } - return PP_ERROR_FAILED; -} - -int32_t Audio::GetSharedMemory(int* shm_handle, int32_t* shm_size) { - if (shared_memory_ != NULL) { -#if defined(OS_POSIX) - *shm_handle = shared_memory_->handle().fd; -#elif defined(OS_WIN) - *shm_handle = reinterpret_cast<int>(shared_memory_->handle()); -#else - #error "Platform not supported." -#endif - *shm_size = shared_memory_size_; - return PP_OK; - } - return PP_ERROR_FAILED; -} - -bool Audio::StartPlayback() { - if (playing_) - return true; - - CHECK(!audio_thread_.get()); - if (callback_ && socket_.get()) { - audio_thread_.reset(new base::DelegateSimpleThread(this, - "plugin_audio_thread")); - audio_thread_->Start(); - } - playing_ = true; - return audio_->StartPlayback(); -} - -bool Audio::StopPlayback() { - if (!playing_) - return true; - - if (!audio_->StopPlayback()) - return false; - - if (audio_thread_.get()) { - audio_thread_->Join(); - audio_thread_.reset(); - } - playing_ = false; - return true; -} - -void Audio::StreamCreated(base::SharedMemoryHandle shared_memory_handle, - size_t shared_memory_size, - base::SyncSocket::Handle socket_handle) { - socket_.reset(new base::SyncSocket(socket_handle)); - shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false)); - shared_memory_size_ = shared_memory_size; - - // Trusted side of proxy can specify a callback to recieve handles. - if (create_callback_pending_) { - PP_RunCompletionCallback(&create_callback_, 0); - create_callback_pending_ = false; - } - - // Trusted, non-proxy audio will invoke buffer filling callback on a - // dedicated thread, see Audio::Run() below. - if (callback_) { - shared_memory_->Map(shared_memory_size_); - - // In common case StartPlayback() was called before StreamCreated(). - if (playing_) { - audio_thread_.reset(new base::DelegateSimpleThread(this, - "plugin_audio_thread")); - audio_thread_->Start(); - } - } -} - -void Audio::Run() { - int pending_data; - void* buffer = shared_memory_->memory(); - size_t buffer_size_in_bytes = config_->BufferSize(); - - while (sizeof(pending_data) == - socket_->Receive(&pending_data, sizeof(pending_data)) && - pending_data >= 0) { - // Exit the thread on pause. - if (pending_data < 0) - return; - callback_(buffer, buffer_size_in_bytes, user_data_); - } -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_audio.h b/webkit/glue/plugins/pepper_audio.h deleted file mode 100644 index 8c14666..0000000 --- a/webkit/glue/plugins/pepper_audio.h +++ /dev/null @@ -1,136 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_DEVICE_CONTEXT_AUDIO_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_DEVICE_CONTEXT_AUDIO_H_ - -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "base/shared_memory.h" -#include "base/simple_thread.h" -#include "base/sync_socket.h" -#include "ppapi/c/dev/ppb_audio_dev.h" -#include "ppapi/c/dev/ppb_audio_config_dev.h" -#include "ppapi/c/dev/ppb_audio_trusted_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace pepper { - -class PluginInstance; -class PluginModule; - -class AudioConfig : public Resource { - public: - AudioConfig(PluginModule* module, - PP_AudioSampleRate_Dev sample_rate, - uint32_t sample_frame_count); - size_t BufferSize(); - static const PPB_AudioConfig_Dev* GetInterface(); - - PP_AudioSampleRate_Dev sample_rate() { return sample_rate_; } - uint32_t sample_frame_count() { return sample_frame_count_; } - - private: - // Resource override. - virtual AudioConfig* AsAudioConfig(); - - PP_AudioSampleRate_Dev sample_rate_; - uint32_t sample_frame_count_; -}; - -class Audio : public Resource, - public PluginDelegate::PlatformAudio::Client, - public base::DelegateSimpleThread::Delegate { - public: - explicit Audio(PluginModule* module, PP_Instance instance_id); - virtual ~Audio(); - - static const PPB_Audio_Dev* GetInterface(); - static const PPB_AudioTrusted_Dev* GetTrustedInterface(); - - bool Init(PluginDelegate* plugin_delegate, - PP_Resource config_id, - PPB_Audio_Callback user_callback, void* user_data); - - int32_t Open(PluginDelegate* plugin_delegate, - PP_Resource config_id, - PP_CompletionCallback create_callback); - - PP_Resource GetCurrentConfiguration() { - return config_->GetReference(); - } - - PP_Instance pp_instance() { - return pp_instance_; - } - - int32_t GetSyncSocket(int* sync_socket); - - int32_t GetSharedMemory(int* shm_handle, int32_t* shm_size); - - bool StartPlayback(); - - bool StopPlayback(); - - // Resource override. - virtual Audio* AsAudio(); - - private: - // pepper::PluginDelegate::PlatformAudio::Client implementation. - virtual void StreamCreated(base::SharedMemoryHandle shared_memory_handle, - size_t shared_memory_size_, - base::SyncSocket::Handle socket); - // End of pepper::PluginDelegate::PlatformAudio::Client implementation. - - // Audio thread. DelegateSimpleThread::Delegate implementation. - virtual void Run(); - // End of DelegateSimpleThread::Delegate implementation. - - // True if playing the stream. - bool playing_; - - // AudioConfig used for creating this Audio object. - scoped_refptr<AudioConfig> config_; - - // Instance id - PP_Instance pp_instance_; - - // PluginDelegate audio object that we delegate audio IPC through. - PluginDelegate::PlatformAudio* audio_; - - // Socket used to notify us when audio is ready to accept new samples. This - // pointer is created in StreamCreated(). - scoped_ptr<base::SyncSocket> socket_; - - // Sample buffer in shared memory. This pointer is created in - // StreamCreated(). The memory is only mapped when the audio thread is - // created. - scoped_ptr<base::SharedMemory> shared_memory_; - - // The size of the sample buffer in bytes. - size_t shared_memory_size_; - - // When the callback is set, this thread is spawned for calling it. - scoped_ptr<base::DelegateSimpleThread> audio_thread_; - - // Callback to call when audio is ready to accept new samples. - volatile PPB_Audio_Callback callback_; - - // User data pointer passed verbatim to the callback function. - void* user_data_; - - // Is a create callback pending to fire? - bool create_callback_pending_; - - // Trusted callback invoked from StreamCreated. - PP_CompletionCallback create_callback_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_DEVICE_CONTEXT_AUDIO_H_ diff --git a/webkit/glue/plugins/pepper_buffer.cc b/webkit/glue/plugins/pepper_buffer.cc deleted file mode 100644 index cee10c9..0000000 --- a/webkit/glue/plugins/pepper_buffer.cc +++ /dev/null @@ -1,117 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_buffer.h" - -#include <algorithm> - -#include "base/logging.h" -#include "base/scoped_ptr.h" -#include "ppapi/c/dev/ppb_buffer_dev.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_resource.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" - -namespace pepper { - -namespace { - -PP_Resource Create(PP_Module module_id, int32_t size) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - scoped_refptr<Buffer> buffer(new Buffer(module)); - if (!buffer->Init(size)) - return 0; - - return buffer->GetReference(); -} - -PP_Bool IsBuffer(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<Buffer>(resource)); -} - -PP_Bool Describe(PP_Resource resource, int32_t* size_in_bytes) { - scoped_refptr<Buffer> buffer(Resource::GetAs<Buffer>(resource)); - if (!buffer) - return PP_FALSE; - buffer->Describe(size_in_bytes); - return PP_TRUE; -} - -void* Map(PP_Resource resource) { - scoped_refptr<Buffer> buffer(Resource::GetAs<Buffer>(resource)); - if (!buffer) - return NULL; - return buffer->Map(); -} - -void Unmap(PP_Resource resource) { - scoped_refptr<Buffer> buffer(Resource::GetAs<Buffer>(resource)); - if (!buffer) - return; - return buffer->Unmap(); -} - -const PPB_Buffer_Dev ppb_buffer = { - &Create, - &IsBuffer, - &Describe, - &Map, - &Unmap, -}; - -} // namespace - -Buffer::Buffer(PluginModule* module) - : Resource(module), - size_(0) { -} - -Buffer::~Buffer() { -} - -// static -const PPB_Buffer_Dev* Buffer::GetInterface() { - return &ppb_buffer; -} - -bool Buffer::Init(int size) { - if (size == 0) - return false; - Unmap(); - size_ = size; - return true; -} - -void Buffer::Describe(int* size_in_bytes) const { - *size_in_bytes = size_; -} - -void* Buffer::Map() { - if (size_ == 0) - return NULL; - - if (!is_mapped()) { - mem_buffer_.reset(new unsigned char[size_]); - memset(mem_buffer_.get(), 0, size_); - } - return mem_buffer_.get(); -} - -void Buffer::Unmap() { - mem_buffer_.reset(); -} - -void Buffer::Swap(Buffer* other) { - swap(other->mem_buffer_, mem_buffer_); - std::swap(other->size_, size_); -} - -} // namespace pepper - diff --git a/webkit/glue/plugins/pepper_buffer.h b/webkit/glue/plugins/pepper_buffer.h deleted file mode 100644 index 2f20e55..0000000 --- a/webkit/glue/plugins/pepper_buffer.h +++ /dev/null @@ -1,56 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_BUFFER_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_BUFFER_H_ - -#include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PPB_Buffer_Dev; - -namespace pepper { - -class PluginInstance; - -class Buffer : public Resource { - public: - explicit Buffer(PluginModule* module); - virtual ~Buffer(); - - int size() const { return size_; } - unsigned char* mapped_buffer() { return mem_buffer_.get(); } - - // Returns true if this buffer is mapped. False means that the buffer is - // either invalid or not mapped. - bool is_mapped() const { return !!mem_buffer_.get(); } - - // Returns a pointer to the interface implementing PPB_Buffer that is - // exposed to the plugin. - static const PPB_Buffer_Dev* GetInterface(); - - // Resource overrides. - Buffer* AsBuffer() { return this; } - - // PPB_Buffer implementation. - bool Init(int size); - void Describe(int* size_in_bytes) const; - void* Map(); - void Unmap(); - - // Swaps the guts of this buffer with another. - void Swap(Buffer* other); - - private: - int size_; - scoped_array<unsigned char> mem_buffer_; - - DISALLOW_COPY_AND_ASSIGN(Buffer); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_BUFFER_H_ - diff --git a/webkit/glue/plugins/pepper_char_set.cc b/webkit/glue/plugins/pepper_char_set.cc deleted file mode 100644 index 1411d59..0000000 --- a/webkit/glue/plugins/pepper_char_set.cc +++ /dev/null @@ -1,166 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_char_set.h" - -#include <stdlib.h> - -#include "base/i18n/icu_string_conversions.h" -#include "ppapi/c/dev/ppb_char_set_dev.h" -#include "unicode/ucnv.h" -#include "unicode/ucnv_cb.h" -#include "unicode/ucnv_err.h" -#include "unicode/ustring.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_var.h" - -namespace pepper { - -namespace { - -// Converts the given PP error handling behavior to the version in base, -// placing the result in |*result| and returning true on success. Returns false -// if the enum is invalid. -bool PPToBaseConversionError(PP_CharSet_ConversionError on_error, - base::OnStringConversionError::Type* result) { - switch (on_error) { - case PP_CHARSET_CONVERSIONERROR_FAIL: - *result = base::OnStringConversionError::FAIL; - return true; - case PP_CHARSET_CONVERSIONERROR_SKIP: - *result = base::OnStringConversionError::SKIP; - return true; - case PP_CHARSET_CONVERSIONERROR_SUBSTITUTE: - *result = base::OnStringConversionError::SUBSTITUTE; - return true; - default: - return false; - } -} - -// The "substitution" behavior of this function does not match the -// implementation in base, so we partially duplicate the code from -// icu_string_conversions.cc with the correct error handling setup required -// by this pepper interface. -char* UTF16ToCharSet(const uint16_t* utf16, uint32_t utf16_len, - const char* output_char_set, - PP_CharSet_ConversionError on_error, - uint32_t* output_length) { - *output_length = 0; - - UErrorCode status = U_ZERO_ERROR; - UConverter* converter = ucnv_open(output_char_set, &status); - if (!U_SUCCESS(status)) - return NULL; - - int encoded_max_length = UCNV_GET_MAX_BYTES_FOR_STRING(utf16_len, - ucnv_getMaxCharSize(converter)); - - // Setup our error handler. - switch (on_error) { - case PP_CHARSET_CONVERSIONERROR_FAIL: - ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, 0, - NULL, NULL, &status); - break; - case PP_CHARSET_CONVERSIONERROR_SKIP: - ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, 0, - NULL, NULL, &status); - break; - case PP_CHARSET_CONVERSIONERROR_SUBSTITUTE: { - // ICU sets the substitution char for some character sets (like latin1) - // to be the ASCII "substitution character" (26). We want to use '?' - // instead for backwards-compat with Windows behavior. - char subst_chars[32]; - int8_t subst_chars_len = 32; - ucnv_getSubstChars(converter, subst_chars, &subst_chars_len, &status); - if (subst_chars_len == 1 && subst_chars[0] == 26) { - // Override to the question mark character if possible. When using - // setSubstString, the input is a Unicode character. The function will - // try to convert it to the destination character set and fail if that - // can not be converted to the destination character set. - // - // We just ignore any failure. If the dest char set has no - // representation for '?', then we'll just stick to the ICU default - // substitution character. - UErrorCode subst_status = U_ZERO_ERROR; - UChar question_mark = '?'; - ucnv_setSubstString(converter, &question_mark, 1, &subst_status); - } - - ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SUBSTITUTE, 0, - NULL, NULL, &status); - break; - } - default: - return NULL; - } - - // ucnv_fromUChars returns size not including terminating null. - char* encoded = static_cast<char*>(malloc(encoded_max_length + 1)); - int actual_size = ucnv_fromUChars(converter, encoded, - encoded_max_length, reinterpret_cast<const UChar*>(utf16), utf16_len, - &status); - ucnv_close(converter); - if (!U_SUCCESS(status)) { - free(encoded); - return NULL; - } - encoded[actual_size] = 0; - *output_length = actual_size; - return encoded; -} - -uint16_t* CharSetToUTF16(const char* input, uint32_t input_len, - const char* input_char_set, - PP_CharSet_ConversionError on_error, - uint32_t* output_length) { - *output_length = 0; - - base::OnStringConversionError::Type base_on_error; - if (!PPToBaseConversionError(on_error, &base_on_error)) - return NULL; // Invalid enum value. - - // We can convert this call to the implementation in base to avoid code - // duplication, although this does introduce an extra copy of the data. - string16 output; - if (!base::CodepageToUTF16(std::string(input, input_len), input_char_set, - base_on_error, &output)) - return NULL; - - uint16_t* ret_buf = static_cast<uint16_t*>( - malloc((output.size() + 1) * sizeof(uint16_t))); - if (!ret_buf) - return NULL; - - *output_length = static_cast<uint32_t>(output.size()); - memcpy(ret_buf, output.c_str(), (output.size() + 1) * sizeof(uint16_t)); - return ret_buf; -} - -PP_Var GetDefaultCharSet(PP_Module pp_module) { - PluginModule* module = ResourceTracker::Get()->GetModule(pp_module); - if (!module) - return PP_MakeUndefined(); - - std::string encoding = - module->GetSomeInstance()->delegate()->GetDefaultEncoding(); - return StringVar::StringToPPVar(module, encoding); -} - -const PPB_CharSet_Dev ppb_charset = { - &UTF16ToCharSet, - &CharSetToUTF16, - &GetDefaultCharSet -}; - -} // namespace - -// static -const struct PPB_CharSet_Dev* CharSet::GetInterface() { - return &ppb_charset; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_char_set.h b/webkit/glue/plugins/pepper_char_set.h deleted file mode 100644 index 5abb54d..0000000 --- a/webkit/glue/plugins/pepper_char_set.h +++ /dev/null @@ -1,21 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_CHAR_SET_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_CHAR_SET_H_ - -struct PPB_CharSet_Dev; - -namespace pepper { - -class CharSet { - public: - // Returns a pointer to the interface implementing PPB_CharSet that is - // exposed to the plugin. - static const PPB_CharSet_Dev* GetInterface(); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_CHAR_SET_H_ diff --git a/webkit/glue/plugins/pepper_class.h b/webkit/glue/plugins/pepper_class.h deleted file mode 100644 index 35bd2c4..0000000 --- a/webkit/glue/plugins/pepper_class.h +++ /dev/null @@ -1,66 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_CLASS_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_CLASS_H_ - -#include "webkit/glue/plugins/pepper_resource.h" - -#include <string> - -#include "base/hash_tables.h" -#include "ppapi/c/ppb_class.h" - -namespace pepper { - -class PluginModule; - -class VarObjectClass : public Resource { - public: - struct Property { - explicit Property(const PP_ClassProperty& prop); - - const PP_ClassFunction method; - const PP_ClassFunction getter; - const PP_ClassFunction setter; - const bool writable; - const bool enumerable; - }; - - struct InstanceData; - - typedef base::hash_map<std::string, Property> PropertyMap; - - // Returns the PPB_Var interface for the plugin to use. - static const PPB_Class* GetInterface(); - - VarObjectClass(PluginModule* module, PP_ClassDestructor destruct, - PP_ClassFunction invoke, PP_ClassProperty* properties); - virtual ~VarObjectClass(); - - // Resource override. - virtual VarObjectClass* AsVarObjectClass() { return this; } - - const PropertyMap &properties() const { return properties_; } - - PP_ClassDestructor instance_native_destructor() { - return instance_native_destructor_; - } - - PP_ClassFunction instance_invoke() { - return instance_invoke_; - } - - private: - PropertyMap properties_; - PP_ClassDestructor instance_native_destructor_; - PP_ClassFunction instance_invoke_; - - DISALLOW_COPY_AND_ASSIGN(VarObjectClass); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_CLASS_H_ - diff --git a/webkit/glue/plugins/pepper_common.h b/webkit/glue/plugins/pepper_common.h deleted file mode 100644 index be9fe3d..0000000 --- a/webkit/glue/plugins/pepper_common.h +++ /dev/null @@ -1,24 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_COMMON_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_COMMON_H_ - -#include "ppapi/c/pp_bool.h" -#include "ppapi/c/pp_var.h" - -namespace pepper { - -inline PP_Bool BoolToPPBool(bool value) { - return value ? PP_TRUE : PP_FALSE; -} - -inline bool PPBoolToBool(PP_Bool value) { - return (PP_TRUE == value); -} - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_COMMON_H_ - diff --git a/webkit/glue/plugins/pepper_cursor_control.cc b/webkit/glue/plugins/pepper_cursor_control.cc deleted file mode 100644 index 62b4e2f..0000000 --- a/webkit/glue/plugins/pepper_cursor_control.cc +++ /dev/null @@ -1,92 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_cursor_control.h" - -#include "base/logging.h" -#include "base/ref_counted.h" -#include "ppapi/c/dev/pp_cursor_type_dev.h" -#include "ppapi/c/dev/ppb_cursor_control_dev.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_resource.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace pepper { - -namespace { - -PP_Bool SetCursor(PP_Instance instance_id, - PP_CursorType_Dev type, - PP_Resource custom_image_id, - const PP_Point* hot_spot) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - - scoped_refptr<ImageData> custom_image( - Resource::GetAs<ImageData>(custom_image_id)); - if (custom_image.get()) { - // TODO(neb): implement custom cursors. - NOTIMPLEMENTED(); - return PP_FALSE; - } - - return BoolToPPBool(instance->SetCursor(type)); -} - -PP_Bool LockCursor(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - - // TODO(neb): implement cursor locking. - return PP_FALSE; -} - -PP_Bool UnlockCursor(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - - // TODO(neb): implement cursor locking. - return PP_FALSE; -} - -PP_Bool HasCursorLock(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - - // TODO(neb): implement cursor locking. - return PP_FALSE; -} - -PP_Bool CanLockCursor(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - - // TODO(neb): implement cursor locking. - return PP_FALSE; -} - -const PPB_CursorControl_Dev cursor_control_interface = { - &SetCursor, - &LockCursor, - &UnlockCursor, - &HasCursorLock, - &CanLockCursor -}; - -} // namespace - -const PPB_CursorControl_Dev* GetCursorControlInterface() { - return &cursor_control_interface; -} - -} // namespace pepper - diff --git a/webkit/glue/plugins/pepper_cursor_control.h b/webkit/glue/plugins/pepper_cursor_control.h deleted file mode 100644 index 693fb4a..0000000 --- a/webkit/glue/plugins/pepper_cursor_control.h +++ /dev/null @@ -1,19 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_CURSOR_CONTROL_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_CURSOR_CONTROL_H_ - -struct PPB_CursorControl_Dev; - -namespace pepper { - -// There's no class implementing CursorControl so we just expose a getter for -// the interface implemented in the .cc file here. -const PPB_CursorControl_Dev* GetCursorControlInterface(); - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_CURSOR_CONTROL_H_ - diff --git a/webkit/glue/plugins/pepper_dir_contents.h b/webkit/glue/plugins/pepper_dir_contents.h deleted file mode 100644 index 661c577..0000000 --- a/webkit/glue/plugins/pepper_dir_contents.h +++ /dev/null @@ -1,18 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_DIR_CONTENTS_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_DIR_CONTENTS_H_ - -#include <vector> -#include "base/file_path.h" - -struct PepperDirEntry { - FilePath name; - bool is_dir; -}; - -typedef std::vector<PepperDirEntry> PepperDirContents; - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_DIR_CONTENTS_H_ diff --git a/webkit/glue/plugins/pepper_directory_reader.cc b/webkit/glue/plugins/pepper_directory_reader.cc deleted file mode 100644 index c476b76..0000000 --- a/webkit/glue/plugins/pepper_directory_reader.cc +++ /dev/null @@ -1,156 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_directory_reader.h" - -#include "base/logging.h" -#include "base/utf_string_conversions.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/dev/ppb_directory_reader_dev.h" -#include "webkit/glue/plugins/pepper_file_callbacks.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_file_system.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" - -namespace pepper { - -namespace { - -std::string FilePathStringToUTF8String(const FilePath::StringType& str) { -#if defined(OS_WIN) - return WideToUTF8(str); -#elif defined(OS_POSIX) - return str; -#else -#error "Unsupported platform." -#endif -} - -FilePath::StringType UTF8StringToFilePathString(const std::string& str) { -#if defined(OS_WIN) - return UTF8ToWide(str); -#elif defined(OS_POSIX) - return str; -#else -#error "Unsupported platform." -#endif -} - -PP_Resource Create(PP_Resource directory_ref_id) { - scoped_refptr<FileRef> directory_ref( - Resource::GetAs<FileRef>(directory_ref_id)); - if (!directory_ref) - return 0; - - DirectoryReader* reader = new DirectoryReader(directory_ref); - return reader->GetReference(); -} - -PP_Bool IsDirectoryReader(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<DirectoryReader>(resource)); -} - -int32_t GetNextEntry(PP_Resource reader_id, - PP_DirectoryEntry_Dev* entry, - PP_CompletionCallback callback) { - scoped_refptr<DirectoryReader> reader( - Resource::GetAs<DirectoryReader>(reader_id)); - if (!reader) - return PP_ERROR_BADRESOURCE; - - return reader->GetNextEntry(entry, callback); -} - -const PPB_DirectoryReader_Dev ppb_directoryreader = { - &Create, - &IsDirectoryReader, - &GetNextEntry -}; - -} // namespace - -DirectoryReader::DirectoryReader(FileRef* directory_ref) - : Resource(directory_ref->module()), - directory_ref_(directory_ref), - has_more_(true), - entry_(NULL) { -} - -DirectoryReader::~DirectoryReader() { -} - -const PPB_DirectoryReader_Dev* DirectoryReader::GetInterface() { - return &ppb_directoryreader; -} - -int32_t DirectoryReader::GetNextEntry(PP_DirectoryEntry_Dev* entry, - PP_CompletionCallback callback) { - if (directory_ref_->GetFileSystemType() == PP_FILESYSTEMTYPE_EXTERNAL) - return PP_ERROR_FAILED; - - entry_ = entry; - if (FillUpEntry()) { - entry_ = NULL; - return PP_OK; - } - - PluginInstance* instance = directory_ref_->GetFileSystem()->instance(); - if (!instance->delegate()->ReadDirectory( - directory_ref_->GetSystemPath(), - new FileCallbacks(instance->module()->AsWeakPtr(), - callback, NULL, NULL, this))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -void DirectoryReader::AddNewEntries( - const std::vector<base::FileUtilProxy::Entry>& entries, bool has_more) { - DCHECK(!entries.empty()); - has_more_ = has_more; - std::string dir_path = directory_ref_->GetPath(); - if (dir_path[dir_path.size() - 1] != '/') - dir_path += '/'; - FilePath::StringType dir_file_path = UTF8StringToFilePathString(dir_path); - for (std::vector<base::FileUtilProxy::Entry>::const_iterator it = - entries.begin(); it != entries.end(); it++) { - base::FileUtilProxy::Entry entry; - entry.name = dir_file_path + it->name; - entry.is_directory = it->is_directory; - entries_.push(entry); - } - - FillUpEntry(); - entry_ = NULL; -} - -bool DirectoryReader::FillUpEntry() { - DCHECK(entry_); - if (!entries_.empty()) { - base::FileUtilProxy::Entry dir_entry = entries_.front(); - entries_.pop(); - if (entry_->file_ref) - ResourceTracker::Get()->UnrefResource(entry_->file_ref); - FileRef* file_ref = new FileRef(module(), directory_ref_->GetFileSystem(), - FilePathStringToUTF8String(dir_entry.name)); - entry_->file_ref = file_ref->GetReference(); - entry_->file_type = - (dir_entry.is_directory ? PP_FILETYPE_DIRECTORY : PP_FILETYPE_REGULAR); - return true; - } - - if (!has_more_) { - entry_->file_ref = 0; - return true; - } - - return false; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_directory_reader.h b/webkit/glue/plugins/pepper_directory_reader.h deleted file mode 100644 index 38496bb..0000000 --- a/webkit/glue/plugins/pepper_directory_reader.h +++ /dev/null @@ -1,51 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_DIRECTORY_READER_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_DIRECTORY_READER_H_ - -#include <queue> - -#include "base/file_util_proxy.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PP_CompletionCallback; -struct PP_DirectoryEntry_Dev; -struct PPB_DirectoryReader_Dev; - -namespace pepper { - -class FileRef; - -class DirectoryReader : public Resource { - public: - explicit DirectoryReader(FileRef* directory_ref); - virtual ~DirectoryReader(); - - // Returns a pointer to the interface implementing PPB_DirectoryReader that - // is exposed to the plugin. - static const PPB_DirectoryReader_Dev* GetInterface(); - - // Resource overrides. - DirectoryReader* AsDirectoryReader() { return this; } - - // PPB_DirectoryReader implementation. - int32_t GetNextEntry(PP_DirectoryEntry_Dev* entry, - PP_CompletionCallback callback); - - void AddNewEntries(const std::vector<base::FileUtilProxy::Entry>& entries, - bool has_more); - - private: - bool FillUpEntry(); - - scoped_refptr<FileRef> directory_ref_; - std::queue<base::FileUtilProxy::Entry> entries_; - bool has_more_; - PP_DirectoryEntry_Dev* entry_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_DIRECTORY_READER_H_ diff --git a/webkit/glue/plugins/pepper_error_util.cc b/webkit/glue/plugins/pepper_error_util.cc deleted file mode 100644 index 7472d4a..0000000 --- a/webkit/glue/plugins/pepper_error_util.cc +++ /dev/null @@ -1,33 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_error_util.h" - -#include "ppapi/c/pp_errors.h" - -namespace pepper { - -int PlatformFileErrorToPepperError(base::PlatformFileError error_code) { - switch (error_code) { - case base::PLATFORM_FILE_OK: - return PP_OK; - case base::PLATFORM_FILE_ERROR_EXISTS: - return PP_ERROR_FILEEXISTS; - case base::PLATFORM_FILE_ERROR_NOT_FOUND: - return PP_ERROR_FILENOTFOUND; - case base::PLATFORM_FILE_ERROR_ACCESS_DENIED: - case base::PLATFORM_FILE_ERROR_SECURITY: - return PP_ERROR_NOACCESS; - case base::PLATFORM_FILE_ERROR_NO_MEMORY: - return PP_ERROR_NOMEMORY; - case base::PLATFORM_FILE_ERROR_NO_SPACE: - return PP_ERROR_NOSPACE; - case base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY: - return PP_ERROR_FAILED; - default: - return PP_ERROR_FAILED; - } -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_error_util.h b/webkit/glue/plugins/pepper_error_util.h deleted file mode 100644 index 12e715c..0000000 --- a/webkit/glue/plugins/pepper_error_util.h +++ /dev/null @@ -1,16 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_ERROR_UTIL_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_ERROR_UTIL_H_ - -#include "base/platform_file.h" - -namespace pepper { - -int PlatformFileErrorToPepperError(base::PlatformFileError error_code); - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_ERROR_UTIL_H_ diff --git a/webkit/glue/plugins/pepper_event_conversion.cc b/webkit/glue/plugins/pepper_event_conversion.cc deleted file mode 100644 index 300592f..0000000 --- a/webkit/glue/plugins/pepper_event_conversion.cc +++ /dev/null @@ -1,301 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_event_conversion.h" - -#include "base/i18n/char_iterator.h" -#include "base/logging.h" -#include "base/scoped_ptr.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "base/utf_string_conversion_utils.h" -#include "ppapi/c/pp_input_event.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "webkit/glue/plugins/pepper_common.h" - -using WebKit::WebInputEvent; -using WebKit::WebKeyboardEvent; -using WebKit::WebMouseEvent; -using WebKit::WebMouseWheelEvent; - -namespace { - -PP_InputEvent_Type ConvertEventTypes(WebInputEvent::Type wetype) { - switch (wetype) { - case WebInputEvent::MouseDown: - return PP_INPUTEVENT_TYPE_MOUSEDOWN; - case WebInputEvent::MouseUp: - return PP_INPUTEVENT_TYPE_MOUSEUP; - case WebInputEvent::MouseMove: - return PP_INPUTEVENT_TYPE_MOUSEMOVE; - case WebInputEvent::MouseEnter: - return PP_INPUTEVENT_TYPE_MOUSEENTER; - case WebInputEvent::MouseLeave: - return PP_INPUTEVENT_TYPE_MOUSELEAVE; - case WebInputEvent::MouseWheel: - return PP_INPUTEVENT_TYPE_MOUSEWHEEL; - case WebInputEvent::RawKeyDown: - return PP_INPUTEVENT_TYPE_RAWKEYDOWN; - case WebInputEvent::KeyDown: - return PP_INPUTEVENT_TYPE_KEYDOWN; - case WebInputEvent::KeyUp: - return PP_INPUTEVENT_TYPE_KEYUP; - case WebInputEvent::Char: - return PP_INPUTEVENT_TYPE_CHAR; - case WebInputEvent::Undefined: - default: - return PP_INPUTEVENT_TYPE_UNDEFINED; - } -} - -// Generates a PP_InputEvent with the fields common to all events, as well as -// the event type from the given web event. Event-specific fields will be zero -// initialized. -PP_InputEvent GetPPEventWithCommonFieldsAndType( - const WebInputEvent& web_event) { - PP_InputEvent result; - memset(&result, 0, sizeof(PP_InputEvent)); - result.type = ConvertEventTypes(web_event.type); - // TODO(brettw) http://code.google.com/p/chromium/issues/detail?id=57448 - // This should use a tick count rather than the wall clock time that WebKit - // uses. - result.time_stamp = web_event.timeStampSeconds; - return result; -} - -void AppendKeyEvent(const WebInputEvent& event, - std::vector<PP_InputEvent>* pp_events) { - const WebKeyboardEvent& key_event = - reinterpret_cast<const WebKeyboardEvent&>(event); - PP_InputEvent result = GetPPEventWithCommonFieldsAndType(event); - result.u.key.modifier = key_event.modifiers; - result.u.key.key_code = key_event.windowsKeyCode; - pp_events->push_back(result); -} - -void AppendCharEvent(const WebInputEvent& event, - std::vector<PP_InputEvent>* pp_events) { - const WebKeyboardEvent& key_event = - reinterpret_cast<const WebKeyboardEvent&>(event); - - // This is a bit complex, the input event will normally just have one 16-bit - // character in it, but may be zero or more than one. The text array is - // just padded with 0 values for the unused ones, but is not necessarily - // null-terminated. - // - // Here we see how many UTF-16 characters we have. - size_t utf16_char_count = 0; - while (utf16_char_count < WebKeyboardEvent::textLengthCap && - key_event.text[utf16_char_count]) - utf16_char_count++; - - // Make a separate PP_InputEvent for each Unicode character in the input. - base::UTF16CharIterator iter(key_event.text, utf16_char_count); - while (!iter.end()) { - PP_InputEvent result = GetPPEventWithCommonFieldsAndType(event); - result.u.character.modifier = key_event.modifiers; - - std::string utf8_char; - base::WriteUnicodeCharacter(iter.get(), &utf8_char); - base::strlcpy(result.u.character.text, utf8_char.c_str(), - sizeof(result.u.character.text)); - - pp_events->push_back(result); - iter.Advance(); - } -} - -void AppendMouseEvent(const WebInputEvent& event, - std::vector<PP_InputEvent>* pp_events) { - COMPILE_ASSERT(static_cast<int>(WebMouseEvent::ButtonNone) == - static_cast<int>(PP_INPUTEVENT_MOUSEBUTTON_NONE), - MouseNone); - COMPILE_ASSERT(static_cast<int>(WebMouseEvent::ButtonLeft) == - static_cast<int>(PP_INPUTEVENT_MOUSEBUTTON_LEFT), - MouseLeft); - COMPILE_ASSERT(static_cast<int>(WebMouseEvent::ButtonRight) == - static_cast<int>(PP_INPUTEVENT_MOUSEBUTTON_RIGHT), - MouseRight); - COMPILE_ASSERT(static_cast<int>(WebMouseEvent::ButtonMiddle) == - static_cast<int>(PP_INPUTEVENT_MOUSEBUTTON_MIDDLE), - MouseMiddle); - - const WebMouseEvent& mouse_event = - reinterpret_cast<const WebMouseEvent&>(event); - PP_InputEvent result = GetPPEventWithCommonFieldsAndType(event); - result.u.mouse.modifier = mouse_event.modifiers; - result.u.mouse.button = - static_cast<PP_InputEvent_MouseButton>(mouse_event.button); - result.u.mouse.x = static_cast<float>(mouse_event.x); - result.u.mouse.y = static_cast<float>(mouse_event.y); - result.u.mouse.click_count = mouse_event.clickCount; - pp_events->push_back(result); -} - -void AppendMouseWheelEvent(const WebInputEvent& event, - std::vector<PP_InputEvent>* pp_events) { - const WebMouseWheelEvent& mouse_wheel_event = - reinterpret_cast<const WebMouseWheelEvent&>(event); - PP_InputEvent result = GetPPEventWithCommonFieldsAndType(event); - result.u.wheel.modifier = mouse_wheel_event.modifiers; - result.u.wheel.delta_x = mouse_wheel_event.deltaX; - result.u.wheel.delta_y = mouse_wheel_event.deltaY; - result.u.wheel.wheel_ticks_x = mouse_wheel_event.wheelTicksX; - result.u.wheel.wheel_ticks_y = mouse_wheel_event.wheelTicksY; - result.u.wheel.scroll_by_page = - pepper::BoolToPPBool(!!mouse_wheel_event.scrollByPage); - pp_events->push_back(result); -} - - -WebKeyboardEvent* BuildKeyEvent(const PP_InputEvent& event) { - WebKeyboardEvent* key_event = new WebKeyboardEvent(); - switch (event.type) { - case PP_INPUTEVENT_TYPE_RAWKEYDOWN: - key_event->type = WebInputEvent::RawKeyDown; - break; - case PP_INPUTEVENT_TYPE_KEYDOWN: - key_event->type = WebInputEvent::KeyDown; - break; - case PP_INPUTEVENT_TYPE_KEYUP: - key_event->type = WebInputEvent::KeyUp; - break; - default: - NOTREACHED(); - } - key_event->timeStampSeconds = event.time_stamp; - key_event->modifiers = event.u.key.modifier; - key_event->windowsKeyCode = event.u.key.key_code; - return key_event; -} - -WebKeyboardEvent* BuildCharEvent(const PP_InputEvent& event) { - WebKeyboardEvent* key_event = new WebKeyboardEvent(); - key_event->type = WebInputEvent::Char; - key_event->timeStampSeconds = event.time_stamp; - key_event->modifiers = event.u.character.modifier; - - // Make sure to not read beyond the buffer in case some bad code doesn't - // NULL-terminate it (this is called from plugins). - size_t text_length_cap = WebKeyboardEvent::textLengthCap; - size_t text_len = 0; - while (text_len < text_length_cap && event.u.character.text[text_len]) - text_len++; - string16 text16 = UTF8ToUTF16(std::string(event.u.character.text, text_len)); - - memset(key_event->text, 0, text_length_cap); - memset(key_event->unmodifiedText, 0, text_length_cap); - for (size_t i = 0; - i < std::min(text_length_cap, text16.size()); - ++i) - key_event->text[i] = text16[i]; - return key_event; -} - -WebMouseEvent* BuildMouseEvent(const PP_InputEvent& event) { - WebMouseEvent* mouse_event = new WebMouseEvent(); - switch (event.type) { - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - mouse_event->type = WebInputEvent::MouseDown; - break; - case PP_INPUTEVENT_TYPE_MOUSEUP: - mouse_event->type = WebInputEvent::MouseUp; - break; - case PP_INPUTEVENT_TYPE_MOUSEMOVE: - mouse_event->type = WebInputEvent::MouseMove; - break; - case PP_INPUTEVENT_TYPE_MOUSEENTER: - mouse_event->type = WebInputEvent::MouseEnter; - break; - case PP_INPUTEVENT_TYPE_MOUSELEAVE: - mouse_event->type = WebInputEvent::MouseLeave; - break; - default: - NOTREACHED(); - } - mouse_event->timeStampSeconds = event.time_stamp; - mouse_event->modifiers = event.u.mouse.modifier; - mouse_event->button = - static_cast<WebMouseEvent::Button>(event.u.mouse.button); - mouse_event->x = static_cast<int>(event.u.mouse.x); - mouse_event->y = static_cast<int>(event.u.mouse.y); - mouse_event->clickCount = event.u.mouse.click_count; - return mouse_event; -} - -WebMouseWheelEvent* BuildMouseWheelEvent(const PP_InputEvent& event) { - WebMouseWheelEvent* mouse_wheel_event = new WebMouseWheelEvent(); - mouse_wheel_event->type = WebInputEvent::MouseWheel; - mouse_wheel_event->timeStampSeconds = event.time_stamp; - mouse_wheel_event->modifiers = event.u.wheel.modifier; - mouse_wheel_event->deltaX = event.u.wheel.delta_x; - mouse_wheel_event->deltaY = event.u.wheel.delta_y; - mouse_wheel_event->wheelTicksX = event.u.wheel.wheel_ticks_x; - mouse_wheel_event->wheelTicksY = event.u.wheel.wheel_ticks_y; - mouse_wheel_event->scrollByPage = event.u.wheel.scroll_by_page; - return mouse_wheel_event; -} - -} // namespace - -namespace pepper { - -void CreatePPEvent(const WebInputEvent& event, - std::vector<PP_InputEvent>* pp_events) { - pp_events->clear(); - - switch (event.type) { - case WebInputEvent::MouseDown: - case WebInputEvent::MouseUp: - case WebInputEvent::MouseMove: - case WebInputEvent::MouseEnter: - case WebInputEvent::MouseLeave: - AppendMouseEvent(event, pp_events); - break; - case WebInputEvent::MouseWheel: - AppendMouseWheelEvent(event, pp_events); - break; - case WebInputEvent::RawKeyDown: - case WebInputEvent::KeyDown: - case WebInputEvent::KeyUp: - AppendKeyEvent(event, pp_events); - break; - case WebInputEvent::Char: - AppendCharEvent(event, pp_events); - break; - case WebInputEvent::Undefined: - default: - break; - } -} - -WebInputEvent* CreateWebInputEvent(const PP_InputEvent& event) { - scoped_ptr<WebInputEvent> web_input_event; - switch (event.type) { - case PP_INPUTEVENT_TYPE_UNDEFINED: - return NULL; - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - case PP_INPUTEVENT_TYPE_MOUSEUP: - case PP_INPUTEVENT_TYPE_MOUSEMOVE: - case PP_INPUTEVENT_TYPE_MOUSEENTER: - case PP_INPUTEVENT_TYPE_MOUSELEAVE: - web_input_event.reset(BuildMouseEvent(event)); - break; - case PP_INPUTEVENT_TYPE_MOUSEWHEEL: - web_input_event.reset(BuildMouseWheelEvent(event)); - break; - case PP_INPUTEVENT_TYPE_RAWKEYDOWN: - case PP_INPUTEVENT_TYPE_KEYDOWN: - case PP_INPUTEVENT_TYPE_KEYUP: - web_input_event.reset(BuildKeyEvent(event)); - break; - case PP_INPUTEVENT_TYPE_CHAR: - web_input_event.reset(BuildCharEvent(event)); - break; - } - - return web_input_event.release(); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_event_conversion.h b/webkit/glue/plugins/pepper_event_conversion.h deleted file mode 100644 index 9eab3e4..0000000 --- a/webkit/glue/plugins/pepper_event_conversion.h +++ /dev/null @@ -1,30 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_EVENT_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_EVENT_H_ - -#include <vector> - -struct PP_InputEvent; - -namespace WebKit { -class WebInputEvent; -} - -namespace pepper { - -// Converts the given WebKit event to one or possibly multiple PP_InputEvents. -// The generated events will be filled into the given vector. On failure, no -// events will ge generated and the vector will be empty. -void CreatePPEvent(const WebKit::WebInputEvent& event, - std::vector<PP_InputEvent>* pp_events); - -// Creates a WebInputEvent from the given PP_InputEvent. If it fails, returns -// NULL. The caller owns the created object on success. -WebKit::WebInputEvent* CreateWebInputEvent(const PP_InputEvent& event); - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_EVENT_H_ diff --git a/webkit/glue/plugins/pepper_file_callbacks.cc b/webkit/glue/plugins/pepper_file_callbacks.cc deleted file mode 100644 index e24927a..0000000 --- a/webkit/glue/plugins/pepper_file_callbacks.cc +++ /dev/null @@ -1,99 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_file_callbacks.h" - -#include "base/file_path.h" -#include "base/logging.h" -#include "ppapi/c/dev/ppb_file_system_dev.h" -#include "ppapi/c/dev/pp_file_info_dev.h" -#include "ppapi/c/pp_errors.h" -#include "webkit/glue/plugins/pepper_directory_reader.h" -#include "webkit/glue/plugins/pepper_error_util.h" -#include "webkit/glue/plugins/pepper_file_system.h" -#include "webkit/fileapi/file_system_types.h" - -namespace pepper { - -FileCallbacks::FileCallbacks(const base::WeakPtr<PluginModule>& module, - PP_CompletionCallback callback, - PP_FileInfo_Dev* info, - scoped_refptr<FileSystem> file_system, - scoped_refptr<DirectoryReader> directory_reader) - : module_(module), - callback_(callback), - info_(info), - file_system_(file_system), - directory_reader_(directory_reader) { -} - -FileCallbacks::~FileCallbacks() {} - -void FileCallbacks::DidSucceed() { - if (!module_.get() || !callback_.func) - return; - - PP_RunCompletionCallback(&callback_, PP_OK); -} - -void FileCallbacks::DidReadMetadata( - const base::PlatformFileInfo& file_info) { - if (!module_.get() || !callback_.func) - return; - - DCHECK(info_); - DCHECK(file_system_); - info_->size = file_info.size; - info_->creation_time = file_info.creation_time.ToDoubleT(); - info_->last_access_time = file_info.last_accessed.ToDoubleT(); - info_->last_modified_time = file_info.last_modified.ToDoubleT(); - info_->system_type = file_system_->type(); - if (file_info.is_directory) - info_->type = PP_FILETYPE_DIRECTORY; - else - info_->type = PP_FILETYPE_REGULAR; - - PP_RunCompletionCallback(&callback_, PP_OK); -} - -void FileCallbacks::DidReadDirectory( - const std::vector<base::FileUtilProxy::Entry>& entries, bool has_more) { - if (!module_.get() || !callback_.func) - return; - - DCHECK(directory_reader_); - directory_reader_->AddNewEntries(entries, has_more); - - PP_RunCompletionCallback(&callback_, PP_OK); -} - -void FileCallbacks::DidOpenFileSystem(const std::string&, - const FilePath& root_path) { - if (!module_.get() || !callback_.func) - return; - - DCHECK(file_system_); - file_system_->set_root_path(root_path); - file_system_->set_opened(true); - - PP_RunCompletionCallback(&callback_, PP_OK); -} - -void FileCallbacks::DidFail(base::PlatformFileError error_code) { - RunCallback(error_code); -} - -void FileCallbacks::DidWrite(int64 bytes, bool complete) { - NOTREACHED(); -} - -void FileCallbacks::RunCallback(base::PlatformFileError error_code) { - if (!module_.get() || !callback_.func) - return; - - PP_RunCompletionCallback( - &callback_, pepper::PlatformFileErrorToPepperError(error_code)); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_file_callbacks.h b/webkit/glue/plugins/pepper_file_callbacks.h deleted file mode 100644 index d4a92f2..0000000 --- a/webkit/glue/plugins/pepper_file_callbacks.h +++ /dev/null @@ -1,57 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_FILE_CALLBACKS_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_FILE_CALLBACKS_H_ - -#include "base/platform_file.h" -#include "base/weak_ptr.h" -#include "ppapi/c/pp_completion_callback.h" -#include "webkit/fileapi/file_system_callback_dispatcher.h" - -struct PP_FileInfo_Dev; - -namespace base { -class FilePath; -} - -namespace pepper { - -class DirectoryReader; -class FileSystem; -class PluginModule; - -// Instances of this class are deleted by FileSystemDispatcher. -class FileCallbacks : public fileapi::FileSystemCallbackDispatcher { - public: - FileCallbacks(const base::WeakPtr<PluginModule>& module, - PP_CompletionCallback callback, - PP_FileInfo_Dev* info, - scoped_refptr<FileSystem> file_system, - scoped_refptr<DirectoryReader> directory_reader); - virtual ~FileCallbacks(); - - // FileSystemCallbackDispatcher implementation. - virtual void DidSucceed(); - virtual void DidReadMetadata(const base::PlatformFileInfo& file_info); - virtual void DidReadDirectory( - const std::vector<base::FileUtilProxy::Entry>& entries, bool has_more); - virtual void DidOpenFileSystem(const std::string&, - const FilePath& root_path); - virtual void DidFail(base::PlatformFileError error_code); - virtual void DidWrite(int64 bytes, bool complete); - - private: - void RunCallback(base::PlatformFileError error_code); - - base::WeakPtr<PluginModule> module_; - PP_CompletionCallback callback_; - PP_FileInfo_Dev* info_; - scoped_refptr<FileSystem> file_system_; - scoped_refptr<DirectoryReader> directory_reader_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_FILE_CALLBACKS_H_ diff --git a/webkit/glue/plugins/pepper_file_chooser.cc b/webkit/glue/plugins/pepper_file_chooser.cc deleted file mode 100644 index 2b54790..0000000 --- a/webkit/glue/plugins/pepper_file_chooser.cc +++ /dev/null @@ -1,161 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_file_chooser.h" - -#include <string> -#include <vector> - -#include "base/logging.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserCompletion.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserParams.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebVector.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" -#include "webkit/glue/webkit_glue.h" - -using WebKit::WebCString; -using WebKit::WebFileChooserCompletion; -using WebKit::WebFileChooserParams; -using WebKit::WebString; -using WebKit::WebVector; - -namespace pepper { - -namespace { - -PP_Resource Create(PP_Instance instance_id, - const PP_FileChooserOptions_Dev* options) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return 0; - - if ((options->mode != PP_FILECHOOSERMODE_OPEN) && - (options->mode != PP_FILECHOOSERMODE_OPENMULTIPLE)) - return 0; - - FileChooser* chooser = new FileChooser(instance, options); - return chooser->GetReference(); -} - -PP_Bool IsFileChooser(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<FileChooser>(resource)); -} - -int32_t Show(PP_Resource chooser_id, PP_CompletionCallback callback) { - scoped_refptr<FileChooser> chooser( - Resource::GetAs<FileChooser>(chooser_id)); - if (!chooser) - return PP_ERROR_BADRESOURCE; - - return chooser->Show(callback); -} - -PP_Resource GetNextChosenFile(PP_Resource chooser_id) { - scoped_refptr<FileChooser> chooser( - Resource::GetAs<FileChooser>(chooser_id)); - if (!chooser) - return 0; - - scoped_refptr<FileRef> file_ref(chooser->GetNextChosenFile()); - if (!file_ref) - return 0; - - return file_ref->GetReference(); -} - -const PPB_FileChooser_Dev ppb_filechooser = { - &Create, - &IsFileChooser, - &Show, - &GetNextChosenFile -}; - -class FileChooserCompletionImpl : public WebFileChooserCompletion { - public: - FileChooserCompletionImpl(pepper::FileChooser* file_chooser) - : file_chooser_(file_chooser) { - DCHECK(file_chooser_); - } - - virtual ~FileChooserCompletionImpl() {} - - virtual void didChooseFile(const WebVector<WebString>& file_names) { - std::vector<std::string> files; - for (size_t i = 0; i < file_names.size(); i++) - files.push_back(file_names[i].utf8().data()); - - file_chooser_->StoreChosenFiles(files); - } - - private: - FileChooser* file_chooser_; -}; - -} // namespace - -FileChooser::FileChooser(PluginInstance* instance, - const PP_FileChooserOptions_Dev* options) - : Resource(instance->module()), - delegate_(instance->delegate()), - mode_(options->mode), - accept_mime_types_(options->accept_mime_types), - completion_callback_() { -} - -FileChooser::~FileChooser() { -} - -// static -const PPB_FileChooser_Dev* FileChooser::GetInterface() { - return &ppb_filechooser; -} - -void FileChooser::StoreChosenFiles(const std::vector<std::string>& files) { - next_chosen_file_index_ = 0; - std::vector<std::string>::const_iterator end_it = files.end(); - for (std::vector<std::string>::const_iterator it = files.begin(); - it != end_it; it++) { - chosen_files_.push_back(make_scoped_refptr( - new FileRef(module(), FilePath().AppendASCII(*it)))); - } - - if (!completion_callback_.func) - return; - - PP_CompletionCallback callback = {0}; - std::swap(callback, completion_callback_); - PP_RunCompletionCallback(&callback, 0); -} - -int32_t FileChooser::Show(PP_CompletionCallback callback) { - DCHECK((mode_ == PP_FILECHOOSERMODE_OPEN) || - (mode_ == PP_FILECHOOSERMODE_OPENMULTIPLE)); - DCHECK(!completion_callback_.func); - completion_callback_ = callback; - - WebFileChooserParams params; - params.multiSelect = (mode_ == PP_FILECHOOSERMODE_OPENMULTIPLE); - params.acceptTypes = WebString::fromUTF8(accept_mime_types_); - params.directory = false; - - return delegate_->RunFileChooser( - params, new FileChooserCompletionImpl(this)); -} - -scoped_refptr<FileRef> FileChooser::GetNextChosenFile() { - if (next_chosen_file_index_ >= chosen_files_.size()) - return NULL; - - return chosen_files_[next_chosen_file_index_++]; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_file_chooser.h b/webkit/glue/plugins/pepper_file_chooser.h deleted file mode 100644 index 664f934..0000000 --- a/webkit/glue/plugins/pepper_file_chooser.h +++ /dev/null @@ -1,52 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_FILE_CHOOSER_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_FILE_CHOOSER_H_ - -#include <string> -#include <vector> - -#include "base/scoped_ptr.h" -#include "ppapi/c/dev/ppb_file_chooser_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace pepper { - -class PluginDelegate; -class PluginInstance; - -class FileChooser : public Resource { - public: - FileChooser(PluginInstance* instance, - const PP_FileChooserOptions_Dev* options); - virtual ~FileChooser(); - - // Returns a pointer to the interface implementing PPB_FileChooser that is - // exposed to the plugin. - static const PPB_FileChooser_Dev* GetInterface(); - - // Resource overrides. - FileChooser* AsFileChooser() { return this; } - - // Stores the list of selected files. - void StoreChosenFiles(const std::vector<std::string>& files); - - // PPB_FileChooser implementation. - int32_t Show(PP_CompletionCallback callback); - scoped_refptr<FileRef> GetNextChosenFile(); - - private: - PluginDelegate* delegate_; - PP_FileChooserMode_Dev mode_; - std::string accept_mime_types_; - PP_CompletionCallback completion_callback_; - std::vector< scoped_refptr<FileRef> > chosen_files_; - size_t next_chosen_file_index_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_FILE_CHOOSER_H_ diff --git a/webkit/glue/plugins/pepper_file_io.cc b/webkit/glue/plugins/pepper_file_io.cc deleted file mode 100644 index 1d3d66e..0000000 --- a/webkit/glue/plugins/pepper_file_io.cc +++ /dev/null @@ -1,433 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_file_io.h" - -#include "base/callback.h" -#include "base/file_util.h" -#include "base/file_util_proxy.h" -#include "base/message_loop_proxy.h" -#include "base/platform_file.h" -#include "base/logging.h" -#include "base/time.h" -#include "ppapi/c/dev/ppb_file_io_dev.h" -#include "ppapi/c/dev/ppb_file_io_trusted_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" - -namespace pepper { - -namespace { - -PP_Resource Create(PP_Module module_id) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - FileIO* file_io = new FileIO(module); - return file_io->GetReference(); -} - -PP_Bool IsFileIO(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<FileIO>(resource)); -} - -int32_t Open(PP_Resource file_io_id, - PP_Resource file_ref_id, - int32_t open_flags, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_ERROR_BADRESOURCE; - - return file_io->Open(file_ref, open_flags, callback); -} - -int32_t Query(PP_Resource file_io_id, - PP_FileInfo_Dev* info, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->Query(info, callback); -} - -int32_t Touch(PP_Resource file_io_id, - PP_Time last_access_time, - PP_Time last_modified_time, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->Touch(last_access_time, last_modified_time, callback); -} - -int32_t Read(PP_Resource file_io_id, - int64_t offset, - char* buffer, - int32_t bytes_to_read, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->Read(offset, buffer, bytes_to_read, callback); -} - -int32_t Write(PP_Resource file_io_id, - int64_t offset, - const char* buffer, - int32_t bytes_to_write, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->Write(offset, buffer, bytes_to_write, callback); -} - -int32_t SetLength(PP_Resource file_io_id, - int64_t length, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->SetLength(length, callback); -} - -int32_t Flush(PP_Resource file_io_id, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->Flush(callback); -} - -void Close(PP_Resource file_io_id) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return; - file_io->Close(); -} - -const PPB_FileIO_Dev ppb_fileio = { - &Create, - &IsFileIO, - &Open, - &Query, - &Touch, - &Read, - &Write, - &SetLength, - &Flush, - &Close -}; - -int32_t GetOSFileDescriptor(PP_Resource file_io_id) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->GetOSFileDescriptor(); -} - -int32_t WillWrite(PP_Resource file_io_id, - int64_t offset, - int32_t bytes_to_write, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->WillWrite(offset, bytes_to_write, callback); -} - -int32_t WillSetLength(PP_Resource file_io_id, - int64_t length, - PP_CompletionCallback callback) { - scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id)); - if (!file_io) - return PP_ERROR_BADRESOURCE; - return file_io->WillSetLength(length, callback); -} - -const PPB_FileIOTrusted_Dev ppb_fileiotrusted = { - &GetOSFileDescriptor, - &WillWrite, - &WillSetLength -}; - -int PlatformFileErrorToPepperError(base::PlatformFileError error_code) { - switch (error_code) { - case base::PLATFORM_FILE_OK: - return PP_OK; - case base::PLATFORM_FILE_ERROR_EXISTS: - return PP_ERROR_FILEEXISTS; - case base::PLATFORM_FILE_ERROR_NOT_FOUND: - return PP_ERROR_FILENOTFOUND; - case base::PLATFORM_FILE_ERROR_ACCESS_DENIED: - return PP_ERROR_NOACCESS; - case base::PLATFORM_FILE_ERROR_NO_MEMORY: - return PP_ERROR_NOMEMORY; - case base::PLATFORM_FILE_ERROR_NO_SPACE: - return PP_ERROR_NOSPACE; - case base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY: - NOTREACHED(); - return PP_ERROR_FAILED; - default: - return PP_ERROR_FAILED; - } -} - -} // namespace - -FileIO::FileIO(PluginModule* module) - : Resource(module), - delegate_(module->GetSomeInstance()->delegate()), - ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)), - file_(base::kInvalidPlatformFileValue), - callback_(), - info_(NULL) { -} - -FileIO::~FileIO() { - Close(); -} - -// static -const PPB_FileIO_Dev* FileIO::GetInterface() { - return &ppb_fileio; -} - -// static -const PPB_FileIOTrusted_Dev* FileIO::GetTrustedInterface() { - return &ppb_fileiotrusted; -} - -int32_t FileIO::Open(FileRef* file_ref, - int32_t open_flags, - PP_CompletionCallback callback) { - if (file_ != base::kInvalidPlatformFileValue) - return PP_ERROR_FAILED; - - DCHECK(!callback_.func); - callback_ = callback; - - int flags = 0; - if (open_flags & PP_FILEOPENFLAG_READ) - flags |= base::PLATFORM_FILE_READ; - if (open_flags & PP_FILEOPENFLAG_WRITE) { - flags |= base::PLATFORM_FILE_WRITE; - flags |= base::PLATFORM_FILE_WRITE_ATTRIBUTES; - } - - if (open_flags & PP_FILEOPENFLAG_TRUNCATE) { - DCHECK(open_flags & PP_FILEOPENFLAG_WRITE); - flags |= base::PLATFORM_FILE_TRUNCATE; - } else if (open_flags & PP_FILEOPENFLAG_CREATE) { - if (open_flags & PP_FILEOPENFLAG_EXCLUSIVE) - flags |= base::PLATFORM_FILE_CREATE; - else - flags |= base::PLATFORM_FILE_OPEN_ALWAYS; - } else - flags |= base::PLATFORM_FILE_OPEN; - - file_system_type_ = file_ref->GetFileSystemType(); - if (!delegate_->AsyncOpenFile( - file_ref->GetSystemPath(), flags, - callback_factory_.NewCallback(&FileIO::AsyncOpenFileCallback))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t FileIO::Query(PP_FileInfo_Dev* info, - PP_CompletionCallback callback) { - if (file_ == base::kInvalidPlatformFileValue) - return PP_ERROR_FAILED; - - DCHECK(!callback_.func); - callback_ = callback; - - DCHECK(!info_); - DCHECK(info); - info_ = info; - - if (!base::FileUtilProxy::GetFileInfoFromPlatformFile( - delegate_->GetFileThreadMessageLoopProxy(), file_, - callback_factory_.NewCallback(&FileIO::QueryInfoCallback))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t FileIO::Touch(PP_Time last_access_time, - PP_Time last_modified_time, - PP_CompletionCallback callback) { - if (file_ == base::kInvalidPlatformFileValue) - return PP_ERROR_FAILED; - - DCHECK(!callback_.func); - callback_ = callback; - - if (!base::FileUtilProxy::Touch( - delegate_->GetFileThreadMessageLoopProxy(), - file_, base::Time::FromDoubleT(last_access_time), - base::Time::FromDoubleT(last_modified_time), - callback_factory_.NewCallback(&FileIO::StatusCallback))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t FileIO::Read(int64_t offset, - char* buffer, - int32_t bytes_to_read, - PP_CompletionCallback callback) { - if (file_ == base::kInvalidPlatformFileValue) - return PP_ERROR_FAILED; - - DCHECK(!callback_.func); - callback_ = callback; - - if (!base::FileUtilProxy::Read( - delegate_->GetFileThreadMessageLoopProxy(), - file_, offset, buffer, bytes_to_read, - callback_factory_.NewCallback(&FileIO::ReadWriteCallback))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t FileIO::Write(int64_t offset, - const char* buffer, - int32_t bytes_to_write, - PP_CompletionCallback callback) { - if (file_ == base::kInvalidPlatformFileValue) - return PP_ERROR_FAILED; - - DCHECK(!callback_.func); - callback_ = callback; - - if (!base::FileUtilProxy::Write( - delegate_->GetFileThreadMessageLoopProxy(), - file_, offset, buffer, bytes_to_write, - callback_factory_.NewCallback(&FileIO::ReadWriteCallback))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t FileIO::SetLength(int64_t length, - PP_CompletionCallback callback) { - if (file_ == base::kInvalidPlatformFileValue) - return PP_ERROR_FAILED; - - DCHECK(!callback_.func); - callback_ = callback; - - if (!base::FileUtilProxy::Truncate( - delegate_->GetFileThreadMessageLoopProxy(), - file_, length, - callback_factory_.NewCallback(&FileIO::StatusCallback))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t FileIO::Flush(PP_CompletionCallback callback) { - if (file_ == base::kInvalidPlatformFileValue) - return PP_ERROR_FAILED; - - DCHECK(!callback_.func); - callback_ = callback; - - if (!base::FileUtilProxy::Flush( - delegate_->GetFileThreadMessageLoopProxy(), file_, - callback_factory_.NewCallback(&FileIO::StatusCallback))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -void FileIO::Close() { - if (file_ != base::kInvalidPlatformFileValue) - base::FileUtilProxy::Close( - delegate_->GetFileThreadMessageLoopProxy(), file_, NULL); -} - -int32_t FileIO::GetOSFileDescriptor() { -#if defined(OS_POSIX) - return file_; -#elif defined(OS_WIN) - return reinterpret_cast<uintptr_t>(file_); -#else -#error "Platform not supported." -#endif -} - -int32_t FileIO::WillWrite(int64_t offset, - int32_t bytes_to_write, - PP_CompletionCallback callback) { - // TODO(dumi): implement me - return PP_OK; -} - -int32_t FileIO::WillSetLength(int64_t length, - PP_CompletionCallback callback) { - // TODO(dumi): implement me - return PP_OK; -} - -void FileIO::RunPendingCallback(int result) { - if (!callback_.func) - return; - - PP_CompletionCallback callback = {0}; - std::swap(callback, callback_); - PP_RunCompletionCallback(&callback, result); -} - -void FileIO::StatusCallback(base::PlatformFileError error_code) { - RunPendingCallback(PlatformFileErrorToPepperError(error_code)); -} - -void FileIO::AsyncOpenFileCallback(base::PlatformFileError error_code, - base::PlatformFile file) { - DCHECK(file_ == base::kInvalidPlatformFileValue); - file_ = file; - RunPendingCallback(PlatformFileErrorToPepperError(error_code)); -} - -void FileIO::QueryInfoCallback(base::PlatformFileError error_code, - const base::PlatformFileInfo& file_info) { - DCHECK(info_); - if (error_code == base::PLATFORM_FILE_OK) { - info_->size = file_info.size; - info_->creation_time = file_info.creation_time.ToDoubleT(); - info_->last_access_time = file_info.last_accessed.ToDoubleT(); - info_->last_modified_time = file_info.last_modified.ToDoubleT(); - info_->system_type = file_system_type_; - if (file_info.is_directory) - info_->type = PP_FILETYPE_DIRECTORY; - else - info_->type = PP_FILETYPE_REGULAR; - } - RunPendingCallback(PlatformFileErrorToPepperError(error_code)); -} - -void FileIO::ReadWriteCallback(base::PlatformFileError error_code, - int bytes_read_or_written) { - if (error_code != base::PLATFORM_FILE_OK) - RunPendingCallback(PlatformFileErrorToPepperError(error_code)); - else - RunPendingCallback(bytes_read_or_written); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_file_io.h b/webkit/glue/plugins/pepper_file_io.h deleted file mode 100644 index 6fee92d..0000000 --- a/webkit/glue/plugins/pepper_file_io.h +++ /dev/null @@ -1,94 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_FILE_IO_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_FILE_IO_H_ - -#include "base/file_path.h" -#include "base/platform_file.h" -#include "base/scoped_callback_factory.h" -#include "base/scoped_ptr.h" -#include "ppapi/c/dev/pp_file_info_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_time.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PP_CompletionCallback; -struct PPB_FileIO_Dev; -struct PPB_FileIOTrusted_Dev; - -namespace pepper { - -class PluginModule; - -class FileIO : public Resource { - public: - explicit FileIO(PluginModule* module); - virtual ~FileIO(); - - // Returns a pointer to the interface implementing PPB_FileIO that is exposed - // to the plugin. - static const PPB_FileIO_Dev* GetInterface(); - - // Returns a pointer to the interface implementing PPB_FileIOTrusted that is - // exposed to the plugin. - static const PPB_FileIOTrusted_Dev* GetTrustedInterface(); - - // Resource overrides. - FileIO* AsFileIO() { return this; } - - // PPB_FileIO implementation. - int32_t Open(FileRef* file_ref, - int32_t open_flags, - PP_CompletionCallback callback); - int32_t Query(PP_FileInfo_Dev* info, - PP_CompletionCallback callback); - int32_t Touch(PP_Time last_access_time, - PP_Time last_modified_time, - PP_CompletionCallback callback); - int32_t Read(int64_t offset, - char* buffer, - int32_t bytes_to_read, - PP_CompletionCallback callback); - int32_t Write(int64_t offset, - const char* buffer, - int32_t bytes_to_write, - PP_CompletionCallback callback); - int32_t SetLength(int64_t length, - PP_CompletionCallback callback); - int32_t Flush(PP_CompletionCallback callback); - void Close(); - - // PPB_FileIOTrusted implementation. - int32_t GetOSFileDescriptor(); - int32_t WillWrite(int64_t offset, - int32_t bytes_to_write, - PP_CompletionCallback callback); - int32_t WillSetLength(int64_t length, - PP_CompletionCallback callback); - - void RunPendingCallback(int result); - void StatusCallback(base::PlatformFileError error_code); - void AsyncOpenFileCallback(base::PlatformFileError error_code, - base::PlatformFile file); - void QueryInfoCallback(base::PlatformFileError error_code, - const base::PlatformFileInfo& file_info); - void ReadWriteCallback(base::PlatformFileError error_code, - int bytes_read_or_written); - - private: - PluginDelegate* delegate_; - base::ScopedCallbackFactory<FileIO> callback_factory_; - - base::PlatformFile file_; - PP_FileSystemType_Dev file_system_type_; - - PP_CompletionCallback callback_; - PP_FileInfo_Dev* info_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_FILE_IO_H_ diff --git a/webkit/glue/plugins/pepper_file_ref.cc b/webkit/glue/plugins/pepper_file_ref.cc deleted file mode 100644 index 6068a29..0000000 --- a/webkit/glue/plugins/pepper_file_ref.cc +++ /dev/null @@ -1,343 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_file_ref.h" - -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "ppapi/c/pp_errors.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_directory_reader.h" -#include "webkit/glue/plugins/pepper_file_callbacks.h" -#include "webkit/glue/plugins/pepper_file_system.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_var.h" - -namespace pepper { - -namespace { - -bool IsValidLocalPath(const std::string& path) { - // The path must start with '/' - if (path.empty() || path[0] != '/') - return false; - - // The path must contain valid UTF-8 characters. - if (!IsStringUTF8(path)) - return false; - - return true; -} - -void TrimTrailingSlash(std::string* path) { - // If this path ends with a slash, then normalize it away unless path is the - // root path. - if (path->size() > 1 && path->at(path->size() - 1) == '/') - path->erase(path->size() - 1, 1); -} - -PP_Resource Create(PP_Resource file_system_id, const char* path) { - scoped_refptr<FileSystem> file_system( - Resource::GetAs<FileSystem>(file_system_id)); - if (!file_system) - return 0; - - if (!file_system->instance()) - return 0; - - std::string validated_path(path); - if (!IsValidLocalPath(validated_path)) - return 0; - TrimTrailingSlash(&validated_path); - - FileRef* file_ref = new FileRef(file_system->instance()->module(), - file_system, - validated_path); - return file_ref->GetReference(); -} - -PP_Bool IsFileRef(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<FileRef>(resource)); -} - -PP_FileSystemType_Dev GetFileSystemType(PP_Resource file_ref_id) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_FILESYSTEMTYPE_EXTERNAL; - return file_ref->GetFileSystemType(); -} - -PP_Var GetName(PP_Resource file_ref_id) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_MakeUndefined(); - return StringVar::StringToPPVar(file_ref->module(), file_ref->GetName()); -} - -PP_Var GetPath(PP_Resource file_ref_id) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_MakeUndefined(); - - if (file_ref->GetFileSystemType() == PP_FILESYSTEMTYPE_EXTERNAL) - return PP_MakeUndefined(); - - return StringVar::StringToPPVar(file_ref->module(), file_ref->GetPath()); -} - -PP_Resource GetParent(PP_Resource file_ref_id) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return 0; - - if (file_ref->GetFileSystemType() == PP_FILESYSTEMTYPE_EXTERNAL) - return 0; - - scoped_refptr<FileRef> parent_ref(file_ref->GetParent()); - if (!parent_ref) - return 0; - - return parent_ref->GetReference(); -} - -int32_t MakeDirectory(PP_Resource directory_ref_id, - PP_Bool make_ancestors, - PP_CompletionCallback callback) { - scoped_refptr<FileRef> directory_ref( - Resource::GetAs<FileRef>(directory_ref_id)); - if (!directory_ref) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<FileSystem> file_system = directory_ref->GetFileSystem(); - if (!file_system || !file_system->opened() || - (file_system->type() == PP_FILESYSTEMTYPE_EXTERNAL)) - return PP_ERROR_NOACCESS; - - PluginInstance* instance = file_system->instance(); - if (!instance->delegate()->MakeDirectory( - directory_ref->GetSystemPath(), PPBoolToBool(make_ancestors), - new FileCallbacks(instance->module()->AsWeakPtr(), - callback, NULL, NULL, NULL))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t Query(PP_Resource file_ref_id, - PP_FileInfo_Dev* info, - PP_CompletionCallback callback) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<FileSystem> file_system = file_ref->GetFileSystem(); - if (!file_system || !file_system->opened() || - (file_system->type() == PP_FILESYSTEMTYPE_EXTERNAL)) - return PP_ERROR_NOACCESS; - - PluginInstance* instance = file_system->instance(); - if (!instance->delegate()->Query( - file_ref->GetSystemPath(), - new FileCallbacks(instance->module()->AsWeakPtr(), - callback, info, file_system, NULL))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t Touch(PP_Resource file_ref_id, - PP_Time last_access_time, - PP_Time last_modified_time, - PP_CompletionCallback callback) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<FileSystem> file_system = file_ref->GetFileSystem(); - if (!file_system || !file_system->opened() || - (file_system->type() == PP_FILESYSTEMTYPE_EXTERNAL)) - return PP_ERROR_NOACCESS; - - PluginInstance* instance = file_system->instance(); - if (!instance->delegate()->Touch( - file_ref->GetSystemPath(), base::Time::FromDoubleT(last_access_time), - base::Time::FromDoubleT(last_modified_time), - new FileCallbacks(instance->module()->AsWeakPtr(), - callback, NULL, NULL, NULL))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t Delete(PP_Resource file_ref_id, - PP_CompletionCallback callback) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<FileSystem> file_system = file_ref->GetFileSystem(); - if (!file_system || !file_system->opened() || - (file_system->type() == PP_FILESYSTEMTYPE_EXTERNAL)) - return PP_ERROR_NOACCESS; - - PluginInstance* instance = file_system->instance(); - if (!instance->delegate()->Delete( - file_ref->GetSystemPath(), - new FileCallbacks(instance->module()->AsWeakPtr(), - callback, NULL, NULL, NULL))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -int32_t Rename(PP_Resource file_ref_id, - PP_Resource new_file_ref_id, - PP_CompletionCallback callback) { - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<FileRef> new_file_ref( - Resource::GetAs<FileRef>(new_file_ref_id)); - if (!new_file_ref) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<FileSystem> file_system = file_ref->GetFileSystem(); - if (!file_system || !file_system->opened() || - (file_system != new_file_ref->GetFileSystem()) || - (file_system->type() == PP_FILESYSTEMTYPE_EXTERNAL)) - return PP_ERROR_NOACCESS; - - PluginInstance* instance = file_system->instance(); - if (!instance->delegate()->Rename( - file_ref->GetSystemPath(), new_file_ref->GetSystemPath(), - new FileCallbacks(instance->module()->AsWeakPtr(), - callback, NULL, NULL, NULL))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -const PPB_FileRef_Dev ppb_fileref = { - &Create, - &IsFileRef, - &GetFileSystemType, - &GetName, - &GetPath, - &GetParent, - &MakeDirectory, - &Query, - &Touch, - &Delete, - &Rename -}; - -} // namespace - -FileRef::FileRef() - : Resource(NULL), - file_system_(NULL) { -} - -FileRef::FileRef(PluginModule* module, - scoped_refptr<FileSystem> file_system, - const std::string& validated_path) - : Resource(module), - file_system_(file_system), - virtual_path_(validated_path) { -} - -FileRef::FileRef(PluginModule* module, - const FilePath& external_file_path) - : Resource(module), - file_system_(NULL), - system_path_(external_file_path) { -} - -FileRef::~FileRef() { -} - -// static -const PPB_FileRef_Dev* FileRef::GetInterface() { - return &ppb_fileref; -} - -std::string FileRef::GetName() const { - if (GetFileSystemType() == PP_FILESYSTEMTYPE_EXTERNAL) { - FilePath::StringType path = system_path_.value(); - size_t pos = path.rfind(FilePath::kSeparators[0]); - DCHECK(pos != FilePath::StringType::npos); -#if defined(OS_WIN) - return WideToUTF8(path.substr(pos + 1)); -#elif defined(OS_POSIX) - return path.substr(pos + 1); -#else -#error "Unsupported platform." -#endif - } - - if (virtual_path_.size() == 1 && virtual_path_[0] == '/') - return virtual_path_; - - // There should always be a leading slash at least! - size_t pos = virtual_path_.rfind('/'); - DCHECK(pos != std::string::npos); - - return virtual_path_.substr(pos + 1); -} - -scoped_refptr<FileRef> FileRef::GetParent() { - if (GetFileSystemType() == PP_FILESYSTEMTYPE_EXTERNAL) - return new FileRef(); - - // There should always be a leading slash at least! - size_t pos = virtual_path_.rfind('/'); - DCHECK(pos != std::string::npos); - - // If the path is "/foo", then we want to include the slash. - if (pos == 0) - pos++; - std::string parent_path = virtual_path_.substr(0, pos); - - FileRef* parent_ref = new FileRef(module(), file_system_, parent_path); - return parent_ref; -} - -scoped_refptr<FileSystem> FileRef::GetFileSystem() const { - return file_system_; -} - -PP_FileSystemType_Dev FileRef::GetFileSystemType() const { - if (!file_system_) - return PP_FILESYSTEMTYPE_EXTERNAL; - - return file_system_->type(); -} - -std::string FileRef::GetPath() const { - return virtual_path_; -} - -FilePath FileRef::GetSystemPath() const { - if (GetFileSystemType() == PP_FILESYSTEMTYPE_EXTERNAL) - return system_path_; - - // Since |virtual_path_| starts with a '/', it is considered an absolute path - // on POSIX systems. We need to remove the '/' before calling Append() or we - // will run into a DCHECK. - FilePath virtual_file_path( -#if defined(OS_WIN) - UTF8ToWide(virtual_path_.substr(1)) -#elif defined(OS_POSIX) - virtual_path_.substr(1) -#else -#error "Unsupported platform." -#endif - ); - return file_system_->root_path().Append(virtual_file_path); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_file_ref.h b/webkit/glue/plugins/pepper_file_ref.h deleted file mode 100644 index 88020c1..0000000 --- a/webkit/glue/plugins/pepper_file_ref.h +++ /dev/null @@ -1,62 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_FILE_REF_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_FILE_REF_H_ - -#include <string> - -#include "base/file_path.h" -#include "ppapi/c/dev/ppb_file_ref_dev.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace pepper { - -class FileSystem; -class PluginInstance; -class PluginModule; - -class FileRef : public Resource { - public: - FileRef(); - FileRef(PluginModule* module, - scoped_refptr<FileSystem> file_system, - const std::string& validated_path); - FileRef(PluginModule* module, - const FilePath& external_file_path); - virtual ~FileRef(); - - // Returns a pointer to the interface implementing PPB_FileRef that is - // exposed to the plugin. - static const PPB_FileRef_Dev* GetInterface(); - - // Resource overrides. - FileRef* AsFileRef() { return this; } - - // PPB_FileRef implementation. - std::string GetName() const; - scoped_refptr<FileRef> GetParent(); - - // Returns the file system to which this FileRef belongs. - scoped_refptr<FileSystem> GetFileSystem() const; - - // Returns the type of the file system to which this FileRef belongs. - PP_FileSystemType_Dev GetFileSystemType() const; - - // Returns the virtual path (i.e., the path that the pepper plugin sees) - // corresponding to this file. - std::string GetPath() const; - - // Returns the system path corresponding to this file. - FilePath GetSystemPath() const; - - private: - scoped_refptr<FileSystem> file_system_; - std::string virtual_path_; // UTF-8 encoded - FilePath system_path_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_FILE_REF_H_ diff --git a/webkit/glue/plugins/pepper_file_system.cc b/webkit/glue/plugins/pepper_file_system.cc deleted file mode 100644 index 9262798..0000000 --- a/webkit/glue/plugins/pepper_file_system.cc +++ /dev/null @@ -1,85 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_file_system.h" - -#include "base/ref_counted.h" -#include "ppapi/c/dev/ppb_file_system_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebElement.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginContainer.h" -#include "webkit/fileapi/file_system_types.h" -#include "webkit/glue/plugins/pepper_directory_reader.h" -#include "webkit/glue/plugins/pepper_file_callbacks.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_resource.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" - -namespace pepper { - -namespace { - -PP_Resource Create(PP_Instance instance, PP_FileSystemType_Dev type) { - PluginInstance* plugin_instance = - ResourceTracker::Get()->GetInstance(instance); - if (!plugin_instance) - return 0; - - FileSystem* file_system = new FileSystem(plugin_instance, type); - return file_system->GetReference(); -} - -int32_t Open(PP_Resource file_system_id, - int64 expected_size, - PP_CompletionCallback callback) { - scoped_refptr<FileSystem> file_system( - Resource::GetAs<FileSystem>(file_system_id)); - if (!file_system) - return PP_ERROR_BADRESOURCE; - - if (file_system->opened()) - return PP_OK; - - if ((file_system->type() != PP_FILESYSTEMTYPE_LOCALPERSISTENT) && - (file_system->type() != PP_FILESYSTEMTYPE_LOCALTEMPORARY)) - return PP_ERROR_FAILED; - - PluginInstance* instance = file_system->instance(); - fileapi::FileSystemType file_system_type = - (file_system->type() == PP_FILESYSTEMTYPE_LOCALTEMPORARY ? - fileapi::kFileSystemTypeTemporary : - fileapi::kFileSystemTypePersistent); - if (!instance->delegate()->OpenFileSystem( - instance->container()->element().document().frame()->url(), - file_system_type, expected_size, - new FileCallbacks(instance->module()->AsWeakPtr(), - callback, NULL, file_system, NULL))) - return PP_ERROR_FAILED; - - return PP_ERROR_WOULDBLOCK; -} - -const PPB_FileSystem_Dev ppb_filesystem = { - &Create, - &Open -}; - -} // namespace - -FileSystem::FileSystem(PluginInstance* instance, PP_FileSystemType_Dev type) - : Resource(instance->module()), - instance_(instance), - type_(type), - opened_(false) { -} - -const PPB_FileSystem_Dev* FileSystem::GetInterface() { - return &ppb_filesystem; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_file_system.h b/webkit/glue/plugins/pepper_file_system.h deleted file mode 100644 index 97f1c7d..0000000 --- a/webkit/glue/plugins/pepper_file_system.h +++ /dev/null @@ -1,44 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_FILE_SYSTEM_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_FILE_SYSTEM_H_ - -#include "base/basictypes.h" -#include "base/file_path.h" -#include "ppapi/c/dev/pp_file_info_dev.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PPB_FileSystem_Dev; - -namespace pepper { - -class PluginInstance; - -class FileSystem : public Resource { - public: - // Returns a pointer to the interface implementing PPB_FileSystem that is - // exposed to the plugin. - static const PPB_FileSystem_Dev* GetInterface(); - - FileSystem(PluginInstance* instance, PP_FileSystemType_Dev type); - FileSystem* AsFileSystem() { return this; } - - PluginInstance* instance() { return instance_; } - PP_FileSystemType_Dev type() { return type_; } - const FilePath& root_path() const { return root_path_; } - void set_root_path(const FilePath& root_path) { root_path_ = root_path; } - bool opened() const { return opened_; } - void set_opened(bool opened) { opened_ = opened; } - - private: - PluginInstance* instance_; - PP_FileSystemType_Dev type_; - FilePath root_path_; - bool opened_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_FILE_SYSTEM_H_ diff --git a/webkit/glue/plugins/pepper_font.cc b/webkit/glue/plugins/pepper_font.cc deleted file mode 100644 index 553c8ed..0000000 --- a/webkit/glue/plugins/pepper_font.cc +++ /dev/null @@ -1,294 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_font.h" - -#include "base/logging.h" -#include "base/utf_string_conversions.h" -#include "ppapi/c/dev/ppb_font_dev.h" -#include "ppapi/c/pp_rect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFont.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFontDescription.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFloatPoint.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFloatRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebTextRun.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_string.h" -#include "webkit/glue/plugins/pepper_var.h" -#include "webkit/glue/webkit_glue.h" - -using WebKit::WebFloatPoint; -using WebKit::WebFloatRect; -using WebKit::WebFont; -using WebKit::WebFontDescription; -using WebKit::WebRect; -using WebKit::WebTextRun; - -namespace pepper { - -namespace { - -bool IsPPFontDescriptionValid(const PP_FontDescription_Dev& desc) { - // Check validity of UTF-8. - if (desc.face.type != PP_VARTYPE_STRING && - desc.face.type != PP_VARTYPE_UNDEFINED) - return false; - - // Check enum ranges. - if (static_cast<int>(desc.family) < PP_FONTFAMILY_DEFAULT || - static_cast<int>(desc.family) > PP_FONTFAMILY_MONOSPACE) - return false; - if (static_cast<int>(desc.weight) < PP_FONTWEIGHT_100 || - static_cast<int>(desc.weight) > PP_FONTWEIGHT_900) - return false; - - // Check for excessive sizes which may cause layout to get confused. - if (desc.size > 200) - return false; - - return true; -} - -// The PP_* version lacks "None", so is just one value shifted from the -// WebFontDescription version. These values are checked in -// PPFontDescToWebFontDesc to make sure the conversion is correct. This is a -// macro so it can also be used in the COMPILE_ASSERTS. -#define PP_FONTFAMILY_TO_WEB_FONTFAMILY(f) \ - static_cast<WebFontDescription::GenericFamily>(f + 1) - -// Assumes the given PP_FontDescription has been validated. -WebFontDescription PPFontDescToWebFontDesc(const PP_FontDescription_Dev& font) { - // Verify that the enums match so we can just static cast. - COMPILE_ASSERT(static_cast<int>(WebFontDescription::Weight100) == - static_cast<int>(PP_FONTWEIGHT_100), - FontWeight100); - COMPILE_ASSERT(static_cast<int>(WebFontDescription::Weight900) == - static_cast<int>(PP_FONTWEIGHT_900), - FontWeight900); - COMPILE_ASSERT(WebFontDescription::GenericFamilyStandard == - PP_FONTFAMILY_TO_WEB_FONTFAMILY(PP_FONTFAMILY_DEFAULT), - StandardFamily); - COMPILE_ASSERT(WebFontDescription::GenericFamilySerif == - PP_FONTFAMILY_TO_WEB_FONTFAMILY(PP_FONTFAMILY_SERIF), - SerifFamily); - COMPILE_ASSERT(WebFontDescription::GenericFamilySansSerif == - PP_FONTFAMILY_TO_WEB_FONTFAMILY(PP_FONTFAMILY_SANSSERIF), - SansSerifFamily); - COMPILE_ASSERT(WebFontDescription::GenericFamilyMonospace == - PP_FONTFAMILY_TO_WEB_FONTFAMILY(PP_FONTFAMILY_MONOSPACE), - MonospaceFamily); - - WebFontDescription result; - scoped_refptr<StringVar> face_name(StringVar::FromPPVar(font.face)); - if (face_name) - result.family = UTF8ToUTF16(face_name->value()); - result.genericFamily = PP_FONTFAMILY_TO_WEB_FONTFAMILY(font.family); - result.size = static_cast<float>(font.size); - result.italic = PPBoolToBool(font.italic); - result.smallCaps = PPBoolToBool(font.small_caps); - result.weight = static_cast<WebFontDescription::Weight>(font.weight); - result.letterSpacing = static_cast<short>(font.letter_spacing); - result.wordSpacing = static_cast<short>(font.word_spacing); - return result; -} - -// Converts the given PP_TextRun to a WebTextRun, returning true on success. -// False means the input was invalid. -bool PPTextRunToWebTextRun(const PP_TextRun_Dev* run, WebTextRun* output) { - scoped_refptr<StringVar> text_string(StringVar::FromPPVar(run->text)); - if (!text_string) - return false; - *output = WebTextRun(UTF8ToUTF16(text_string->value()), - PPBoolToBool(run->rtl), - PPBoolToBool(run->override_direction)); - return true; -} - -PP_Resource Create(PP_Module module_id, - const PP_FontDescription_Dev* description) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - if (!IsPPFontDescriptionValid(*description)) - return 0; - - scoped_refptr<Font> font(new Font(module, *description)); - return font->GetReference(); -} - -PP_Bool IsFont(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<Font>(resource).get()); -} - -PP_Bool Describe(PP_Resource font_id, - PP_FontDescription_Dev* description, - PP_FontMetrics_Dev* metrics) { - scoped_refptr<Font> font(Resource::GetAs<Font>(font_id)); - if (!font.get()) - return PP_FALSE; - return BoolToPPBool(font->Describe(description, metrics)); -} - -PP_Bool DrawTextAt(PP_Resource font_id, - PP_Resource image_data, - const PP_TextRun_Dev* text, - const PP_Point* position, - uint32_t color, - const PP_Rect* clip, - PP_Bool image_data_is_opaque) { - scoped_refptr<Font> font(Resource::GetAs<Font>(font_id)); - if (!font.get()) - return PP_FALSE; - return BoolToPPBool(font->DrawTextAt(image_data, text, position, color, clip, - PPBoolToBool(image_data_is_opaque))); -} - -int32_t MeasureText(PP_Resource font_id, const PP_TextRun_Dev* text) { - scoped_refptr<Font> font(Resource::GetAs<Font>(font_id)); - if (!font.get()) - return -1; - return font->MeasureText(text); -} - -uint32_t CharacterOffsetForPixel(PP_Resource font_id, - const PP_TextRun_Dev* text, - int32_t pixel_position) { - scoped_refptr<Font> font(Resource::GetAs<Font>(font_id)); - if (!font.get()) - return false; - return font->CharacterOffsetForPixel(text, pixel_position); -} - -int32_t PixelOffsetForCharacter(PP_Resource font_id, - const PP_TextRun_Dev* text, - uint32_t char_offset) { - scoped_refptr<Font> font(Resource::GetAs<Font>(font_id)); - if (!font.get()) - return false; - return font->PixelOffsetForCharacter(text, char_offset); -} - -const PPB_Font_Dev ppb_font = { - &Create, - &IsFont, - &Describe, - &DrawTextAt, - &MeasureText, - &CharacterOffsetForPixel, - &PixelOffsetForCharacter -}; - -} // namespace - -Font::Font(PluginModule* module, const PP_FontDescription_Dev& desc) - : Resource(module) { - WebFontDescription web_font_desc = PPFontDescToWebFontDesc(desc); - font_.reset(WebFont::create(web_font_desc)); -} - -Font::~Font() { -} - -// static -const PPB_Font_Dev* Font::GetInterface() { - return &ppb_font; -} - -bool Font::Describe(PP_FontDescription_Dev* description, - PP_FontMetrics_Dev* metrics) { - if (description->face.type != PP_VARTYPE_UNDEFINED) - return false; - - WebFontDescription web_desc = font_->fontDescription(); - - // While converting the other way in PPFontDescToWebFontDesc we validated - // that the enums can be casted. - description->face = StringVar::StringToPPVar(module(), - UTF16ToUTF8(web_desc.family)); - description->family = static_cast<PP_FontFamily_Dev>(web_desc.genericFamily); - description->size = static_cast<uint32_t>(web_desc.size); - description->weight = static_cast<PP_FontWeight_Dev>(web_desc.weight); - description->italic = BoolToPPBool(web_desc.italic); - description->small_caps = BoolToPPBool(web_desc.smallCaps); - - metrics->height = font_->height(); - metrics->ascent = font_->ascent(); - metrics->descent = font_->descent(); - metrics->line_spacing = font_->lineSpacing(); - metrics->x_height = static_cast<int32_t>(font_->xHeight()); - - return true; -} - -bool Font::DrawTextAt(PP_Resource image_data, - const PP_TextRun_Dev* text, - const PP_Point* position, - uint32_t color, - const PP_Rect* clip, - bool image_data_is_opaque) { - WebTextRun run; - if (!PPTextRunToWebTextRun(text, &run)) - return false; - - // Get and map the image data we're painting to. - scoped_refptr<ImageData> image_resource( - Resource::GetAs<ImageData>(image_data)); - if (!image_resource.get()) - return false; - ImageDataAutoMapper mapper(image_resource); - if (!mapper.is_valid()) - return false; - - // Convert position and clip. - WebFloatPoint web_position(static_cast<float>(position->x), - static_cast<float>(position->y)); - WebRect web_clip; - if (!clip) { - // Use entire canvas. - web_clip = WebRect(0, 0, image_resource->width(), image_resource->height()); - } else { - web_clip = WebRect(clip->point.x, clip->point.y, - clip->size.width, clip->size.height); - } - - font_->drawText(webkit_glue::ToWebCanvas(image_resource->mapped_canvas()), - run, web_position, color, web_clip, image_data_is_opaque); - return true; -} - -int32_t Font::MeasureText(const PP_TextRun_Dev* text) { - WebTextRun run; - if (!PPTextRunToWebTextRun(text, &run)) - return -1; - return font_->calculateWidth(run); -} - -uint32_t Font::CharacterOffsetForPixel(const PP_TextRun_Dev* text, - int32_t pixel_position) { - WebTextRun run; - if (!PPTextRunToWebTextRun(text, &run)) - return -1; - - return static_cast<uint32_t>(font_->offsetForPosition( - run, static_cast<float>(pixel_position))); -} - -int32_t Font::PixelOffsetForCharacter(const PP_TextRun_Dev* text, - uint32_t char_offset) { - WebTextRun run; - if (!PPTextRunToWebTextRun(text, &run)) - return -1; - if (char_offset >= run.text.length()) - return -1; - - WebFloatRect rect = font_->selectionRectForText( - run, WebFloatPoint(0.0f, 0.0f), font_->height(), 0, char_offset); - return static_cast<int>(rect.width); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_font.h b/webkit/glue/plugins/pepper_font.h deleted file mode 100644 index 3cc001c..0000000 --- a/webkit/glue/plugins/pepper_font.h +++ /dev/null @@ -1,53 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_FONT_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_FONT_H_ - -#include "base/scoped_ptr.h" -#include "ppapi/c/dev/ppb_font_dev.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace WebKit { -class WebFont; -} - -namespace pepper { - -class PluginInstance; - -class Font : public Resource { - public: - Font(PluginModule* module, const PP_FontDescription_Dev& desc); - virtual ~Font(); - - // Returns a pointer to the interface implementing PPB_Font that is exposed to - // the plugin. - static const PPB_Font_Dev* GetInterface(); - - // Resource overrides. - Font* AsFont() { return this; } - - // PPB_Font implementation. - bool Describe(PP_FontDescription_Dev* description, - PP_FontMetrics_Dev* metrics); - bool DrawTextAt(PP_Resource image_data, - const PP_TextRun_Dev* text, - const PP_Point* position, - uint32_t color, - const PP_Rect* clip, - bool image_data_is_opaque); - int32_t MeasureText(const PP_TextRun_Dev* text); - uint32_t CharacterOffsetForPixel(const PP_TextRun_Dev* text, - int32_t pixel_position); - int32_t PixelOffsetForCharacter(const PP_TextRun_Dev* text, - uint32_t char_offset); - - private: - scoped_ptr<WebKit::WebFont> font_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_FONT_H_ diff --git a/webkit/glue/plugins/pepper_fullscreen_container.h b/webkit/glue/plugins/pepper_fullscreen_container.h deleted file mode 100644 index 7d86320..0000000 --- a/webkit/glue/plugins/pepper_fullscreen_container.h +++ /dev/null @@ -1,36 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_FULLSCREEN_CONTAINER_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_FULLSCREEN_CONTAINER_H_ - -namespace WebKit { -struct WebRect; -} // namespace WebKit - -namespace pepper { - -// This class is like a lightweight WebPluginContainer for fullscreen pepper -// plugins, that only handles painting. -class FullscreenContainer { - public: - virtual ~FullscreenContainer() {} - - // Invalidates the full plugin region. - virtual void Invalidate() = 0; - - // Invalidates a partial region of the plugin. - virtual void InvalidateRect(const WebKit::WebRect&) = 0; - - // Scrolls a partial region of the plugin in the given direction. - virtual void ScrollRect(int dx, int dy, const WebKit::WebRect&) = 0; - - // Destroys the fullscreen window. This also destroys the FullscreenContainer - // instance. - virtual void Destroy() = 0; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_FULLSCREEN_CONTAINER_H_ diff --git a/webkit/glue/plugins/pepper_graphics_2d.cc b/webkit/glue/plugins/pepper_graphics_2d.cc deleted file mode 100644 index 7ccfae5..0000000 --- a/webkit/glue/plugins/pepper_graphics_2d.cc +++ /dev/null @@ -1,638 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_graphics_2d.h" - -#include <iterator> - -#include "base/logging.h" -#include "base/message_loop.h" -#include "base/task.h" -#include "gfx/blit.h" -#include "gfx/point.h" -#include "gfx/rect.h" -#include "skia/ext/platform_canvas.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/ppb_graphics_2d.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" - -#if defined(OS_MACOSX) -#include "base/mac_util.h" -#include "base/mac/scoped_cftyperef.h" -#endif - -namespace pepper { - -namespace { - -// Converts a rect inside an image of the given dimensions. The rect may be -// NULL to indicate it should be the entire image. If the rect is outside of -// the image, this will do nothing and return false. -bool ValidateAndConvertRect(const PP_Rect* rect, - int image_width, int image_height, - gfx::Rect* dest) { - if (!rect) { - // Use the entire image area. - *dest = gfx::Rect(0, 0, image_width, image_height); - } else { - // Validate the passed-in area. - if (rect->point.x < 0 || rect->point.y < 0 || - rect->size.width <= 0 || rect->size.height <= 0) - return false; - - // Check the max bounds, being careful of overflow. - if (static_cast<int64>(rect->point.x) + - static_cast<int64>(rect->size.width) > - static_cast<int64>(image_width)) - return false; - if (static_cast<int64>(rect->point.y) + - static_cast<int64>(rect->size.height) > - static_cast<int64>(image_height)) - return false; - - *dest = gfx::Rect(rect->point.x, rect->point.y, - rect->size.width, rect->size.height); - } - return true; -} - -// Converts BGRA <-> RGBA. -void ConvertBetweenBGRAandRGBA(const uint32_t* input, - int pixel_length, - uint32_t* output) { - for (int i = 0; i < pixel_length; i++) { - const unsigned char* pixel_in = - reinterpret_cast<const unsigned char*>(&input[i]); - unsigned char* pixel_out = reinterpret_cast<unsigned char*>(&output[i]); - pixel_out[0] = pixel_in[2]; - pixel_out[1] = pixel_in[1]; - pixel_out[2] = pixel_in[0]; - pixel_out[3] = pixel_in[3]; - } -} - -// Converts ImageData from PP_IMAGEDATAFORMAT_BGRA_PREMUL to -// PP_IMAGEDATAFORMAT_RGBA_PREMUL, or reverse. -void ConvertImageData(ImageData* src_image, const SkIRect& src_rect, - ImageData* dest_image, const SkRect& dest_rect) { - DCHECK(src_image->format() != dest_image->format()); - DCHECK(ImageData::IsImageDataFormatSupported(src_image->format())); - DCHECK(ImageData::IsImageDataFormatSupported(dest_image->format())); - - const SkBitmap* src_bitmap = src_image->GetMappedBitmap(); - const SkBitmap* dest_bitmap = dest_image->GetMappedBitmap(); - if (src_rect.width() == src_image->width() && - dest_rect.width() == dest_image->width()) { - // Fast path if the full line needs to be converted. - ConvertBetweenBGRAandRGBA( - src_bitmap->getAddr32(static_cast<int>(src_rect.fLeft), - static_cast<int>(src_rect.fTop)), - src_rect.width() * src_rect.height(), - dest_bitmap->getAddr32(static_cast<int>(dest_rect.fLeft), - static_cast<int>(dest_rect.fTop))); - } else { - // Slow path where we convert line by line. - for (int y = 0; y < src_rect.height(); y++) { - ConvertBetweenBGRAandRGBA( - src_bitmap->getAddr32(static_cast<int>(src_rect.fLeft), - static_cast<int>(src_rect.fTop + y)), - src_rect.width(), - dest_bitmap->getAddr32(static_cast<int>(dest_rect.fLeft), - static_cast<int>(dest_rect.fTop + y))); - } - } -} - -PP_Resource Create(PP_Module module_id, - const PP_Size* size, - PP_Bool is_always_opaque) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - scoped_refptr<Graphics2D> context(new Graphics2D(module)); - if (!context->Init(size->width, size->height, PPBoolToBool(is_always_opaque))) - return 0; - return context->GetReference(); -} - -PP_Bool IsGraphics2D(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<Graphics2D>(resource)); -} - -PP_Bool Describe(PP_Resource graphics_2d, - PP_Size* size, - PP_Bool* is_always_opaque) { - scoped_refptr<Graphics2D> context( - Resource::GetAs<Graphics2D>(graphics_2d)); - if (!context) - return PP_FALSE; - return context->Describe(size, is_always_opaque); -} - -void PaintImageData(PP_Resource graphics_2d, - PP_Resource image_data, - const PP_Point* top_left, - const PP_Rect* src_rect) { - scoped_refptr<Graphics2D> context( - Resource::GetAs<Graphics2D>(graphics_2d)); - if (context) - context->PaintImageData(image_data, top_left, src_rect); -} - -void Scroll(PP_Resource graphics_2d, - const PP_Rect* clip_rect, - const PP_Point* amount) { - scoped_refptr<Graphics2D> context( - Resource::GetAs<Graphics2D>(graphics_2d)); - if (context) - context->Scroll(clip_rect, amount); -} - -void ReplaceContents(PP_Resource graphics_2d, PP_Resource image_data) { - scoped_refptr<Graphics2D> context( - Resource::GetAs<Graphics2D>(graphics_2d)); - if (context) - context->ReplaceContents(image_data); -} - -int32_t Flush(PP_Resource graphics_2d, - PP_CompletionCallback callback) { - scoped_refptr<Graphics2D> context( - Resource::GetAs<Graphics2D>(graphics_2d)); - if (!context) - return PP_ERROR_BADRESOURCE; - return context->Flush(callback); -} - -const PPB_Graphics2D ppb_graphics_2d = { - &Create, - &IsGraphics2D, - &Describe, - &PaintImageData, - &Scroll, - &ReplaceContents, - &Flush -}; - -} // namespace - -struct Graphics2D::QueuedOperation { - enum Type { - PAINT, - SCROLL, - REPLACE - }; - - QueuedOperation(Type t) - : type(t), - paint_x(0), - paint_y(0), - scroll_dx(0), - scroll_dy(0) { - } - - Type type; - - // Valid when type == PAINT. - scoped_refptr<ImageData> paint_image; - int paint_x, paint_y; - gfx::Rect paint_src_rect; - - // Valid when type == SCROLL. - gfx::Rect scroll_clip_rect; - int scroll_dx, scroll_dy; - - // Valid when type == REPLACE. - scoped_refptr<ImageData> replace_image; -}; - -Graphics2D::Graphics2D(PluginModule* module) - : Resource(module), - bound_instance_(NULL), - flushed_any_data_(false), - offscreen_flush_pending_(false), - is_always_opaque_(false) { -} - -Graphics2D::~Graphics2D() { -} - -// static -const PPB_Graphics2D* Graphics2D::GetInterface() { - return &ppb_graphics_2d; -} - -bool Graphics2D::Init(int width, int height, bool is_always_opaque) { - // The underlying ImageData will validate the dimensions. - image_data_ = new ImageData(module()); - if (!image_data_->Init(ImageData::GetNativeImageDataFormat(), width, height, - true) || !image_data_->Map()) { - image_data_ = NULL; - return false; - } - is_always_opaque_ = is_always_opaque; - return true; -} - -PP_Bool Graphics2D::Describe(PP_Size* size, PP_Bool* is_always_opaque) { - size->width = image_data_->width(); - size->height = image_data_->height(); - *is_always_opaque = PP_FALSE; // TODO(brettw) implement this. - return PP_TRUE; -} - -void Graphics2D::PaintImageData(PP_Resource image_data, - const PP_Point* top_left, - const PP_Rect* src_rect) { - if (!top_left) - return; - - scoped_refptr<ImageData> image_resource( - Resource::GetAs<ImageData>(image_data)); - if (!image_resource) - return; - - QueuedOperation operation(QueuedOperation::PAINT); - operation.paint_image = image_resource; - if (!ValidateAndConvertRect(src_rect, image_resource->width(), - image_resource->height(), - &operation.paint_src_rect)) - return; - - // Validate the bitmap position using the previously-validated rect, there - // should be no painted area outside of the image. - int64 x64 = static_cast<int64>(top_left->x); - int64 y64 = static_cast<int64>(top_left->y); - if (x64 + static_cast<int64>(operation.paint_src_rect.x()) < 0 || - x64 + static_cast<int64>(operation.paint_src_rect.right()) > - image_data_->width()) - return; - if (y64 + static_cast<int64>(operation.paint_src_rect.y()) < 0 || - y64 + static_cast<int64>(operation.paint_src_rect.bottom()) > - image_data_->height()) - return; - operation.paint_x = top_left->x; - operation.paint_y = top_left->y; - - queued_operations_.push_back(operation); -} - -void Graphics2D::Scroll(const PP_Rect* clip_rect, const PP_Point* amount) { - QueuedOperation operation(QueuedOperation::SCROLL); - if (!ValidateAndConvertRect(clip_rect, - image_data_->width(), - image_data_->height(), - &operation.scroll_clip_rect)) - return; - - // If we're being asked to scroll by more than the clip rect size, just - // ignore this scroll command and say it worked. - int32 dx = amount->x; - int32 dy = amount->y; - if (dx <= -image_data_->width() || dx >= image_data_->width() || - dy <= -image_data_->height() || dy >= image_data_->height()) - return; - - operation.scroll_dx = dx; - operation.scroll_dy = dy; - - queued_operations_.push_back(operation); -} - -void Graphics2D::ReplaceContents(PP_Resource image_data) { - scoped_refptr<ImageData> image_resource( - Resource::GetAs<ImageData>(image_data)); - if (!image_resource) - return; - if (!ImageData::IsImageDataFormatSupported(image_resource->format())) - return; - - if (image_resource->width() != image_data_->width() || - image_resource->height() != image_data_->height()) - return; - - QueuedOperation operation(QueuedOperation::REPLACE); - operation.replace_image = image_resource; - queued_operations_.push_back(operation); -} - -int32_t Graphics2D::Flush(const PP_CompletionCallback& callback) { - // Don't allow more than one pending flush at a time. - if (HasPendingFlush()) - return PP_ERROR_INPROGRESS; - - // TODO(brettw) check that the current thread is not the main one and - // implement blocking flushes in this case. - if (!callback.func) - return PP_ERROR_BADARGUMENT; - - bool nothing_visible = true; - for (size_t i = 0; i < queued_operations_.size(); i++) { - QueuedOperation& operation = queued_operations_[i]; - gfx::Rect op_rect; - switch (operation.type) { - case QueuedOperation::PAINT: - ExecutePaintImageData(operation.paint_image, - operation.paint_x, operation.paint_y, - operation.paint_src_rect, - &op_rect); - break; - case QueuedOperation::SCROLL: - ExecuteScroll(operation.scroll_clip_rect, - operation.scroll_dx, operation.scroll_dy, - &op_rect); - break; - case QueuedOperation::REPLACE: - ExecuteReplaceContents(operation.replace_image, &op_rect); - break; - } - - // We need the rect to be in terms of the current clip rect of the plugin - // since that's what will actually be painted. If we issue an invalidate - // for a clipped-out region, WebKit will do nothing and we won't get any - // ViewInitiatedPaint/ViewFlushedPaint calls, leaving our callback stranded. - gfx::Rect visible_changed_rect; - if (bound_instance_ && !op_rect.IsEmpty()) - visible_changed_rect = bound_instance_->clip().Intersect(op_rect); - - if (bound_instance_ && !visible_changed_rect.IsEmpty()) { - if (operation.type == QueuedOperation::SCROLL) { - bound_instance_->ScrollRect(operation.scroll_dx, operation.scroll_dy, - visible_changed_rect); - } else { - bound_instance_->InvalidateRect(visible_changed_rect); - } - nothing_visible = false; - } - } - queued_operations_.clear(); - flushed_any_data_ = true; - - if (nothing_visible) { - // There's nothing visible to invalidate so just schedule the callback to - // execute in the next round of the message loop. - ScheduleOffscreenCallback(FlushCallbackData(callback)); - } else { - unpainted_flush_callback_.Set(callback); - } - return PP_ERROR_WOULDBLOCK; -} - -bool Graphics2D::ReadImageData(PP_Resource image, - const PP_Point* top_left) { - // Get and validate the image object to paint into. - scoped_refptr<ImageData> image_resource(Resource::GetAs<ImageData>(image)); - if (!image_resource) - return false; - if (!ImageData::IsImageDataFormatSupported(image_resource->format())) - return false; // Must be in the right format. - - // Validate the bitmap position. - int x = top_left->x; - if (x < 0 || - static_cast<int64>(x) + static_cast<int64>(image_resource->width()) > - image_data_->width()) - return false; - int y = top_left->y; - if (y < 0 || - static_cast<int64>(y) + static_cast<int64>(image_resource->height()) > - image_data_->height()) - return false; - - ImageDataAutoMapper auto_mapper(image_resource); - if (!auto_mapper.is_valid()) - return false; - - SkIRect src_irect = { x, y, - x + image_resource->width(), - y + image_resource->height() }; - SkRect dest_rect = { SkIntToScalar(0), - SkIntToScalar(0), - SkIntToScalar(image_resource->width()), - SkIntToScalar(image_resource->height()) }; - - ImageDataAutoMapper auto_mapper2(image_data_); - if (image_resource->format() != image_data_->format()) { - // Convert the image data if the format does not match. - ConvertImageData(image_data_, src_irect, image_resource.get(), dest_rect); - } else { - skia::PlatformCanvas* dest_canvas = image_resource->mapped_canvas(); - - // We want to replace the contents of the bitmap rather than blend. - SkPaint paint; - paint.setXfermodeMode(SkXfermode::kSrc_Mode); - dest_canvas->drawBitmapRect(*image_data_->GetMappedBitmap(), - &src_irect, dest_rect, &paint); - } - return true; -} - -bool Graphics2D::BindToInstance(PluginInstance* new_instance) { - if (bound_instance_ == new_instance) - return true; // Rebinding the same device, nothing to do. - if (bound_instance_ && new_instance) - return false; // Can't change a bound device. - - if (!new_instance) { - // When the device is detached, we'll not get any more paint callbacks so - // we need to clear the list, but we still want to issue any pending - // callbacks to the plugin. - if (!unpainted_flush_callback_.is_null()) { - ScheduleOffscreenCallback(unpainted_flush_callback_); - unpainted_flush_callback_.Clear(); - } - if (!painted_flush_callback_.is_null()) { - ScheduleOffscreenCallback(painted_flush_callback_); - painted_flush_callback_.Clear(); - } - } else if (flushed_any_data_) { - // Only schedule a paint if this backing store has had any data flushed to - // it. This is an optimization. A "normal" plugin will first allocated a - // backing store, bind it, and then execute their normal painting and - // update loop. If binding a device always invalidated, it would mean we - // would get one paint for the bind, and one for the first time the plugin - // actually painted something. By not bothering to schedule an invalidate - // when an empty device is initially bound, we can save an extra paint for - // many plugins during the critical page initialization phase. - new_instance->InvalidateRect(gfx::Rect()); - } - - bound_instance_ = new_instance; - return true; -} - -void Graphics2D::Paint(WebKit::WebCanvas* canvas, - const gfx::Rect& plugin_rect, - const gfx::Rect& paint_rect) { - ImageDataAutoMapper auto_mapper(image_data_); - const SkBitmap& backing_bitmap = *image_data_->GetMappedBitmap(); - -#if defined(OS_MACOSX) - SkAutoLockPixels lock(backing_bitmap); - - base::mac::ScopedCFTypeRef<CGDataProviderRef> data_provider( - CGDataProviderCreateWithData( - NULL, backing_bitmap.getAddr32(0, 0), - backing_bitmap.rowBytes() * backing_bitmap.height(), NULL)); - base::mac::ScopedCFTypeRef<CGImageRef> image( - CGImageCreate( - backing_bitmap.width(), backing_bitmap.height(), - 8, 32, backing_bitmap.rowBytes(), - mac_util::GetSystemColorSpace(), - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, - data_provider, NULL, false, kCGRenderingIntentDefault)); - - // Flip the transform - CGContextSaveGState(canvas); - float window_height = static_cast<float>(CGBitmapContextGetHeight(canvas)); - CGContextTranslateCTM(canvas, 0, window_height); - CGContextScaleCTM(canvas, 1.0, -1.0); - - CGRect bounds; - bounds.origin.x = plugin_rect.origin().x(); - bounds.origin.y = window_height - plugin_rect.origin().y() - - backing_bitmap.height(); - bounds.size.width = backing_bitmap.width(); - bounds.size.height = backing_bitmap.height(); - - // TODO(brettw) bug 56673: do a direct memcpy instead of going through CG - // if the is_always_opaque_ flag is set. - - CGContextDrawImage(canvas, bounds, image); - CGContextRestoreGState(canvas); -#else - SkPaint paint; - if (is_always_opaque_) { - // When we know the device is opaque, we can disable blending for slightly - // more optimized painting. - paint.setXfermodeMode(SkXfermode::kSrc_Mode); - } - - gfx::Point origin(plugin_rect.origin().x(), plugin_rect.origin().y()); - canvas->drawBitmap(backing_bitmap, - SkIntToScalar(plugin_rect.origin().x()), - SkIntToScalar(plugin_rect.origin().y()), - &paint); -#endif -} - -void Graphics2D::ViewInitiatedPaint() { - // Move any "unpainted" callback to the painted state. See - // |unpainted_flush_callback_| in the header for more. - if (!unpainted_flush_callback_.is_null()) { - DCHECK(painted_flush_callback_.is_null()); - std::swap(painted_flush_callback_, unpainted_flush_callback_); - } -} - -void Graphics2D::ViewFlushedPaint() { - // Notify any "painted" callback. See |unpainted_flush_callback_| in the - // header for more. - if (!painted_flush_callback_.is_null()) { - // We must clear this variable before issuing the callback. It will be - // common for the plugin to issue another invalidate in response to a flush - // callback, and we don't want to think that a callback is already pending. - FlushCallbackData callback; - std::swap(callback, painted_flush_callback_); - callback.Execute(PP_OK); - } -} - -void Graphics2D::ExecutePaintImageData(ImageData* image, - int x, int y, - const gfx::Rect& src_rect, - gfx::Rect* invalidated_rect) { - // Ensure the source image is mapped to read from it. - ImageDataAutoMapper auto_mapper(image); - if (!auto_mapper.is_valid()) - return; - - // Portion within the source image to cut out. - SkIRect src_irect = { src_rect.x(), src_rect.y(), - src_rect.right(), src_rect.bottom() }; - - // Location within the backing store to copy to. - *invalidated_rect = src_rect; - invalidated_rect->Offset(x, y); - SkRect dest_rect = { SkIntToScalar(invalidated_rect->x()), - SkIntToScalar(invalidated_rect->y()), - SkIntToScalar(invalidated_rect->right()), - SkIntToScalar(invalidated_rect->bottom()) }; - - if (image->format() != image_data_->format()) { - // Convert the image data if the format does not match. - ConvertImageData(image, src_irect, image_data_, dest_rect); - } else { - // We're guaranteed to have a mapped canvas since we mapped it in Init(). - skia::PlatformCanvas* backing_canvas = image_data_->mapped_canvas(); - - // We want to replace the contents of the bitmap rather than blend. - SkPaint paint; - paint.setXfermodeMode(SkXfermode::kSrc_Mode); - backing_canvas->drawBitmapRect(*image->GetMappedBitmap(), - &src_irect, dest_rect, &paint); - } -} - -void Graphics2D::ExecuteScroll(const gfx::Rect& clip, int dx, int dy, - gfx::Rect* invalidated_rect) { - gfx::ScrollCanvas(image_data_->mapped_canvas(), - clip, gfx::Point(dx, dy)); - *invalidated_rect = clip; -} - -void Graphics2D::ExecuteReplaceContents(ImageData* image, - gfx::Rect* invalidated_rect) { - if (image->format() != image_data_->format()) { - DCHECK(image->width() == image_data_->width() && - image->height() == image_data_->height()); - // Convert the image data if the format does not match. - SkIRect src_irect = { 0, 0, image->width(), image->height() }; - SkRect dest_rect = { SkIntToScalar(0), - SkIntToScalar(0), - SkIntToScalar(image_data_->width()), - SkIntToScalar(image_data_->height()) }; - ConvertImageData(image, src_irect, image_data_, dest_rect); - } else { - image_data_->Swap(image); - } - *invalidated_rect = gfx::Rect(0, 0, - image_data_->width(), image_data_->height()); -} - -void Graphics2D::ScheduleOffscreenCallback(const FlushCallbackData& callback) { - DCHECK(!HasPendingFlush()); - offscreen_flush_pending_ = true; - MessageLoop::current()->PostTask( - FROM_HERE, - NewRunnableMethod(this, - &Graphics2D::ExecuteOffscreenCallback, - callback)); -} - -void Graphics2D::ExecuteOffscreenCallback(FlushCallbackData data) { - DCHECK(offscreen_flush_pending_); - - // We must clear this flag before issuing the callback. It will be - // common for the plugin to issue another invalidate in response to a flush - // callback, and we don't want to think that a callback is already pending. - offscreen_flush_pending_ = false; - data.Execute(PP_OK); -} - -bool Graphics2D::HasPendingFlush() const { - return !unpainted_flush_callback_.is_null() || - !painted_flush_callback_.is_null() || - offscreen_flush_pending_; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_graphics_2d.h b/webkit/glue/plugins/pepper_graphics_2d.h deleted file mode 100644 index 78170ab..0000000 --- a/webkit/glue/plugins/pepper_graphics_2d.h +++ /dev/null @@ -1,180 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_GRAPHICS_2D_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_GRAPHICS_2D_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/ppb_graphics_2d.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCanvas.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PPB_Graphics2D; - -namespace gfx { -class Rect; -} - -namespace pepper { - -class ImageData; -class PluginInstance; -class PluginModule; - -class Graphics2D : public Resource { - public: - Graphics2D(PluginModule* module); - virtual ~Graphics2D(); - - // Returns a pointer to the interface implementing PPB_ImageData that is - // exposed to the plugin. - static const PPB_Graphics2D* GetInterface(); - - bool Init(int width, int height, bool is_always_opaque); - - bool is_always_opaque() const { return is_always_opaque_; } - - // Resource override. - virtual Graphics2D* AsGraphics2D() { return this; } - - // PPB_Graphics2D functions. - PP_Bool Describe(PP_Size* size, PP_Bool* is_always_opaque); - void PaintImageData(PP_Resource image_data, - const PP_Point* top_left, - const PP_Rect* src_rect); - void Scroll(const PP_Rect* clip_rect, const PP_Point* amount); - void ReplaceContents(PP_Resource image_data); - int32_t Flush(const PP_CompletionCallback& callback); - - bool ReadImageData(PP_Resource image, const PP_Point* top_left); - - // Assciates this device with the given plugin instance. You can pass NULL to - // clear the existing device. Returns true on success. In this case, a - // repaint of the page will also be scheduled. Failure means that the device - // is already bound to a different instance, and nothing will happen. - bool BindToInstance(PluginInstance* new_instance); - - // Paints the current backing store to the web page. - void Paint(WebKit::WebCanvas* canvas, - const gfx::Rect& plugin_rect, - const gfx::Rect& paint_rect); - - // Notifications that the view has rendered the page and that it has been - // flushed to the screen. These messages are used to send Flush callbacks to - // the plugin. See - void ViewInitiatedPaint(); - void ViewFlushedPaint(); - - ImageData* image_data() { return image_data_.get(); } - - private: - // Tracks a call to flush that requires a callback. - class FlushCallbackData { - public: - FlushCallbackData() { - Clear(); - } - - FlushCallbackData(const PP_CompletionCallback& callback) { - Set(callback); - } - - bool is_null() const { return !callback_.func; } - - void Set(const PP_CompletionCallback& callback) { - callback_ = callback; - } - - void Clear() { - callback_ = PP_MakeCompletionCallback(NULL, 0); - } - - void Execute(int32_t result) { - PP_RunCompletionCallback(&callback_, result); - } - - private: - PP_CompletionCallback callback_; - }; - - // Called internally to execute the different queued commands. The - // parameters to these functions will have already been validated. The last - // rect argument will be filled by each function with the area affected by - // the update that requires invalidation. If there were no pixels changed, - // this rect can be untouched. - void ExecutePaintImageData(ImageData* image, - int x, int y, - const gfx::Rect& src_rect, - gfx::Rect* invalidated_rect); - void ExecuteScroll(const gfx::Rect& clip, int dx, int dy, - gfx::Rect* invalidated_rect); - void ExecuteReplaceContents(ImageData* image, - gfx::Rect* invalidated_rect); - - // Schedules the offscreen callback to be fired at a future time. This - // will add the given item to the offscreen_flush_callbacks_ vector. - void ScheduleOffscreenCallback(const FlushCallbackData& callback); - - // Function scheduled to execute by ScheduleOffscreenCallback that actually - // issues the offscreen callbacks. - void ExecuteOffscreenCallback(FlushCallbackData data); - - // Returns true if there is any type of flush callback pending. - bool HasPendingFlush() const; - - scoped_refptr<ImageData> image_data_; - - // Non-owning pointer to the plugin instance this context is currently bound - // to, if any. If the context is currently unbound, this will be NULL. - PluginInstance* bound_instance_; - - // Keeps track of all drawing commands queued before a Flush call. - struct QueuedOperation; - typedef std::vector<QueuedOperation> OperationQueue; - OperationQueue queued_operations_; - - // Indicates whether any changes have been flushed to the backing store. - // This is initially false and is set to true at the first Flush() call. - bool flushed_any_data_; - - // The plugin can give us one "Flush" at a time. This flush will either be in - // the "unpainted" state (in which case unpainted_flush_callback_ will be - // non-NULL) or painted, in which case painted_flush_callback_ will be - // non-NULL). There can also be an offscreen callback which is handled - // separately (see offscreen_callback_pending_). Only one of these three - // things may be set at a time to enforce the "only one pending flush at a - // time" constraint. - // - // "Unpainted" ones are flush requests which have never been painted. These - // could have been done while the RenderView was already waiting for an ACK - // from a previous paint, so won't generate a new one yet. - // - // "Painted" ones are those flushes that have been painted by RenderView, but - // for which the ACK from the browser has not yet been received. - // - // When we get updates from a plugin with a callback, it is first added to - // the unpainted callbacks. When the renderer has initiated a paint, we'll - // move it to the painted callbacks list. When the renderer receives a flush, - // we'll execute the callback and remove it from the list. - FlushCallbackData unpainted_flush_callback_; - FlushCallbackData painted_flush_callback_; - - // When doing offscreen flushes, we issue a task that issues the callback - // later. This is set when one of those tasks is pending so that we can - // enforce the "only one pending flush at a time" constraint in the API. - bool offscreen_flush_pending_; - - // Set to true if the plugin declares that this device will always be opaque. - // This allows us to do more optimized painting in some cases. - bool is_always_opaque_; - - DISALLOW_COPY_AND_ASSIGN(Graphics2D); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_GRAPHICS_2D_H_ diff --git a/webkit/glue/plugins/pepper_graphics_3d.cc b/webkit/glue/plugins/pepper_graphics_3d.cc deleted file mode 100644 index 2dc4def..0000000 --- a/webkit/glue/plugins/pepper_graphics_3d.cc +++ /dev/null @@ -1,256 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_graphics_3d.h" - -#include "gpu/command_buffer/common/command_buffer.h" -#include "base/singleton.h" -#include "base/thread_local.h" -#include "ppapi/c/dev/ppb_graphics_3d_dev.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" - -namespace pepper { - -namespace { - -struct CurrentContextTag {}; -typedef Singleton<base::ThreadLocalPointer<Graphics3D>, - DefaultSingletonTraits<base::ThreadLocalPointer<Graphics3D> >, - CurrentContextTag> CurrentContextKey; - -// Size of the transfer buffer. -enum { kTransferBufferSize = 512 * 1024 }; - -PP_Bool IsGraphics3D(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<Graphics3D>(resource)); -} - -PP_Bool GetConfigs(int32_t* configs, int32_t config_size, int32_t* num_config) { - // TODO(neb): Implement me! - return PP_FALSE; -} - -PP_Bool ChooseConfig(const int32_t* attrib_list, int32_t* configs, - int32_t config_size, int32_t* num_config) { - // TODO(neb): Implement me! - return PP_FALSE; -} - -PP_Bool GetConfigAttrib(int32_t config, int32_t attribute, int32_t* value) { - // TODO(neb): Implement me! - return PP_FALSE; -} - -const char* QueryString(int32_t name) { - switch (name) { - case EGL_CLIENT_APIS: - return "OpenGL_ES"; - case EGL_EXTENSIONS: - return ""; - case EGL_VENDOR: - return "Google"; - case EGL_VERSION: - return "1.0 Google"; - default: - return NULL; - } -} - -PP_Resource CreateContext(PP_Instance instance_id, int32_t config, - int32_t share_context, - const int32_t* attrib_list) { - DCHECK_EQ(0, share_context); - - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) { - return 0; - } - - scoped_refptr<Graphics3D> context(new Graphics3D(instance->module())); - if (!context->Init(instance_id, config, attrib_list)) { - return 0; - } - - return context->GetReference(); -} - -void* GetProcAddress(const char* name) { - // TODO(neb): Implement me! - return NULL; -} - -PP_Bool MakeCurrent(PP_Resource graphics3d) { - if (!graphics3d) { - Graphics3D::ResetCurrent(); - return PP_TRUE; - } else { - scoped_refptr<Graphics3D> context(Resource::GetAs<Graphics3D>(graphics3d)); - return BoolToPPBool(context.get() && context->MakeCurrent()); - } -} - -PP_Resource GetCurrentContext() { - Graphics3D* current_context = Graphics3D::GetCurrent(); - return current_context ? current_context->GetReference() : 0; -} - -PP_Bool SwapBuffers(PP_Resource graphics3d) { - scoped_refptr<Graphics3D> context(Resource::GetAs<Graphics3D>(graphics3d)); - return BoolToPPBool(context && context->SwapBuffers()); -} - -uint32_t GetError() { - // Technically, this should return the last error that occurred on the current - // thread, rather than an error associated with a particular context. - // TODO(apatrick): Fix this. - Graphics3D* current_context = Graphics3D::GetCurrent(); - if (!current_context) - return 0; - - return current_context->GetError(); -} - -const PPB_Graphics3D_Dev ppb_graphics3d = { - &IsGraphics3D, - &GetConfigs, - &ChooseConfig, - &GetConfigAttrib, - &QueryString, - &CreateContext, - &GetProcAddress, - &MakeCurrent, - &GetCurrentContext, - &SwapBuffers, - &GetError -}; - -} // namespace - -Graphics3D::Graphics3D(PluginModule* module) - : Resource(module), - bound_instance_(NULL) { -} - -const PPB_Graphics3D_Dev* Graphics3D::GetInterface() { - return &ppb_graphics3d; -} - -Graphics3D* Graphics3D::GetCurrent() { - return CurrentContextKey::get()->Get(); -} - -void Graphics3D::ResetCurrent() { - CurrentContextKey::get()->Set(NULL); -} - -Graphics3D::~Graphics3D() { - Destroy(); -} - -bool Graphics3D::Init(PP_Instance instance_id, int32_t config, - const int32_t* attrib_list) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) { - return false; - } - - // Create and initialize the objects required to issue GLES2 calls. - platform_context_.reset(instance->delegate()->CreateContext3D()); - if (!platform_context_.get()) { - Destroy(); - return false; - } - - if (!platform_context_->Init()) { - Destroy(); - return false; - } - - gles2_implementation_ = platform_context_->GetGLES2Implementation(); - DCHECK(gles2_implementation_); - - return true; -} - -bool Graphics3D::BindToInstance(PluginInstance* new_instance) { - if (bound_instance_ == new_instance) - return true; // Rebinding the same device, nothing to do. - if (bound_instance_ && new_instance) - return false; // Can't change a bound device. - - if (new_instance) { - // Resize the backing texture to the size of the instance when it is bound. - platform_context_->ResizeBackingTexture(new_instance->position().size()); - - // This is a temporary hack. The SwapBuffers is issued to force the resize - // to take place before any subsequent rendering. This might lead to a - // partially rendered frame being displayed. It is also not thread safe - // since the SwapBuffers is written to the command buffer and that command - // buffer might be written to by another thread. - // TODO(apatrick): Figure out the semantics of binding and resizing. - platform_context_->SwapBuffers(); - } - - bound_instance_ = new_instance; - return true; -} - -bool Graphics3D::MakeCurrent() { - if (!platform_context_.get()) - return false; - - CurrentContextKey::get()->Set(this); - - // TODO(apatrick): Return false on context lost. - return true; -} - -bool Graphics3D::SwapBuffers() { - if (!platform_context_.get()) - return false; - - return platform_context_->SwapBuffers(); -} - -unsigned Graphics3D::GetError() { - if (!platform_context_.get()) - return 0; - - return platform_context_->GetError(); -} - -void Graphics3D::ResizeBackingTexture(const gfx::Size& size) { - if (!platform_context_.get()) - return; - - platform_context_->ResizeBackingTexture(size); -} - -void Graphics3D::SetSwapBuffersCallback(Callback0::Type* callback) { - if (!platform_context_.get()) - return; - - platform_context_->SetSwapBuffersCallback(callback); -} - -unsigned Graphics3D::GetBackingTextureId() { - if (!platform_context_.get()) - return 0; - - return platform_context_->GetBackingTextureId(); -} - -void Graphics3D::Destroy() { - if (GetCurrent() == this) { - ResetCurrent(); - } - - gles2_implementation_ = NULL; - - platform_context_.reset(); -} - -} // namespace pepper - diff --git a/webkit/glue/plugins/pepper_graphics_3d.h b/webkit/glue/plugins/pepper_graphics_3d.h deleted file mode 100644 index 5c00068..0000000 --- a/webkit/glue/plugins/pepper_graphics_3d.h +++ /dev/null @@ -1,90 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_GRAPHICS_3D_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_GRAPHICS_3D_H_ - -#include "base/callback.h" -#include "base/scoped_ptr.h" -#include "gfx/size.h" -#include "gpu/command_buffer/client/gles2_cmd_helper.h" -#include "gpu/command_buffer/client/gles2_implementation.h" -#include "ppapi/c/pp_instance.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace gpu { -namespace gles2 { -class GLES2Implementation; -} -} // namespace gpu - -struct PPB_Graphics3D_Dev; -struct PPB_OpenGLES_Dev; - -namespace pepper { - -class Graphics3D : public Resource { - public: - explicit Graphics3D(PluginModule* module); - - virtual ~Graphics3D(); - - static const PPB_Graphics3D_Dev* GetInterface(); - static const PPB_OpenGLES_Dev* GetOpenGLESInterface(); - - static bool Shutdown(); - - static Graphics3D* GetCurrent(); - - static void ResetCurrent(); - - // Resource override. - virtual Graphics3D* AsGraphics3D() { - return this; - } - - bool Init(PP_Instance instance_id, int32_t config, - const int32_t* attrib_list); - - // Associates this Graphics3D with the given plugin instance. You can pass - // NULL to clear the existing device. Returns true on success. In this case, - // the last rendered frame is displayed. - // TODO(apatrick): Figure out the best semantics here. - bool BindToInstance(PluginInstance* new_instance); - - bool MakeCurrent(); - - bool SwapBuffers(); - - unsigned GetError(); - - void ResizeBackingTexture(const gfx::Size& size); - - void SetSwapBuffersCallback(Callback0::Type* callback); - - unsigned GetBackingTextureId(); - - gpu::gles2::GLES2Implementation* impl() { - return gles2_implementation_; - } - - private: - void Destroy(); - - // Non-owning pointer to the plugin instance this context is currently bound - // to, if any. If the context is currently unbound, this will be NULL. - PluginInstance* bound_instance_; - - // PluginDelegate's 3D Context. Responsible for providing the command buffer. - scoped_ptr<PluginDelegate::PlatformContext3D> platform_context_; - - // GLES2 Implementation instance. Owned by the platform context's GGL context. - gpu::gles2::GLES2Implementation* gles2_implementation_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_GRAPHICS_3D_H_ - diff --git a/webkit/glue/plugins/pepper_graphics_3d_gl.cc b/webkit/glue/plugins/pepper_graphics_3d_gl.cc deleted file mode 100644 index 0a7076f..0000000 --- a/webkit/glue/plugins/pepper_graphics_3d_gl.cc +++ /dev/null @@ -1,671 +0,0 @@ -// 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. - -// This file is auto-generated. DO NOT EDIT! - -#include "webkit/glue/plugins/pepper_graphics_3d.h" - -#include "gpu/command_buffer/client/gles2_implementation.h" -#include "ppapi/c/dev/ppb_opengles_dev.h" - -namespace pepper { - -namespace { - -void ActiveTexture(GLenum texture) { - Graphics3D::GetCurrent()->impl()->ActiveTexture(texture); -} -void AttachShader(GLuint program, GLuint shader) { - Graphics3D::GetCurrent()->impl()->AttachShader(program, shader); -} -void BindAttribLocation(GLuint program, GLuint index, const char* name) { - Graphics3D::GetCurrent()->impl()->BindAttribLocation(program, index, name); -} -void BindBuffer(GLenum target, GLuint buffer) { - Graphics3D::GetCurrent()->impl()->BindBuffer(target, buffer); -} -void BindFramebuffer(GLenum target, GLuint framebuffer) { - Graphics3D::GetCurrent()->impl()->BindFramebuffer(target, framebuffer); -} -void BindRenderbuffer(GLenum target, GLuint renderbuffer) { - Graphics3D::GetCurrent()->impl()->BindRenderbuffer(target, renderbuffer); -} -void BindTexture(GLenum target, GLuint texture) { - Graphics3D::GetCurrent()->impl()->BindTexture(target, texture); -} -void BlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { - Graphics3D::GetCurrent()->impl()->BlendColor(red, green, blue, alpha); -} -void BlendEquation(GLenum mode) { - Graphics3D::GetCurrent()->impl()->BlendEquation(mode); -} -void BlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha) { - Graphics3D::GetCurrent()->impl()->BlendEquationSeparate(modeRGB, modeAlpha); -} -void BlendFunc(GLenum sfactor, GLenum dfactor) { - Graphics3D::GetCurrent()->impl()->BlendFunc(sfactor, dfactor); -} -void BlendFuncSeparate( - GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) { - Graphics3D::GetCurrent()->impl()->BlendFuncSeparate( - srcRGB, dstRGB, srcAlpha, dstAlpha); -} -void BufferData( - GLenum target, GLsizeiptr size, const void* data, GLenum usage) { - Graphics3D::GetCurrent()->impl()->BufferData(target, size, data, usage); -} -void BufferSubData( - GLenum target, GLintptr offset, GLsizeiptr size, const void* data) { - Graphics3D::GetCurrent()->impl()->BufferSubData(target, offset, size, data); -} -GLenum CheckFramebufferStatus(GLenum target) { - return Graphics3D::GetCurrent()->impl()->CheckFramebufferStatus(target); -} -void Clear(GLbitfield mask) { - Graphics3D::GetCurrent()->impl()->Clear(mask); -} -void ClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { - Graphics3D::GetCurrent()->impl()->ClearColor(red, green, blue, alpha); -} -void ClearDepthf(GLclampf depth) { - Graphics3D::GetCurrent()->impl()->ClearDepthf(depth); -} -void ClearStencil(GLint s) { - Graphics3D::GetCurrent()->impl()->ClearStencil(s); -} -void ColorMask( - GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { - Graphics3D::GetCurrent()->impl()->ColorMask(red, green, blue, alpha); -} -void CompileShader(GLuint shader) { - Graphics3D::GetCurrent()->impl()->CompileShader(shader); -} -void CompressedTexImage2D( - GLenum target, GLint level, GLenum internalformat, GLsizei width, - GLsizei height, GLint border, GLsizei imageSize, const void* data) { - Graphics3D::GetCurrent()->impl()->CompressedTexImage2D( - target, level, internalformat, width, height, border, imageSize, data); -} -void CompressedTexSubImage2D( - GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, - GLsizei height, GLenum format, GLsizei imageSize, const void* data) { - Graphics3D::GetCurrent()->impl()->CompressedTexSubImage2D( - target, level, xoffset, yoffset, width, height, format, imageSize, data); -} -void CopyTexImage2D( - GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, - GLsizei width, GLsizei height, GLint border) { - Graphics3D::GetCurrent()->impl()->CopyTexImage2D( - target, level, internalformat, x, y, width, height, border); -} -void CopyTexSubImage2D( - GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, - GLsizei width, GLsizei height) { - Graphics3D::GetCurrent()->impl()->CopyTexSubImage2D( - target, level, xoffset, yoffset, x, y, width, height); -} -GLuint CreateProgram() { - return Graphics3D::GetCurrent()->impl()->CreateProgram(); -} -GLuint CreateShader(GLenum type) { - return Graphics3D::GetCurrent()->impl()->CreateShader(type); -} -void CullFace(GLenum mode) { - Graphics3D::GetCurrent()->impl()->CullFace(mode); -} -void DeleteBuffers(GLsizei n, const GLuint* buffers) { - Graphics3D::GetCurrent()->impl()->DeleteBuffers(n, buffers); -} -void DeleteFramebuffers(GLsizei n, const GLuint* framebuffers) { - Graphics3D::GetCurrent()->impl()->DeleteFramebuffers(n, framebuffers); -} -void DeleteProgram(GLuint program) { - Graphics3D::GetCurrent()->impl()->DeleteProgram(program); -} -void DeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers) { - Graphics3D::GetCurrent()->impl()->DeleteRenderbuffers(n, renderbuffers); -} -void DeleteShader(GLuint shader) { - Graphics3D::GetCurrent()->impl()->DeleteShader(shader); -} -void DeleteTextures(GLsizei n, const GLuint* textures) { - Graphics3D::GetCurrent()->impl()->DeleteTextures(n, textures); -} -void DepthFunc(GLenum func) { - Graphics3D::GetCurrent()->impl()->DepthFunc(func); -} -void DepthMask(GLboolean flag) { - Graphics3D::GetCurrent()->impl()->DepthMask(flag); -} -void DepthRangef(GLclampf zNear, GLclampf zFar) { - Graphics3D::GetCurrent()->impl()->DepthRangef(zNear, zFar); -} -void DetachShader(GLuint program, GLuint shader) { - Graphics3D::GetCurrent()->impl()->DetachShader(program, shader); -} -void Disable(GLenum cap) { - Graphics3D::GetCurrent()->impl()->Disable(cap); -} -void DisableVertexAttribArray(GLuint index) { - Graphics3D::GetCurrent()->impl()->DisableVertexAttribArray(index); -} -void DrawArrays(GLenum mode, GLint first, GLsizei count) { - Graphics3D::GetCurrent()->impl()->DrawArrays(mode, first, count); -} -void DrawElements( - GLenum mode, GLsizei count, GLenum type, const void* indices) { - Graphics3D::GetCurrent()->impl()->DrawElements(mode, count, type, indices); -} -void Enable(GLenum cap) { - Graphics3D::GetCurrent()->impl()->Enable(cap); -} -void EnableVertexAttribArray(GLuint index) { - Graphics3D::GetCurrent()->impl()->EnableVertexAttribArray(index); -} -void Finish() { - Graphics3D::GetCurrent()->impl()->Finish(); -} -void Flush() { - Graphics3D::GetCurrent()->impl()->Flush(); -} -void FramebufferRenderbuffer( - GLenum target, GLenum attachment, GLenum renderbuffertarget, - GLuint renderbuffer) { - Graphics3D::GetCurrent()->impl()->FramebufferRenderbuffer( - target, attachment, renderbuffertarget, renderbuffer); -} -void FramebufferTexture2D( - GLenum target, GLenum attachment, GLenum textarget, GLuint texture, - GLint level) { - Graphics3D::GetCurrent()->impl()->FramebufferTexture2D( - target, attachment, textarget, texture, level); -} -void FrontFace(GLenum mode) { - Graphics3D::GetCurrent()->impl()->FrontFace(mode); -} -void GenBuffers(GLsizei n, GLuint* buffers) { - Graphics3D::GetCurrent()->impl()->GenBuffers(n, buffers); -} -void GenerateMipmap(GLenum target) { - Graphics3D::GetCurrent()->impl()->GenerateMipmap(target); -} -void GenFramebuffers(GLsizei n, GLuint* framebuffers) { - Graphics3D::GetCurrent()->impl()->GenFramebuffers(n, framebuffers); -} -void GenRenderbuffers(GLsizei n, GLuint* renderbuffers) { - Graphics3D::GetCurrent()->impl()->GenRenderbuffers(n, renderbuffers); -} -void GenTextures(GLsizei n, GLuint* textures) { - Graphics3D::GetCurrent()->impl()->GenTextures(n, textures); -} -void GetActiveAttrib( - GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, - GLenum* type, char* name) { - Graphics3D::GetCurrent()->impl()->GetActiveAttrib( - program, index, bufsize, length, size, type, name); -} -void GetActiveUniform( - GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, - GLenum* type, char* name) { - Graphics3D::GetCurrent()->impl()->GetActiveUniform( - program, index, bufsize, length, size, type, name); -} -void GetAttachedShaders( - GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders) { - Graphics3D::GetCurrent()->impl()->GetAttachedShaders( - program, maxcount, count, shaders); -} -GLint GetAttribLocation(GLuint program, const char* name) { - return Graphics3D::GetCurrent()->impl()->GetAttribLocation(program, name); -} -void GetBooleanv(GLenum pname, GLboolean* params) { - Graphics3D::GetCurrent()->impl()->GetBooleanv(pname, params); -} -void GetBufferParameteriv(GLenum target, GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetBufferParameteriv( - target, pname, params); -} -GLenum GetError() { - return Graphics3D::GetCurrent()->impl()->GetError(); -} -void GetFloatv(GLenum pname, GLfloat* params) { - Graphics3D::GetCurrent()->impl()->GetFloatv(pname, params); -} -void GetFramebufferAttachmentParameteriv( - GLenum target, GLenum attachment, GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetFramebufferAttachmentParameteriv( - target, attachment, pname, params); -} -void GetIntegerv(GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetIntegerv(pname, params); -} -void GetProgramiv(GLuint program, GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetProgramiv(program, pname, params); -} -void GetProgramInfoLog( - GLuint program, GLsizei bufsize, GLsizei* length, char* infolog) { - Graphics3D::GetCurrent()->impl()->GetProgramInfoLog( - program, bufsize, length, infolog); -} -void GetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetRenderbufferParameteriv( - target, pname, params); -} -void GetShaderiv(GLuint shader, GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetShaderiv(shader, pname, params); -} -void GetShaderInfoLog( - GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog) { - Graphics3D::GetCurrent()->impl()->GetShaderInfoLog( - shader, bufsize, length, infolog); -} -void GetShaderPrecisionFormat( - GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) { - Graphics3D::GetCurrent()->impl()->GetShaderPrecisionFormat( - shadertype, precisiontype, range, precision); -} -void GetShaderSource( - GLuint shader, GLsizei bufsize, GLsizei* length, char* source) { - Graphics3D::GetCurrent()->impl()->GetShaderSource( - shader, bufsize, length, source); -} -const GLubyte* GetString(GLenum name) { - return Graphics3D::GetCurrent()->impl()->GetString(name); -} -void GetTexParameterfv(GLenum target, GLenum pname, GLfloat* params) { - Graphics3D::GetCurrent()->impl()->GetTexParameterfv(target, pname, params); -} -void GetTexParameteriv(GLenum target, GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetTexParameteriv(target, pname, params); -} -void GetUniformfv(GLuint program, GLint location, GLfloat* params) { - Graphics3D::GetCurrent()->impl()->GetUniformfv(program, location, params); -} -void GetUniformiv(GLuint program, GLint location, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetUniformiv(program, location, params); -} -GLint GetUniformLocation(GLuint program, const char* name) { - return Graphics3D::GetCurrent()->impl()->GetUniformLocation(program, name); -} -void GetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params) { - Graphics3D::GetCurrent()->impl()->GetVertexAttribfv(index, pname, params); -} -void GetVertexAttribiv(GLuint index, GLenum pname, GLint* params) { - Graphics3D::GetCurrent()->impl()->GetVertexAttribiv(index, pname, params); -} -void GetVertexAttribPointerv(GLuint index, GLenum pname, void** pointer) { - Graphics3D::GetCurrent()->impl()->GetVertexAttribPointerv( - index, pname, pointer); -} -void Hint(GLenum target, GLenum mode) { - Graphics3D::GetCurrent()->impl()->Hint(target, mode); -} -GLboolean IsBuffer(GLuint buffer) { - return Graphics3D::GetCurrent()->impl()->IsBuffer(buffer); -} -GLboolean IsEnabled(GLenum cap) { - return Graphics3D::GetCurrent()->impl()->IsEnabled(cap); -} -GLboolean IsFramebuffer(GLuint framebuffer) { - return Graphics3D::GetCurrent()->impl()->IsFramebuffer(framebuffer); -} -GLboolean IsProgram(GLuint program) { - return Graphics3D::GetCurrent()->impl()->IsProgram(program); -} -GLboolean IsRenderbuffer(GLuint renderbuffer) { - return Graphics3D::GetCurrent()->impl()->IsRenderbuffer(renderbuffer); -} -GLboolean IsShader(GLuint shader) { - return Graphics3D::GetCurrent()->impl()->IsShader(shader); -} -GLboolean IsTexture(GLuint texture) { - return Graphics3D::GetCurrent()->impl()->IsTexture(texture); -} -void LineWidth(GLfloat width) { - Graphics3D::GetCurrent()->impl()->LineWidth(width); -} -void LinkProgram(GLuint program) { - Graphics3D::GetCurrent()->impl()->LinkProgram(program); -} -void PixelStorei(GLenum pname, GLint param) { - Graphics3D::GetCurrent()->impl()->PixelStorei(pname, param); -} -void PolygonOffset(GLfloat factor, GLfloat units) { - Graphics3D::GetCurrent()->impl()->PolygonOffset(factor, units); -} -void ReadPixels( - GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, - void* pixels) { - Graphics3D::GetCurrent()->impl()->ReadPixels( - x, y, width, height, format, type, pixels); -} -void ReleaseShaderCompiler() { - Graphics3D::GetCurrent()->impl()->ReleaseShaderCompiler(); -} -void RenderbufferStorage( - GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { - Graphics3D::GetCurrent()->impl()->RenderbufferStorage( - target, internalformat, width, height); -} -void SampleCoverage(GLclampf value, GLboolean invert) { - Graphics3D::GetCurrent()->impl()->SampleCoverage(value, invert); -} -void Scissor(GLint x, GLint y, GLsizei width, GLsizei height) { - Graphics3D::GetCurrent()->impl()->Scissor(x, y, width, height); -} -void ShaderBinary( - GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, - GLsizei length) { - Graphics3D::GetCurrent()->impl()->ShaderBinary( - n, shaders, binaryformat, binary, length); -} -void ShaderSource( - GLuint shader, GLsizei count, const char** str, const GLint* length) { - Graphics3D::GetCurrent()->impl()->ShaderSource(shader, count, str, length); -} -void StencilFunc(GLenum func, GLint ref, GLuint mask) { - Graphics3D::GetCurrent()->impl()->StencilFunc(func, ref, mask); -} -void StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask) { - Graphics3D::GetCurrent()->impl()->StencilFuncSeparate(face, func, ref, mask); -} -void StencilMask(GLuint mask) { - Graphics3D::GetCurrent()->impl()->StencilMask(mask); -} -void StencilMaskSeparate(GLenum face, GLuint mask) { - Graphics3D::GetCurrent()->impl()->StencilMaskSeparate(face, mask); -} -void StencilOp(GLenum fail, GLenum zfail, GLenum zpass) { - Graphics3D::GetCurrent()->impl()->StencilOp(fail, zfail, zpass); -} -void StencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass) { - Graphics3D::GetCurrent()->impl()->StencilOpSeparate( - face, fail, zfail, zpass); -} -void TexImage2D( - GLenum target, GLint level, GLint internalformat, GLsizei width, - GLsizei height, GLint border, GLenum format, GLenum type, - const void* pixels) { - Graphics3D::GetCurrent()->impl()->TexImage2D( - target, level, internalformat, width, height, border, format, type, - pixels); -} -void TexParameterf(GLenum target, GLenum pname, GLfloat param) { - Graphics3D::GetCurrent()->impl()->TexParameterf(target, pname, param); -} -void TexParameterfv(GLenum target, GLenum pname, const GLfloat* params) { - Graphics3D::GetCurrent()->impl()->TexParameterfv(target, pname, params); -} -void TexParameteri(GLenum target, GLenum pname, GLint param) { - Graphics3D::GetCurrent()->impl()->TexParameteri(target, pname, param); -} -void TexParameteriv(GLenum target, GLenum pname, const GLint* params) { - Graphics3D::GetCurrent()->impl()->TexParameteriv(target, pname, params); -} -void TexSubImage2D( - GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, - GLsizei height, GLenum format, GLenum type, const void* pixels) { - Graphics3D::GetCurrent()->impl()->TexSubImage2D( - target, level, xoffset, yoffset, width, height, format, type, pixels); -} -void Uniform1f(GLint location, GLfloat x) { - Graphics3D::GetCurrent()->impl()->Uniform1f(location, x); -} -void Uniform1fv(GLint location, GLsizei count, const GLfloat* v) { - Graphics3D::GetCurrent()->impl()->Uniform1fv(location, count, v); -} -void Uniform1i(GLint location, GLint x) { - Graphics3D::GetCurrent()->impl()->Uniform1i(location, x); -} -void Uniform1iv(GLint location, GLsizei count, const GLint* v) { - Graphics3D::GetCurrent()->impl()->Uniform1iv(location, count, v); -} -void Uniform2f(GLint location, GLfloat x, GLfloat y) { - Graphics3D::GetCurrent()->impl()->Uniform2f(location, x, y); -} -void Uniform2fv(GLint location, GLsizei count, const GLfloat* v) { - Graphics3D::GetCurrent()->impl()->Uniform2fv(location, count, v); -} -void Uniform2i(GLint location, GLint x, GLint y) { - Graphics3D::GetCurrent()->impl()->Uniform2i(location, x, y); -} -void Uniform2iv(GLint location, GLsizei count, const GLint* v) { - Graphics3D::GetCurrent()->impl()->Uniform2iv(location, count, v); -} -void Uniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z) { - Graphics3D::GetCurrent()->impl()->Uniform3f(location, x, y, z); -} -void Uniform3fv(GLint location, GLsizei count, const GLfloat* v) { - Graphics3D::GetCurrent()->impl()->Uniform3fv(location, count, v); -} -void Uniform3i(GLint location, GLint x, GLint y, GLint z) { - Graphics3D::GetCurrent()->impl()->Uniform3i(location, x, y, z); -} -void Uniform3iv(GLint location, GLsizei count, const GLint* v) { - Graphics3D::GetCurrent()->impl()->Uniform3iv(location, count, v); -} -void Uniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { - Graphics3D::GetCurrent()->impl()->Uniform4f(location, x, y, z, w); -} -void Uniform4fv(GLint location, GLsizei count, const GLfloat* v) { - Graphics3D::GetCurrent()->impl()->Uniform4fv(location, count, v); -} -void Uniform4i(GLint location, GLint x, GLint y, GLint z, GLint w) { - Graphics3D::GetCurrent()->impl()->Uniform4i(location, x, y, z, w); -} -void Uniform4iv(GLint location, GLsizei count, const GLint* v) { - Graphics3D::GetCurrent()->impl()->Uniform4iv(location, count, v); -} -void UniformMatrix2fv( - GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { - Graphics3D::GetCurrent()->impl()->UniformMatrix2fv( - location, count, transpose, value); -} -void UniformMatrix3fv( - GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { - Graphics3D::GetCurrent()->impl()->UniformMatrix3fv( - location, count, transpose, value); -} -void UniformMatrix4fv( - GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { - Graphics3D::GetCurrent()->impl()->UniformMatrix4fv( - location, count, transpose, value); -} -void UseProgram(GLuint program) { - Graphics3D::GetCurrent()->impl()->UseProgram(program); -} -void ValidateProgram(GLuint program) { - Graphics3D::GetCurrent()->impl()->ValidateProgram(program); -} -void VertexAttrib1f(GLuint indx, GLfloat x) { - Graphics3D::GetCurrent()->impl()->VertexAttrib1f(indx, x); -} -void VertexAttrib1fv(GLuint indx, const GLfloat* values) { - Graphics3D::GetCurrent()->impl()->VertexAttrib1fv(indx, values); -} -void VertexAttrib2f(GLuint indx, GLfloat x, GLfloat y) { - Graphics3D::GetCurrent()->impl()->VertexAttrib2f(indx, x, y); -} -void VertexAttrib2fv(GLuint indx, const GLfloat* values) { - Graphics3D::GetCurrent()->impl()->VertexAttrib2fv(indx, values); -} -void VertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z) { - Graphics3D::GetCurrent()->impl()->VertexAttrib3f(indx, x, y, z); -} -void VertexAttrib3fv(GLuint indx, const GLfloat* values) { - Graphics3D::GetCurrent()->impl()->VertexAttrib3fv(indx, values); -} -void VertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { - Graphics3D::GetCurrent()->impl()->VertexAttrib4f(indx, x, y, z, w); -} -void VertexAttrib4fv(GLuint indx, const GLfloat* values) { - Graphics3D::GetCurrent()->impl()->VertexAttrib4fv(indx, values); -} -void VertexAttribPointer( - GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, - const void* ptr) { - Graphics3D::GetCurrent()->impl()->VertexAttribPointer( - indx, size, type, normalized, stride, ptr); -} -void Viewport(GLint x, GLint y, GLsizei width, GLsizei height) { - Graphics3D::GetCurrent()->impl()->Viewport(x, y, width, height); -} -void SwapBuffers() { - Graphics3D::GetCurrent()->impl()->SwapBuffers(); -} - -const struct PPB_OpenGLES_Dev ppb_opengles = { - &ActiveTexture, - &AttachShader, - &BindAttribLocation, - &BindBuffer, - &BindFramebuffer, - &BindRenderbuffer, - &BindTexture, - &BlendColor, - &BlendEquation, - &BlendEquationSeparate, - &BlendFunc, - &BlendFuncSeparate, - &BufferData, - &BufferSubData, - &CheckFramebufferStatus, - &Clear, - &ClearColor, - &ClearDepthf, - &ClearStencil, - &ColorMask, - &CompileShader, - &CompressedTexImage2D, - &CompressedTexSubImage2D, - &CopyTexImage2D, - &CopyTexSubImage2D, - &CreateProgram, - &CreateShader, - &CullFace, - &DeleteBuffers, - &DeleteFramebuffers, - &DeleteProgram, - &DeleteRenderbuffers, - &DeleteShader, - &DeleteTextures, - &DepthFunc, - &DepthMask, - &DepthRangef, - &DetachShader, - &Disable, - &DisableVertexAttribArray, - &DrawArrays, - &DrawElements, - &Enable, - &EnableVertexAttribArray, - &Finish, - &Flush, - &FramebufferRenderbuffer, - &FramebufferTexture2D, - &FrontFace, - &GenBuffers, - &GenerateMipmap, - &GenFramebuffers, - &GenRenderbuffers, - &GenTextures, - &GetActiveAttrib, - &GetActiveUniform, - &GetAttachedShaders, - &GetAttribLocation, - &GetBooleanv, - &GetBufferParameteriv, - &GetError, - &GetFloatv, - &GetFramebufferAttachmentParameteriv, - &GetIntegerv, - &GetProgramiv, - &GetProgramInfoLog, - &GetRenderbufferParameteriv, - &GetShaderiv, - &GetShaderInfoLog, - &GetShaderPrecisionFormat, - &GetShaderSource, - &GetString, - &GetTexParameterfv, - &GetTexParameteriv, - &GetUniformfv, - &GetUniformiv, - &GetUniformLocation, - &GetVertexAttribfv, - &GetVertexAttribiv, - &GetVertexAttribPointerv, - &Hint, - &IsBuffer, - &IsEnabled, - &IsFramebuffer, - &IsProgram, - &IsRenderbuffer, - &IsShader, - &IsTexture, - &LineWidth, - &LinkProgram, - &PixelStorei, - &PolygonOffset, - &ReadPixels, - &ReleaseShaderCompiler, - &RenderbufferStorage, - &SampleCoverage, - &Scissor, - &ShaderBinary, - &ShaderSource, - &StencilFunc, - &StencilFuncSeparate, - &StencilMask, - &StencilMaskSeparate, - &StencilOp, - &StencilOpSeparate, - &TexImage2D, - &TexParameterf, - &TexParameterfv, - &TexParameteri, - &TexParameteriv, - &TexSubImage2D, - &Uniform1f, - &Uniform1fv, - &Uniform1i, - &Uniform1iv, - &Uniform2f, - &Uniform2fv, - &Uniform2i, - &Uniform2iv, - &Uniform3f, - &Uniform3fv, - &Uniform3i, - &Uniform3iv, - &Uniform4f, - &Uniform4fv, - &Uniform4i, - &Uniform4iv, - &UniformMatrix2fv, - &UniformMatrix3fv, - &UniformMatrix4fv, - &UseProgram, - &ValidateProgram, - &VertexAttrib1f, - &VertexAttrib1fv, - &VertexAttrib2f, - &VertexAttrib2fv, - &VertexAttrib3f, - &VertexAttrib3fv, - &VertexAttrib4f, - &VertexAttrib4fv, - &VertexAttribPointer, - &Viewport, - &SwapBuffers -}; - -} // namespace - -const PPB_OpenGLES_Dev* Graphics3D::GetOpenGLESInterface() { - return &ppb_opengles; -} - -} // namespace pepper - diff --git a/webkit/glue/plugins/pepper_image_data.cc b/webkit/glue/plugins/pepper_image_data.cc deleted file mode 100644 index 92d4364..0000000 --- a/webkit/glue/plugins/pepper_image_data.cc +++ /dev/null @@ -1,210 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_image_data.h" - -#include <algorithm> -#include <limits> - -#include "base/logging.h" -#include "base/scoped_ptr.h" -#include "skia/ext/platform_canvas.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/ppb_image_data.h" -#include "ppapi/c/trusted/ppb_image_data_trusted.h" -#include "third_party/skia/include/core/SkColorPriv.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" - -namespace pepper { - -namespace { - -PP_ImageDataFormat GetNativeImageDataFormat() { - return ImageData::GetNativeImageDataFormat(); -} - -PP_Bool IsImageDataFormatSupported(PP_ImageDataFormat format) { - return BoolToPPBool(ImageData::IsImageDataFormatSupported(format)); -} - -PP_Resource Create(PP_Module module_id, - PP_ImageDataFormat format, - const PP_Size* size, - PP_Bool init_to_zero) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - scoped_refptr<ImageData> data(new ImageData(module)); - if (!data->Init(format, - size->width, - size->height, - PPBoolToBool(init_to_zero))) { - return 0; - } - - return data->GetReference(); -} - -PP_Bool IsImageData(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<ImageData>(resource)); -} - -PP_Bool Describe(PP_Resource resource, PP_ImageDataDesc* desc) { - // Give predictable values on failure. - memset(desc, 0, sizeof(PP_ImageDataDesc)); - - scoped_refptr<ImageData> image_data(Resource::GetAs<ImageData>(resource)); - if (!image_data) - return PP_FALSE; - image_data->Describe(desc); - return PP_TRUE; -} - -void* Map(PP_Resource resource) { - scoped_refptr<ImageData> image_data(Resource::GetAs<ImageData>(resource)); - if (!image_data) - return NULL; - return image_data->Map(); -} - -void Unmap(PP_Resource resource) { - scoped_refptr<ImageData> image_data(Resource::GetAs<ImageData>(resource)); - if (image_data) - image_data->Unmap(); -} - -uint64_t GetNativeMemoryHandle2(PP_Resource resource, uint32_t* byte_count) { - scoped_refptr<ImageData> image_data(Resource::GetAs<ImageData>(resource)); - if (image_data) - return image_data->GetNativeMemoryHandle(byte_count); - return 0; -} - -const PPB_ImageData ppb_imagedata = { - &GetNativeImageDataFormat, - &IsImageDataFormatSupported, - &Create, - &IsImageData, - &Describe, - &Map, - &Unmap, -}; - -const PPB_ImageDataTrusted ppb_imagedata_trusted = { - &GetNativeMemoryHandle2, -}; - -} // namespace - -ImageData::ImageData(PluginModule* module) - : Resource(module), - format_(PP_IMAGEDATAFORMAT_BGRA_PREMUL), - width_(0), - height_(0) { -} - -ImageData::~ImageData() { -} - -// static -const PPB_ImageData* ImageData::GetInterface() { - return &ppb_imagedata; -} - -// static -const PPB_ImageDataTrusted* ImageData::GetTrustedInterface() { - return &ppb_imagedata_trusted; -} - -// static -PP_ImageDataFormat ImageData::GetNativeImageDataFormat() { - if (SK_B32_SHIFT == 0) - return PP_IMAGEDATAFORMAT_BGRA_PREMUL; - else if (SK_R32_SHIFT == 0) - return PP_IMAGEDATAFORMAT_RGBA_PREMUL; - else - return PP_IMAGEDATAFORMAT_BGRA_PREMUL; // Default to something on failure. -} - -// static -bool ImageData::IsImageDataFormatSupported(PP_ImageDataFormat format) { - return format == PP_IMAGEDATAFORMAT_BGRA_PREMUL || - format == PP_IMAGEDATAFORMAT_RGBA_PREMUL; -} - -bool ImageData::Init(PP_ImageDataFormat format, - int width, int height, - bool init_to_zero) { - // TODO(brettw) this should be called only on the main thread! - // TODO(brettw) use init_to_zero when we implement caching. - if (!IsImageDataFormatSupported(format)) - return false; // Only support this one format for now. - if (width <= 0 || height <= 0) - return false; - if (static_cast<int64>(width) * static_cast<int64>(height) >= - std::numeric_limits<int32>::max()) - return false; // Prevent overflow of signed 32-bit ints. - - platform_image_.reset( - module()->GetSomeInstance()->delegate()->CreateImage2D(width, height)); - format_ = format; - width_ = width; - height_ = height; - return !!platform_image_.get(); -} - -void ImageData::Describe(PP_ImageDataDesc* desc) const { - desc->format = format_; - desc->size.width = width_; - desc->size.height = height_; - desc->stride = width_ * 4; -} - -void* ImageData::Map() { - if (!mapped_canvas_.get()) { - mapped_canvas_.reset(platform_image_->Map()); - if (!mapped_canvas_.get()) - return NULL; - } - const SkBitmap& bitmap = - mapped_canvas_->getTopPlatformDevice().accessBitmap(true); - - // Our platform bitmaps are set to opaque by default, which we don't want. - const_cast<SkBitmap&>(bitmap).setIsOpaque(false); - - bitmap.lockPixels(); - return bitmap.getAddr32(0, 0); -} - -void ImageData::Unmap() { - // This is currently unimplemented, which is OK. The data will just always - // be around once it's mapped. Chrome's TransportDIB isn't currently - // unmappable without freeing it, but this may be something we want to support - // in the future to save some memory. -} - -uint64 ImageData::GetNativeMemoryHandle(uint32* byte_count) const { - return platform_image_->GetSharedMemoryHandle(byte_count); -} - -const SkBitmap* ImageData::GetMappedBitmap() const { - if (!mapped_canvas_.get()) - return NULL; - return &mapped_canvas_->getTopPlatformDevice().accessBitmap(false); -} - -void ImageData::Swap(ImageData* other) { - swap(other->platform_image_, platform_image_); - swap(other->mapped_canvas_, mapped_canvas_); - std::swap(other->format_, format_); - std::swap(other->width_, width_); - std::swap(other->height_, height_); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_image_data.h b/webkit/glue/plugins/pepper_image_data.h deleted file mode 100644 index 473d4aa..0000000 --- a/webkit/glue/plugins/pepper_image_data.h +++ /dev/null @@ -1,131 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_IMAGE_DATA_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_IMAGE_DATA_H_ - -#include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "ppapi/c/ppb_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace skia { -class PlatformCanvas; -} - -struct PPB_ImageDataTrusted; -class SkBitmap; - -namespace pepper { - -class ImageData : public Resource { - public: - explicit ImageData(PluginModule* module); - virtual ~ImageData(); - - int width() const { return width_; } - int height() const { return height_; } - - // Returns the image format. - PP_ImageDataFormat format() const { return format_; } - - // Returns true if this image is mapped. False means that the image is either - // invalid or not mapped. See ImageDataAutoMapper below. - bool is_mapped() const { return !!mapped_canvas_.get(); } - - PluginDelegate::PlatformImage2D* platform_image() const { - return platform_image_.get(); - } - - // Returns a pointer to the interface implementing PPB_ImageData that is - // exposed to the plugin. - static const PPB_ImageData* GetInterface(); - static const PPB_ImageDataTrusted* GetTrustedInterface(); - - // Returns the image data format used by the browser. If the plugin uses the - // same format, there is no conversion. Otherwise the browser will be in - // charge of converting from a supported format to its native format. - static PP_ImageDataFormat GetNativeImageDataFormat(); - - // Returns true if the format is supported by the browser. - static bool IsImageDataFormatSupported(PP_ImageDataFormat format); - - // Resource overrides. - virtual ImageData* AsImageData() { return this; } - - // PPB_ImageData implementation. - bool Init(PP_ImageDataFormat format, - int width, int height, - bool init_to_zero); - void Describe(PP_ImageDataDesc* desc) const; - void* Map(); - void Unmap(); - - // PPB_ImageDataTrusted implementation. - uint64 GetNativeMemoryHandle(uint32* byte_count) const; - - // The mapped bitmap and canvas will be NULL if the image is not mapped. - skia::PlatformCanvas* mapped_canvas() const { return mapped_canvas_.get(); } - const SkBitmap* GetMappedBitmap() const; - - // Swaps the guts of this image data with another. - void Swap(ImageData* other); - - private: - // This will be NULL before initialization, and if this ImageData is - // swapped with another. - scoped_ptr<PluginDelegate::PlatformImage2D> platform_image_; - - // When the device is mapped, this is the image. Null when umapped. - scoped_ptr<skia::PlatformCanvas> mapped_canvas_; - - PP_ImageDataFormat format_; - int width_; - int height_; - - DISALLOW_COPY_AND_ASSIGN(ImageData); -}; - -// Manages mapping an image resource if necessary. Use this to ensure the -// image is mapped. The destructor will put the image back into the previous -// state. You must check is_valid() to make sure the image was successfully -// mapped before using it. -// -// Example: -// ImageDataAutoMapper mapper(image_data); -// if (!mapper.is_valid()) -// return utter_failure; -// image_data->mapped_canvas()->blah(); // Guaranteed valid. -class ImageDataAutoMapper { - public: - ImageDataAutoMapper(ImageData* image_data) : image_data_(image_data) { - if (image_data_->is_mapped()) { - is_valid_ = true; - needs_unmap_ = false; - } else { - is_valid_ = needs_unmap_ = !!image_data_->Map(); - } - } - - ~ImageDataAutoMapper() { - if (needs_unmap_) - image_data_->Unmap(); - } - - // Check this to see if the image was successfully mapped. If this is false, - // the image could not be mapped and is unusable. - bool is_valid() const { return is_valid_; } - - private: - ImageData* image_data_; - bool is_valid_; - bool needs_unmap_; - - DISALLOW_COPY_AND_ASSIGN(ImageDataAutoMapper); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_IMAGE_DATA_H_ diff --git a/webkit/glue/plugins/pepper_plugin_delegate.h b/webkit/glue/plugins/pepper_plugin_delegate.h deleted file mode 100644 index 7032c2c..0000000 --- a/webkit/glue/plugins/pepper_plugin_delegate.h +++ /dev/null @@ -1,281 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_DELEGATE_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_DELEGATE_H_ - -#include <string> - -#include "base/callback.h" -#include "base/platform_file.h" -#include "base/ref_counted.h" -#include "base/shared_memory.h" -#include "base/sync_socket.h" -#include "gfx/size.h" -#include "googleurl/src/gurl.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/pp_stdint.h" -#include "webkit/fileapi/file_system_types.h" -#include "webkit/glue/plugins/pepper_dir_contents.h" - -class AudioMessageFilter; -class GURL; - -namespace base { -class MessageLoopProxy; -class Time; -} - -namespace fileapi { -class FileSystemCallbackDispatcher; -} - -namespace gfx { -class Rect; -} - -namespace gpu { -namespace gles2 { -class GLES2Implementation; -} -} - -namespace skia { -class PlatformCanvas; -} - -namespace WebKit { -class WebFileChooserCompletion; -struct WebFileChooserParams; -} - -struct PP_VideoCompressedDataBuffer_Dev; -struct PP_VideoDecoderConfig_Dev; -struct PP_VideoUncompressedDataBuffer_Dev; - -class TransportDIB; - -namespace pepper { - -class FileIO; -class PluginInstance; -class FullscreenContainer; - -// Virtual interface that the browser implements to implement features for -// Pepper plugins. -class PluginDelegate { - public: - // Represents an image. This is to allow the browser layer to supply a correct - // image representation. In Chrome, this will be a TransportDIB. - class PlatformImage2D { - public: - virtual ~PlatformImage2D() {} - - // Caller will own the returned pointer, returns NULL on failure. - virtual skia::PlatformCanvas* Map() = 0; - - // Returns the platform-specific shared memory handle of the data backing - // this image. This is used by PPAPI proxying to send the image to the - // out-of-process plugin. On success, the size in bytes will be placed into - // |*bytes_count|. Returns 0 on failure. - virtual intptr_t GetSharedMemoryHandle(uint32* byte_count) const = 0; - - virtual TransportDIB* GetTransportDIB() const = 0; - }; - - class PlatformContext3D { - public: - virtual ~PlatformContext3D() {} - - // Initialize the context. - virtual bool Init() = 0; - - // Present the rendered frame to the compositor. - virtual bool SwapBuffers() = 0; - - // Get the last EGL error. - virtual unsigned GetError() = 0; - - // Resize the backing texture used as a back buffer by OpenGL. - virtual void ResizeBackingTexture(const gfx::Size& size) = 0; - - // Set an optional callback that will be invoked when the side effects of - // a SwapBuffers call become visible to the compositor. Takes ownership - // of the callback. - virtual void SetSwapBuffersCallback(Callback0::Type* callback) = 0; - - // If the plugin instance is backed by an OpenGL, return its ID in the - // compositors namespace. Otherwise return 0. Returns 0 by default. - virtual unsigned GetBackingTextureId() = 0; - - // This call will return the address of the GLES2 implementation for this - // context that is constructed in Initialize() and is valid until this - // context is destroyed. - virtual gpu::gles2::GLES2Implementation* GetGLES2Implementation() = 0; - }; - - class PlatformAudio { - public: - class Client { - protected: - virtual ~Client() {} - - public: - // Called when the stream is created. - virtual void StreamCreated(base::SharedMemoryHandle shared_memory_handle, - size_t shared_memory_size, - base::SyncSocket::Handle socket) = 0; - }; - - // Starts the playback. Returns false on error or if called before the - // stream is created or after the stream is closed. - virtual bool StartPlayback() = 0; - - // Stops the playback. Returns false on error or if called before the stream - // is created or after the stream is closed. - virtual bool StopPlayback() = 0; - - // Closes the stream. Make sure to call this before the object is - // destructed. - virtual void ShutDown() = 0; - - protected: - virtual ~PlatformAudio() {} - }; - - class PlatformVideoDecoder { - public: - virtual ~PlatformVideoDecoder() {} - - // Returns false on failure. - virtual bool Decode(PP_VideoCompressedDataBuffer_Dev& input_buffer) = 0; - virtual int32_t Flush(PP_CompletionCallback& callback) = 0; - virtual bool ReturnUncompressedDataBuffer( - PP_VideoUncompressedDataBuffer_Dev& buffer) = 0; - }; - - // Indicates that the given instance has been created. - virtual void InstanceCreated(pepper::PluginInstance* instance) = 0; - - // Indicates that the given instance is being destroyed. This is called from - // the destructor, so it's important that the instance is not dereferenced - // from this call. - virtual void InstanceDeleted(pepper::PluginInstance* instance) = 0; - - // The caller will own the pointer returned from this. - virtual PlatformImage2D* CreateImage2D(int width, int height) = 0; - - // The caller will own the pointer returned from this. - virtual PlatformContext3D* CreateContext3D() = 0; - - // The caller will own the pointer returned from this. - virtual PlatformVideoDecoder* CreateVideoDecoder( - const PP_VideoDecoderConfig_Dev& decoder_config) = 0; - - // The caller will own the pointer returned from this. - virtual PlatformAudio* CreateAudio(uint32_t sample_rate, - uint32_t sample_count, - PlatformAudio::Client* client) = 0; - - // Notifies that the number of find results has changed. - virtual void NumberOfFindResultsChanged(int identifier, - int total, - bool final_result) = 0; - - // Notifies that the index of the currently selected item has been updated. - virtual void SelectedFindResultChanged(int identifier, int index) = 0; - - // Runs a file chooser. - virtual bool RunFileChooser( - const WebKit::WebFileChooserParams& params, - WebKit::WebFileChooserCompletion* chooser_completion) = 0; - - // Sends an async IPC to open a file. - typedef Callback2<base::PlatformFileError, base::PlatformFile - >::Type AsyncOpenFileCallback; - virtual bool AsyncOpenFile(const FilePath& path, - int flags, - AsyncOpenFileCallback* callback) = 0; - virtual bool OpenFileSystem( - const GURL& url, - fileapi::FileSystemType type, - long long size, - fileapi::FileSystemCallbackDispatcher* dispatcher) = 0; - virtual bool MakeDirectory( - const FilePath& path, - bool recursive, - fileapi::FileSystemCallbackDispatcher* dispatcher) = 0; - virtual bool Query(const FilePath& path, - fileapi::FileSystemCallbackDispatcher* dispatcher) = 0; - virtual bool Touch(const FilePath& path, - const base::Time& last_access_time, - const base::Time& last_modified_time, - fileapi::FileSystemCallbackDispatcher* dispatcher) = 0; - virtual bool Delete(const FilePath& path, - fileapi::FileSystemCallbackDispatcher* dispatcher) = 0; - virtual bool Rename(const FilePath& file_path, - const FilePath& new_file_path, - fileapi::FileSystemCallbackDispatcher* dispatcher) = 0; - virtual bool ReadDirectory( - const FilePath& directory_path, - fileapi::FileSystemCallbackDispatcher* dispatcher) = 0; - - virtual base::PlatformFileError OpenModuleLocalFile( - const std::string& module_name, - const FilePath& path, - int flags, - base::PlatformFile* file) = 0; - virtual base::PlatformFileError RenameModuleLocalFile( - const std::string& module_name, - const FilePath& path_from, - const FilePath& path_to) = 0; - virtual base::PlatformFileError DeleteModuleLocalFileOrDir( - const std::string& module_name, - const FilePath& path, - bool recursive) = 0; - virtual base::PlatformFileError CreateModuleLocalDir( - const std::string& module_name, - const FilePath& path) = 0; - virtual base::PlatformFileError QueryModuleLocalFile( - const std::string& module_name, - const FilePath& path, - base::PlatformFileInfo* info) = 0; - virtual base::PlatformFileError GetModuleLocalDirContents( - const std::string& module_name, - const FilePath& path, - PepperDirContents* contents) = 0; - - // Returns a MessageLoopProxy instance associated with the message loop - // of the file thread in this renderer. - virtual scoped_refptr<base::MessageLoopProxy> - GetFileThreadMessageLoopProxy() = 0; - - // Create a fullscreen container for a plugin instance. This effectively - // switches the plugin to fullscreen. - virtual FullscreenContainer* CreateFullscreenContainer( - PluginInstance* instance) = 0; - - // Returns a string with the name of the default 8-bit char encoding. - virtual std::string GetDefaultEncoding() = 0; - - // Sets the mininum and maximium zoom factors. - virtual void ZoomLimitsChanged(double minimum_factor, - double maximum_factor) = 0; - - // Retrieves the proxy information for the given URL in PAC format. On error, - // this will return an empty string. - virtual std::string ResolveProxy(const GURL& url) = 0; - - // Tell the browser when resource loading starts/ends. - virtual void DidStartLoading() = 0; - virtual void DidStopLoading() = 0; - - // Sets restrictions on how the content can be used (i.e. no print/copy). - virtual void SetContentRestriction(int restrictions) = 0; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_DELEGATE_H_ diff --git a/webkit/glue/plugins/pepper_plugin_instance.cc b/webkit/glue/plugins/pepper_plugin_instance.cc deleted file mode 100644 index f705178..0000000 --- a/webkit/glue/plugins/pepper_plugin_instance.cc +++ /dev/null @@ -1,1179 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_plugin_instance.h" - -#include "base/logging.h" -#include "base/metrics/histogram.h" -#if defined(OS_MACOSX) -#include "base/mac_util.h" -#include "base/mac/scoped_cftyperef.h" -#endif -#include "base/scoped_ptr.h" -#include "base/utf_string_conversions.h" -#include "gfx/rect.h" -#if defined(OS_WIN) -#include "gfx/codec/jpeg_codec.h" -#include "gfx/gdi_util.h" -#endif -#include "gfx/skia_util.h" -#include "ppapi/c/dev/ppb_find_dev.h" -#include "ppapi/c/dev/ppb_fullscreen_dev.h" -#include "ppapi/c/dev/ppb_zoom_dev.h" -#include "ppapi/c/dev/ppp_find_dev.h" -#include "ppapi/c/dev/ppp_selection_dev.h" -#include "ppapi/c/dev/ppp_zoom_dev.h" -#include "ppapi/c/pp_input_event.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/ppb_instance.h" -#include "ppapi/c/ppp_instance.h" -#include "printing/native_metafile.h" -#include "printing/units.h" -#include "skia/ext/vector_platform_device.h" -#include "skia/ext/platform_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebBindings.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebElement.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginContainer.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/plugins/pepper_buffer.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_graphics_2d.h" -#include "webkit/glue/plugins/pepper_graphics_3d.h" -#include "webkit/glue/plugins/pepper_event_conversion.h" -#include "webkit/glue/plugins/pepper_fullscreen_container.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_string.h" -#include "webkit/glue/plugins/pepper_url_loader.h" -#include "webkit/glue/plugins/pepper_var.h" -#include "webkit/glue/plugins/ppp_private.h" - -using WebKit::WebBindings; -using WebKit::WebCanvas; -using WebKit::WebCursorInfo; -using WebKit::WebDocument; -using WebKit::WebFrame; -using WebKit::WebInputEvent; -using WebKit::WebPluginContainer; -using WebKit::WebString; -using WebKit::WebURLRequest; -using WebKit::WebView; - -namespace pepper { - -#if defined(OS_WIN) -// Exported by pdf.dll -typedef bool (*RenderPDFPageToDCProc)( - const unsigned char* pdf_buffer, int buffer_size, int page_number, HDC dc, - int dpi_x, int dpi_y, int bounds_origin_x, int bounds_origin_y, - int bounds_width, int bounds_height, bool fit_to_bounds, - bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds); -#endif // defined(OS_WIN) - -namespace { - -#define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \ - COMPILE_ASSERT(int(WebCursorInfo::webkit_name) == int(np_name), \ - mismatching_enums) - -COMPILE_ASSERT_MATCHING_ENUM(TypePointer, PP_CURSORTYPE_POINTER); -COMPILE_ASSERT_MATCHING_ENUM(TypeCross, PP_CURSORTYPE_CROSS); -COMPILE_ASSERT_MATCHING_ENUM(TypeHand, PP_CURSORTYPE_HAND); -COMPILE_ASSERT_MATCHING_ENUM(TypeIBeam, PP_CURSORTYPE_IBEAM); -COMPILE_ASSERT_MATCHING_ENUM(TypeWait, PP_CURSORTYPE_WAIT); -COMPILE_ASSERT_MATCHING_ENUM(TypeHelp, PP_CURSORTYPE_HELP); -COMPILE_ASSERT_MATCHING_ENUM(TypeEastResize, PP_CURSORTYPE_EASTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_CURSORTYPE_NORTHRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastResize, - PP_CURSORTYPE_NORTHEASTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestResize, - PP_CURSORTYPE_NORTHWESTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_CURSORTYPE_SOUTHRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastResize, - PP_CURSORTYPE_SOUTHEASTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestResize, - PP_CURSORTYPE_SOUTHWESTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeWestResize, PP_CURSORTYPE_WESTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthSouthResize, - PP_CURSORTYPE_NORTHSOUTHRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeEastWestResize, PP_CURSORTYPE_EASTWESTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize, - PP_CURSORTYPE_NORTHEASTSOUTHWESTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize, - PP_CURSORTYPE_NORTHWESTSOUTHEASTRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeColumnResize, PP_CURSORTYPE_COLUMNRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeRowResize, PP_CURSORTYPE_ROWRESIZE); -COMPILE_ASSERT_MATCHING_ENUM(TypeMiddlePanning, PP_CURSORTYPE_MIDDLEPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_CURSORTYPE_EASTPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthPanning, PP_CURSORTYPE_NORTHPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastPanning, - PP_CURSORTYPE_NORTHEASTPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestPanning, - PP_CURSORTYPE_NORTHWESTPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeSouthPanning, PP_CURSORTYPE_SOUTHPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastPanning, - PP_CURSORTYPE_SOUTHEASTPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestPanning, - PP_CURSORTYPE_SOUTHWESTPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_CURSORTYPE_WESTPANNING); -COMPILE_ASSERT_MATCHING_ENUM(TypeMove, PP_CURSORTYPE_MOVE); -COMPILE_ASSERT_MATCHING_ENUM(TypeVerticalText, PP_CURSORTYPE_VERTICALTEXT); -COMPILE_ASSERT_MATCHING_ENUM(TypeCell, PP_CURSORTYPE_CELL); -COMPILE_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_CURSORTYPE_CONTEXTMENU); -COMPILE_ASSERT_MATCHING_ENUM(TypeAlias, PP_CURSORTYPE_ALIAS); -COMPILE_ASSERT_MATCHING_ENUM(TypeProgress, PP_CURSORTYPE_PROGRESS); -COMPILE_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_CURSORTYPE_NODROP); -COMPILE_ASSERT_MATCHING_ENUM(TypeCopy, PP_CURSORTYPE_COPY); -COMPILE_ASSERT_MATCHING_ENUM(TypeNone, PP_CURSORTYPE_NONE); -COMPILE_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_CURSORTYPE_NOTALLOWED); -COMPILE_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_CURSORTYPE_ZOOMIN); -COMPILE_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_CURSORTYPE_ZOOMOUT); -COMPILE_ASSERT_MATCHING_ENUM(TypeCustom, PP_CURSORTYPE_CUSTOM); - -void RectToPPRect(const gfx::Rect& input, PP_Rect* output) { - *output = PP_MakeRectFromXYWH(input.x(), input.y(), - input.width(), input.height()); -} - -PP_Var GetWindowObject(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_MakeUndefined(); - return instance->GetWindowObject(); -} - -PP_Var GetOwnerElementObject(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_MakeUndefined(); - return instance->GetOwnerElementObject(); -} - -PP_Bool BindGraphics(PP_Instance instance_id, PP_Resource graphics_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - return BoolToPPBool(instance->BindGraphics(graphics_id)); -} - -PP_Bool IsFullFrame(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - return BoolToPPBool(instance->full_frame()); -} - -PP_Var ExecuteScript(PP_Instance instance_id, - PP_Var script, - PP_Var* exception) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_MakeUndefined(); - return instance->ExecuteScript(script, exception); -} - -const PPB_Instance ppb_instance = { - &GetWindowObject, - &GetOwnerElementObject, - &BindGraphics, - &IsFullFrame, - &ExecuteScript, -}; - -void NumberOfFindResultsChanged(PP_Instance instance_id, - int32_t total, - PP_Bool final_result) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return; - - DCHECK_NE(instance->find_identifier(), -1); - instance->delegate()->NumberOfFindResultsChanged( - instance->find_identifier(), total, PPBoolToBool(final_result)); -} - -void SelectedFindResultChanged(PP_Instance instance_id, - int32_t index) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return; - - DCHECK_NE(instance->find_identifier(), -1); - instance->delegate()->SelectedFindResultChanged( - instance->find_identifier(), index); -} - -const PPB_Find_Dev ppb_find = { - &NumberOfFindResultsChanged, - &SelectedFindResultChanged, -}; - -PP_Bool IsFullscreen(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - return BoolToPPBool(instance->IsFullscreen()); -} - -PP_Bool SetFullscreen(PP_Instance instance_id, PP_Bool fullscreen) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_FALSE; - return BoolToPPBool(instance->SetFullscreen(PPBoolToBool(fullscreen))); -} - -const PPB_Fullscreen_Dev ppb_fullscreen = { - &IsFullscreen, - &SetFullscreen, -}; - -void ZoomChanged(PP_Instance instance_id, double factor) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return; - - // We only want to tell the page to change its zoom if the whole page is the - // PDF. If we're in an iframe, then don't do anything. - WebFrame* frame = instance->container()->element().document().frame(); - if (!frame->view()->mainFrame()->document().isPluginDocument()) - return; - - double zoom_level = WebView::zoomFactorToZoomLevel(factor); - // The conversino from zoom level to factor, and back, can introduce rounding - // errors. i.e. WebKit originally tells us 3.0, but by the time we tell the - // plugin and it tells us back, the level becomes 3.000000000004. Need to - // round or else otherwise if the user zooms out, it will go to 3.0 instead of - // 2.0. - int rounded = - static_cast<int>(zoom_level + (zoom_level > 0 ? 0.001 : -0.001)); - if (abs(rounded - zoom_level) < 0.001) - zoom_level = rounded; - instance->container()->zoomLevelChanged(zoom_level); -} - -void ZoomLimitsChanged(PP_Instance instance_id, - double minimum_factor, - double maximium_factor) { - if (minimum_factor > maximium_factor) { - NOTREACHED(); - return; - } - - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return; - instance->delegate()->ZoomLimitsChanged(minimum_factor, maximium_factor); -} - -const PPB_Zoom_Dev ppb_zoom = { - &ZoomChanged, - &ZoomLimitsChanged -}; - -} // namespace - -PluginInstance::PluginInstance(PluginDelegate* delegate, - PluginModule* module, - const PPP_Instance* instance_interface) - : delegate_(delegate), - module_(module), - instance_interface_(instance_interface), - pp_instance_(0), - container_(NULL), - full_frame_(false), - has_webkit_focus_(false), - has_content_area_focus_(false), - find_identifier_(-1), - plugin_find_interface_(NULL), - plugin_private_interface_(NULL), - plugin_selection_interface_(NULL), - plugin_zoom_interface_(NULL), -#if defined (OS_LINUX) - num_pages_(0), - pdf_output_done_(false), -#endif // defined (OS_LINUX) - plugin_print_interface_(NULL), - plugin_graphics_3d_interface_(NULL), - always_on_top_(false), - fullscreen_container_(NULL) { - pp_instance_ = ResourceTracker::Get()->AddInstance(this); - - memset(¤t_print_settings_, 0, sizeof(current_print_settings_)); - DCHECK(delegate); - module_->InstanceCreated(this); - delegate_->InstanceCreated(this); -} - -PluginInstance::~PluginInstance() { - FOR_EACH_OBSERVER(Observer, observers_, InstanceDestroyed(this)); - - delegate_->InstanceDeleted(this); - module_->InstanceDeleted(this); - - ResourceTracker::Get()->InstanceDeleted(pp_instance_); -} - -// static -const PPB_Instance* PluginInstance::GetInterface() { - return &ppb_instance; -} - -// static -const PPB_Find_Dev* PluginInstance::GetFindInterface() { - return &ppb_find; -} - -// static -const PPB_Fullscreen_Dev* PluginInstance::GetFullscreenInterface() { - return &ppb_fullscreen; -} - -// static -const PPB_Zoom_Dev* PluginInstance::GetZoomInterface() { - return &ppb_zoom; -} - -void PluginInstance::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void PluginInstance::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -void PluginInstance::Paint(WebCanvas* canvas, - const gfx::Rect& plugin_rect, - const gfx::Rect& paint_rect) { - if (bound_graphics_2d()) - bound_graphics_2d()->Paint(canvas, plugin_rect, paint_rect); -} - -void PluginInstance::InvalidateRect(const gfx::Rect& rect) { - if (fullscreen_container_) { - if (rect.IsEmpty()) - fullscreen_container_->Invalidate(); - else - fullscreen_container_->InvalidateRect(rect); - } else { - if (!container_ || position_.IsEmpty()) - return; // Nothing to do. - if (rect.IsEmpty()) - container_->invalidate(); - else - container_->invalidateRect(rect); - } -} - -void PluginInstance::ScrollRect(int dx, int dy, const gfx::Rect& rect) { - if (fullscreen_container_) { - fullscreen_container_->ScrollRect(dx, dy, rect); - } else { - if (full_frame_) { - container_->scrollRect(dx, dy, rect); - } else { - // Can't do optimized scrolling since there could be other elements on top - // of us. - InvalidateRect(rect); - } - } -} - -unsigned PluginInstance::GetBackingTextureId() { - if (!bound_graphics_3d()) - return 0; - - return bound_graphics_3d()->GetBackingTextureId(); -} - -void PluginInstance::CommitBackingTexture() { - container_->commitBackingTexture(); -} - -PP_Var PluginInstance::GetWindowObject() { - if (!container_) - return PP_MakeUndefined(); - - WebFrame* frame = container_->element().document().frame(); - if (!frame) - return PP_MakeUndefined(); - - return ObjectVar::NPObjectToPPVar(module(), frame->windowObject()); -} - -PP_Var PluginInstance::GetOwnerElementObject() { - if (!container_) - return PP_MakeUndefined(); - return ObjectVar::NPObjectToPPVar(module(), - container_->scriptableObjectForElement()); -} - -bool PluginInstance::BindGraphics(PP_Resource graphics_id) { - if (!graphics_id) { - // Special-case clearing the current device. - if (bound_graphics_.get()) { - if (bound_graphics_2d()) { - bound_graphics_2d()->BindToInstance(NULL); - } else if (bound_graphics_.get()) { - bound_graphics_3d()->SetSwapBuffersCallback(NULL); - bound_graphics_3d()->BindToInstance(NULL); - } - InvalidateRect(gfx::Rect()); - } - bound_graphics_ = NULL; - return true; - } - - scoped_refptr<Graphics2D> graphics_2d = - Resource::GetAs<Graphics2D>(graphics_id); - scoped_refptr<Graphics3D> graphics_3d = - Resource::GetAs<Graphics3D>(graphics_id); - - if (graphics_2d) { - if (!graphics_2d->BindToInstance(this)) - return false; // Can't bind to more than one instance. - - // See http://crbug.com/49403: this can be further optimized by keeping the - // old device around and painting from it. - if (bound_graphics_2d()) { - // Start the new image with the content of the old image until the plugin - // repaints. - const SkBitmap* old_backing_bitmap = - bound_graphics_2d()->image_data()->GetMappedBitmap(); - SkRect old_size = SkRect::MakeWH( - SkScalar(static_cast<float>(old_backing_bitmap->width())), - SkScalar(static_cast<float>(old_backing_bitmap->height()))); - - SkCanvas canvas(*graphics_2d->image_data()->GetMappedBitmap()); - canvas.drawBitmap(*old_backing_bitmap, 0, 0); - - // Fill in any extra space with white. - canvas.clipRect(old_size, SkRegion::kDifference_Op); - canvas.drawARGB(255, 255, 255, 255); - } - - bound_graphics_ = graphics_2d; - // BindToInstance will have invalidated the plugin if necessary. - } else if (graphics_3d) { - if (!graphics_3d->BindToInstance(this)) - return false; - - bound_graphics_ = graphics_3d; - bound_graphics_3d()->SetSwapBuffersCallback( - NewCallback(this, &PluginInstance::CommitBackingTexture)); - } - - return true; -} - -bool PluginInstance::SetCursor(PP_CursorType_Dev type) { - cursor_.reset(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type))); - return true; -} - -PP_Var PluginInstance::ExecuteScript(PP_Var script, PP_Var* exception) { - TryCatch try_catch(module(), exception); - if (try_catch.has_exception()) - return PP_MakeUndefined(); - - // Convert the script into an inconvenient NPString object. - scoped_refptr<StringVar> script_string(StringVar::FromPPVar(script)); - if (!script_string) { - try_catch.SetException("Script param to ExecuteScript must be a string."); - return PP_MakeUndefined(); - } - NPString np_script; - np_script.UTF8Characters = script_string->value().c_str(); - np_script.UTF8Length = script_string->value().length(); - - // Get the current frame to pass to the evaluate function. - WebFrame* frame = container_->element().document().frame(); - if (!frame) { - try_catch.SetException("No frame to execute script in."); - return PP_MakeUndefined(); - } - - NPVariant result; - bool ok = WebBindings::evaluate(NULL, frame->windowObject(), &np_script, - &result); - if (!ok) { - // TODO(brettw) bug 54011: The TryCatch isn't working properly and - // doesn't actually catch this exception. - try_catch.SetException("Exception caught"); - WebBindings::releaseVariantValue(&result); - return PP_MakeUndefined(); - } - - PP_Var ret = Var::NPVariantToPPVar(module_, &result); - WebBindings::releaseVariantValue(&result); - return ret; -} - -void PluginInstance::Delete() { - instance_interface_->DidDestroy(pp_instance()); - - if (fullscreen_container_) { - fullscreen_container_->Destroy(); - fullscreen_container_ = NULL; - } - container_ = NULL; -} - -bool PluginInstance::Initialize(WebPluginContainer* container, - const std::vector<std::string>& arg_names, - const std::vector<std::string>& arg_values, - bool full_frame) { - container_ = container; - full_frame_ = full_frame; - - size_t argc = 0; - scoped_array<const char*> argn(new const char*[arg_names.size()]); - scoped_array<const char*> argv(new const char*[arg_names.size()]); - for (size_t i = 0; i < arg_names.size(); ++i) { - argn[argc] = arg_names[i].c_str(); - argv[argc] = arg_values[i].c_str(); - argc++; - } - - return PPBoolToBool(instance_interface_->DidCreate(pp_instance(), - argc, - argn.get(), - argv.get())); -} - -bool PluginInstance::HandleDocumentLoad(URLLoader* loader) { - Resource::ScopedResourceId resource(loader); - return PPBoolToBool(instance_interface_->HandleDocumentLoad(pp_instance(), - resource.id)); -} - -bool PluginInstance::HandleInputEvent(const WebKit::WebInputEvent& event, - WebCursorInfo* cursor_info) { - std::vector<PP_InputEvent> pp_events; - CreatePPEvent(event, &pp_events); - - // Each input event may generate more than one PP_InputEvent. - bool rv = false; - for (size_t i = 0; i < pp_events.size(); i++) { - rv |= PPBoolToBool(instance_interface_->HandleInputEvent(pp_instance(), - &pp_events[i])); - } - - if (cursor_.get()) - *cursor_info = *cursor_; - return rv; -} - -PP_Var PluginInstance::GetInstanceObject() { - return instance_interface_->GetInstanceObject(pp_instance()); -} - -void PluginInstance::ViewChanged(const gfx::Rect& position, - const gfx::Rect& clip) { - if (position.size() != position_.size() && bound_graphics_3d()) { - // TODO(apatrick): This is a hack to force the back buffer to resize. - // It is obviously wrong to call SwapBuffers when a partial frame has - // potentially been rendered. Plan is to embed resize commands in the - // command buffer just before ViewChanged is called. - bound_graphics_3d()->ResizeBackingTexture(position.size()); - bound_graphics_3d()->SwapBuffers(); - } - - position_ = position; - - if (clip.IsEmpty()) { - // WebKit can give weird (x,y) positions for empty clip rects (since the - // position technically doesn't matter). But we want to make these - // consistent since this is given to the plugin, so force everything to 0 - // in the "everything is clipped" case. - clip_ = gfx::Rect(); - } else { - clip_ = clip; - } - - PP_Rect pp_position, pp_clip; - RectToPPRect(position_, &pp_position); - RectToPPRect(clip_, &pp_clip); - instance_interface_->DidChangeView(pp_instance(), &pp_position, &pp_clip); -} - -void PluginInstance::SetWebKitFocus(bool has_focus) { - if (has_webkit_focus_ == has_focus) - return; - - bool old_plugin_focus = PluginHasFocus(); - has_webkit_focus_ = has_focus; - if (PluginHasFocus() != old_plugin_focus) { - instance_interface_->DidChangeFocus(pp_instance(), - BoolToPPBool(PluginHasFocus())); - } -} - -void PluginInstance::SetContentAreaFocus(bool has_focus) { - if (has_content_area_focus_ == has_focus) - return; - - bool old_plugin_focus = PluginHasFocus(); - has_content_area_focus_ = has_focus; - if (PluginHasFocus() != old_plugin_focus) { - instance_interface_->DidChangeFocus(pp_instance(), - BoolToPPBool(PluginHasFocus())); - } -} - -void PluginInstance::ViewInitiatedPaint() { - if (bound_graphics_2d()) - bound_graphics_2d()->ViewInitiatedPaint(); -} - -void PluginInstance::ViewFlushedPaint() { - if (bound_graphics_2d()) - bound_graphics_2d()->ViewFlushedPaint(); -} - -bool PluginInstance::GetBitmapForOptimizedPluginPaint( - const gfx::Rect& paint_bounds, - TransportDIB** dib, - gfx::Rect* location, - gfx::Rect* clip) { - if (!always_on_top_) - return false; - if (!bound_graphics_2d() || !bound_graphics_2d()->is_always_opaque()) - return false; - - // We specifically want to compare against the area covered by the backing - // store when seeing if we cover the given paint bounds, since the backing - // store could be smaller than the declared plugin area. - ImageData* image_data = bound_graphics_2d()->image_data(); - gfx::Rect plugin_backing_store_rect(position_.origin(), - gfx::Size(image_data->width(), - image_data->height())); - gfx::Rect clip_page(clip_); - clip_page.Offset(position_.origin()); - gfx::Rect plugin_paint_rect = plugin_backing_store_rect.Intersect(clip_page); - if (!plugin_paint_rect.Contains(paint_bounds)) - return false; - - *dib = image_data->platform_image()->GetTransportDIB(); - *location = plugin_backing_store_rect; - *clip = clip_page; - return true; -} - -string16 PluginInstance::GetSelectedText(bool html) { - if (!LoadSelectionInterface()) - return string16(); - - PP_Var rv = plugin_selection_interface_->GetSelectedText(pp_instance(), - BoolToPPBool(html)); - scoped_refptr<StringVar> string(StringVar::FromPPVar(rv)); - Var::PluginReleasePPVar(rv); // Release the ref the plugin transfered to us. - if (!string) - return string16(); - return UTF8ToUTF16(string->value()); -} - -string16 PluginInstance::GetLinkAtPosition(const gfx::Point& point) { - if (!LoadPrivateInterface()) - return string16(); - - PP_Point p; - p.x = point.x(); - p.y = point.y(); - PP_Var rv = plugin_private_interface_->GetLinkAtPosition(pp_instance(), p); - scoped_refptr<StringVar> string(StringVar::FromPPVar(rv)); - Var::PluginReleasePPVar(rv); // Release the ref the plugin transfered to us. - if (!string) - return string16(); - return UTF8ToUTF16(string->value()); -} - -void PluginInstance::Zoom(double factor, bool text_only) { - if (!LoadZoomInterface()) - return; - plugin_zoom_interface_->Zoom(pp_instance(), factor, BoolToPPBool(text_only)); -} - -bool PluginInstance::StartFind(const string16& search_text, - bool case_sensitive, - int identifier) { - if (!LoadFindInterface()) - return false; - find_identifier_ = identifier; - return PPBoolToBool( - plugin_find_interface_->StartFind( - pp_instance(), - UTF16ToUTF8(search_text.c_str()).c_str(), - BoolToPPBool(case_sensitive))); -} - -void PluginInstance::SelectFindResult(bool forward) { - if (LoadFindInterface()) - plugin_find_interface_->SelectFindResult(pp_instance(), - BoolToPPBool(forward)); -} - -void PluginInstance::StopFind() { - if (!LoadFindInterface()) - return; - find_identifier_ = -1; - plugin_find_interface_->StopFind(pp_instance()); -} - -bool PluginInstance::LoadFindInterface() { - if (!plugin_find_interface_) { - plugin_find_interface_ = - reinterpret_cast<const PPP_Find_Dev*>(module_->GetPluginInterface( - PPP_FIND_DEV_INTERFACE)); - } - - return !!plugin_find_interface_; -} - -bool PluginInstance::LoadPrivateInterface() { - if (!plugin_private_interface_) { - plugin_private_interface_ = - reinterpret_cast<const PPP_Private*>(module_->GetPluginInterface( - PPP_PRIVATE_INTERFACE)); - } - - return !!plugin_private_interface_; -} - -bool PluginInstance::LoadSelectionInterface() { - if (!plugin_selection_interface_) { - plugin_selection_interface_ = - reinterpret_cast<const PPP_Selection_Dev*>(module_->GetPluginInterface( - PPP_SELECTION_DEV_INTERFACE)); - } - - return !!plugin_selection_interface_; -} - -bool PluginInstance::LoadZoomInterface() { - if (!plugin_zoom_interface_) { - plugin_zoom_interface_ = - reinterpret_cast<const PPP_Zoom_Dev*>(module_->GetPluginInterface( - PPP_ZOOM_DEV_INTERFACE)); - } - - return !!plugin_zoom_interface_; -} - -bool PluginInstance::PluginHasFocus() const { - return has_webkit_focus_ && has_content_area_focus_; -} - -bool PluginInstance::GetPreferredPrintOutputFormat( - PP_PrintOutputFormat_Dev* format) { - if (!plugin_print_interface_) { - plugin_print_interface_ = - reinterpret_cast<const PPP_Printing_Dev*>(module_->GetPluginInterface( - PPP_PRINTING_DEV_INTERFACE)); - } - if (!plugin_print_interface_) - return false; - uint32_t format_count = 0; - PP_PrintOutputFormat_Dev* supported_formats = - plugin_print_interface_->QuerySupportedFormats(pp_instance(), - &format_count); - if (!supported_formats) - return false; - - bool found_supported_format = false; - for (uint32_t index = 0; index < format_count; index++) { - if (supported_formats[index] == PP_PRINTOUTPUTFORMAT_PDF) { - // If we found PDF, we are done. - found_supported_format = true; - *format = PP_PRINTOUTPUTFORMAT_PDF; - break; - } else if (supported_formats[index] == PP_PRINTOUTPUTFORMAT_RASTER) { - // We found raster. Keep looking. - found_supported_format = true; - *format = PP_PRINTOUTPUTFORMAT_RASTER; - } - } - PluginModule::GetCore()->MemFree(supported_formats); - return found_supported_format; -} - -bool PluginInstance::SupportsPrintInterface() { - PP_PrintOutputFormat_Dev format; - return GetPreferredPrintOutputFormat(&format); -} - -int PluginInstance::PrintBegin(const gfx::Rect& printable_area, - int printer_dpi) { - PP_PrintOutputFormat_Dev format; - if (!GetPreferredPrintOutputFormat(&format)) { - // PrintBegin should not have been called since SupportsPrintInterface - // would have returned false; - NOTREACHED(); - return 0; - } - - PP_PrintSettings_Dev print_settings; - RectToPPRect(printable_area, &print_settings.printable_area); - print_settings.dpi = printer_dpi; - print_settings.orientation = PP_PRINTORIENTATION_NORMAL; - print_settings.grayscale = PP_FALSE; - print_settings.format = format; - int num_pages = plugin_print_interface_->Begin(pp_instance(), - &print_settings); - if (!num_pages) - return 0; - current_print_settings_ = print_settings; -#if defined (OS_LINUX) - num_pages_ = num_pages; - pdf_output_done_ = false; -#endif // (OS_LINUX) - return num_pages; -} - -bool PluginInstance::PrintPage(int page_number, WebKit::WebCanvas* canvas) { - DCHECK(plugin_print_interface_); - PP_PrintPageNumberRange_Dev page_range; -#if defined(OS_LINUX) - if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF) { - // On Linux we will try and output all pages as PDF in the first call to - // PrintPage. This is a temporary hack. - // TODO(sanjeevr): Remove this hack and fix this by changing the print - // interfaces for WebFrame and WebPlugin. - if (page_number != 0) - return pdf_output_done_; - page_range.first_page_number = 0; - page_range.last_page_number = num_pages_ - 1; - } -#else // defined(OS_LINUX) - page_range.first_page_number = page_range.last_page_number = page_number; -#endif // defined(OS_LINUX) - - PP_Resource print_output = - plugin_print_interface_->PrintPages(pp_instance(), &page_range, 1); - - if (!print_output) - return false; - - bool ret = false; - - if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF) - ret = PrintPDFOutput(print_output, canvas); - else if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_RASTER) - ret = PrintRasterOutput(print_output, canvas); - - // Now we need to release the print output resource. - PluginModule::GetCore()->ReleaseResource(print_output); - - return ret; -} - -void PluginInstance::PrintEnd() { - DCHECK(plugin_print_interface_); - if (plugin_print_interface_) - plugin_print_interface_->End(pp_instance()); - memset(¤t_print_settings_, 0, sizeof(current_print_settings_)); -#if defined(OS_MACOSX) - last_printed_page_ = NULL; -#elif defined(OS_LINUX) - num_pages_ = 0; - pdf_output_done_ = false; -#endif // defined(OS_LINUX) -} - -bool PluginInstance::IsFullscreen() { - return fullscreen_container_ != NULL; -} - -bool PluginInstance::SetFullscreen(bool fullscreen) { - bool is_fullscreen = (fullscreen_container_ != NULL); - if (fullscreen == is_fullscreen) - return true; - VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off"); - if (fullscreen) { - fullscreen_container_ = delegate_->CreateFullscreenContainer(this); - } else { - fullscreen_container_->Destroy(); - fullscreen_container_ = NULL; - // TODO(piman): currently the fullscreen container resizes the plugin to the - // fullscreen size so we need to reset the size here. Eventually it will - // transparently scale and this won't be necessary. - if (container_) { - container_->reportGeometry(); - container_->invalidate(); - } - } - return true; -} - -bool PluginInstance::NavigateToURL(const char* url, const char* target) { - if (!url || !target || !container_) - return false; - - WebDocument document = container_->element().document(); - GURL complete_url = document.completeURL(WebString::fromUTF8(url)); - // Don't try to deal with the security issues of javascript. - if (complete_url.SchemeIs("javascript")) - return false; - - WebURLRequest request(complete_url); - document.frame()->setReferrerForRequest(request, GURL()); - request.setHTTPMethod(WebString::fromUTF8("GET")); - request.setFirstPartyForCookies(document.firstPartyForCookies()); - - WebString target_str = WebString::fromUTF8(target); - container_->loadFrameRequest(request, target_str, false, NULL); - return true; -} - -bool PluginInstance::PrintPDFOutput(PP_Resource print_output, - WebKit::WebCanvas* canvas) { - scoped_refptr<Buffer> buffer(Resource::GetAs<Buffer>(print_output)); - if (!buffer.get() || !buffer->is_mapped() || !buffer->size()) { - NOTREACHED(); - return false; - } -#if defined(OS_WIN) - // For Windows, we need the PDF DLL to render the output PDF to a DC. - HMODULE pdf_module = GetModuleHandle(L"pdf.dll"); - if (!pdf_module) - return false; - RenderPDFPageToDCProc render_proc = - reinterpret_cast<RenderPDFPageToDCProc>( - GetProcAddress(pdf_module, "RenderPDFPageToDC")); - if (!render_proc) - return false; -#endif // defined(OS_WIN) - - bool ret = false; -#if defined(OS_LINUX) - // On Linux we need to get the backing PdfPsMetafile and write the bits - // directly. - cairo_t* context = canvas->beginPlatformPaint(); - printing::NativeMetafile* metafile = - printing::NativeMetafile::FromCairoContext(context); - DCHECK(metafile); - if (metafile) { - ret = metafile->SetRawData(buffer->mapped_buffer(), buffer->size()); - if (ret) - pdf_output_done_ = true; - } - canvas->endPlatformPaint(); -#elif defined(OS_MACOSX) - printing::NativeMetafile metafile; - // Create a PDF metafile and render from there into the passed in context. - if (metafile.Init(buffer->mapped_buffer(), buffer->size())) { - // Flip the transform. - CGContextSaveGState(canvas); - CGContextTranslateCTM(canvas, 0, - current_print_settings_.printable_area.size.height); - CGContextScaleCTM(canvas, 1.0, -1.0); - CGRect page_rect; - page_rect.origin.x = current_print_settings_.printable_area.point.x; - page_rect.origin.y = current_print_settings_.printable_area.point.y; - page_rect.size.width = current_print_settings_.printable_area.size.width; - page_rect.size.height = current_print_settings_.printable_area.size.height; - - ret = metafile.RenderPage(1, canvas, page_rect, true, false, true, true); - CGContextRestoreGState(canvas); - } -#elif defined(OS_WIN) - // On Windows, we now need to render the PDF to the DC that backs the - // supplied canvas. - skia::VectorPlatformDevice& device = - static_cast<skia::VectorPlatformDevice&>( - canvas->getTopPlatformDevice()); - HDC dc = device.getBitmapDC(); - gfx::Size size_in_pixels; - size_in_pixels.set_width( - printing::ConvertUnit(current_print_settings_.printable_area.size.width, - static_cast<int>(printing::kPointsPerInch), - current_print_settings_.dpi)); - size_in_pixels.set_height( - printing::ConvertUnit(current_print_settings_.printable_area.size.height, - static_cast<int>(printing::kPointsPerInch), - current_print_settings_.dpi)); - // We need to render using the actual printer DPI (rendering to a smaller - // set of pixels leads to a blurry output). However, we need to counter the - // scaling up that will happen in the browser. - XFORM xform = {0}; - xform.eM11 = xform.eM22 = static_cast<float>(printing::kPointsPerInch) / - static_cast<float>(current_print_settings_.dpi); - ModifyWorldTransform(dc, &xform, MWT_LEFTMULTIPLY); - - ret = render_proc(buffer->mapped_buffer(), buffer->size(), 0, dc, - current_print_settings_.dpi, current_print_settings_.dpi, - 0, 0, size_in_pixels.width(), - size_in_pixels.height(), true, false, true, true); -#endif // defined(OS_WIN) - - return ret; -} - -bool PluginInstance::PrintRasterOutput(PP_Resource print_output, - WebKit::WebCanvas* canvas) { - scoped_refptr<ImageData> image(Resource::GetAs<ImageData>(print_output)); - if (!image.get() || !image->is_mapped()) - return false; - - const SkBitmap* bitmap = image->GetMappedBitmap(); - if (!bitmap) - return false; - - // Draw the printed image into the supplied canvas. - SkIRect src_rect; - src_rect.set(0, 0, bitmap->width(), bitmap->height()); - SkRect dest_rect; - dest_rect.set( - SkIntToScalar(current_print_settings_.printable_area.point.x), - SkIntToScalar(current_print_settings_.printable_area.point.y), - SkIntToScalar(current_print_settings_.printable_area.point.x + - current_print_settings_.printable_area.size.width), - SkIntToScalar(current_print_settings_.printable_area.point.y + - current_print_settings_.printable_area.size.height)); - bool draw_to_canvas = true; - gfx::Rect dest_rect_gfx; - dest_rect_gfx.set_x(current_print_settings_.printable_area.point.x); - dest_rect_gfx.set_y(current_print_settings_.printable_area.point.y); - dest_rect_gfx.set_width(current_print_settings_.printable_area.size.width); - dest_rect_gfx.set_height(current_print_settings_.printable_area.size.height); - -#if defined(OS_WIN) - // Since this is a raster output, the size of the bitmap can be - // huge (especially at high printer DPIs). On Windows, this can - // result in a HUGE EMF (on Mac and Linux the output goes to PDF - // which appears to Flate compress the bitmap). So, if this bitmap - // is larger than 20 MB, we save the bitmap as a JPEG into the EMF - // DC. Note: We chose JPEG over PNG because JPEG compression seems - // way faster (about 4 times faster). - static const int kCompressionThreshold = 20 * 1024 * 1024; - if (bitmap->getSize() > kCompressionThreshold) { - DrawJPEGToPlatformDC(*bitmap, dest_rect_gfx, canvas); - draw_to_canvas = false; - } -#endif // defined(OS_WIN) -#if defined(OS_MACOSX) - draw_to_canvas = false; - DrawSkBitmapToCanvas(*bitmap, canvas, dest_rect_gfx, - current_print_settings_.printable_area.size.height); - // See comments in the header file. - last_printed_page_ = image; -#else // defined(OS_MACOSX) - if (draw_to_canvas) - canvas->drawBitmapRect(*bitmap, &src_rect, dest_rect); -#endif // defined(OS_MACOSX) - return true; -} - -#if defined(OS_WIN) -bool PluginInstance::DrawJPEGToPlatformDC( - const SkBitmap& bitmap, - const gfx::Rect& printable_area, - WebKit::WebCanvas* canvas) { - skia::VectorPlatformDevice& device = - static_cast<skia::VectorPlatformDevice&>( - canvas->getTopPlatformDevice()); - HDC dc = device.getBitmapDC(); - // TODO(sanjeevr): This is a temporary hack. If we output a JPEG - // to the EMF, the EnumEnhMetaFile call fails in the browser - // process. The failure also happens if we output nothing here. - // We need to investigate the reason for this failure and fix it. - // In the meantime this temporary hack of drawing an empty - // rectangle in the DC gets us by. - Rectangle(dc, 0, 0, 0, 0); - - // Ideally we should add JPEG compression to the VectorPlatformDevice class - // However, Skia currently has no JPEG compression code and we cannot - // depend on gfx/jpeg_codec.h in Skia. So we do the compression here. - SkAutoLockPixels lock(bitmap); - DCHECK(bitmap.getConfig() == SkBitmap::kARGB_8888_Config); - const uint32_t* pixels = - static_cast<const uint32_t*>(bitmap.getPixels()); - std::vector<unsigned char> compressed_image; - base::TimeTicks start_time = base::TimeTicks::Now(); - bool encoded = gfx::JPEGCodec::Encode( - reinterpret_cast<const unsigned char*>(pixels), - gfx::JPEGCodec::FORMAT_BGRA, bitmap.width(), bitmap.height(), - static_cast<int>(bitmap.rowBytes()), 100, &compressed_image); - UMA_HISTOGRAM_TIMES("PepperPluginPrint.RasterBitmapCompressTime", - base::TimeTicks::Now() - start_time); - if (!encoded) { - NOTREACHED(); - return false; - } - BITMAPINFOHEADER bmi = {0}; - gfx::CreateBitmapHeader(bitmap.width(), bitmap.height(), &bmi); - bmi.biCompression = BI_JPEG; - bmi.biSizeImage = compressed_image.size(); - bmi.biHeight = -bmi.biHeight; - StretchDIBits(dc, printable_area.x(), printable_area.y(), - printable_area.width(), printable_area.height(), - 0, 0, bitmap.width(), bitmap.height(), - &compressed_image.front(), - reinterpret_cast<const BITMAPINFO*>(&bmi), - DIB_RGB_COLORS, SRCCOPY); - return true; -} -#endif // OS_WIN - -#if defined(OS_MACOSX) -void PluginInstance::DrawSkBitmapToCanvas( - const SkBitmap& bitmap, WebKit::WebCanvas* canvas, - const gfx::Rect& dest_rect, - int canvas_height) { - SkAutoLockPixels lock(bitmap); - DCHECK(bitmap.getConfig() == SkBitmap::kARGB_8888_Config); - base::mac::ScopedCFTypeRef<CGDataProviderRef> data_provider( - CGDataProviderCreateWithData( - NULL, bitmap.getAddr32(0, 0), - bitmap.rowBytes() * bitmap.height(), NULL)); - base::mac::ScopedCFTypeRef<CGImageRef> image( - CGImageCreate( - bitmap.width(), bitmap.height(), - 8, 32, bitmap.rowBytes(), - mac_util::GetSystemColorSpace(), - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, - data_provider, NULL, false, kCGRenderingIntentDefault)); - - // Flip the transform - CGContextSaveGState(canvas); - CGContextTranslateCTM(canvas, 0, canvas_height); - CGContextScaleCTM(canvas, 1.0, -1.0); - - CGRect bounds; - bounds.origin.x = dest_rect.x(); - bounds.origin.y = canvas_height - dest_rect.y() - dest_rect.height(); - bounds.size.width = dest_rect.width(); - bounds.size.height = dest_rect.height(); - - CGContextDrawImage(canvas, bounds, image); - CGContextRestoreGState(canvas); -} -#endif // defined(OS_MACOSX) - -Graphics2D* PluginInstance::bound_graphics_2d() const { - if (bound_graphics_.get() == NULL) - return NULL; - - return bound_graphics_->Cast<Graphics2D>(); -} - -Graphics3D* PluginInstance::bound_graphics_3d() const { - if (bound_graphics_.get() == NULL) - return NULL; - - return bound_graphics_->Cast<Graphics3D>(); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_plugin_instance.h b/webkit/glue/plugins/pepper_plugin_instance.h deleted file mode 100644 index bd99843..0000000 --- a/webkit/glue/plugins/pepper_plugin_instance.h +++ /dev/null @@ -1,318 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_INSTANCE_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_INSTANCE_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/observer_list.h" -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "base/string16.h" -#include "gfx/rect.h" -#include "ppapi/c/dev/pp_cursor_type_dev.h" -#include "ppapi/c/dev/ppp_graphics_3d_dev.h" -#include "ppapi/c/dev/ppp_printing_dev.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_resource.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCanvas.h" - -struct PP_Var; -struct PPB_Instance; -struct PPB_Find_Dev; -struct PPB_Fullscreen_Dev; -struct PPB_Zoom_Dev; -struct PPP_Find_Dev; -struct PPP_Instance; -struct PPP_Private; -struct PPP_Selection_Dev; -struct PPP_Zoom_Dev; - -class SkBitmap; -class TransportDIB; - -namespace gfx { -class Rect; -} - -namespace WebKit { -struct WebCursorInfo; -class WebInputEvent; -class WebPluginContainer; -} - -namespace pepper { - -class Graphics2D; -class Graphics3D; -class ImageData; -class PluginDelegate; -class PluginModule; -class Resource; -class URLLoader; -class FullscreenContainer; - -// Represents one time a plugin appears on one web page. -// -// Note: to get from a PP_Instance to a PluginInstance*, use the -// ResourceTracker. -class PluginInstance : public base::RefCounted<PluginInstance> { - public: - class Observer { - public: - // Indicates that the instance is being destroyed. This will be called from - // the instance's destructor so don't do anything in this callback that - // uses the instance. - virtual void InstanceDestroyed(PluginInstance* instance) = 0; - }; - - PluginInstance(PluginDelegate* delegate, - PluginModule* module, - const PPP_Instance* instance_interface); - ~PluginInstance(); - - static const PPB_Instance* GetInterface(); - - // Returns a pointer to the interface implementing PPB_Find that is - // exposed to the plugin. - static const PPB_Find_Dev* GetFindInterface(); - static const PPB_Fullscreen_Dev* GetFullscreenInterface(); - static const PPB_Zoom_Dev* GetZoomInterface(); - - PluginDelegate* delegate() const { return delegate_; } - PluginModule* module() const { return module_.get(); } - - WebKit::WebPluginContainer* container() const { return container_; } - - const gfx::Rect& position() const { return position_; } - const gfx::Rect& clip() const { return clip_; } - - int find_identifier() const { return find_identifier_; } - - void set_always_on_top(bool on_top) { always_on_top_ = on_top; } - - // Returns the PP_Instance uniquely identifying this instance. Guaranteed - // nonzero. - PP_Instance pp_instance() const { return pp_instance_; } - - // Other classes can register an observer for instance events. These pointers - // are NOT owned by the Instance. If the object implementing the observer - // goes away, it must take care to unregister itself. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - // Paints the current backing store to the web page. - void Paint(WebKit::WebCanvas* canvas, - const gfx::Rect& plugin_rect, - const gfx::Rect& paint_rect); - - // Schedules a paint of the page for the given region. The coordinates are - // relative to the top-left of the plugin. This does nothing if the plugin - // has not yet been positioned. You can supply an empty gfx::Rect() to - // invalidate the entire plugin. - void InvalidateRect(const gfx::Rect& rect); - - // Schedules a scroll of the plugin. This uses optimized scrolling only for - // full-frame plugins, as otherwise there could be other elements on top. The - // slow path can also be triggered if there is an overlapping frame. - void ScrollRect(int dx, int dy, const gfx::Rect& rect); - - // If the plugin instance is backed by a texture, return its texture ID in the - // compositor's namespace. Otherwise return 0. Returns 0 by default. - virtual unsigned GetBackingTextureId(); - - // Commit the backing texture to the screen once the side effects some - // rendering up to an offscreen SwapBuffers are visible. - void CommitBackingTexture(); - - // PPB_Instance implementation. - PP_Var GetWindowObject(); - PP_Var GetOwnerElementObject(); - bool BindGraphics(PP_Resource graphics_id); - bool full_frame() const { return full_frame_; } - bool SetCursor(PP_CursorType_Dev type); - PP_Var ExecuteScript(PP_Var script, PP_Var* exception); - - // PPP_Instance pass-through. - void Delete(); - bool Initialize(WebKit::WebPluginContainer* container, - const std::vector<std::string>& arg_names, - const std::vector<std::string>& arg_values, - bool full_frame); - bool HandleDocumentLoad(URLLoader* loader); - bool HandleInputEvent(const WebKit::WebInputEvent& event, - WebKit::WebCursorInfo* cursor_info); - PP_Var GetInstanceObject(); - void ViewChanged(const gfx::Rect& position, const gfx::Rect& clip); - - // Notifications about focus changes, see has_webkit_focus_ below. - void SetWebKitFocus(bool has_focus); - void SetContentAreaFocus(bool has_focus); - - // Notifications that the view has rendered the page and that it has been - // flushed to the screen. These messages are used to send Flush callbacks to - // the plugin for DeviceContext2D. - void ViewInitiatedPaint(); - void ViewFlushedPaint(); - - // If this plugin can be painted merely by copying the backing store to the - // screen, and the plugin bounds encloses the given paint bounds, returns - // true. In this case, the location, clipping, and ID of the backing store - // will be filled into the given output parameters. - bool GetBitmapForOptimizedPluginPaint( - const gfx::Rect& paint_bounds, - TransportDIB** dib, - gfx::Rect* dib_bounds, - gfx::Rect* clip); - - string16 GetSelectedText(bool html); - string16 GetLinkAtPosition(const gfx::Point& point); - void Zoom(double factor, bool text_only); - bool StartFind(const string16& search_text, - bool case_sensitive, - int identifier); - void SelectFindResult(bool forward); - void StopFind(); - - bool SupportsPrintInterface(); - int PrintBegin(const gfx::Rect& printable_area, int printer_dpi); - bool PrintPage(int page_number, WebKit::WebCanvas* canvas); - void PrintEnd(); - - void Graphics3DContextLost(); - - // Implementation of PPB_Fullscreen_Dev. - bool IsFullscreen(); - bool SetFullscreen(bool fullscreen); - - // Implementation of PPB_Private2. - bool NavigateToURL(const char* url, const char* target); - - private: - bool LoadFindInterface(); - bool LoadPrivateInterface(); - bool LoadSelectionInterface(); - bool LoadZoomInterface(); - - // Determines if we think the plugin has focus, both content area and webkit - // (see has_webkit_focus_ below). - bool PluginHasFocus() const; - - // Queries the plugin for supported print formats and sets |format| to the - // best format to use. Returns false if the plugin does not support any - // print format that we can handle (we can handle raster and PDF). - bool GetPreferredPrintOutputFormat(PP_PrintOutputFormat_Dev* format); - bool PrintPDFOutput(PP_Resource print_output, WebKit::WebCanvas* canvas); - bool PrintRasterOutput(PP_Resource print_output, WebKit::WebCanvas* canvas); -#if defined(OS_WIN) - bool DrawJPEGToPlatformDC(const SkBitmap& bitmap, - const gfx::Rect& printable_area, - WebKit::WebCanvas* canvas); -#elif defined(OS_MACOSX) - // Draws the given kARGB_8888_Config bitmap to the specified canvas starting - // at the specified destination rect. - void DrawSkBitmapToCanvas(const SkBitmap& bitmap, WebKit::WebCanvas* canvas, - const gfx::Rect& dest_rect, int canvas_height); -#endif // OS_MACOSX - - // Get the bound graphics context as a concrete 2D graphics context or returns - // null if the context is not 2D. - Graphics2D* bound_graphics_2d() const; - - // Get the bound graphics context as a concrete 3D graphics context or returns - // null if the context is not 3D. - Graphics3D* bound_graphics_3d() const; - - PluginDelegate* delegate_; - scoped_refptr<PluginModule> module_; - const PPP_Instance* instance_interface_; - - PP_Instance pp_instance_; - - // NULL until we have been initialized. - WebKit::WebPluginContainer* container_; - - // Indicates whether this is a full frame instance, which means it represents - // an entire document rather than an embed tag. - bool full_frame_; - - // Position in the viewport (which moves as the page is scrolled) of this - // plugin. This will be a 0-sized rectangle if the plugin has not yet been - // laid out. - gfx::Rect position_; - - // Current clip rect. This will be empty if the plugin is not currently - // visible. This is in the plugin's coordinate system, so fully visible will - // be (0, 0, w, h) regardless of scroll position. - gfx::Rect clip_; - - // The current device context for painting in 2D or 3D. - scoped_refptr<Resource> bound_graphics_; - - // We track two types of focus, one from WebKit, which is the focus among - // all elements of the page, one one from the browser, which is whether the - // tab/window has focus. We tell the plugin it has focus only when both of - // these values are set to true. - bool has_webkit_focus_; - bool has_content_area_focus_; - - // The id of the current find operation, or -1 if none is in process. - int find_identifier_; - - // The plugin-provided interfaces. - const PPP_Find_Dev* plugin_find_interface_; - const PPP_Private* plugin_private_interface_; - const PPP_Selection_Dev* plugin_selection_interface_; - const PPP_Zoom_Dev* plugin_zoom_interface_; - - // This is only valid between a successful PrintBegin call and a PrintEnd - // call. - PP_PrintSettings_Dev current_print_settings_; -#if defined(OS_MACOSX) - // On the Mac, when we draw the bitmap to the PDFContext, it seems necessary - // to keep the pixels valid until CGContextEndPage is called. We use this - // variable to hold on to the pixels. - scoped_refptr<ImageData> last_printed_page_; -#elif defined(OS_LINUX) - // On Linux, we always send all pages from the renderer to the browser. - // So, if the plugin supports printPagesAsPDF we print the entire output - // in one shot in the first call to PrintPage. - // (This is a temporary hack until we change the WebFrame and WebPlugin print - // interfaces). - // Specifies the total number of pages to be printed. It it set in PrintBegin. - int32 num_pages_; - // Specifies whether we have already output all pages. This is used to ignore - // subsequent PrintPage requests. - bool pdf_output_done_; -#endif // defined(OS_LINUX) - - // The plugin print interface. - const PPP_Printing_Dev* plugin_print_interface_; - - // The plugin 3D interface. - const PPP_Graphics3D_Dev* plugin_graphics_3d_interface_; - - // Containes the cursor if it's set by the plugin. - scoped_ptr<WebKit::WebCursorInfo> cursor_; - - // Set to true if this plugin thinks it will always be on top. This allows us - // to use a more optimized painting path in some cases. - bool always_on_top_; - - // Plugin container for fullscreen mode. NULL if not in fullscreen mode. - FullscreenContainer* fullscreen_container_; - - // Non-owning pointers to all active observers. - ObserverList<Observer, false> observers_; - - DISALLOW_COPY_AND_ASSIGN(PluginInstance); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_INSTANCE_H_ diff --git a/webkit/glue/plugins/pepper_plugin_module.cc b/webkit/glue/plugins/pepper_plugin_module.cc deleted file mode 100644 index b7bad9f..0000000 --- a/webkit/glue/plugins/pepper_plugin_module.cc +++ /dev/null @@ -1,553 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_plugin_module.h" - -#include <set> - -#include "base/command_line.h" -#include "base/message_loop.h" -#include "base/message_loop_proxy.h" -#include "base/logging.h" -#include "base/scoped_ptr.h" -#include "base/time.h" -#include "ppapi/c/dev/ppb_buffer_dev.h" -#include "ppapi/c/dev/ppb_char_set_dev.h" -#include "ppapi/c/dev/ppb_cursor_control_dev.h" -#include "ppapi/c/dev/ppb_directory_reader_dev.h" -#include "ppapi/c/dev/ppb_file_io_dev.h" -#include "ppapi/c/dev/ppb_file_io_trusted_dev.h" -#include "ppapi/c/dev/ppb_file_system_dev.h" -#include "ppapi/c/dev/ppb_find_dev.h" -#include "ppapi/c/dev/ppb_font_dev.h" -#include "ppapi/c/dev/ppb_fullscreen_dev.h" -#include "ppapi/c/dev/ppb_graphics_3d_dev.h" -#include "ppapi/c/dev/ppb_opengles_dev.h" -#include "ppapi/c/dev/ppb_scrollbar_dev.h" -#include "ppapi/c/dev/ppb_testing_dev.h" -#include "ppapi/c/dev/ppb_transport_dev.h" -#include "ppapi/c/dev/ppb_url_util_dev.h" -#include "ppapi/c/dev/ppb_var_deprecated.h" -#include "ppapi/c/dev/ppb_video_decoder_dev.h" -#include "ppapi/c/dev/ppb_widget_dev.h" -#include "ppapi/c/dev/ppb_zoom_dev.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_class.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/ppb_graphics_2d.h" -#include "ppapi/c/ppb_image_data.h" -#include "ppapi/c/ppb_instance.h" -#include "ppapi/c/ppb_url_loader.h" -#include "ppapi/c/ppb_url_request_info.h" -#include "ppapi/c/ppb_url_response_info.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/ppp.h" -#include "ppapi/c/ppp_instance.h" -#include "ppapi/c/trusted/ppb_image_data_trusted.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" -#include "ppapi/proxy/host_dispatcher.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "webkit/glue/plugins/pepper_audio.h" -#include "webkit/glue/plugins/pepper_buffer.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_char_set.h" -#include "webkit/glue/plugins/pepper_class.h" -#include "webkit/glue/plugins/pepper_cursor_control.h" -#include "webkit/glue/plugins/pepper_directory_reader.h" -#include "webkit/glue/plugins/pepper_file_chooser.h" -#include "webkit/glue/plugins/pepper_file_io.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_file_system.h" -#include "webkit/glue/plugins/pepper_font.h" -#include "webkit/glue/plugins/pepper_graphics_2d.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_object.h" -#include "webkit/glue/plugins/pepper_private.h" -#include "webkit/glue/plugins/pepper_private2.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" -#include "webkit/glue/plugins/pepper_scrollbar.h" -#include "webkit/glue/plugins/pepper_transport.h" -#include "webkit/glue/plugins/pepper_url_loader.h" -#include "webkit/glue/plugins/pepper_url_request_info.h" -#include "webkit/glue/plugins/pepper_url_response_info.h" -#include "webkit/glue/plugins/pepper_url_util.h" -#include "webkit/glue/plugins/pepper_var.h" -#include "webkit/glue/plugins/pepper_video_decoder.h" -#include "webkit/glue/plugins/pepper_widget.h" -#include "webkit/glue/plugins/ppb_private.h" -#include "webkit/glue/plugins/ppb_private2.h" - -#ifdef ENABLE_GPU -#include "webkit/glue/plugins/pepper_graphics_3d.h" -#endif // ENABLE_GPU - -#if defined(OS_POSIX) -#include "ipc/ipc_channel_posix.h" -#endif - -namespace pepper { - -namespace { - -// Maintains all currently loaded plugin libs for validating PP_Module -// identifiers. -typedef std::set<PluginModule*> PluginModuleSet; - -PluginModuleSet* GetLivePluginSet() { - static PluginModuleSet live_plugin_libs; - return &live_plugin_libs; -} - -base::MessageLoopProxy* GetMainThreadMessageLoop() { - static scoped_refptr<base::MessageLoopProxy> proxy( - base::MessageLoopProxy::CreateForCurrentThread()); - return proxy.get(); -} - -// PPB_Core -------------------------------------------------------------------- - -void AddRefResource(PP_Resource resource) { - if (!ResourceTracker::Get()->AddRefResource(resource)) { - DLOG(WARNING) << "AddRefResource()ing a nonexistent resource"; - } -} - -void ReleaseResource(PP_Resource resource) { - if (!ResourceTracker::Get()->UnrefResource(resource)) { - DLOG(WARNING) << "ReleaseResource()ing a nonexistent resource"; - } -} - -void* MemAlloc(size_t num_bytes) { - return malloc(num_bytes); -} - -void MemFree(void* ptr) { - free(ptr); -} - -double GetTime() { - return base::Time::Now().ToDoubleT(); -} - -double GetTickTime() { - // TODO(brettw) http://code.google.com/p/chromium/issues/detail?id=57448 - // This should be a tick timer rather than wall clock time, but needs to - // match message times, which also currently use wall clock time. - return GetTime(); -} - -void CallOnMainThread(int delay_in_msec, - PP_CompletionCallback callback, - int32_t result) { - GetMainThreadMessageLoop()->PostDelayedTask( - FROM_HERE, - NewRunnableFunction(callback.func, callback.user_data, result), - delay_in_msec); -} - -PP_Bool IsMainThread() { - return BoolToPPBool(GetMainThreadMessageLoop()->BelongsToCurrentThread()); -} - -const PPB_Core core_interface = { - &AddRefResource, - &ReleaseResource, - &MemAlloc, - &MemFree, - &GetTime, - &GetTickTime, - &CallOnMainThread, - &IsMainThread -}; - -// PPB_Testing ----------------------------------------------------------------- - -PP_Bool ReadImageData(PP_Resource device_context_2d, - PP_Resource image, - const PP_Point* top_left) { - scoped_refptr<Graphics2D> context( - Resource::GetAs<Graphics2D>(device_context_2d)); - if (!context.get()) - return PP_FALSE; - return BoolToPPBool(context->ReadImageData(image, top_left)); -} - -void RunMessageLoop() { - bool old_state = MessageLoop::current()->NestableTasksAllowed(); - MessageLoop::current()->SetNestableTasksAllowed(true); - MessageLoop::current()->Run(); - MessageLoop::current()->SetNestableTasksAllowed(old_state); -} - -void QuitMessageLoop() { - MessageLoop::current()->QuitNow(); -} - -uint32_t GetLiveObjectCount(PP_Module module_id) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return static_cast<uint32_t>(-1); - return ResourceTracker::Get()->GetLiveObjectsForModule(module); -} - -const PPB_Testing_Dev testing_interface = { - &ReadImageData, - &RunMessageLoop, - &QuitMessageLoop, - &GetLiveObjectCount -}; - -// GetInterface ---------------------------------------------------------------- - -const void* GetInterface(const char* name) { - if (strcmp(name, PPB_CORE_INTERFACE) == 0) - return &core_interface; - if (strcmp(name, PPB_VAR_DEPRECATED_INTERFACE) == 0) - return Var::GetDeprecatedInterface(); - if (strcmp(name, PPB_VAR_INTERFACE) == 0) - return Var::GetInterface(); - if (strcmp(name, PPB_INSTANCE_INTERFACE) == 0) - return PluginInstance::GetInterface(); - if (strcmp(name, PPB_IMAGEDATA_INTERFACE) == 0) - return ImageData::GetInterface(); - if (strcmp(name, PPB_IMAGEDATA_TRUSTED_INTERFACE) == 0) - return ImageData::GetTrustedInterface(); - if (strcmp(name, PPB_AUDIO_CONFIG_DEV_INTERFACE) == 0) - return AudioConfig::GetInterface(); - if (strcmp(name, PPB_AUDIO_DEV_INTERFACE) == 0) - return Audio::GetInterface(); - if (strcmp(name, PPB_AUDIO_TRUSTED_DEV_INTERFACE) == 0) - return Audio::GetTrustedInterface(); - if (strcmp(name, PPB_GRAPHICS_2D_INTERFACE) == 0) - return Graphics2D::GetInterface(); -#ifdef ENABLE_GPU - if (strcmp(name, PPB_GRAPHICS_3D_DEV_INTERFACE) == 0) - return Graphics3D::GetInterface(); - if (strcmp(name, PPB_OPENGLES_DEV_INTERFACE) == 0) - return Graphics3D::GetOpenGLESInterface(); -#endif // ENABLE_GPU - if (strcmp(name, PPB_TRANSPORT_DEV_INTERFACE) == 0) - return Transport::GetInterface(); - if (strcmp(name, PPB_URLLOADER_INTERFACE) == 0) - return URLLoader::GetInterface(); - if (strcmp(name, PPB_URLLOADERTRUSTED_INTERFACE) == 0) - return URLLoader::GetTrustedInterface(); - if (strcmp(name, PPB_URLREQUESTINFO_INTERFACE) == 0) - return URLRequestInfo::GetInterface(); - if (strcmp(name, PPB_URLRESPONSEINFO_INTERFACE) == 0) - return URLResponseInfo::GetInterface(); - if (strcmp(name, PPB_BUFFER_DEV_INTERFACE) == 0) - return Buffer::GetInterface(); - if (strcmp(name, PPB_FILEREF_DEV_INTERFACE) == 0) - return FileRef::GetInterface(); - if (strcmp(name, PPB_FILEIO_DEV_INTERFACE) == 0) - return FileIO::GetInterface(); - if (strcmp(name, PPB_FILEIOTRUSTED_DEV_INTERFACE) == 0) - return FileIO::GetTrustedInterface(); - if (strcmp(name, PPB_FILESYSTEM_DEV_INTERFACE) == 0) - return FileSystem::GetInterface(); - if (strcmp(name, PPB_DIRECTORYREADER_DEV_INTERFACE) == 0) - return DirectoryReader::GetInterface(); - if (strcmp(name, PPB_WIDGET_DEV_INTERFACE) == 0) - return Widget::GetInterface(); - if (strcmp(name, PPB_SCROLLBAR_DEV_INTERFACE) == 0) - return Scrollbar::GetInterface(); - if (strcmp(name, PPB_FONT_DEV_INTERFACE) == 0) - return Font::GetInterface(); - if (strcmp(name, PPB_FIND_DEV_INTERFACE) == 0) - return PluginInstance::GetFindInterface(); - if (strcmp(name, PPB_FULLSCREEN_DEV_INTERFACE) == 0) - return PluginInstance::GetFullscreenInterface(); - if (strcmp(name, PPB_URLUTIL_DEV_INTERFACE) == 0) - return UrlUtil::GetInterface(); - if (strcmp(name, PPB_PRIVATE_INTERFACE) == 0) - return Private::GetInterface(); - if (strcmp(name, PPB_PRIVATE2_INTERFACE) == 0) - return Private2::GetInterface(); - if (strcmp(name, PPB_FILECHOOSER_DEV_INTERFACE) == 0) - return FileChooser::GetInterface(); - if (strcmp(name, PPB_VIDEODECODER_DEV_INTERFACE) == 0) - return VideoDecoder::GetInterface(); - if (strcmp(name, PPB_CHAR_SET_DEV_INTERFACE) == 0) - return CharSet::GetInterface(); - if (strcmp(name, PPB_CURSOR_CONTROL_DEV_INTERFACE) == 0) - return GetCursorControlInterface(); - if (strcmp(name, PPB_ZOOM_DEV_INTERFACE) == 0) - return PluginInstance::GetZoomInterface(); - if (strcmp(name, PPB_CLASS_INTERFACE) == 0) - return VarObjectClass::GetInterface(); - - // Only support the testing interface when the command line switch is - // specified. This allows us to prevent people from (ab)using this interface - // in production code. - if (strcmp(name, PPB_TESTING_DEV_INTERFACE) == 0) { - if (CommandLine::ForCurrentProcess()->HasSwitch("enable-pepper-testing")) - return &testing_interface; - } - return NULL; -} - -} // namespace - -PluginModule::PluginModule() - : initialized_(false), - library_(NULL) { - pp_module_ = ResourceTracker::Get()->AddModule(this); - GetMainThreadMessageLoop(); // Initialize the main thread message loop. - GetLivePluginSet()->insert(this); -} - -PluginModule::~PluginModule() { - // Free all the plugin objects. This will automatically clear the back- - // pointer from the NPObject so WebKit can't call into the plugin any more. - // - // Swap out the set so we can delete from it (the objects will try to - // unregister themselves inside the delete call). - PluginObjectSet plugin_object_copy; - live_plugin_objects_.swap(plugin_object_copy); - for (PluginObjectSet::iterator i = live_plugin_objects_.begin(); - i != live_plugin_objects_.end(); ++i) - delete *i; - - // When the module is being deleted, there should be no more instances still - // holding a reference to us. - DCHECK(instances_.empty()); - - GetLivePluginSet()->erase(this); - - if (entry_points_.shutdown_module) - entry_points_.shutdown_module(); - - if (library_) - base::UnloadNativeLibrary(library_); - - ResourceTracker::Get()->ModuleDeleted(pp_module_); -} - -// static -scoped_refptr<PluginModule> PluginModule::CreateModule( - const FilePath& path) { - // FIXME(brettw) do uniquifying of the plugin here like the NPAPI one. - - scoped_refptr<PluginModule> lib(new PluginModule()); - if (!lib->InitFromFile(path)) - return NULL; - - return lib; -} - -// static -scoped_refptr<PluginModule> PluginModule::CreateInternalModule( - EntryPoints entry_points) { - scoped_refptr<PluginModule> lib(new PluginModule()); - if (!lib->InitFromEntryPoints(entry_points)) - return NULL; - - return lib; -} - -// static -scoped_refptr<PluginModule> PluginModule::CreateOutOfProcessModule( - MessageLoop* ipc_message_loop, - const IPC::ChannelHandle& handle, - base::WaitableEvent* shutdown_event) { - scoped_refptr<PluginModule> lib(new PluginModule); - if (!lib->InitForOutOfProcess(ipc_message_loop, handle, shutdown_event)) - return NULL; - return lib; -} - -// static -const PPB_Core* PluginModule::GetCore() { - return &core_interface; -} - -bool PluginModule::InitFromEntryPoints(const EntryPoints& entry_points) { - if (initialized_) - return true; - - // Attempt to run the initialization funciton. - int retval = entry_points.initialize_module(pp_module(), &GetInterface); - if (retval != 0) { - LOG(WARNING) << "PPP_InitializeModule returned failure " << retval; - return false; - } - - entry_points_ = entry_points; - initialized_ = true; - return true; -} - -bool PluginModule::InitFromFile(const FilePath& path) { - if (initialized_) - return true; - - base::NativeLibrary library = base::LoadNativeLibrary(path); - if (!library) - return false; - - EntryPoints entry_points; - if (!LoadEntryPoints(library, &entry_points) || - !InitFromEntryPoints(entry_points)) { - base::UnloadNativeLibrary(library); - return false; - } - - // We let InitFromEntryPoints() handle setting the all the internal state - // of the object other than the |library_| reference. - library_ = library; - return true; -} - -bool PluginModule::InitForOutOfProcess(MessageLoop* ipc_message_loop, - const IPC::ChannelHandle& handle, - base::WaitableEvent* shutdown_event) { - const PPB_Var_Deprecated* var_interface = - reinterpret_cast<const PPB_Var_Deprecated*>( - GetInterface(PPB_VAR_DEPRECATED_INTERFACE)); - dispatcher_.reset(new pp::proxy::HostDispatcher(var_interface, - pp_module(), &GetInterface)); - -#if defined(OS_POSIX) - // If we received a ChannelHandle, register it now. - if (handle.socket.fd >= 0) - IPC::AddChannelSocket(handle.name, handle.socket.fd); -#endif - - if (!dispatcher_->InitWithChannel(ipc_message_loop, handle.name, true, - shutdown_event)) { - dispatcher_.reset(); - return false; - } - - bool init_result = false; - dispatcher_->Send(new PpapiMsg_InitializeModule(pp_module(), &init_result)); - - if (!init_result) { - // TODO(brettw) does the module get unloaded in this case? - dispatcher_.reset(); - return false; - } - return true; -} - -// static -bool PluginModule::LoadEntryPoints(const base::NativeLibrary& library, - EntryPoints* entry_points) { - entry_points->get_interface = - reinterpret_cast<PPP_GetInterfaceFunc>( - base::GetFunctionPointerFromNativeLibrary(library, - "PPP_GetInterface")); - if (!entry_points->get_interface) { - LOG(WARNING) << "No PPP_GetInterface in plugin library"; - return false; - } - - entry_points->initialize_module = - reinterpret_cast<PPP_InitializeModuleFunc>( - base::GetFunctionPointerFromNativeLibrary(library, - "PPP_InitializeModule")); - if (!entry_points->initialize_module) { - LOG(WARNING) << "No PPP_InitializeModule in plugin library"; - return false; - } - - // It's okay for PPP_ShutdownModule to not be defined and shutdown_module to - // be NULL. - entry_points->shutdown_module = - reinterpret_cast<PPP_ShutdownModuleFunc>( - base::GetFunctionPointerFromNativeLibrary(library, - "PPP_ShutdownModule")); - - return true; -} - -PluginInstance* PluginModule::CreateInstance(PluginDelegate* delegate) { - const PPP_Instance* plugin_instance_interface = - reinterpret_cast<const PPP_Instance*>(GetPluginInterface( - PPP_INSTANCE_INTERFACE)); - if (!plugin_instance_interface) { - LOG(WARNING) << "Plugin doesn't support instance interface, failing."; - return NULL; - } - PluginInstance* instance = new PluginInstance(delegate, this, - plugin_instance_interface); - if (dispatcher_.get()) { - pp::proxy::HostDispatcher::SetForInstance(instance->pp_instance(), - dispatcher_.get()); - } - return instance; -} - -PluginInstance* PluginModule::GetSomeInstance() const { - // This will generally crash later if there is not actually any instance to - // return, so we force a crash now to make bugs easier to track down. - CHECK(!instances_.empty()); - return *instances_.begin(); -} - -const void* PluginModule::GetPluginInterface(const char* name) const { - if (dispatcher_.get()) - return dispatcher_->GetProxiedInterface(name); - - // In-process plugins. - if (!entry_points_.get_interface) - return NULL; - return entry_points_.get_interface(name); -} - -void PluginModule::InstanceCreated(PluginInstance* instance) { - instances_.insert(instance); -} - -void PluginModule::InstanceDeleted(PluginInstance* instance) { - pp::proxy::HostDispatcher::RemoveForInstance(instance->pp_instance()); - instances_.erase(instance); -} - -void PluginModule::AddNPObjectVar(ObjectVar* object_var) { - DCHECK(np_object_to_object_var_.find(object_var->np_object()) == - np_object_to_object_var_.end()) << "ObjectVar already in map"; - np_object_to_object_var_[object_var->np_object()] = object_var; -} - -void PluginModule::RemoveNPObjectVar(ObjectVar* object_var) { - NPObjectToObjectVarMap::iterator found = - np_object_to_object_var_.find(object_var->np_object()); - if (found == np_object_to_object_var_.end()) { - NOTREACHED() << "ObjectVar not registered."; - return; - } - if (found->second != object_var) { - NOTREACHED() << "ObjectVar doesn't match."; - return; - } - np_object_to_object_var_.erase(found); -} - -ObjectVar* PluginModule::ObjectVarForNPObject(NPObject* np_object) const { - NPObjectToObjectVarMap::const_iterator found = - np_object_to_object_var_.find(np_object); - if (found == np_object_to_object_var_.end()) - return NULL; - return found->second; -} - -void PluginModule::AddPluginObject(PluginObject* plugin_object) { - DCHECK(live_plugin_objects_.find(plugin_object) == - live_plugin_objects_.end()); - live_plugin_objects_.insert(plugin_object); -} - -void PluginModule::RemovePluginObject(PluginObject* plugin_object) { - // Don't actually verify that the object is in the set since during module - // deletion we'll be in the process of freeing them. - live_plugin_objects_.erase(plugin_object); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_plugin_module.h b/webkit/glue/plugins/pepper_plugin_module.h deleted file mode 100644 index 80eccda..0000000 --- a/webkit/glue/plugins/pepper_plugin_module.h +++ /dev/null @@ -1,169 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_MODULE_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_MODULE_H_ - -#include <map> -#include <set> - -#include "base/basictypes.h" -#include "base/native_library.h" -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "base/weak_ptr.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/ppb.h" - -class FilePath; -class MessageLoop; -typedef struct NPObject NPObject; -struct PPB_Core; -typedef void* NPIdentifier; - -namespace base { -class WaitableEvent; -} - -namespace pp { -namespace proxy { -class HostDispatcher; -} // proxy -} // pp - -namespace IPC { -struct ChannelHandle; -} - -namespace pepper { - -class ObjectVar; -class PluginDelegate; -class PluginInstance; -class PluginObject; - -// Represents one plugin library loaded into one renderer. This library may -// have multiple instances. -// -// Note: to get from a PP_Instance to a PluginInstance*, use the -// ResourceTracker. -class PluginModule : public base::RefCounted<PluginModule>, - public base::SupportsWeakPtr<PluginModule> { - public: - typedef const void* (*PPP_GetInterfaceFunc)(const char*); - typedef int (*PPP_InitializeModuleFunc)(PP_Module, PPB_GetInterface); - typedef void (*PPP_ShutdownModuleFunc)(); - - struct EntryPoints { - EntryPoints() - : get_interface(NULL), - initialize_module(NULL), - shutdown_module(NULL) { - } - - PPP_GetInterfaceFunc get_interface; - PPP_InitializeModuleFunc initialize_module; - PPP_ShutdownModuleFunc shutdown_module; - }; - - ~PluginModule(); - - static scoped_refptr<PluginModule> CreateModule(const FilePath& path); - static scoped_refptr<PluginModule> CreateInternalModule( - EntryPoints entry_points); - static scoped_refptr<PluginModule> CreateOutOfProcessModule( - MessageLoop* ipc_message_loop, - const IPC::ChannelHandle& handle, - base::WaitableEvent* shutdown_event); - - static const PPB_Core* GetCore(); - - PP_Module pp_module() const { return pp_module_; } - - void set_name(const std::string& name) { name_ = name; } - const std::string& name() const { return name_; } - - PluginInstance* CreateInstance(PluginDelegate* delegate); - - // Returns "some" plugin instance associated with this module. This is not - // guaranteed to be any one in particular. This is normally used to execute - // callbacks up to the browser layer that are not inherently per-instance, - // but the delegate lives only on the plugin instance so we need one of them. - PluginInstance* GetSomeInstance() const; - - const void* GetPluginInterface(const char* name) const; - - // This module is associated with a set of instances. The PluginInstance - // object declares its association with this module in its destructor and - // releases us in its destructor. - void InstanceCreated(PluginInstance* instance); - void InstanceDeleted(PluginInstance* instance); - - // Tracks all live ObjectVar. This is so we can map between PluginModule + - // NPObject and get the ObjectVar corresponding to it. This Add/Remove - // function should be called by the ObjectVar when it is created and - // destroyed. - void AddNPObjectVar(ObjectVar* object_var); - void RemoveNPObjectVar(ObjectVar* object_var); - - // Looks up a previously registered ObjectVar for the given NPObject and - // module. Returns NULL if there is no ObjectVar corresponding to the given - // NPObject for the given module. See AddNPObjectVar above. - ObjectVar* ObjectVarForNPObject(NPObject* np_object) const; - - // Tracks all live PluginObjects. - void AddPluginObject(PluginObject* plugin_object); - void RemovePluginObject(PluginObject* plugin_object); - - private: - PluginModule(); - - bool InitFromEntryPoints(const EntryPoints& entry_points); - bool InitFromFile(const FilePath& path); - bool InitForOutOfProcess(MessageLoop* ipc_message_loop, - const IPC::ChannelHandle& handle, - base::WaitableEvent* shutdown_event); - static bool LoadEntryPoints(const base::NativeLibrary& library, - EntryPoints* entry_points); - - // Dispatcher for out-of-process plugins. This will be null when the plugin - // is being run in-process. - scoped_ptr<pp::proxy::HostDispatcher> dispatcher_; - - PP_Module pp_module_; - - bool initialized_; - - // Holds a reference to the base::NativeLibrary handle if this PluginModule - // instance wraps functions loaded from a library. Can be NULL. If - // |library_| is non-NULL, PluginModule will attempt to unload the library - // during destruction. - base::NativeLibrary library_; - - // Contains pointers to the entry points of the actual plugin - // implementation. These will be NULL for out-of-process plugins. - EntryPoints entry_points_; - - // The name of the module. - std::string name_; - - // Non-owning pointers to all instances associated with this module. When - // there are no more instances, this object should be deleted. - typedef std::set<PluginInstance*> PluginInstanceSet; - PluginInstanceSet instances_; - - // Tracks all live ObjectVars used by this module so we can map NPObjects to - // the corresponding object. These are non-owning references. - typedef std::map<NPObject*, ObjectVar*> NPObjectToObjectVarMap;; - NPObjectToObjectVarMap np_object_to_object_var_; - - typedef std::set<PluginObject*> PluginObjectSet; - PluginObjectSet live_plugin_objects_; - - DISALLOW_COPY_AND_ASSIGN(PluginModule); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_MODULE_H_ diff --git a/webkit/glue/plugins/pepper_plugin_object.cc b/webkit/glue/plugins/pepper_plugin_object.cc deleted file mode 100644 index 2705809..0000000 --- a/webkit/glue/plugins/pepper_plugin_object.cc +++ /dev/null @@ -1,887 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_plugin_object.h" - -#include "base/logging.h" -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "base/string_number_conversions.h" -#include "base/string_util.h" -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/npruntime.h" -#include "ppapi/c/dev/ppb_var_deprecated.h" -#include "ppapi/c/dev/ppp_class_deprecated.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_class.h" -#include "third_party/WebKit/WebKit/chromium/public/WebBindings.h" -#include "webkit/glue/plugins/pepper_class.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_resource.h" -#include "webkit/glue/plugins/pepper_string.h" -#include "webkit/glue/plugins/pepper_var.h" - -using WebKit::WebBindings; - -namespace pepper { - -namespace { - -const char kInvalidValueException[] = "Error: Invalid value"; -const char kInvalidPluginValue[] = "Error: Plugin returned invalid value."; - -// ----------------------------------------------------------------------------- -// Utilities - -// Converts the given PP_Var to an NPVariant, returning true on success. -// False means that the given variant is invalid. In this case, the result -// NPVariant will be set to a void one. -// -// The contents of the PP_Var will be copied unless the PP_Var corresponds to -// an object. -bool PPVarToNPVariant(PP_Var var, NPVariant* result) { - switch (var.type) { - case PP_VARTYPE_UNDEFINED: - VOID_TO_NPVARIANT(*result); - break; - case PP_VARTYPE_NULL: - NULL_TO_NPVARIANT(*result); - break; - case PP_VARTYPE_BOOL: - BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); - break; - case PP_VARTYPE_INT32: - INT32_TO_NPVARIANT(var.value.as_int, *result); - break; - case PP_VARTYPE_DOUBLE: - DOUBLE_TO_NPVARIANT(var.value.as_double, *result); - break; - case PP_VARTYPE_STRING: { - scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); - if (!string) { - VOID_TO_NPVARIANT(*result); - return false; - } - const std::string& value = string->value(); - STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result); - break; - } - case PP_VARTYPE_OBJECT: { - scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); - if (!object) { - VOID_TO_NPVARIANT(*result); - return false; - } - OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()), - *result); - break; - } - } - return true; -} - -// PPVarArrayFromNPVariantArray ------------------------------------------------ - -// Converts an array of NPVariants to an array of PP_Var, and scopes the -// ownership of the PP_Var. This is used when converting argument lists from -// WebKit to the plugin. -class PPVarArrayFromNPVariantArray { - public: - PPVarArrayFromNPVariantArray(PluginModule* module, - size_t size, - const NPVariant* variants) - : size_(size) { - if (size_ > 0) { - array_.reset(new PP_Var[size_]); - for (size_t i = 0; i < size_; i++) - array_[i] = Var::NPVariantToPPVar(module, &variants[i]); - } - } - - ~PPVarArrayFromNPVariantArray() { - for (size_t i = 0; i < size_; i++) - Var::PluginReleasePPVar(array_[i]); - } - - PP_Var* array() { return array_.get(); } - - private: - size_t size_; - scoped_array<PP_Var> array_; - - DISALLOW_COPY_AND_ASSIGN(PPVarArrayFromNPVariantArray); -}; - -// PPVarFromNPObject ----------------------------------------------------------- - -// Converts an NPObject tp PP_Var, and scopes the ownership of the PP_Var. This -// is used when converting 'this' pointer from WebKit to the plugin. -class PPVarFromNPObject { - public: - PPVarFromNPObject(PluginModule* module, NPObject* object) - : var_(ObjectVar::NPObjectToPPVar(module, object)) { - } - ~PPVarFromNPObject() { - Var::PluginReleasePPVar(var_); - } - PP_Var var() const { return var_; } - private: - const PP_Var var_; - - DISALLOW_COPY_AND_ASSIGN(PPVarFromNPObject); -}; - -// PPResultAndExceptionToNPResult ---------------------------------------------- - -// Convenience object for converting a PPAPI call that can throw an exception -// and optionally return a value, back to the NPAPI layer which expects a -// NPVariant as a result. -// -// Normal usage is that you will pass the result of exception() to the -// PPAPI function as the exception output parameter. Then you will either -// call SetResult with the result of the PPAPI call, or -// CheckExceptionForNoResult if the PPAPI call doesn't return a PP_Var. -// -// Both SetResult and CheckExceptionForNoResult will throw an exception to -// the JavaScript library if the plugin reported an exception. SetResult -// will additionally convert the result to an NPVariant and write it to the -// output parameter given in the constructor. -class PPResultAndExceptionToNPResult { - public: - // The object_var parameter is the object to associate any exception with. - // It may not be NULL. - // - // The np_result parameter is the NPAPI result output parameter. This may be - // NULL if there is no NPVariant result (like for HasProperty). If this is - // specified, you must call SetResult() to set it. If it is not, you must - // call CheckExceptionForNoResult to do the exception checking with no result - // conversion. - PPResultAndExceptionToNPResult(NPObject* object_var, - NPVariant* np_result) - : object_var_(object_var), - np_result_(np_result), - exception_(PP_MakeUndefined()), - success_(false), - checked_exception_(false) { - } - - ~PPResultAndExceptionToNPResult() { - // The user should have called SetResult or CheckExceptionForNoResult - // before letting this class go out of scope, or the exception will have - // been lost. - DCHECK(checked_exception_); - - ObjectVar::PluginReleasePPVar(exception_); - } - - // Returns true if an exception has been set. - bool has_exception() const { return exception_.type != PP_VARTYPE_UNDEFINED; } - - // Returns a pointer to the exception. You would pass this to the PPAPI - // function as the exception parameter. If it is set to non-void, this object - // will take ownership of destroying it. - PP_Var* exception() { return &exception_; } - - // Returns true if everything succeeded with no exception. This is valid only - // after calling SetResult/CheckExceptionForNoResult. - bool success() const { - DCHECK(checked_exception_); - return success_; - } - - // Call this with the return value of the PPAPI function. It will convert - // the result to the NPVariant output parameter and pass any exception on to - // the JS engine. It will update the success flag and return it. - bool SetResult(PP_Var result) { - DCHECK(!checked_exception_); // Don't call more than once. - DCHECK(np_result_); // Should be expecting a result. - - checked_exception_ = true; - - if (has_exception()) { - ThrowException(); - success_ = false; - } else if (!PPVarToNPVariant(result, np_result_)) { - WebBindings::setException(object_var_, kInvalidPluginValue); - success_ = false; - } else { - success_ = true; - } - - // No matter what happened, we need to release the reference to the - // value passed in. On success, a reference to this value will be in - // the np_result_. - Var::PluginReleasePPVar(result); - return success_; - } - - // Call this after calling a PPAPI function that could have set the - // exception. It will pass the exception on to the JS engine and update - // the success flag. - // - // The success flag will be returned. - bool CheckExceptionForNoResult() { - DCHECK(!checked_exception_); // Don't call more than once. - DCHECK(!np_result_); // Can't have a result when doing this. - - checked_exception_ = true; - - if (has_exception()) { - ThrowException(); - success_ = false; - return false; - } - success_ = true; - return true; - } - - // Call this to ignore any exception. This prevents the DCHECK from failing - // in the destructor. - void IgnoreException() { - checked_exception_ = true; - } - - private: - // Throws the current exception to JS. The exception must be set. - void ThrowException() { - scoped_refptr<StringVar> string(StringVar::FromPPVar(exception_)); - if (string) { - WebBindings::setException(object_var_, string->value().c_str()); - } - } - - NPObject* object_var_; // Non-owning ref (see constructor). - NPVariant* np_result_; // Output value, possibly NULL (see constructor). - PP_Var exception_; // Exception set by the PPAPI call. We own a ref to it. - bool success_; // See the success() function above. - bool checked_exception_; // SetResult/CheckExceptionForNoResult was called. - - DISALLOW_COPY_AND_ASSIGN(PPResultAndExceptionToNPResult); -}; - -// NPObjectAccessorWithIdentifier ---------------------------------------------- - -// Helper class for our NPObject wrapper. This converts a call from WebKit -// where it gives us an NPObject and an NPIdentifier to an easily-accessible -// ObjectVar (corresponding to the NPObject) and PP_Var (corresponding to the -// NPIdentifier). -// -// If the NPObject or identifier is invalid, we'll set is_valid() to false. -// The caller should check is_valid() before doing anything with the class. -// -// JS can't have integer functions, so when dealing with these, we don't want -// to allow integer identifiers. The calling code can decode if it wants to -// allow integer identifiers (like for property access) or prohibit them -// (like for method calling) by setting |allow_integer_identifier|. If this -// is false and the identifier is an integer, we'll set is_valid() to false. -// -// Getting an integer identifier in this case should be impossible. V8 -// shouldn't be allowing this, and the Pepper Var calls from the plugin are -// supposed to error out before calling into V8 (which will then call us back). -// Aside from an egregious error, the only time this could happen is an NPAPI -// plugin calling us. -class NPObjectAccessorWithIdentifier { - public: - NPObjectAccessorWithIdentifier(NPObject* object, - NPIdentifier identifier, - bool allow_integer_identifier) - : object_(PluginObject::FromNPObject(object)), - identifier_(PP_MakeUndefined()) { - if (object_) { - identifier_ = Var::NPIdentifierToPPVar(object_->module(), identifier); - if (identifier_.type == PP_VARTYPE_INT32 && !allow_integer_identifier) - identifier_.type = PP_VARTYPE_UNDEFINED; // Mark it invalid. - } - } - - ~NPObjectAccessorWithIdentifier() { - Var::PluginReleasePPVar(identifier_); - } - - // Returns true if both the object and identifier are valid. - bool is_valid() const { - return object_ && identifier_.type != PP_VARTYPE_UNDEFINED; - } - - PluginObject* object() { return object_; } - PP_Var identifier() const { return identifier_; } - - private: - PluginObject* object_; - PP_Var identifier_; - - DISALLOW_COPY_AND_ASSIGN(NPObjectAccessorWithIdentifier); -}; - -// NPObject implementation in terms of PPP_Class_Deprecated -------------------- - -NPObject* WrapperClass_Allocate(NPP npp, NPClass* unused) { - return PluginObject::AllocateObjectWrapper(); -} - -void WrapperClass_Deallocate(NPObject* np_object) { - PluginObject* plugin_object = PluginObject::FromNPObject(np_object); - if (!plugin_object) - return; - plugin_object->ppp_class()->Deallocate(plugin_object->ppp_class_data()); - delete plugin_object; -} - -void WrapperClass_Invalidate(NPObject* object) { -} - -bool WrapperClass_HasMethod(NPObject* object, NPIdentifier method_name) { - NPObjectAccessorWithIdentifier accessor(object, method_name, false); - if (!accessor.is_valid()) - return false; - - PPResultAndExceptionToNPResult result_converter( - accessor.object()->GetNPObject(), NULL); - bool rv = accessor.object()->ppp_class()->HasMethod( - accessor.object()->ppp_class_data(), accessor.identifier(), - result_converter.exception()); - result_converter.CheckExceptionForNoResult(); - return rv; -} - -bool WrapperClass_Invoke(NPObject* object, NPIdentifier method_name, - const NPVariant* argv, uint32_t argc, - NPVariant* result) { - NPObjectAccessorWithIdentifier accessor(object, method_name, false); - if (!accessor.is_valid()) - return false; - - PPResultAndExceptionToNPResult result_converter( - accessor.object()->GetNPObject(), result); - PPVarArrayFromNPVariantArray args(accessor.object()->module(), argc, argv); - - return result_converter.SetResult(accessor.object()->ppp_class()->Call( - accessor.object()->ppp_class_data(), accessor.identifier(), - argc, args.array(), result_converter.exception())); -} - -bool WrapperClass_InvokeDefault(NPObject* np_object, const NPVariant* argv, - uint32_t argc, NPVariant* result) { - PluginObject* obj = PluginObject::FromNPObject(np_object); - if (!obj) - return false; - - PPVarArrayFromNPVariantArray args(obj->module(), argc, argv); - PPResultAndExceptionToNPResult result_converter(obj->GetNPObject(), result); - - result_converter.SetResult(obj->ppp_class()->Call( - obj->ppp_class_data(), PP_MakeUndefined(), argc, args.array(), - result_converter.exception())); - return result_converter.success(); -} - -bool WrapperClass_HasProperty(NPObject* object, NPIdentifier property_name) { - NPObjectAccessorWithIdentifier accessor(object, property_name, true); - if (!accessor.is_valid()) - return false; - - PPResultAndExceptionToNPResult result_converter( - accessor.object()->GetNPObject(), NULL); - bool rv = accessor.object()->ppp_class()->HasProperty( - accessor.object()->ppp_class_data(), accessor.identifier(), - result_converter.exception()); - result_converter.CheckExceptionForNoResult(); - return rv; -} - -bool WrapperClass_GetProperty(NPObject* object, NPIdentifier property_name, - NPVariant* result) { - NPObjectAccessorWithIdentifier accessor(object, property_name, true); - if (!accessor.is_valid()) - return false; - - PPResultAndExceptionToNPResult result_converter( - accessor.object()->GetNPObject(), result); - return result_converter.SetResult(accessor.object()->ppp_class()->GetProperty( - accessor.object()->ppp_class_data(), accessor.identifier(), - result_converter.exception())); -} - -bool WrapperClass_SetProperty(NPObject* object, NPIdentifier property_name, - const NPVariant* value) { - NPObjectAccessorWithIdentifier accessor(object, property_name, true); - if (!accessor.is_valid()) - return false; - - PPResultAndExceptionToNPResult result_converter( - accessor.object()->GetNPObject(), NULL); - PP_Var value_var = Var::NPVariantToPPVar(accessor.object()->module(), value); - accessor.object()->ppp_class()->SetProperty( - accessor.object()->ppp_class_data(), accessor.identifier(), value_var, - result_converter.exception()); - Var::PluginReleasePPVar(value_var); - return result_converter.CheckExceptionForNoResult(); -} - -bool WrapperClass_RemoveProperty(NPObject* object, NPIdentifier property_name) { - NPObjectAccessorWithIdentifier accessor(object, property_name, true); - if (!accessor.is_valid()) - return false; - - PPResultAndExceptionToNPResult result_converter( - accessor.object()->GetNPObject(), NULL); - accessor.object()->ppp_class()->RemoveProperty( - accessor.object()->ppp_class_data(), accessor.identifier(), - result_converter.exception()); - return result_converter.CheckExceptionForNoResult(); -} - -bool WrapperClass_Enumerate(NPObject* object, NPIdentifier** values, - uint32_t* count) { - *values = NULL; - *count = 0; - PluginObject* obj = PluginObject::FromNPObject(object); - if (!obj) - return false; - - uint32_t property_count = 0; - PP_Var* properties = NULL; // Must be freed! - PPResultAndExceptionToNPResult result_converter(obj->GetNPObject(), NULL); - obj->ppp_class()->GetAllPropertyNames(obj->ppp_class_data(), - &property_count, &properties, - result_converter.exception()); - - // Convert the array of PP_Var to an array of NPIdentifiers. If any - // conversions fail, we will set the exception. - if (!result_converter.has_exception()) { - if (property_count > 0) { - *values = static_cast<NPIdentifier*>( - malloc(sizeof(NPIdentifier) * property_count)); - *count = 0; // Will be the number of items successfully converted. - for (uint32_t i = 0; i < property_count; ++i) { - if (!((*values)[i] = Var::PPVarToNPIdentifier(properties[i]))) { - // Throw an exception for the failed convertion. - *result_converter.exception() = StringVar::StringToPPVar( - obj->module(), kInvalidValueException); - break; - } - (*count)++; - } - - if (result_converter.has_exception()) { - // We don't actually have to free the identifiers we converted since - // all identifiers leak anyway :( . - free(*values); - *values = NULL; - *count = 0; - } - } - } - - // This will actually throw the exception, either from GetAllPropertyNames, - // or if anything was set during the conversion process. - result_converter.CheckExceptionForNoResult(); - - // Release the PP_Var that the plugin allocated. On success, they will all - // be converted to NPVariants, and on failure, we want them to just go away. - for (uint32_t i = 0; i < property_count; ++i) - Var::PluginReleasePPVar(properties[i]); - free(properties); - return result_converter.success(); -} - -bool WrapperClass_Construct(NPObject* object, const NPVariant* argv, - uint32_t argc, NPVariant* result) { - PluginObject* obj = PluginObject::FromNPObject(object); - if (!obj) - return false; - - PPVarArrayFromNPVariantArray args(obj->module(), argc, argv); - PPResultAndExceptionToNPResult result_converter(obj->GetNPObject(), result); - return result_converter.SetResult(obj->ppp_class()->Construct( - obj->ppp_class_data(), argc, args.array(), - result_converter.exception())); -} - -const NPClass wrapper_class = { - NP_CLASS_STRUCT_VERSION, - WrapperClass_Allocate, - WrapperClass_Deallocate, - WrapperClass_Invalidate, - WrapperClass_HasMethod, - WrapperClass_Invoke, - WrapperClass_InvokeDefault, - WrapperClass_HasProperty, - WrapperClass_GetProperty, - WrapperClass_SetProperty, - WrapperClass_RemoveProperty, - WrapperClass_Enumerate, - WrapperClass_Construct -}; - -} // namespace - -// PluginObject ---------------------------------------------------------------- - -struct PluginObject::NPObjectWrapper : public NPObject { - // Points to the var object that owns this wrapper. This value may be NULL - // if there is no var owning this wrapper. This can happen if the plugin - // releases all references to the var, but a reference to the underlying - // NPObject is still held by script on the page. - PluginObject* obj; -}; - -PluginObject::PluginObject(PluginModule* module, - NPObjectWrapper* object_wrapper, - const PPP_Class_Deprecated* ppp_class, - void* ppp_class_data) - : module_(module), - object_wrapper_(object_wrapper), - ppp_class_(ppp_class), - ppp_class_data_(ppp_class_data) { - // Make the object wrapper refer back to this class so our NPObject - // implementation can call back into the Pepper layer. - object_wrapper_->obj = this; - module_->AddPluginObject(this); -} - -PluginObject::~PluginObject() { - // The wrapper we made for this NPObject may still have a reference to it - // from JavaScript, so we clear out its ObjectVar back pointer which will - // cause all calls "up" to the plugin to become NOPs. Our ObjectVar base - // class will release our reference to the object, which may or may not - // delete the NPObject. - DCHECK(object_wrapper_->obj == this); - object_wrapper_->obj = NULL; - module_->RemovePluginObject(this); -} - -PP_Var PluginObject::Create(PluginModule* module, - const PPP_Class_Deprecated* ppp_class, - void* ppp_class_data) { - // This will internally end up calling our AllocateObjectWrapper via the - // WrapperClass_Allocated function which will have created an object wrapper - // appropriate for this class (derived from NPObject). - NPObjectWrapper* wrapper = static_cast<NPObjectWrapper*>( - WebBindings::createObject(NULL, const_cast<NPClass*>(&wrapper_class))); - - // This object will register itself both with the NPObject and with the - // PluginModule. The NPObject will normally handle its lifetime, and it - // will get deleted in the destroy method. It may also get deleted when the - // plugin module is deallocated. - new PluginObject(module, wrapper, ppp_class, ppp_class_data); - - // We can just use a normal ObjectVar to refer to this object from the - // plugin. It will hold a ref to the underlying NPObject which will in turn - // hold our pluginObject. - return ObjectVar::NPObjectToPPVar(module, wrapper); -} - -NPObject* PluginObject::GetNPObject() const { - return object_wrapper_; -} - -// static -bool PluginObject::IsInstanceOf(NPObject* np_object, - const PPP_Class_Deprecated* ppp_class, - void** ppp_class_data) { - // Validate that this object is implemented by our wrapper class before - // trying to get the PluginObject. - if (np_object->_class != &wrapper_class) - return false; - - PluginObject* plugin_object = FromNPObject(np_object); - if (!plugin_object) - return false; // Object is no longer alive. - - if (plugin_object->ppp_class() != ppp_class) - return false; - if (ppp_class_data) - *ppp_class_data = plugin_object->ppp_class_data(); - return true; -} - -// static -PluginObject* PluginObject::FromNPObject(NPObject* object) { - return static_cast<NPObjectWrapper*>(object)->obj; -} - -// static -NPObject* PluginObject::AllocateObjectWrapper() { - NPObjectWrapper* wrapper = new NPObjectWrapper; - memset(wrapper, 0, sizeof(NPObjectWrapper)); - return wrapper; -} - -// VarObjectClass::InstanceData ----------------------------------------------- - -struct VarObjectClass::InstanceData : public NPObject { - InstanceData() : native_data(NULL) {} - - scoped_refptr<VarObjectClass> object_class; - void* native_data; -}; - -// VarObjectClass::Property --------------------------------------------------- - -VarObjectClass::Property::Property(const PP_ClassProperty& prop) - : method(prop.method), - getter(prop.getter), - setter(prop.setter), - writable(!(prop.modifiers & PP_OBJECTPROPERTY_MODIFIER_READONLY)), - enumerable(!(prop.modifiers & PP_OBJECTPROPERTY_MODIFIER_DONTENUM)) { -} - - -// VarObjectAccessorWithIdentifier --------------------------------------------- - -// Helper class for the new (PPB_Class) NPObject wrapper. This converts a call -// from WebKit where it gives us an NPObject and an NPIdentifier to an -// easily-accessible InstanceData (corresponding to the NPObject) and -// std::string and Property (corresponding to the NPIdentifier). -class VarObjectAccessorWithIdentifier { - public: - VarObjectAccessorWithIdentifier(NPObject* object, NPIdentifier identifier) - : exists_(false), - instance_(static_cast<VarObjectClass::InstanceData*>(object)), - property_(NULL) { - if (instance_) { - const NPUTF8* string_value = NULL; - int32_t int_value = 0; - bool is_string = false; - WebBindings::extractIdentifierData(identifier, string_value, int_value, - is_string); - if (is_string) { - property_name_ = string_value; - - const VarObjectClass::PropertyMap& properties = - instance_->object_class->properties(); - VarObjectClass::PropertyMap::const_iterator it = - properties.find(property_name_); - if (it != properties.end()) { - property_ = &it->second; - exists_ = true; - } - } - } - } - - // Return true if the object is valid, the identifier is valid, and the - // property with said name exists. - bool exists() const { return exists_; } - bool is_method() const { return exists() && property_->method; } - bool is_readable() const { return exists() && property_->getter; } - bool is_writable() const { - return exists() && property_->setter && property_->writable; - } - const VarObjectClass::InstanceData* instance() const { return instance_; } - const VarObjectClass::Property* property() const { return property_; } - PluginModule* module() const { - return instance_ ? instance_->object_class->module() : NULL; - } - - private: - bool exists_; - const VarObjectClass::InstanceData* instance_; - std::string property_name_; - const VarObjectClass::Property* property_; - - DISALLOW_COPY_AND_ASSIGN(VarObjectAccessorWithIdentifier); -}; - -// NPObject implementation in terms of PPB_Class ------------------------------- - -namespace { - -NPObject* VarObjectClassAllocate(NPP npp, NPClass* the_class) { - return new VarObjectClass::InstanceData; -} - -void VarObjectClassDeallocate(NPObject* object) { - VarObjectClass::InstanceData* instance = - static_cast<VarObjectClass::InstanceData*>(object); - if (instance->object_class->instance_native_destructor()) - instance->object_class->instance_native_destructor()(instance->native_data); - delete instance; -} - -bool VarObjectClassHasMethod(NPObject* np_obj, NPIdentifier name) { - VarObjectAccessorWithIdentifier accessor(np_obj, name); - return accessor.is_method(); -} - -bool VarObjectClassInvoke(NPObject* np_obj, NPIdentifier name, - const NPVariant* args, uint32 arg_count, - NPVariant* result) { - VarObjectAccessorWithIdentifier accessor(np_obj, name); - if (!accessor.is_method()) - return false; - - PPResultAndExceptionToNPResult result_converter(np_obj, result); - PPVarArrayFromNPVariantArray arguments(accessor.module(), arg_count, args); - PPVarFromNPObject self(accessor.module(), np_obj); - - return result_converter.SetResult(accessor.property()->method( - accessor.instance()->native_data, self.var(), arguments.array(), arg_count, - result_converter.exception())); -} - -bool VarObjectClassInvokeDefault(NPObject* np_obj, - const NPVariant* args, - uint32 arg_count, - NPVariant* result) { - VarObjectClass::InstanceData* instance = - static_cast<VarObjectClass::InstanceData*>(np_obj); - if (!instance || !instance->object_class->instance_invoke()) - return false; - - PPResultAndExceptionToNPResult result_converter(np_obj, result); - PPVarArrayFromNPVariantArray arguments(instance->object_class->module(), - arg_count, args); - PPVarFromNPObject self(instance->object_class->module(), np_obj); - - return result_converter.SetResult(instance->object_class->instance_invoke()( - instance->native_data, self.var(), arguments.array(), arg_count, - result_converter.exception())); -} - -bool VarObjectClassHasProperty(NPObject* np_obj, NPIdentifier name) { - VarObjectAccessorWithIdentifier accessor(np_obj, name); - return accessor.is_readable(); -} - -bool VarObjectClassGetProperty(NPObject* np_obj, NPIdentifier name, - NPVariant* result) { - VarObjectAccessorWithIdentifier accessor(np_obj, name); - if (!accessor.is_readable()) { - return false; - } - - PPResultAndExceptionToNPResult result_converter(np_obj, result); - PPVarFromNPObject self(accessor.module(), np_obj); - - return result_converter.SetResult(accessor.property()->getter( - accessor.instance()->native_data, self.var(), 0, 0, - result_converter.exception())); -} - -bool VarObjectClassSetProperty(NPObject* np_obj, NPIdentifier name, - const NPVariant* variant) { - VarObjectAccessorWithIdentifier accessor(np_obj, name); - if (!accessor.is_writable()) { - return false; - } - - PPResultAndExceptionToNPResult result_converter(np_obj, NULL); - PPVarArrayFromNPVariantArray arguments(accessor.module(), 1, variant); - PPVarFromNPObject self(accessor.module(), np_obj); - - // Ignore return value. - Var::PluginReleasePPVar(accessor.property()->setter( - accessor.instance()->native_data, self.var(), arguments.array(), 1, - result_converter.exception())); - - return result_converter.CheckExceptionForNoResult(); -} - -bool VarObjectClassEnumerate(NPObject *np_obj, NPIdentifier **value, - uint32_t *count) { - VarObjectClass::InstanceData* instance = - static_cast<VarObjectClass::InstanceData*>(np_obj); - *count = 0; - *value = NULL; - if (!instance) - return false; - - const VarObjectClass::PropertyMap& properties = - instance->object_class->properties(); - - // Don't bother calculating the size of enumerable properties, just allocate - // enough for all and then fill it partially. - *value = static_cast<NPIdentifier*>( - malloc(sizeof(NPIdentifier) * properties.size())); - - NPIdentifier* inserter = *value; - for (VarObjectClass::PropertyMap::const_iterator i = properties.begin(); - i != properties.end(); ++i) - if (i->second.enumerable) - *inserter++ = WebBindings::getStringIdentifier(i->first.c_str()); - - *count = inserter - *value; - return true; -} - -NPClass objectclassvar_class = { - NP_CLASS_STRUCT_VERSION, - &VarObjectClassAllocate, - &VarObjectClassDeallocate, - NULL, - &VarObjectClassHasMethod, - &VarObjectClassInvoke, - &VarObjectClassInvokeDefault, - &VarObjectClassHasProperty, - &VarObjectClassGetProperty, - &VarObjectClassSetProperty, - NULL, - &VarObjectClassEnumerate, -}; - -// PPB_Class interface --------------------------------------------------------- - -PP_Resource Create(PP_Module module, PP_ClassDestructor destruct, - PP_ClassFunction invoke, PP_ClassProperty* properties) { - PluginModule* plugin_module = ResourceTracker::Get()->GetModule(module); - if (!properties || !plugin_module) - return 0; - scoped_refptr<VarObjectClass> cls = new VarObjectClass(plugin_module, - destruct, - invoke, - properties); - if (!cls) - return 0; - return cls->GetReference(); -} - -PP_Var Instantiate(PP_Resource class_object, void* native_data, - PP_Var* exception) { - scoped_refptr<VarObjectClass> object_class = - Resource::GetAs<VarObjectClass>(class_object); - if (!object_class) - return PP_MakeUndefined(); - NPObject* obj = WebBindings::createObject(NULL, &objectclassvar_class); - VarObjectClass::InstanceData* instance_data = - static_cast<VarObjectClass::InstanceData*>(obj); - instance_data->object_class = object_class; - instance_data->native_data = native_data; - return ObjectVar::NPObjectToPPVar(object_class->module(), obj); -} - -} // namespace - -// VarObjectClass -------------------------------------------------------------- - -VarObjectClass::VarObjectClass(PluginModule* module, - PP_ClassDestructor destruct, - PP_ClassFunction invoke, - PP_ClassProperty* properties) - : Resource(module), - instance_native_destructor_(destruct), - instance_invoke_(invoke) { - PP_ClassProperty* prop = properties; - while (prop->name) { - properties_.insert(std::make_pair(std::string(prop->name), - Property(*prop))); - ++prop; - } -} - -// static -const PPB_Class* VarObjectClass::GetInterface() { - static PPB_Class interface = { - &Create, - &Instantiate - }; - return &interface; -} - -// virtual -VarObjectClass::~VarObjectClass() { } - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_plugin_object.h b/webkit/glue/plugins/pepper_plugin_object.h deleted file mode 100644 index e31c1b1..0000000 --- a/webkit/glue/plugins/pepper_plugin_object.h +++ /dev/null @@ -1,89 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_OBJECT_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_OBJECT_H_ - -#include <string> - -#include "base/basictypes.h" - -struct PP_Var; -struct PPP_Class_Deprecated; -typedef struct NPObject NPObject; -typedef struct _NPVariant NPVariant; - -namespace pepper { - -class PluginModule; - -class PluginObject { - public: - virtual ~PluginObject(); - - // Allocates a new PluginObject and returns it as a PP_Var with a - // refcount of 1. - static PP_Var Create(PluginModule* module, - const PPP_Class_Deprecated* ppp_class, - void* ppp_class_data); - - PluginModule* module() const { return module_; } - - const PPP_Class_Deprecated* ppp_class() { return ppp_class_; } - void* ppp_class_data() { return ppp_class_data_; }; - - NPObject* GetNPObject() const; - - // Returns true if the given var is an object implemented by the same plugin - // that owns the var object, and that the class matches. If it matches, - // returns true and places the class data into |*ppp_class_data| (which can - // optionally be NULL if no class data is desired). - static bool IsInstanceOf(NPObject* np_object, - const PPP_Class_Deprecated* ppp_class, - void** ppp_class_data); - - // Converts the given NPObject to the corresponding ObjectVar. - // - // The given NPObject must be one corresponding to a PluginObject or this - // will crash. If the object is a PluginObject but the plugin has gone - // away (the object could still be alive because of a reference from JS), - // then the return value will be NULL. - static PluginObject* FromNPObject(NPObject* object); - - // Allocates a plugin wrapper object and returns it as an NPObject. This is - // used internally only. - static NPObject* AllocateObjectWrapper(); - - private: - struct NPObjectWrapper; - - // This object must be created using the CreateObject function of the which - // will set up the correct NPObject. - // - // The NPObjectWrapper (an NPObject) should already have the reference - // incremented on it, and this class will take ownership of that reference. - PluginObject(PluginModule* module, - NPObjectWrapper* object_wrapper, - const PPP_Class_Deprecated* ppp_class, - void* ppp_class_data); - - PluginModule* module_; - - // Holds a pointer to the NPObject wrapper backing the var. This class - // derives from NPObject and we hold a reference to it, so it must be - // refcounted. When the type is not an object, this value will be NULL. - // - // We don't actually own this pointer, it's the NPObject that actually - // owns us. - NPObjectWrapper* object_wrapper_; - - const PPP_Class_Deprecated* ppp_class_; - void* ppp_class_data_; - - DISALLOW_COPY_AND_ASSIGN(PluginObject); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_PLUGIN_OBJECT_H_ diff --git a/webkit/glue/plugins/pepper_private.cc b/webkit/glue/plugins/pepper_private.cc deleted file mode 100644 index 0675bee..0000000 --- a/webkit/glue/plugins/pepper_private.cc +++ /dev/null @@ -1,302 +0,0 @@ -// 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 "build/build_config.h" - -#include "webkit/glue/plugins/pepper_private.h" - -#include "unicode/usearch.h" - -#include "app/resource_bundle.h" -#include "base/metrics/histogram.h" -#include "base/utf_string_conversions.h" -#include "grit/webkit_resources.h" -#include "grit/webkit_strings.h" -#include "skia/ext/platform_canvas.h" -#include "ppapi/c/pp_resource.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_var.h" -#include "webkit/glue/plugins/ppb_private.h" -#include "webkit/glue/plugins/pepper_var.h" - -namespace pepper { - -#if defined(OS_LINUX) -class PrivateFontFile : public Resource { - public: - PrivateFontFile(PluginModule* module, int fd) - : Resource(module), - fd_(fd) { - } - virtual ~PrivateFontFile() { - } - - // Resource overrides. - PrivateFontFile* AsPrivateFontFile() { return this; } - - bool GetFontTable(uint32_t table, - void* output, - uint32_t* output_length); - - private: - int fd_; -}; -#endif - -namespace { - -struct ResourceImageInfo { - PP_ResourceImage pp_id; - int res_id; -}; - -static const ResourceImageInfo kResourceImageMap[] = { - { PP_RESOURCEIMAGE_PDF_BUTTON_FTH, IDR_PDF_BUTTON_FTH }, - { PP_RESOURCEIMAGE_PDF_BUTTON_FTH_HOVER, IDR_PDF_BUTTON_FTH_HOVER }, - { PP_RESOURCEIMAGE_PDF_BUTTON_FTH_PRESSED, IDR_PDF_BUTTON_FTH_PRESSED }, - { PP_RESOURCEIMAGE_PDF_BUTTON_FTW, IDR_PDF_BUTTON_FTW }, - { PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, IDR_PDF_BUTTON_FTW_HOVER }, - { PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED, IDR_PDF_BUTTON_FTW_PRESSED }, - { PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN, IDR_PDF_BUTTON_ZOOMIN }, - { PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER, IDR_PDF_BUTTON_ZOOMIN_HOVER }, - { PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED, IDR_PDF_BUTTON_ZOOMIN_PRESSED }, - { PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, IDR_PDF_BUTTON_ZOOMOUT }, - { PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, IDR_PDF_BUTTON_ZOOMOUT_HOVER }, - { PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED, - IDR_PDF_BUTTON_ZOOMOUT_PRESSED }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0, IDR_PDF_THUMBNAIL_0 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1, IDR_PDF_THUMBNAIL_1 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2, IDR_PDF_THUMBNAIL_2 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3, IDR_PDF_THUMBNAIL_3 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4, IDR_PDF_THUMBNAIL_4 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5, IDR_PDF_THUMBNAIL_5 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6, IDR_PDF_THUMBNAIL_6 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7, IDR_PDF_THUMBNAIL_7 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8, IDR_PDF_THUMBNAIL_8 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9, IDR_PDF_THUMBNAIL_9 }, - { PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND, - IDR_PDF_THUMBNAIL_NUM_BACKGROUND }, -}; - -PP_Var GetLocalizedString(PP_Module module_id, PP_ResourceString string_id) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return PP_MakeUndefined(); - - std::string rv; - if (string_id == PP_RESOURCESTRING_PDFGETPASSWORD) { - rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_NEED_PASSWORD)); - } else if (string_id == PP_RESOURCESTRING_PDFLOADING) { - rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOADING)); - } else if (string_id == PP_RESOURCESTRING_PDFLOAD_FAILED) { - rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOAD_FAILED)); - } else { - NOTREACHED(); - } - - return StringVar::StringToPPVar(module, rv); -} - -PP_Resource GetResourceImage(PP_Module module_id, PP_ResourceImage image_id) { - int res_id = 0; - for (size_t i = 0; i < arraysize(kResourceImageMap); ++i) { - if (kResourceImageMap[i].pp_id == image_id) { - res_id = kResourceImageMap[i].res_id; - break; - } - } - if (res_id == 0) - return 0; - - SkBitmap* res_bitmap = - ResourceBundle::GetSharedInstance().GetBitmapNamed(res_id); - - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - scoped_refptr<pepper::ImageData> image_data(new pepper::ImageData(module)); - if (!image_data->Init(ImageData::GetNativeImageDataFormat(), - res_bitmap->width(), res_bitmap->height(), false)) { - return 0; - } - - ImageDataAutoMapper mapper(image_data); - if (!mapper.is_valid()) - return 0; - - skia::PlatformCanvas* canvas = image_data->mapped_canvas(); - SkBitmap& ret_bitmap = - const_cast<SkBitmap&>(canvas->getTopPlatformDevice().accessBitmap(true)); - if (!res_bitmap->copyTo(&ret_bitmap, SkBitmap::kARGB_8888_Config, NULL)) { - return 0; - } - - return image_data->GetReference(); -} - -PP_Resource GetFontFileWithFallback( - PP_Module module_id, - const PP_FontDescription_Dev* description, - PP_PrivateFontCharset charset) { -#if defined(OS_LINUX) - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - scoped_refptr<StringVar> face_name(StringVar::FromPPVar(description->face)); - if (!face_name) - return 0; - - int fd = webkit_glue::MatchFontWithFallback( - face_name->value().c_str(), - description->weight >= PP_FONTWEIGHT_BOLD, - description->italic, - charset); - if (fd == -1) - return 0; - - scoped_refptr<PrivateFontFile> font(new PrivateFontFile(module, fd)); - - return font->GetReference(); -#else - // For trusted pepper plugins, this is only needed in Linux since font loading - // on Windows and Mac works through the renderer sandbox. - return 0; -#endif -} - -bool GetFontTableForPrivateFontFile(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length) { -#if defined(OS_LINUX) - scoped_refptr<PrivateFontFile> font( - Resource::GetAs<PrivateFontFile>(font_file)); - if (!font.get()) - return false; - return font->GetFontTable(table, output, output_length); -#else - return false; -#endif -} - -void SearchString(PP_Module module, - const unsigned short* input_string, - const unsigned short* input_term, - bool case_sensitive, - PP_PrivateFindResult** results, - int* count) { - const char16* string = reinterpret_cast<const char16*>(input_string); - const char16* term = reinterpret_cast<const char16*>(input_term); - - UErrorCode status = U_ZERO_ERROR; - UStringSearch* searcher = usearch_open( - term, -1, string, -1, webkit_glue::GetWebKitLocale().c_str(), 0, - &status); - DCHECK(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING || - status == U_USING_DEFAULT_WARNING); - UCollationStrength strength = case_sensitive ? UCOL_TERTIARY : UCOL_PRIMARY; - - UCollator* collator = usearch_getCollator(searcher); - if (ucol_getStrength(collator) != strength) { - ucol_setStrength(collator, strength); - usearch_reset(searcher); - } - - status = U_ZERO_ERROR; - int match_start = usearch_first(searcher, &status); - DCHECK(status == U_ZERO_ERROR); - - std::vector<PP_PrivateFindResult> pp_results; - while (match_start != USEARCH_DONE) { - size_t matched_length = usearch_getMatchedLength(searcher); - PP_PrivateFindResult result; - result.start_index = match_start; - result.length = matched_length; - pp_results.push_back(result); - match_start = usearch_next(searcher, &status); - DCHECK(status == U_ZERO_ERROR); - } - - *count = pp_results.size(); - if (*count) { - *results = reinterpret_cast<PP_PrivateFindResult*>( - malloc(*count * sizeof(PP_PrivateFindResult))); - memcpy(*results, &pp_results[0], *count * sizeof(PP_PrivateFindResult)); - } else { - *results = NULL; - } - - usearch_close(searcher); -} - -void DidStartLoading(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return; - instance->delegate()->DidStartLoading(); -} - -void DidStopLoading(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return; - instance->delegate()->DidStopLoading(); -} - -void SetContentRestriction(PP_Instance instance_id, int restrictions) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return; - instance->delegate()->SetContentRestriction(restrictions); -} - -void HistogramPDFPageCount(int count) { - UMA_HISTOGRAM_COUNTS_10000("PDF.PageCount", count); -} - -void UserMetricsRecordAction(PP_Var action) { - scoped_refptr<StringVar> action_str(StringVar::FromPPVar(action)); - if (action_str) - webkit_glue::UserMetricsRecordAction(action_str->value()); -} - -const PPB_Private ppb_private = { - &GetLocalizedString, - &GetResourceImage, - &GetFontFileWithFallback, - &GetFontTableForPrivateFontFile, - &SearchString, - &DidStartLoading, - &DidStopLoading, - &SetContentRestriction, - &HistogramPDFPageCount, - &UserMetricsRecordAction -}; - -} // namespace - -// static -const PPB_Private* Private::GetInterface() { - return &ppb_private; -} - -#if defined(OS_LINUX) -bool PrivateFontFile::GetFontTable(uint32_t table, - void* output, - uint32_t* output_length) { - size_t temp_size = static_cast<size_t>(*output_length); - bool rv = webkit_glue::GetFontTable( - fd_, table, static_cast<uint8_t*>(output), &temp_size); - *output_length = static_cast<uint32_t>(temp_size); - return rv; -} -#endif - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_private.h b/webkit/glue/plugins/pepper_private.h deleted file mode 100644 index 06016f0..0000000 --- a/webkit/glue/plugins/pepper_private.h +++ /dev/null @@ -1,23 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_PRIVATE_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_PRIVATE_H_ - -#include "webkit/glue/plugins/pepper_resource.h" - -struct PPB_Private; - -namespace pepper { - -class Private { - public: - // Returns a pointer to the interface implementing PPB_Private that is exposed - // to the plugin. - static const PPB_Private* GetInterface(); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_PRIVATE_H_ diff --git a/webkit/glue/plugins/pepper_private2.cc b/webkit/glue/plugins/pepper_private2.cc deleted file mode 100644 index 8492b65..0000000 --- a/webkit/glue/plugins/pepper_private2.cc +++ /dev/null @@ -1,243 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_private2.h" - -#include <string.h> - -#include "base/file_path.h" -#include "base/stringprintf.h" -#include "base/utf_string_conversions.h" -#include "googleurl/src/gurl.h" -#include "ppapi/c/dev/pp_file_info_dev.h" -#include "ppapi/c/dev/ppb_file_io_dev.h" -#include "webkit/glue/plugins/pepper_error_util.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_var.h" -#include "webkit/glue/plugins/ppb_private2.h" - -namespace pepper { - -namespace { - -PluginInstance* GetSomeInstance(PP_Module pp_module) { - PluginModule* module = ResourceTracker::Get()->GetModule(pp_module); - if (!module) - return NULL; - - return module->GetSomeInstance(); -} - -void SetInstanceAlwaysOnTop(PP_Instance pp_instance, bool on_top) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(pp_instance); - if (!instance) - return; - instance->set_always_on_top(on_top); -} - -PP_Var GetProxyForURL(PP_Module pp_module, const char* url) { - PluginInstance* instance = GetSomeInstance(pp_module); - if (!instance) - return PP_MakeUndefined(); - - GURL gurl(url); - if (!gurl.is_valid()) - return PP_MakeUndefined(); - - std::string proxy_host = instance->delegate()->ResolveProxy(gurl); - if (proxy_host.empty()) - return PP_MakeUndefined(); // No proxy. - return StringVar::StringToPPVar(instance->module(), proxy_host); -} - -FilePath GetFilePathFromUTF8(const char* path) { -#if defined(OS_WIN) - return FilePath(UTF8ToUTF16(path)); -#else - return FilePath(path); -#endif -} - -int32_t OpenModuleLocalFile(PP_Module module, - const char* path, - int32_t mode, - PP_FileHandle* file) { - PluginInstance* instance = GetSomeInstance(module); - if (!instance) - return PP_ERROR_FAILED; - - int flags = 0; - if (mode & PP_FILEOPENFLAG_READ) - flags |= base::PLATFORM_FILE_READ; - if (mode & PP_FILEOPENFLAG_WRITE) { - flags |= base::PLATFORM_FILE_WRITE; - flags |= base::PLATFORM_FILE_WRITE_ATTRIBUTES; - } - if (mode & PP_FILEOPENFLAG_TRUNCATE) { - DCHECK(mode & PP_FILEOPENFLAG_WRITE); - flags |= base::PLATFORM_FILE_TRUNCATE; - } - - if (mode & PP_FILEOPENFLAG_CREATE) { - if (mode & PP_FILEOPENFLAG_EXCLUSIVE) - flags |= base::PLATFORM_FILE_CREATE; - else - flags |= base::PLATFORM_FILE_OPEN_ALWAYS; - } else { - flags |= base::PLATFORM_FILE_OPEN; - } - - base::PlatformFile base_file; - base::PlatformFileError result = instance->delegate()->OpenModuleLocalFile( - instance->module()->name(), - GetFilePathFromUTF8(path), - flags, - &base_file); - *file = base_file; - return PlatformFileErrorToPepperError(result); -} - - -int32_t RenameModuleLocalFile(PP_Module module, - const char* path_from, - const char* path_to) { - PluginInstance* instance = GetSomeInstance(module); - if (!instance) - return PP_ERROR_FAILED; - - base::PlatformFileError result = instance->delegate()->RenameModuleLocalFile( - instance->module()->name(), - GetFilePathFromUTF8(path_from), - GetFilePathFromUTF8(path_to)); - return PlatformFileErrorToPepperError(result); -} - -int32_t DeleteModuleLocalFileOrDir(PP_Module module, - const char* path, - bool recursive) { - PluginInstance* instance = GetSomeInstance(module); - if (!instance) - return PP_ERROR_FAILED; - - base::PlatformFileError result = - instance->delegate()->DeleteModuleLocalFileOrDir( - instance->module()->name(), GetFilePathFromUTF8(path), recursive); - return PlatformFileErrorToPepperError(result); -} - -int32_t CreateModuleLocalDir(PP_Module module, const char* path) { - PluginInstance* instance = GetSomeInstance(module); - if (!instance) - return PP_ERROR_FAILED; - - base::PlatformFileError result = instance->delegate()->CreateModuleLocalDir( - instance->module()->name(), GetFilePathFromUTF8(path)); - return PlatformFileErrorToPepperError(result); -} - -int32_t QueryModuleLocalFile(PP_Module module, - const char* path, - PP_FileInfo_Dev* info) { - PluginInstance* instance = GetSomeInstance(module); - if (!instance) - return PP_ERROR_FAILED; - - base::PlatformFileInfo file_info; - base::PlatformFileError result = instance->delegate()->QueryModuleLocalFile( - instance->module()->name(), GetFilePathFromUTF8(path), &file_info); - if (result == base::PLATFORM_FILE_OK) { - info->size = file_info.size; - info->creation_time = file_info.creation_time.ToDoubleT(); - info->last_access_time = file_info.last_accessed.ToDoubleT(); - info->last_modified_time = file_info.last_modified.ToDoubleT(); - info->system_type = PP_FILESYSTEMTYPE_EXTERNAL; - if (file_info.is_directory) - info->type = PP_FILETYPE_DIRECTORY; - else - info->type = PP_FILETYPE_REGULAR; - } - return PlatformFileErrorToPepperError(result); -} - -int32_t GetModuleLocalDirContents(PP_Module module, - const char* path, - PP_DirContents_Dev** contents) { - PluginInstance* instance = GetSomeInstance(module); - if (!instance) - return PP_ERROR_FAILED; - - *contents = NULL; - PepperDirContents pepper_contents; - base::PlatformFileError result = - instance->delegate()->GetModuleLocalDirContents( - instance->module()->name(), - GetFilePathFromUTF8(path), - &pepper_contents); - - if (result != base::PLATFORM_FILE_OK) - return PlatformFileErrorToPepperError(result); - - *contents = new PP_DirContents_Dev; - size_t count = pepper_contents.size(); - (*contents)->count = count; - (*contents)->entries = new PP_DirEntry_Dev[count]; - for (size_t i = 0; i < count; ++i) { - PP_DirEntry_Dev& entry = (*contents)->entries[i]; -#if defined(OS_WIN) - const std::string& name = UTF16ToUTF8(pepper_contents[i].name.value()); -#else - const std::string& name = pepper_contents[i].name.value(); -#endif - size_t size = name.size() + 1; - char* name_copy = new char[size]; - memcpy(name_copy, name.c_str(), size); - entry.name = name_copy; - entry.is_dir = pepper_contents[i].is_dir; - } - return PP_OK; -} - -void FreeModuleLocalDirContents(PP_Module module, - PP_DirContents_Dev* contents) { - DCHECK(contents); - for (int32_t i = 0; i < contents->count; ++i) { - delete [] contents->entries[i].name; - } - delete [] contents->entries; - delete contents; -} - -bool NavigateToURL(PP_Instance pp_instance, - const char* url, - const char* target) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(pp_instance); - if (!instance) - return false; - return instance->NavigateToURL(url, target); -} - -const PPB_Private2 ppb_private2 = { - &SetInstanceAlwaysOnTop, - &Private2::DrawGlyphs, - &GetProxyForURL, - &OpenModuleLocalFile, - &RenameModuleLocalFile, - &DeleteModuleLocalFileOrDir, - &CreateModuleLocalDir, - &QueryModuleLocalFile, - &GetModuleLocalDirContents, - &FreeModuleLocalDirContents, - &NavigateToURL, -}; - -} // namespace - -// static -const PPB_Private2* Private2::GetInterface() { - return &ppb_private2; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_private2.h b/webkit/glue/plugins/pepper_private2.h deleted file mode 100644 index 64a766f..0000000 --- a/webkit/glue/plugins/pepper_private2.h +++ /dev/null @@ -1,42 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_PRIVATE2_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_PRIVATE2_H_ - -#include "build/build_config.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_rect.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PP_FontDescription_Dev; -struct PPB_Private2; - -namespace pepper { - -class Private2 { - public: - // Returns a pointer to the interface implementing PPB_Private2 that is - // exposed to the plugin. - static const PPB_Private2* GetInterface(); - - static bool DrawGlyphs(PP_Resource pp_image_data, - const PP_FontDescription_Dev* font_desc, - uint32_t color, - PP_Point position, - PP_Rect clip, - float transformation[3][3], - uint32_t glyph_count, - uint16_t glyph_indices[], - PP_Point glyph_advances[]) -#if defined(OS_LINUX) - ; -#else - { return false; } -#endif -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_PRIVATE2_H_ diff --git a/webkit/glue/plugins/pepper_private2_linux.cc b/webkit/glue/plugins/pepper_private2_linux.cc deleted file mode 100644 index ed2c04a..0000000 --- a/webkit/glue/plugins/pepper_private2_linux.cc +++ /dev/null @@ -1,110 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_private2.h" - -#include "skia/ext/platform_canvas.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/dev/ppb_font_dev.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkMatrix.h" -#include "third_party/skia/include/core/SkPaint.h" -#include "third_party/skia/include/core/SkPoint.h" -#include "third_party/skia/include/core/SkTemplates.h" -#include "third_party/skia/include/core/SkTypeface.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_var.h" - -namespace pepper { - -bool Private2::DrawGlyphs(PP_Resource pp_image_data, - const PP_FontDescription_Dev* font_desc, - uint32_t color, - PP_Point position, - PP_Rect clip, - float transformation[3][3], - uint32_t glyph_count, - uint16_t glyph_indices[], - PP_Point glyph_advances[]) { - scoped_refptr<ImageData> image_resource( - Resource::GetAs<ImageData>(pp_image_data)); - if (!image_resource.get()) - return false; - ImageDataAutoMapper mapper(image_resource); - if (!mapper.is_valid()) - return false; - - // Set up the typeface. - scoped_refptr<StringVar> face_name(StringVar::FromPPVar(font_desc->face)); - if (!face_name) - return false; - int style = SkTypeface::kNormal; - if (font_desc->weight >= PP_FONTWEIGHT_BOLD) - style |= SkTypeface::kBold; - if (font_desc->italic) - style |= SkTypeface::kItalic; - SkTypeface* typeface = - SkTypeface::CreateFromName(face_name->value().c_str(), - static_cast<SkTypeface::Style>(style)); - if (!typeface) - return false; - - // Set up the canvas. - SkCanvas* canvas = image_resource->mapped_canvas(); - canvas->save(); - - // Clip is applied in pixels before the transform. - SkRect clip_rect = { clip.point.x, clip.point.y, - clip.point.x + clip.size.width, - clip.point.y + clip.size.height }; - canvas->clipRect(clip_rect); - - // -- Do not return early below this. The canvas needs restoring and the - // typeface will leak if it's not assigned to the paint (it's refcounted and - // the refcount is currently 0). - - // Convert & set the matrix. - SkMatrix matrix; - matrix.set(SkMatrix::kMScaleX, SkFloatToScalar(transformation[0][0])); - matrix.set(SkMatrix::kMSkewX, SkFloatToScalar(transformation[0][1])); - matrix.set(SkMatrix::kMTransX, SkFloatToScalar(transformation[0][2])); - matrix.set(SkMatrix::kMSkewY, SkFloatToScalar(transformation[1][0])); - matrix.set(SkMatrix::kMScaleY, SkFloatToScalar(transformation[1][1])); - matrix.set(SkMatrix::kMTransY, SkFloatToScalar(transformation[1][2])); - matrix.set(SkMatrix::kMPersp0, SkFloatToScalar(transformation[2][0])); - matrix.set(SkMatrix::kMPersp1, SkFloatToScalar(transformation[2][1])); - matrix.set(SkMatrix::kMPersp2, SkFloatToScalar(transformation[2][2])); - canvas->concat(matrix); - - SkPaint paint; - paint.setColor(color); - paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); - paint.setAntiAlias(true); - paint.setHinting(SkPaint::kFull_Hinting); - paint.setTextSize(SkIntToScalar(font_desc->size)); - paint.setTypeface(typeface); // Takes a ref and manages lifetime. - paint.setSubpixelText(true); - paint.setLCDRenderText(true); - - SkScalar x = SkIntToScalar(position.x); - SkScalar y = SkIntToScalar(position.y); - - // Build up the skia advances. - SkAutoSTMalloc<32, SkPoint> storage(glyph_count); - SkPoint* sk_positions = storage.get(); - for (uint32_t i = 0; i < glyph_count; i++) { - sk_positions[i].set(x, y); - x += SkFloatToScalar(glyph_advances[i].x); - y += SkFloatToScalar(glyph_advances[i].y); - } - - canvas->drawPosText(glyph_indices, glyph_count * 2, sk_positions, paint); - - canvas->restore(); - return true; -} - -} // namespace pepper - diff --git a/webkit/glue/plugins/pepper_resource.cc b/webkit/glue/plugins/pepper_resource.cc deleted file mode 100644 index 851d6e7..0000000 --- a/webkit/glue/plugins/pepper_resource.cc +++ /dev/null @@ -1,37 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_resource.h" - -#include "base/logging.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" - -namespace pepper { - -Resource::Resource(PluginModule* module) - : resource_id_(0), module_(module) { -} - -Resource::~Resource() { -} - -PP_Resource Resource::GetReference() { - ResourceTracker *tracker = ResourceTracker::Get(); - if (resource_id_) - tracker->AddRefResource(resource_id_); - else - resource_id_ = tracker->AddResource(this); - return resource_id_; -} - -PP_Resource Resource::GetReferenceNoAddRef() const { - return resource_id_; -} - -void Resource::StoppedTracking() { - DCHECK(resource_id_ != 0); - resource_id_ = 0; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_resource.h b/webkit/glue/plugins/pepper_resource.h deleted file mode 100644 index 3c4ebca..0000000 --- a/webkit/glue/plugins/pepper_resource.h +++ /dev/null @@ -1,140 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_RESOURCE_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_RESOURCE_H_ - -#include "base/basictypes.h" -#include "base/ref_counted.h" -#include "ppapi/c/pp_resource.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" - -namespace pepper { - -// If you inherit from resource, make sure you add the class name here. -#define FOR_ALL_RESOURCES(F) \ - F(Audio) \ - F(AudioConfig) \ - F(Buffer) \ - F(DirectoryReader) \ - F(FileChooser) \ - F(FileIO) \ - F(FileRef) \ - F(FileSystem) \ - F(Font) \ - F(Graphics2D) \ - F(Graphics3D) \ - F(ImageData) \ - F(ObjectVar) \ - F(PluginModule) \ - F(PrivateFontFile) \ - F(Scrollbar) \ - F(StringVar) \ - F(Transport) \ - F(URLLoader) \ - F(URLRequestInfo) \ - F(URLResponseInfo) \ - F(Var) \ - F(VarObjectClass) \ - F(VideoDecoder) \ - F(Widget) - -// Forward declaration of Resource classes. -#define DECLARE_RESOURCE_CLASS(RESOURCE) class RESOURCE; -FOR_ALL_RESOURCES(DECLARE_RESOURCE_CLASS) -#undef DECLARE_RESOURCE_CLASS - -class Resource : public base::RefCountedThreadSafe<Resource> { - public: - explicit Resource(PluginModule* module); - virtual ~Resource(); - - // Returns NULL if the resource is invalid or is a different type. - template<typename T> - static scoped_refptr<T> GetAs(PP_Resource res) { - scoped_refptr<Resource> resource = ResourceTracker::Get()->GetResource(res); - return resource ? resource->Cast<T>() : NULL; - } - - PluginModule* module() const { return module_; } - - // Cast the resource into a specified type. This will return NULL if the - // resource does not match the specified type. Specializations of this - // template call into As* functions. - template <typename T> T* Cast() { return NULL; } - - // Returns an resource id of this object. If the object doesn't have a - // resource id, new one is created with plugin refcount of 1. If it does, - // the refcount is incremented. Use this when you need to return a new - // reference to the plugin. - PP_Resource GetReference(); - - // Returns the resource ID of this object OR NULL IF THERE IS NONE ASSIGNED. - // This will happen if the plugin doesn't have a reference to the given - // resource. The resource will not be addref'ed. - // - // This should only be used as an input parameter to the plugin for status - // updates in the proxy layer, where if the plugin has no reference, it will - // just give up since nothing needs to be updated. - // - // Generally you should use GetReference instead. This is why it has this - // obscure name rather than pp_resource(). - PP_Resource GetReferenceNoAddRef() const; - - // When you need to ensure that a resource has a reference, but you do not - // want to increase the refcount (for example, if you need to call a plugin - // callback function with a reference), you can use this class. For example: - // - // plugin_callback(.., ScopedResourceId(resource).id, ...); - class ScopedResourceId { - public: - explicit ScopedResourceId(Resource* resource) - : id(resource->GetReference()) {} - ~ScopedResourceId() { - ResourceTracker::Get()->UnrefResource(id); - } - const PP_Resource id; - }; - - private: - // Type-specific getters for individual resource types. These will return - // NULL if the resource does not match the specified type. Used by the Cast() - // function. - #define DEFINE_TYPE_GETTER(RESOURCE) \ - virtual RESOURCE* As##RESOURCE() { return NULL; } - FOR_ALL_RESOURCES(DEFINE_TYPE_GETTER) - #undef DEFINE_TYPE_GETTER - - // If referenced by a plugin, holds the id of this resource object. Do not - // access this member directly, because it is possible that the plugin holds - // no references to the object, and therefore the resource_id_ is zero. Use - // either GetReference() to obtain a new resource_id and increase the - // refcount, or TemporaryReference when you do not want to increase the - // refcount. - PP_Resource resource_id_; - - // Non-owning pointer to our module. - PluginModule* module_; - - // Called by the resource tracker when the last plugin reference has been - // dropped. - friend class ResourceTracker; - void StoppedTracking(); - - DISALLOW_COPY_AND_ASSIGN(Resource); -}; - -// Cast() specializations. -#define DEFINE_RESOURCE_CAST(Type) \ - template <> inline Type* Resource::Cast<Type>() { \ - return As##Type(); \ - } - -FOR_ALL_RESOURCES(DEFINE_RESOURCE_CAST) -#undef DEFINE_RESOURCE_CAST - -#undef FOR_ALL_RESOURCES -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_RESOURCE_H_ diff --git a/webkit/glue/plugins/pepper_resource_tracker.cc b/webkit/glue/plugins/pepper_resource_tracker.cc deleted file mode 100644 index ba6f8f0..0000000 --- a/webkit/glue/plugins/pepper_resource_tracker.cc +++ /dev/null @@ -1,167 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_resource_tracker.h" - -#include <limits> -#include <set> - -#include "base/logging.h" -#include "base/rand_util.h" -#include "ppapi/c/pp_resource.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace pepper { - -scoped_refptr<Resource> ResourceTracker::GetResource(PP_Resource res) const { - ResourceMap::const_iterator result = live_resources_.find(res); - if (result == live_resources_.end()) { - return scoped_refptr<Resource>(); - } - return result->second.first; -} - -ResourceTracker::ResourceTracker() - : last_id_(0) { -} - -ResourceTracker::~ResourceTracker() { -} - -PP_Resource ResourceTracker::AddResource(Resource* resource) { - // If the plugin manages to create 4B resources... - if (last_id_ == std::numeric_limits<PP_Resource>::max()) { - return 0; - } - // Add the resource with plugin use-count 1. - ++last_id_; - live_resources_.insert(std::make_pair(last_id_, std::make_pair(resource, 1))); - return last_id_; -} - -bool ResourceTracker::AddRefResource(PP_Resource res) { - ResourceMap::iterator i = live_resources_.find(res); - if (i != live_resources_.end()) { - // We don't protect against overflow, since a plugin as malicious as to ref - // once per every byte in the address space could have just as well unrefed - // one time too many. - ++i->second.second; - return true; - } else { - return false; - } -} - -bool ResourceTracker::UnrefResource(PP_Resource res) { - ResourceMap::iterator i = live_resources_.find(res); - if (i != live_resources_.end()) { - if (!--i->second.second) { - i->second.first->StoppedTracking(); - live_resources_.erase(i); - } - return true; - } else { - return false; - } -} - -void ResourceTracker::ForceDeletePluginResourceRefs(PP_Resource res) { - ResourceMap::iterator i = live_resources_.find(res); - if (i != live_resources_.end()) - return; // Nothing to do. - - i->second.second = 0; - i->second.first->StoppedTracking(); - live_resources_.erase(i); -} - -uint32 ResourceTracker::GetLiveObjectsForModule(PluginModule* module) const { - // Since this is for testing only, we'll just go through all of them and - // count. - // - // TODO(brettw) we will eventually need to implement more efficient - // module->resource lookup to free resources when a module is unloaded. In - // this case, this function can be implemented using that system. - uint32 count = 0; - for (ResourceMap::const_iterator i = live_resources_.begin(); - i != live_resources_.end(); ++i) - count++; - return count; -} - -PP_Instance ResourceTracker::AddInstance(PluginInstance* instance) { -#ifndef NDEBUG - // Make sure we're not adding one more than once. - for (InstanceMap::const_iterator i = instance_map_.begin(); - i != instance_map_.end(); ++i) - DCHECK(i->second != instance); -#endif - - // Use a random 64-bit number for the instance ID. This helps prevent some - // mischeif where you could misallocate resources if you gave a different - // instance ID. - // - // See also AddModule below. - // - // Need to make sure the random number isn't a duplicate or 0. - PP_Instance new_instance; - do { - new_instance = static_cast<PP_Instance>(base::RandUint64()); - } while (!new_instance || - instance_map_.find(new_instance) != instance_map_.end()); - instance_map_[new_instance] = instance; - return new_instance; -} - -void ResourceTracker::InstanceDeleted(PP_Instance instance) { - InstanceMap::iterator found = instance_map_.find(instance); - if (found == instance_map_.end()) { - NOTREACHED(); - return; - } - instance_map_.erase(found); -} - -PluginInstance* ResourceTracker::GetInstance(PP_Instance instance) { - InstanceMap::iterator found = instance_map_.find(instance); - if (found == instance_map_.end()) - return NULL; - return found->second; -} - -PP_Module ResourceTracker::AddModule(PluginModule* module) { -#ifndef NDEBUG - // Make sure we're not adding one more than once. - for (ModuleMap::const_iterator i = module_map_.begin(); - i != module_map_.end(); ++i) - DCHECK(i->second != module); -#endif - - // See AddInstance above. - PP_Module new_module; - do { - new_module = static_cast<PP_Module>(base::RandUint64()); - } while (!new_module || - module_map_.find(new_module) != module_map_.end()); - module_map_[new_module] = module; - return new_module; -} - -void ResourceTracker::ModuleDeleted(PP_Module module) { - ModuleMap::iterator found = module_map_.find(module); - if (found == module_map_.end()) { - NOTREACHED(); - return; - } - module_map_.erase(found); -} - -PluginModule* ResourceTracker::GetModule(PP_Module module) { - ModuleMap::iterator found = module_map_.find(module); - if (found == module_map_.end()) - return NULL; - return found->second; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_resource_tracker.h b/webkit/glue/plugins/pepper_resource_tracker.h deleted file mode 100644 index ad25d1a..0000000 --- a/webkit/glue/plugins/pepper_resource_tracker.h +++ /dev/null @@ -1,134 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_RESOURCE_TRACKER_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_RESOURCE_TRACKER_H_ - -#include <map> -#include <utility> - -#include "base/basictypes.h" -#include "base/hash_tables.h" -#include "base/ref_counted.h" -#include "base/singleton.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_resource.h" - -namespace pepper { - -class PluginInstance; -class PluginModule; -class Resource; - -// This class maintains a global list of all live pepper resources. It allows -// us to check resource ID validity and to map them to a specific module. -// -// This object is threadsafe. -class ResourceTracker { - public: - // Returns the pointer to the singleton object. - static ResourceTracker* Get() { - return Singleton<ResourceTracker>::get(); - } - - // PP_Resources -------------------------------------------------------------- - - // The returned pointer will be NULL if there is no resource. Note that this - // return value is a scoped_refptr so that we ensure the resource is valid - // from the point of the lookup to the point that the calling code needs it. - // Otherwise, the plugin could Release() the resource on another thread and - // the object will get deleted out from under us. - scoped_refptr<Resource> GetResource(PP_Resource res) const; - - // Increment resource's plugin refcount. See ResourceAndRefCount comments - // below. - bool AddRefResource(PP_Resource res); - bool UnrefResource(PP_Resource res); - - // Forces the plugin refcount of the given resource to 0. This can be used to - // delete an object the plugin has leaked or whose lifetime is otherwise - // exceeded. - // - // Note that this may not necessarily delete the resource object since the - // regular refcount is maintained separately from the plugin refcount and - // random components in the Pepper implementation could still have - // references to it. - void ForceDeletePluginResourceRefs(PP_Resource res); - - // Returns the number of resources associated with this module. - // - // This is slow, use only for testing. - uint32 GetLiveObjectsForModule(PluginModule* module) const; - - // PP_Modules ---------------------------------------------------------------- - - // Adds a new plugin module to the list of tracked module, and returns a new - // module handle to identify it. - PP_Module AddModule(PluginModule* module); - - // Called when a plugin modulde was deleted and should no longer be tracked. - // The given handle should be one generated by AddModule. - void ModuleDeleted(PP_Module module); - - // Returns a pointer to the plugin modulde object associated with the given - // modulde handle. The return value will be NULL if the handle is invalid. - PluginModule* GetModule(PP_Module module); - - // PP_Instances -------------------------------------------------------------- - - // Adds a new plugin instance to the list of tracked instances, and returns a - // new instance handle to identify it. - PP_Instance AddInstance(PluginInstance* instance); - - // Called when a plugin instance was deleted and should no longer be tracked. - // The given handle should be one generated by AddInstance. - void InstanceDeleted(PP_Instance instance); - - // Returns a pointer to the plugin instance object associated with the given - // instance handle. The return value will be NULL if the handle is invalid. - PluginInstance* GetInstance(PP_Instance instance); - - private: - friend struct DefaultSingletonTraits<ResourceTracker>; - friend class Resource; - - // Prohibit creation other then by the Singleton class. - ResourceTracker(); - ~ResourceTracker(); - - // Adds the given resource to the tracker and assigns it a resource ID and - // refcount of 1. The assigned resource ID will be returned. Used only by the - // Resource class. - PP_Resource AddResource(Resource* resource); - - // Last assigned resource ID. - PP_Resource last_id_; - - // For each PP_Resource, keep the Resource* (as refptr) and plugin use count. - // This use count is different then Resource's RefCount, and is manipulated - // using this RefResource/UnrefResource. When it drops to zero, we just remove - // the resource from this resource tracker, but the resource object will be - // alive so long as some scoped_refptr still holds it's reference. This - // prevents plugins from forcing destruction of Resource objects. - typedef std::pair<scoped_refptr<Resource>, size_t> ResourceAndRefCount; - typedef base::hash_map<PP_Resource, ResourceAndRefCount> ResourceMap; - ResourceMap live_resources_; - - // Tracks all live instances. The pointers are non-owning, the PluginInstance - // destructor will notify us when the instance is deleted. - typedef std::map<PP_Instance, PluginInstance*> InstanceMap; - InstanceMap instance_map_; - - // Tracks all live modules. The pointers are non-owning, the PluginModule - // destructor will notify us when the module is deleted. - typedef std::map<PP_Module, PluginModule*> ModuleMap; - ModuleMap module_map_; - - DISALLOW_COPY_AND_ASSIGN(ResourceTracker); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_RESOURCE_TRACKER_H_ diff --git a/webkit/glue/plugins/pepper_scrollbar.cc b/webkit/glue/plugins/pepper_scrollbar.cc deleted file mode 100644 index 2b96259..0000000 --- a/webkit/glue/plugins/pepper_scrollbar.cc +++ /dev/null @@ -1,242 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_scrollbar.h" - -#include "base/logging.h" -#include "base/message_loop.h" -#include "ppapi/c/dev/ppp_scrollbar_dev.h" -#include "skia/ext/platform_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebScrollbar.h" -#include "third_party/WebKit/WebKit/chromium/public/WebVector.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_event_conversion.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/webkit_glue.h" - -#if defined(OS_WIN) -#include "base/win/windows_version.h" -#endif - -using WebKit::WebInputEvent; -using WebKit::WebRect; -using WebKit::WebScrollbar; - -namespace pepper { - -namespace { - -PP_Resource Create(PP_Instance instance_id, PP_Bool vertical) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return 0; - - scoped_refptr<Scrollbar> scrollbar(new Scrollbar(instance, - PPBoolToBool(vertical))); - return scrollbar->GetReference(); -} - -PP_Bool IsScrollbar(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<Scrollbar>(resource)); -} - -uint32_t GetThickness() { - return WebScrollbar::defaultThickness(); -} - -uint32_t GetValue(PP_Resource resource) { - scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource)); - if (!scrollbar) - return 0; - return scrollbar->GetValue(); -} - -void SetValue(PP_Resource resource, uint32_t value) { - scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource)); - if (scrollbar) - scrollbar->SetValue(value); -} - -void SetDocumentSize(PP_Resource resource, uint32_t size) { - scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource)); - if (scrollbar) - scrollbar->SetDocumentSize(size); -} - -void SetTickMarks(PP_Resource resource, - const PP_Rect* tick_marks, - uint32_t count) { - scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource)); - if (scrollbar) - scrollbar->SetTickMarks(tick_marks, count); -} - -void ScrollBy(PP_Resource resource, PP_ScrollBy_Dev unit, int32_t multiplier) { - scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource)); - if (scrollbar) - scrollbar->ScrollBy(unit, multiplier); -} - -const PPB_Scrollbar_Dev ppb_scrollbar = { - &Create, - &IsScrollbar, - &GetThickness, - &GetValue, - &SetValue, - &SetDocumentSize, - &SetTickMarks, - &ScrollBy -}; - -} // namespace - -Scrollbar::Scrollbar(PluginInstance* instance, bool vertical) - : Widget(instance) { - scrollbar_.reset(WebScrollbar::create( - static_cast<WebKit::WebScrollbarClient*>(this), - vertical ? WebScrollbar::Vertical : WebScrollbar::Horizontal)); -} - -Scrollbar::~Scrollbar() { -} - -// static -const PPB_Scrollbar_Dev* Scrollbar::GetInterface() { - return &ppb_scrollbar; -} - -uint32_t Scrollbar::GetValue() { - return scrollbar_->value(); -} - -void Scrollbar::SetValue(uint32_t value) { - scrollbar_->setValue(value); -} - -void Scrollbar::SetDocumentSize(uint32_t size) { - scrollbar_->setDocumentSize(size); -} - -void Scrollbar::SetTickMarks(const PP_Rect* tick_marks, uint32_t count) { - tickmarks_.resize(count); - for (uint32 i = 0; i < count; ++i) { - tickmarks_[i] = WebRect(tick_marks[i].point.x, - tick_marks[i].point.y, - tick_marks[i].size.width, - tick_marks[i].size.height);; - } - PP_Rect rect = location(); - Invalidate(&rect); -} - -void Scrollbar::ScrollBy(PP_ScrollBy_Dev unit, int32_t multiplier) { - WebScrollbar::ScrollDirection direction = multiplier >= 0 ? - WebScrollbar::ScrollForward : WebScrollbar::ScrollBackward; - float fmultiplier = 1.0; - - WebScrollbar::ScrollGranularity granularity; - if (unit == PP_SCROLLBY_LINE) { - granularity = WebScrollbar::ScrollByLine; - } else if (unit == PP_SCROLLBY_PAGE) { - granularity = WebScrollbar::ScrollByPage; - } else if (unit == PP_SCROLLBY_DOCUMENT) { - granularity = WebScrollbar::ScrollByDocument; - } else { - granularity = WebScrollbar::ScrollByPixel; - fmultiplier = static_cast<float>(multiplier); - if (fmultiplier < 0) - fmultiplier *= -1; - } - scrollbar_->scroll(direction, granularity, fmultiplier); -} - -bool Scrollbar::Paint(const PP_Rect* rect, ImageData* image) { - gfx::Rect gfx_rect(rect->point.x, - rect->point.y, - rect->size.width, - rect->size.height); - skia::PlatformCanvas* canvas = image->mapped_canvas(); - if (!canvas) - return false; - scrollbar_->paint(webkit_glue::ToWebCanvas(canvas), gfx_rect); - -#if defined(OS_WIN) - if (base::win::GetVersion() == base::win::VERSION_XP) { - canvas->getTopPlatformDevice().makeOpaque( - gfx_rect.x(), gfx_rect.y(), gfx_rect.width(), gfx_rect.height()); - } -#endif - - return true; -} - -bool Scrollbar::HandleEvent(const PP_InputEvent* event) { - scoped_ptr<WebInputEvent> web_input_event(CreateWebInputEvent(*event)); - if (!web_input_event.get()) - return false; - - return scrollbar_->handleInputEvent(*web_input_event.get()); -} - -void Scrollbar::SetLocationInternal(const PP_Rect* location) { - scrollbar_->setLocation(WebRect(location->point.x, - location->point.y, - location->size.width, - location->size.height)); -} - -void Scrollbar::valueChanged(WebKit::WebScrollbar* scrollbar) { - const PPP_Scrollbar_Dev* ppp_scrollbar = - static_cast<const PPP_Scrollbar_Dev*>( - module()->GetPluginInterface(PPP_SCROLLBAR_DEV_INTERFACE)); - if (!ppp_scrollbar) - return; - ScopedResourceId resource(this); - ppp_scrollbar->ValueChanged( - instance()->pp_instance(), resource.id, scrollbar_->value()); -} - -void Scrollbar::invalidateScrollbarRect(WebKit::WebScrollbar* scrollbar, - const WebKit::WebRect& rect) { - gfx::Rect gfx_rect(rect.x, - rect.y, - rect.width, - rect.height); - dirty_ = dirty_.Union(gfx_rect); - // Can't call into the client to tell them about the invalidate right away, - // since the Scrollbar code is still in the middle of updating its internal - // state. - MessageLoop::current()->PostTask( - FROM_HERE, - NewRunnableMethod(this, &Scrollbar::NotifyInvalidate)); -} - -void Scrollbar::getTickmarks( - WebKit::WebScrollbar* scrollbar, - WebKit::WebVector<WebKit::WebRect>* tick_marks) const { - if (tickmarks_.empty()) { - WebRect* rects = NULL; - tick_marks->assign(rects, 0); - } else { - tick_marks->assign(&tickmarks_[0], tickmarks_.size()); - } -} - -void Scrollbar::NotifyInvalidate() { - if (dirty_.IsEmpty()) - return; - PP_Rect pp_rect; - pp_rect.point.x = dirty_.x(); - pp_rect.point.y = dirty_.y(); - pp_rect.size.width = dirty_.width(); - pp_rect.size.height = dirty_.height(); - dirty_ = gfx::Rect(); - Invalidate(&pp_rect); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_scrollbar.h b/webkit/glue/plugins/pepper_scrollbar.h deleted file mode 100644 index c444bb3..0000000 --- a/webkit/glue/plugins/pepper_scrollbar.h +++ /dev/null @@ -1,62 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_SCROLLBAR_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_SCROLLBAR_H_ - -#include <vector> - -#include "gfx/rect.h" -#include "ppapi/c/dev/ppb_scrollbar_dev.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebScrollbarClient.h" -#include "webkit/glue/plugins/pepper_widget.h" - -namespace pepper { - -class PluginInstance; - -class Scrollbar : public Widget, public WebKit::WebScrollbarClient { - public: - Scrollbar(PluginInstance* instance, bool vertical); - virtual ~Scrollbar(); - - // Returns a pointer to the interface implementing PPB_Scrollbar that is - // exposed to the plugin. - static const PPB_Scrollbar_Dev* GetInterface(); - - // Resource overrides. - Scrollbar* AsScrollbar() { return this; } - - // PPB_Scrollbar implementation. - uint32_t GetValue(); - void SetValue(uint32_t value); - void SetDocumentSize(uint32_t size); - void SetTickMarks(const PP_Rect* tick_marks, uint32_t count); - void ScrollBy(PP_ScrollBy_Dev unit, int32_t multiplier); - - // PPB_Widget implementation. - virtual bool Paint(const PP_Rect* rect, ImageData* image); - virtual bool HandleEvent(const PP_InputEvent* event); - virtual void SetLocationInternal(const PP_Rect* location); - - private: - // WebKit::WebScrollbarClient implementation. - virtual void valueChanged(WebKit::WebScrollbar* scrollbar); - virtual void invalidateScrollbarRect(WebKit::WebScrollbar* scrollbar, - const WebKit::WebRect& rect); - virtual void getTickmarks( - WebKit::WebScrollbar* scrollbar, - WebKit::WebVector<WebKit::WebRect>* tick_marks) const; - - void NotifyInvalidate(); - - gfx::Rect dirty_; - std::vector<WebKit::WebRect> tickmarks_; - scoped_ptr<WebKit::WebScrollbar> scrollbar_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_SCROLLBAR_H_ diff --git a/webkit/glue/plugins/pepper_string.cc b/webkit/glue/plugins/pepper_string.cc deleted file mode 100644 index 53c8943..0000000 --- a/webkit/glue/plugins/pepper_string.cc +++ /dev/null @@ -1,13 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_string.h" - -namespace pepper { - -String::String(const char* str, uint32 len) : value_(str, len) {} - -String::~String() {} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_string.h b/webkit/glue/plugins/pepper_string.h deleted file mode 100644 index fa1ab2f..0000000 --- a/webkit/glue/plugins/pepper_string.h +++ /dev/null @@ -1,30 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_STRING_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_STRING_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/ref_counted.h" - -namespace pepper { - -class String : public base::RefCountedThreadSafe<String> { - public: - String(const char* str, uint32 len); - virtual ~String(); - - const std::string& value() const { return value_; } - - private: - std::string value_; - - DISALLOW_COPY_AND_ASSIGN(String); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_STRING_H_ diff --git a/webkit/glue/plugins/pepper_transport.cc b/webkit/glue/plugins/pepper_transport.cc deleted file mode 100644 index 29a4495..0000000 --- a/webkit/glue/plugins/pepper_transport.cc +++ /dev/null @@ -1,140 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_transport.h" - -#include "base/singleton.h" -#include "base/thread_local.h" -#include "ppapi/c/dev/ppb_transport_dev.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" - -namespace pepper { - -namespace { - -// Creates a new transport object with the specified name -// using the specified protocol. -PP_Resource CreateTransport(PP_Module module, - const char* name, - const char* proto) { - // TODO(juberti): implement me - PP_Resource p(0); - return p; -} - -// Returns whether or not resource is Transport -PP_Bool IsTransport(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<Transport>(resource)); -} - -// Returns whether the transport is currently writable -// (i.e. can send data to the remote peer) -PP_Bool IsWritable(PP_Resource transport) { - // TODO(juberti): impelement me - return PP_FALSE; -} - - -// TODO(juberti): other getters/setters -// connect state -// connect type, protocol -// RTT - - -// Establishes a connection to the remote peer. -// Returns PP_ERROR_WOULDBLOCK and notifies on |cb| -// when connectivity is established (or timeout occurs). -int32_t Connect(PP_Resource transport, - PP_CompletionCallback cb) { - // TODO(juberti): impelement me - return 0; -} - - -// Obtains another ICE candidate address to be provided -// to the remote peer. Returns PP_ERROR_WOULDBLOCK -// if there are no more addresses to be sent. -int32_t GetNextAddress(PP_Resource transport, - PP_Var* address, - PP_CompletionCallback cb) { - // TODO(juberti): implement me - return 0; -} - - -// Provides an ICE candidate address that was received -// from the remote peer. -int32_t ReceiveRemoteAddress(PP_Resource transport, - PP_Var address) { - // TODO(juberti): implement me - return 0; -} - - -// Like recv(), receives data. Returns PP_ERROR_WOULDBLOCK -// if there is currently no data to receive. -int32_t Recv(PP_Resource transport, - void* data, - uint32_t len, - PP_CompletionCallback cb) { - // TODO(juberti): implement me - return 0; -} - - -// Like send(), sends data. Returns PP_ERROR_WOULDBLOCK -// if the socket is currently flow-controlled. -int32_t Send(PP_Resource transport, - const void* data, - uint32_t len, - PP_CompletionCallback cb) { - // TODO(juberti): implement me - return 0; -} - - -// Disconnects from the remote peer. -int32_t Close(PP_Resource transport) { - // TODO(juberti): implement me - return 0; -} - - -const PPB_Transport_Dev ppb_transport = { - &CreateTransport, - &IsTransport, - &IsWritable, - &Connect, - &GetNextAddress, - &ReceiveRemoteAddress, - &Recv, - &Send, - &Close, -}; - -} // namespace - -Transport::Transport(PluginModule* module) - : Resource(module) { - // TODO(juberti): impl -} - -const PPB_Transport_Dev* Transport::GetInterface() { - return &ppb_transport; -} - -Transport::~Transport() { - // TODO(juberti): teardown -} - -bool Transport::Init(const char* name, - const char* proto) { - // TODO(juberti): impl - return false; -} - -} // namespace pepper - diff --git a/webkit/glue/plugins/pepper_transport.h b/webkit/glue/plugins/pepper_transport.h deleted file mode 100644 index fbba691..0000000 --- a/webkit/glue/plugins/pepper_transport.h +++ /dev/null @@ -1,35 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_TRANSPORT_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_TRANSPORT_H_ - -#include "base/scoped_ptr.h" -#include "ppapi/c/pp_instance.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PPB_Transport_Dev; - -namespace pepper { - -class Transport : public Resource { - public: - explicit Transport(PluginModule* module); - virtual ~Transport(); - static const PPB_Transport_Dev* GetInterface(); - virtual Transport* AsTransport() { - return this; - } - bool Init(const char* name, - const char* proto); - private: - - DISALLOW_COPY_AND_ASSIGN(Transport); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_TRANSPORT_H_ - diff --git a/webkit/glue/plugins/pepper_url_loader.cc b/webkit/glue/plugins/pepper_url_loader.cc deleted file mode 100644 index 2d94172..0000000 --- a/webkit/glue/plugins/pepper_url_loader.cc +++ /dev/null @@ -1,532 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_url_loader.h" - -#include "base/logging.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_url_loader.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebElement.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKitClient.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginContainer.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSecurityOrigin.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLLoader.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" -#include "webkit/appcache/web_application_cache_host_impl.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_url_request_info.h" -#include "webkit/glue/plugins/pepper_url_response_info.h" - -using appcache::WebApplicationCacheHostImpl; -using WebKit::WebFrame; -using WebKit::WebString; -using WebKit::WebURL; -using WebKit::WebURLError; -using WebKit::WebURLLoader; -using WebKit::WebURLRequest; -using WebKit::WebURLResponse; - -#ifdef _MSC_VER -// Do not warn about use of std::copy with raw pointers. -#pragma warning(disable : 4996) -#endif - -namespace pepper { - -namespace { - -PP_Resource Create(PP_Instance instance_id) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return 0; - - URLLoader* loader = new URLLoader(instance, false); - return loader->GetReference(); -} - -PP_Bool IsURLLoader(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<URLLoader>(resource)); -} - -int32_t Open(PP_Resource loader_id, - PP_Resource request_id, - PP_CompletionCallback callback) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return PP_ERROR_BADRESOURCE; - - scoped_refptr<URLRequestInfo> request( - Resource::GetAs<URLRequestInfo>(request_id)); - if (!request) - return PP_ERROR_BADRESOURCE; - - return loader->Open(request, callback); -} - -int32_t FollowRedirect(PP_Resource loader_id, - PP_CompletionCallback callback) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return PP_ERROR_BADRESOURCE; - - return loader->FollowRedirect(callback); -} - -PP_Bool GetUploadProgress(PP_Resource loader_id, - int64_t* bytes_sent, - int64_t* total_bytes_to_be_sent) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return PP_FALSE; - - return BoolToPPBool(loader->GetUploadProgress(bytes_sent, - total_bytes_to_be_sent)); -} - -PP_Bool GetDownloadProgress(PP_Resource loader_id, - int64_t* bytes_received, - int64_t* total_bytes_to_be_received) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return PP_FALSE; - - return BoolToPPBool(loader->GetDownloadProgress(bytes_received, - total_bytes_to_be_received)); -} - -PP_Resource GetResponseInfo(PP_Resource loader_id) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return 0; - - URLResponseInfo* response_info = loader->response_info(); - if (!response_info) - return 0; - - return response_info->GetReference(); -} - -int32_t ReadResponseBody(PP_Resource loader_id, - char* buffer, - int32_t bytes_to_read, - PP_CompletionCallback callback) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return PP_ERROR_BADRESOURCE; - - return loader->ReadResponseBody(buffer, bytes_to_read, callback); -} - -int32_t FinishStreamingToFile(PP_Resource loader_id, - PP_CompletionCallback callback) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return PP_ERROR_BADRESOURCE; - - return loader->FinishStreamingToFile(callback); -} - -void Close(PP_Resource loader_id) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return; - - loader->Close(); -} - -const PPB_URLLoader ppb_urlloader = { - &Create, - &IsURLLoader, - &Open, - &FollowRedirect, - &GetUploadProgress, - &GetDownloadProgress, - &GetResponseInfo, - &ReadResponseBody, - &FinishStreamingToFile, - &Close -}; - -void GrantUniversalAccess(PP_Resource loader_id) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return; - - loader->GrantUniversalAccess(); -} - -void SetStatusCallback(PP_Resource loader_id, - PP_URLLoaderTrusted_StatusCallback cb) { - scoped_refptr<URLLoader> loader(Resource::GetAs<URLLoader>(loader_id)); - if (!loader) - return; - loader->SetStatusCallback(cb); -} - -const PPB_URLLoaderTrusted ppb_urlloadertrusted = { - &GrantUniversalAccess, - &SetStatusCallback -}; - -WebKit::WebFrame* GetFrame(PluginInstance* instance) { - return instance->container()->element().document().frame(); -} - -} // namespace - -URLLoader::URLLoader(PluginInstance* instance, bool main_document_loader) - : Resource(instance->module()), - instance_(instance), - main_document_loader_(main_document_loader), - pending_callback_(), - bytes_sent_(0), - total_bytes_to_be_sent_(-1), - bytes_received_(0), - total_bytes_to_be_received_(-1), - user_buffer_(NULL), - user_buffer_size_(0), - done_status_(PP_ERROR_WOULDBLOCK), - has_universal_access_(false), - status_callback_(NULL) { - instance->AddObserver(this); -} - -URLLoader::~URLLoader() { - if (instance_) - instance_->RemoveObserver(this); -} - -// static -const PPB_URLLoader* URLLoader::GetInterface() { - return &ppb_urlloader; -} - -// static -const PPB_URLLoaderTrusted* URLLoader::GetTrustedInterface() { - return &ppb_urlloadertrusted; -} - -int32_t URLLoader::Open(URLRequestInfo* request, - PP_CompletionCallback callback) { - if (loader_.get()) - return PP_ERROR_INPROGRESS; - - // We only support non-blocking calls. - if (!callback.func) - return PP_ERROR_BADARGUMENT; - - WebFrame* frame = GetFrame(instance_); - if (!frame) - return PP_ERROR_FAILED; - WebURLRequest web_request(request->ToWebURLRequest(frame)); - - int32_t rv = CanRequest(frame, web_request.url()); - if (rv != PP_OK) - return rv; - - frame->dispatchWillSendRequest(web_request); - - // Sets the appcache host id to allow retrieval from the appcache. - if (WebApplicationCacheHostImpl* appcache_host = - WebApplicationCacheHostImpl::FromFrame(frame)) { - appcache_host->willStartSubResourceRequest(web_request); - } - - loader_.reset(WebKit::webKitClient()->createURLLoader()); - if (!loader_.get()) - return PP_ERROR_FAILED; - - loader_->loadAsynchronously(web_request, this); - - request_info_ = scoped_refptr<URLRequestInfo>(request); - pending_callback_ = callback; - - // Notify completion when we receive a redirect or response headers. - return PP_ERROR_WOULDBLOCK; -} - -int32_t URLLoader::FollowRedirect(PP_CompletionCallback callback) { - if (pending_callback_.func) - return PP_ERROR_INPROGRESS; - - // We only support non-blocking calls. - if (!callback.func) - return PP_ERROR_BADARGUMENT; - - WebURL redirect_url = GURL(response_info_->redirect_url()); - - int32_t rv = CanRequest(GetFrame(instance_), redirect_url); - if (rv != PP_OK) - return rv; - - pending_callback_ = callback; - loader_->setDefersLoading(false); // Allow the redirect to continue. - return PP_ERROR_WOULDBLOCK; -} - -bool URLLoader::GetUploadProgress(int64_t* bytes_sent, - int64_t* total_bytes_to_be_sent) { - if (!RecordUploadProgress()) { - *bytes_sent = 0; - *total_bytes_to_be_sent = 0; - return false; - } - *bytes_sent = bytes_sent_; - *total_bytes_to_be_sent = total_bytes_to_be_sent_; - return true; -} - -bool URLLoader::GetDownloadProgress(int64_t* bytes_received, - int64_t* total_bytes_to_be_received) { - if (!RecordDownloadProgress()) { - *bytes_received = 0; - *total_bytes_to_be_received = 0; - return false; - } - *bytes_received = bytes_received_; - *total_bytes_to_be_received = total_bytes_to_be_received_; - return true; -} - -int32_t URLLoader::ReadResponseBody(char* buffer, int32_t bytes_to_read, - PP_CompletionCallback callback) { - if (!response_info_ || response_info_->body()) - return PP_ERROR_FAILED; - if (bytes_to_read <= 0 || !buffer) - return PP_ERROR_BADARGUMENT; - if (pending_callback_.func) - return PP_ERROR_INPROGRESS; - - // We only support non-blocking calls. - if (!callback.func) - return PP_ERROR_BADARGUMENT; - - user_buffer_ = buffer; - user_buffer_size_ = bytes_to_read; - - if (!buffer_.empty()) - return FillUserBuffer(); - - // We may have already reached EOF. - if (done_status_ != PP_ERROR_WOULDBLOCK) { - user_buffer_ = NULL; - user_buffer_size_ = 0; - return done_status_; - } - - pending_callback_ = callback; - return PP_ERROR_WOULDBLOCK; -} - -int32_t URLLoader::FinishStreamingToFile(PP_CompletionCallback callback) { - if (!response_info_ || !response_info_->body()) - return PP_ERROR_FAILED; - if (pending_callback_.func) - return PP_ERROR_INPROGRESS; - - // We may have already reached EOF. - if (done_status_ != PP_ERROR_WOULDBLOCK) - return done_status_; - - // Wait for didFinishLoading / didFail. - pending_callback_ = callback; - return PP_ERROR_WOULDBLOCK; -} - -void URLLoader::Close() { - if (loader_.get()) { - loader_->cancel(); - } else if (main_document_loader_) { - WebFrame* frame = instance_->container()->element().document().frame(); - frame->stopLoading(); - } -} - -void URLLoader::GrantUniversalAccess() { - has_universal_access_ = true; -} - -void URLLoader::SetStatusCallback(PP_URLLoaderTrusted_StatusCallback cb) { - status_callback_ = cb; -} - -void URLLoader::willSendRequest(WebURLLoader* loader, - WebURLRequest& new_request, - const WebURLResponse& redirect_response) { - if (!request_info_->follow_redirects()) { - SaveResponse(redirect_response); - loader_->setDefersLoading(true); - RunCallback(PP_OK); - } else { - int32_t rv = CanRequest(GetFrame(instance_), new_request.url()); - if (rv != PP_OK) { - loader_->setDefersLoading(true); - RunCallback(rv); - } - } -} - -void URLLoader::didSendData(WebURLLoader* loader, - unsigned long long bytes_sent, - unsigned long long total_bytes_to_be_sent) { - // TODO(darin): Bounds check input? - bytes_sent_ = static_cast<int64_t>(bytes_sent); - total_bytes_to_be_sent_ = static_cast<int64_t>(total_bytes_to_be_sent); - UpdateStatus(); -} - -void URLLoader::didReceiveResponse(WebURLLoader* loader, - const WebURLResponse& response) { - SaveResponse(response); - - // Sets -1 if the content length is unknown. - total_bytes_to_be_received_ = response.expectedContentLength(); - UpdateStatus(); - - RunCallback(PP_OK); -} - -void URLLoader::didDownloadData(WebURLLoader* loader, - int data_length) { - bytes_received_ += data_length; - UpdateStatus(); -} - -void URLLoader::didReceiveData(WebURLLoader* loader, - const char* data, - int data_length) { - bytes_received_ += data_length; - - buffer_.insert(buffer_.end(), data, data + data_length); - if (user_buffer_) { - RunCallback(FillUserBuffer()); - } else { - DCHECK(!pending_callback_.func); - } -} - -void URLLoader::didFinishLoading(WebURLLoader* loader, double finish_time) { - done_status_ = PP_OK; - RunCallback(done_status_); -} - -void URLLoader::didFail(WebURLLoader* loader, const WebURLError& error) { - // TODO(darin): Provide more detailed error information. - done_status_ = PP_ERROR_FAILED; - RunCallback(done_status_); -} - -void URLLoader::InstanceDestroyed(PluginInstance* instance) { - // When the instance is destroyed, we force delete any associated loads. - DCHECK(instance == instance_); - instance_ = NULL; - - // Normally the only ref to this class will be from the plugin which - // ForceDeletePluginResourceRefs will free. We don't want our object to be - // deleted out from under us until the function completes. - scoped_refptr<URLLoader> death_grip(this); - - // Force delete any plugin refs to us. If the instance is being deleted, we - // don't want to allow the requests to continue to use bandwidth and send us - // callbacks (for which we might have no plugin). - ResourceTracker *tracker = ResourceTracker::Get(); - PP_Resource loader_resource = GetReferenceNoAddRef(); - if (loader_resource) - tracker->ForceDeletePluginResourceRefs(loader_resource); - - // Also force free the response from the plugin, both the plugin's ref(s) - // and ours. - if (response_info_.get()) { - PP_Resource response_info_resource = response_info_->GetReferenceNoAddRef(); - if (response_info_resource) - tracker->ForceDeletePluginResourceRefs(response_info_resource); - response_info_ = NULL; - } - - // Free the WebKit request. - loader_.reset(); - - // Often, |this| will be deleted at the end of this function when death_grip - // goes out of scope. -} - -void URLLoader::RunCallback(int32_t result) { - if (!pending_callback_.func) - return; - - PP_CompletionCallback callback = {0}; - std::swap(callback, pending_callback_); - PP_RunCompletionCallback(&callback, result); -} - -size_t URLLoader::FillUserBuffer() { - DCHECK(user_buffer_); - DCHECK(user_buffer_size_); - - size_t bytes_to_copy = std::min(buffer_.size(), user_buffer_size_); - std::copy(buffer_.begin(), buffer_.begin() + bytes_to_copy, user_buffer_); - buffer_.erase(buffer_.begin(), buffer_.begin() + bytes_to_copy); - - // Reset for next time. - user_buffer_ = NULL; - user_buffer_size_ = 0; - return bytes_to_copy; -} - -void URLLoader::SaveResponse(const WebKit::WebURLResponse& response) { - scoped_refptr<URLResponseInfo> response_info(new URLResponseInfo(module())); - if (response_info->Initialize(response)) - response_info_ = response_info; -} - -// Checks that the client can request the URL. Returns a PPAPI error code. -int32_t URLLoader::CanRequest(const WebKit::WebFrame* frame, - const WebKit::WebURL& url) { - if (!has_universal_access_ && - !frame->securityOrigin().canRequest(url)) - return PP_ERROR_NOACCESS; - - return PP_OK; -} - -void URLLoader::UpdateStatus() { - if (status_callback_ && - (RecordDownloadProgress() || RecordUploadProgress())) { - PP_Resource pp_resource = GetReferenceNoAddRef(); - if (pp_resource) { - // The PP_Resource on the plugin will be NULL if the plugin has no - // reference to this object. That's fine, because then we don't need to - // call UpdateStatus. - // - // Here we go through some effort to only send the exact information that - // the requestor wanted in the request flags. It would be just as - // efficient to send all of it, but we don't want people to rely on - // getting download progress when they happen to set the upload progress - // flag. - status_callback_( - instance_->pp_instance(), pp_resource, - RecordUploadProgress() ? bytes_sent_ : -1, - RecordUploadProgress() ? total_bytes_to_be_sent_ : -1, - RecordDownloadProgress() ? bytes_received_ : -1, - RecordDownloadProgress() ? total_bytes_to_be_received_ : -1); - } - } -} - -bool URLLoader::RecordDownloadProgress() const { - return request_info_ && request_info_->record_download_progress(); -} - -bool URLLoader::RecordUploadProgress() const { - return request_info_ && request_info_->record_upload_progress(); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_url_loader.h b/webkit/glue/plugins/pepper_url_loader.h deleted file mode 100644 index ee8ddd7..0000000 --- a/webkit/glue/plugins/pepper_url_loader.h +++ /dev/null @@ -1,140 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_URL_LOADER_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_URL_LOADER_H_ - -#include <deque> - -#include "base/scoped_ptr.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PPB_URLLoader; -struct PPB_URLLoaderTrusted; - -namespace WebKit { -class WebFrame; -class WebURL; -} - -namespace pepper { - -class PluginInstance; -class URLRequestInfo; -class URLResponseInfo; - -class URLLoader : public Resource, - public WebKit::WebURLLoaderClient, - public PluginInstance::Observer { - public: - URLLoader(PluginInstance* instance, bool main_document_loader); - virtual ~URLLoader(); - - // Returns a pointer to the interface implementing PPB_URLLoader that is - // exposed to the plugin. - static const PPB_URLLoader* GetInterface(); - - // Returns a pointer to the interface implementing PPB_URLLoaderTrusted that - // is exposed to the plugin. - static const PPB_URLLoaderTrusted* GetTrustedInterface(); - - // Resource overrides. - URLLoader* AsURLLoader() { return this; } - - // PPB_URLLoader implementation. - int32_t Open(URLRequestInfo* request, PP_CompletionCallback callback); - int32_t FollowRedirect(PP_CompletionCallback callback); - bool GetUploadProgress(int64_t* bytes_sent, - int64_t* total_bytes_to_be_sent); - bool GetDownloadProgress(int64_t* bytes_received, - int64_t* total_bytes_to_be_received); - int32_t ReadResponseBody(char* buffer, int32_t bytes_to_read, - PP_CompletionCallback callback); - int32_t FinishStreamingToFile(PP_CompletionCallback callback); - void Close(); - - // PPB_URLLoaderTrusted implementation. - void GrantUniversalAccess(); - void SetStatusCallback(PP_URLLoaderTrusted_StatusCallback cb); - - // WebKit::WebURLLoaderClient implementation. - virtual void willSendRequest(WebKit::WebURLLoader* loader, - WebKit::WebURLRequest& new_request, - const WebKit::WebURLResponse& redir_response); - virtual void didSendData(WebKit::WebURLLoader* loader, - unsigned long long bytes_sent, - unsigned long long total_bytes_to_be_sent); - virtual void didReceiveResponse(WebKit::WebURLLoader* loader, - const WebKit::WebURLResponse& response); - virtual void didDownloadData(WebKit::WebURLLoader* loader, - int data_length); - virtual void didReceiveData(WebKit::WebURLLoader* loader, - const char* data, - int data_length); - virtual void didFinishLoading(WebKit::WebURLLoader* loader, - double finish_time); - virtual void didFail(WebKit::WebURLLoader* loader, - const WebKit::WebURLError& error); - - // PluginInstance::Observer implementation. - void InstanceDestroyed(PluginInstance* instance); - - URLResponseInfo* response_info() const { return response_info_; } - - private: - void RunCallback(int32_t result); - size_t FillUserBuffer(); - - // Converts a WebURLResponse to a URLResponseInfo and saves it. - void SaveResponse(const WebKit::WebURLResponse& response); - - int32_t CanRequest(const WebKit::WebFrame* frame, const WebKit::WebURL& url); - - // Calls the status_callback_ (if any) with the current upload and download - // progress. Call this function if you update any of these values to - // synchronize an out-of-process plugin's state. - void UpdateStatus(); - - // Returns true if the plugin has requested we record download or upload - // progress. When false, we don't need to update the counters. We go out of - // our way not to allow access to this information unless it's requested, - // even when it would be easier just to return it and not check, so that - // plugins don't depend on access without setting the flag. - bool RecordDownloadProgress() const; - bool RecordUploadProgress() const; - - // This will be NULL if the instance has been deleted but this URLLoader was - // somehow leaked. In general, you should not need to check this for NULL. - // However, if you see a NULL pointer crash, that means somebody is holding - // a reference to this object longer than the PluginInstance's lifetime. - PluginInstance* instance_; - - // If true, then the plugin instance is a full-frame plugin and we're just - // wrapping the main document's loader (i.e. loader_ is null). - bool main_document_loader_; - scoped_ptr<WebKit::WebURLLoader> loader_; - scoped_refptr<URLRequestInfo> request_info_; - scoped_refptr<URLResponseInfo> response_info_; - PP_CompletionCallback pending_callback_; - std::deque<char> buffer_; - int64_t bytes_sent_; - int64_t total_bytes_to_be_sent_; - int64_t bytes_received_; - int64_t total_bytes_to_be_received_; - char* user_buffer_; - size_t user_buffer_size_; - int32_t done_status_; - - bool has_universal_access_; - - PP_URLLoaderTrusted_StatusCallback status_callback_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_URL_LOADER_H_ diff --git a/webkit/glue/plugins/pepper_url_request_info.cc b/webkit/glue/plugins/pepper_url_request_info.cc deleted file mode 100644 index f606509..0000000 --- a/webkit/glue/plugins/pepper_url_request_info.cc +++ /dev/null @@ -1,278 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_url_request_info.h" - -#include "base/logging.h" -#include "base/string_util.h" -#include "googleurl/src/gurl.h" -#include "net/http/http_util.h" -#include "ppapi/c/pp_var.h" -#include "third_party/WebKit/WebKit/chromium/public/WebData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_string.h" -#include "webkit/glue/plugins/pepper_var.h" -#include "webkit/glue/webkit_glue.h" - -using WebKit::WebData; -using WebKit::WebHTTPBody; -using WebKit::WebString; -using WebKit::WebFrame; -using WebKit::WebURL; -using WebKit::WebURLRequest; - -namespace pepper { - -namespace { - -// If any of these request headers are specified, they will not be sent. -// TODO(darin): Add more based on security considerations? -const char* const kIgnoredRequestHeaders[] = { - "content-length" -}; - -PP_Bool IsIgnoredRequestHeader(const std::string& name) { - for (size_t i = 0; i < arraysize(kIgnoredRequestHeaders); ++i) { - if (LowerCaseEqualsASCII(name, kIgnoredRequestHeaders[i])) - return PP_TRUE; - } - return PP_FALSE; -} - -PP_Resource Create(PP_Module module_id) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return 0; - - URLRequestInfo* request = new URLRequestInfo(module); - - return request->GetReference(); -} - -PP_Bool IsURLRequestInfo(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<URLRequestInfo>(resource)); -} - -PP_Bool SetProperty(PP_Resource request_id, - PP_URLRequestProperty property, - PP_Var var) { - scoped_refptr<URLRequestInfo> request( - Resource::GetAs<URLRequestInfo>(request_id)); - if (!request) - return PP_FALSE; - - if (var.type == PP_VARTYPE_BOOL) { - return BoolToPPBool( - request->SetBooleanProperty(property, - PPBoolToBool(var.value.as_bool))); - } - - if (var.type == PP_VARTYPE_STRING) { - scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); - if (string) { - return BoolToPPBool(request->SetStringProperty(property, - string->value())); - } - } - - return PP_FALSE; -} - -PP_Bool AppendDataToBody(PP_Resource request_id, - const char* data, - uint32_t len) { - scoped_refptr<URLRequestInfo> request( - Resource::GetAs<URLRequestInfo>(request_id)); - if (!request) - return PP_FALSE; - - return BoolToPPBool(request->AppendDataToBody(std::string(data, len))); -} - -PP_Bool AppendFileToBody(PP_Resource request_id, - PP_Resource file_ref_id, - int64_t start_offset, - int64_t number_of_bytes, - PP_Time expected_last_modified_time) { - scoped_refptr<URLRequestInfo> request( - Resource::GetAs<URLRequestInfo>(request_id)); - if (!request) - return PP_FALSE; - - scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id)); - if (!file_ref) - return PP_FALSE; - - return BoolToPPBool(request->AppendFileToBody(file_ref, - start_offset, - number_of_bytes, - expected_last_modified_time)); -} - -const PPB_URLRequestInfo ppb_urlrequestinfo = { - &Create, - &IsURLRequestInfo, - &SetProperty, - &AppendDataToBody, - &AppendFileToBody -}; - -} // namespace - -struct URLRequestInfo::BodyItem { - BodyItem(const std::string& data) - : data(data), - start_offset(0), - number_of_bytes(-1), - expected_last_modified_time(0.0) { - } - - BodyItem(FileRef* file_ref, - int64_t start_offset, - int64_t number_of_bytes, - PP_Time expected_last_modified_time) - : file_ref(file_ref), - start_offset(start_offset), - number_of_bytes(number_of_bytes), - expected_last_modified_time(expected_last_modified_time) { - } - - std::string data; - scoped_refptr<FileRef> file_ref; - int64_t start_offset; - int64_t number_of_bytes; - PP_Time expected_last_modified_time; -}; - -URLRequestInfo::URLRequestInfo(PluginModule* module) - : Resource(module), - stream_to_file_(false), - follow_redirects_(true), - record_download_progress_(false), - record_upload_progress_(false) { -} - -URLRequestInfo::~URLRequestInfo() { -} - -// static -const PPB_URLRequestInfo* URLRequestInfo::GetInterface() { - return &ppb_urlrequestinfo; -} - -bool URLRequestInfo::SetBooleanProperty(PP_URLRequestProperty property, - bool value) { - switch (property) { - case PP_URLREQUESTPROPERTY_STREAMTOFILE: - stream_to_file_ = value; - return true; - case PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS: - follow_redirects_ = value; - return true; - case PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS: - record_download_progress_ = value; - return true; - case PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS: - record_upload_progress_ = value; - return true; - default: - //NOTIMPLEMENTED(); // TODO(darin): Implement me! - return false; - } -} - -bool URLRequestInfo::SetStringProperty(PP_URLRequestProperty property, - const std::string& value) { - // TODO(darin): Validate input. Perhaps at a different layer? - switch (property) { - case PP_URLREQUESTPROPERTY_URL: - url_ = value; // NOTE: This may be a relative URL. - return true; - case PP_URLREQUESTPROPERTY_METHOD: - method_ = value; - return true; - case PP_URLREQUESTPROPERTY_HEADERS: - headers_ = value; - return true; - default: - return false; - } -} - -bool URLRequestInfo::AppendDataToBody(const std::string& data) { - if (!data.empty()) - body_.push_back(BodyItem(data)); - return true; -} - -bool URLRequestInfo::AppendFileToBody(FileRef* file_ref, - int64_t start_offset, - int64_t number_of_bytes, - PP_Time expected_last_modified_time) { - // Ignore a call to append nothing. - if (number_of_bytes == 0) - return true; - - // Check for bad values. (-1 means read until end of file.) - if (start_offset < 0 || number_of_bytes < -1) - return false; - - body_.push_back(BodyItem(file_ref, - start_offset, - number_of_bytes, - expected_last_modified_time)); - return true; -} - -WebURLRequest URLRequestInfo::ToWebURLRequest(WebFrame* frame) const { - WebURLRequest web_request; - web_request.initialize(); - web_request.setURL(frame->document().completeURL(WebString::fromUTF8(url_))); - web_request.setDownloadToFile(stream_to_file_); - - if (!method_.empty()) - web_request.setHTTPMethod(WebString::fromUTF8(method_)); - - if (!headers_.empty()) { - net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(), "\n"); - while (it.GetNext()) { - if (!IsIgnoredRequestHeader(it.name())) { - web_request.addHTTPHeaderField( - WebString::fromUTF8(it.name()), - WebString::fromUTF8(it.values())); - } - } - } - - if (!body_.empty()) { - WebHTTPBody http_body; - http_body.initialize(); - for (size_t i = 0; i < body_.size(); ++i) { - if (body_[i].file_ref) { - http_body.appendFileRange( - webkit_glue::FilePathToWebString( - body_[i].file_ref->GetSystemPath()), - body_[i].start_offset, - body_[i].number_of_bytes, - body_[i].expected_last_modified_time); - } else { - DCHECK(!body_[i].data.empty()); - http_body.appendData(WebData(body_[i].data)); - } - } - web_request.setHTTPBody(http_body); - } - - frame->setReferrerForRequest(web_request, WebURL()); // Use default. - return web_request; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_url_request_info.h b/webkit/glue/plugins/pepper_url_request_info.h deleted file mode 100644 index 7aa9fc1..0000000 --- a/webkit/glue/plugins/pepper_url_request_info.h +++ /dev/null @@ -1,69 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_URL_REQUEST_INFO_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_URL_REQUEST_INFO_H_ - -#include <string> -#include <vector> - -#include "base/ref_counted.h" -#include "ppapi/c/ppb_url_request_info.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace WebKit { -class WebFrame; -class WebURLRequest; -} - -namespace pepper { - -class URLRequestInfo : public Resource { - public: - explicit URLRequestInfo(PluginModule* module); - virtual ~URLRequestInfo(); - - // Returns a pointer to the interface implementing PPB_URLRequestInfo that is - // exposed to the plugin. - static const PPB_URLRequestInfo* GetInterface(); - - // Resource overrides. - URLRequestInfo* AsURLRequestInfo() { return this; } - - // PPB_URLRequestInfo implementation. - bool SetBooleanProperty(PP_URLRequestProperty property, bool value); - bool SetStringProperty(PP_URLRequestProperty property, - const std::string& value); - bool AppendDataToBody(const std::string& data); - bool AppendFileToBody(FileRef* file_ref, - int64_t start_offset, - int64_t number_of_bytes, - PP_Time expected_last_modified_time); - - WebKit::WebURLRequest ToWebURLRequest(WebKit::WebFrame* frame) const; - - bool follow_redirects() { return follow_redirects_; } - - bool record_download_progress() const { return record_download_progress_; } - bool record_upload_progress() const { return record_upload_progress_; } - - private: - struct BodyItem; - typedef std::vector<BodyItem> Body; - - std::string url_; - std::string method_; - std::string headers_; - Body body_; - - bool stream_to_file_; - bool follow_redirects_; - bool record_download_progress_; - bool record_upload_progress_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_URL_REQUEST_INFO_H_ diff --git a/webkit/glue/plugins/pepper_url_response_info.cc b/webkit/glue/plugins/pepper_url_response_info.cc deleted file mode 100644 index 5ae484f..0000000 --- a/webkit/glue/plugins/pepper_url_response_info.cc +++ /dev/null @@ -1,137 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_url_response_info.h" - -#include "base/logging.h" -#include "ppapi/c/pp_var.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPHeaderVisitor.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_var.h" -#include "webkit/glue/webkit_glue.h" - -using WebKit::WebHTTPHeaderVisitor; -using WebKit::WebString; -using WebKit::WebURLResponse; - -namespace pepper { - -namespace { - -class HeaderFlattener : public WebHTTPHeaderVisitor { - public: - const std::string& buffer() const { return buffer_; } - - virtual void visitHeader(const WebString& name, const WebString& value) { - if (!buffer_.empty()) - buffer_.append("\n"); - buffer_.append(name.utf8()); - buffer_.append(": "); - buffer_.append(value.utf8()); - } - - private: - std::string buffer_; -}; - -PP_Bool IsURLResponseInfo(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<URLResponseInfo>(resource)); -} - -PP_Var GetProperty(PP_Resource response_id, - PP_URLResponseProperty property) { - scoped_refptr<URLResponseInfo> response( - Resource::GetAs<URLResponseInfo>(response_id)); - if (!response) - return PP_MakeUndefined(); - - return response->GetProperty(property); -} - -PP_Resource GetBody(PP_Resource response_id) { - scoped_refptr<URLResponseInfo> response( - Resource::GetAs<URLResponseInfo>(response_id)); - if (!response.get()) - return 0; - - FileRef* body = response->body(); - if (!body) - return 0; - body->AddRef(); // AddRef for the caller. - - return body->GetReference(); -} - -const PPB_URLResponseInfo ppb_urlresponseinfo = { - &IsURLResponseInfo, - &GetProperty, - &GetBody -}; - -bool IsRedirect(int32_t status) { - return status >= 300 && status <= 399; -} - -} // namespace - -URLResponseInfo::URLResponseInfo(PluginModule* module) - : Resource(module), - status_code_(-1) { -} - -URLResponseInfo::~URLResponseInfo() { -} - -// static -const PPB_URLResponseInfo* URLResponseInfo::GetInterface() { - return &ppb_urlresponseinfo; -} - -PP_Var URLResponseInfo::GetProperty(PP_URLResponseProperty property) { - switch (property) { - case PP_URLRESPONSEPROPERTY_URL: - return StringVar::StringToPPVar(module(), url_); - case PP_URLRESPONSEPROPERTY_REDIRECTURL: - if (IsRedirect(status_code_)) - return StringVar::StringToPPVar(module(), redirect_url_); - break; - case PP_URLRESPONSEPROPERTY_REDIRECTMETHOD: - if (IsRedirect(status_code_)) - return StringVar::StringToPPVar(module(), status_text_); - break; - case PP_URLRESPONSEPROPERTY_STATUSCODE: - return PP_MakeInt32(status_code_); - case PP_URLRESPONSEPROPERTY_STATUSLINE: - return StringVar::StringToPPVar(module(), status_text_); - case PP_URLRESPONSEPROPERTY_HEADERS: - return StringVar::StringToPPVar(module(), headers_); - } - // The default is to return an undefined PP_Var. - return PP_MakeUndefined(); -} - -bool URLResponseInfo::Initialize(const WebURLResponse& response) { - url_ = response.url().spec(); - status_code_ = response.httpStatusCode(); - status_text_ = response.httpStatusText().utf8(); - if (IsRedirect(status_code_)) { - redirect_url_ = response.httpHeaderField( - WebString::fromUTF8("Location")).utf8(); - } - - HeaderFlattener flattener; - response.visitHTTPHeaderFields(&flattener); - headers_ = flattener.buffer(); - - WebString file_path = response.downloadFilePath(); - if (!file_path.isEmpty()) - body_ = new FileRef(module(), webkit_glue::WebStringToFilePath(file_path)); - return true; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_url_response_info.h b/webkit/glue/plugins/pepper_url_response_info.h deleted file mode 100644 index adbf8ef..0000000 --- a/webkit/glue/plugins/pepper_url_response_info.h +++ /dev/null @@ -1,51 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_URL_RESPONSE_INFO_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_URL_RESPONSE_INFO_H_ - -#include <string> - -#include "ppapi/c/ppb_url_response_info.h" -#include "webkit/glue/plugins/pepper_resource.h" - -namespace WebKit { -class WebURLResponse; -} - -namespace pepper { - -class URLResponseInfo : public Resource { - public: - explicit URLResponseInfo(PluginModule* module); - virtual ~URLResponseInfo(); - - // Returns a pointer to the interface implementing PPB_URLResponseInfo that - // is exposed to the plugin. - static const PPB_URLResponseInfo* GetInterface(); - - // Resource overrides. - URLResponseInfo* AsURLResponseInfo() { return this; } - - // PPB_URLResponseInfo implementation. - PP_Var GetProperty(PP_URLResponseProperty property); - - bool Initialize(const WebKit::WebURLResponse& response); - - FileRef* body() { return body_; } - - std::string redirect_url() { return redirect_url_; } - - private: - std::string url_; - std::string headers_; - int32_t status_code_; - std::string status_text_; - std::string redirect_url_; - scoped_refptr<FileRef> body_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_URL_RESPONSE_INFO_H_ diff --git a/webkit/glue/plugins/pepper_url_util.cc b/webkit/glue/plugins/pepper_url_util.cc deleted file mode 100644 index 2f97e6c..0000000 --- a/webkit/glue/plugins/pepper_url_util.cc +++ /dev/null @@ -1,177 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_url_util.h" - -#include "googleurl/src/gurl.h" -#include "ppapi/c/dev/ppb_url_util_dev.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebElement.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebNode.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginContainer.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSecurityOrigin.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_string.h" -#include "webkit/glue/plugins/pepper_var.h" - -namespace pepper { - -namespace { - -void ConvertComponent(const url_parse::Component& input, - PP_UrlComponent_Dev* output) { - output->begin = input.begin; - output->len = input.len; -} - -// Output can be NULL to specify "do nothing." This rule is followed by all the -// url util functions, so we implement it once here. -void ConvertComponents(const url_parse::Parsed& input, - PP_UrlComponents_Dev* output) { - if (!output) - return; - - ConvertComponent(input.scheme, &output->scheme); - ConvertComponent(input.username, &output->username); - ConvertComponent(input.password, &output->password); - ConvertComponent(input.host, &output->host); - ConvertComponent(input.port, &output->port); - ConvertComponent(input.path, &output->path); - ConvertComponent(input.query, &output->query); - ConvertComponent(input.ref, &output->ref); -} - -// Used for returning the given GURL from a PPAPI function, with an optional -// out param indicating the components. -PP_Var GenerateUrlReturn(PluginModule* module, const GURL& url, - PP_UrlComponents_Dev* components) { - if (!url.is_valid()) - return PP_MakeNull(); - ConvertComponents(url.parsed_for_possibly_invalid_spec(), components); - return StringVar::StringToPPVar(module, url.possibly_invalid_spec()); -} - -// Sets |*security_origin| to be the WebKit security origin associated with the -// document containing the given plugin instance. On success, returns true. If -// the instance is invalid, returns false and |*security_origin| will be -// unchanged. -bool SecurityOriginForInstance(PP_Instance instance_id, - WebKit::WebSecurityOrigin* security_origin) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return false; - - WebKit::WebElement plugin_element = instance->container()->element(); - WebKit::WebFrame* plugin_frame = plugin_element.document().frame(); - if (!plugin_frame) - return false; - - *security_origin = plugin_frame->securityOrigin(); - return true; -} - -PP_Var Canonicalize(PP_Var url, PP_UrlComponents_Dev* components) { - scoped_refptr<StringVar> url_string(StringVar::FromPPVar(url)); - if (!url_string) - return PP_MakeNull(); - return GenerateUrlReturn(url_string->module(), - GURL(url_string->value()), components); -} - -PP_Var ResolveRelativeToUrl(PP_Var base_url, - PP_Var relative, - PP_UrlComponents_Dev* components) { - scoped_refptr<StringVar> base_url_string(StringVar::FromPPVar(base_url)); - scoped_refptr<StringVar> relative_string(StringVar::FromPPVar(relative)); - if (!base_url_string || !relative_string) - return PP_MakeNull(); - - GURL base_gurl(base_url_string->value()); - if (!base_gurl.is_valid()) - return PP_MakeNull(); - return GenerateUrlReturn(base_url_string->module(), - base_gurl.Resolve(relative_string->value()), - components); -} - -PP_Var ResolveRelativeToDocument(PP_Instance instance_id, - PP_Var relative, - PP_UrlComponents_Dev* components) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return PP_MakeNull(); - - scoped_refptr<StringVar> relative_string(StringVar::FromPPVar(relative)); - if (!relative_string) - return PP_MakeNull(); - - WebKit::WebElement plugin_element = instance->container()->element(); - GURL document_url = plugin_element.document().baseURL(); - return GenerateUrlReturn(instance->module(), - document_url.Resolve(relative_string->value()), - components); -} - -PP_Bool IsSameSecurityOrigin(PP_Var url_a, PP_Var url_b) { - scoped_refptr<StringVar> url_a_string(StringVar::FromPPVar(url_a)); - scoped_refptr<StringVar> url_b_string(StringVar::FromPPVar(url_b)); - if (!url_a_string || !url_b_string) - return PP_FALSE; - - GURL gurl_a(url_a_string->value()); - GURL gurl_b(url_b_string->value()); - if (!gurl_a.is_valid() || !gurl_b.is_valid()) - return PP_FALSE; - - return BoolToPPBool(gurl_a.GetOrigin() == gurl_b.GetOrigin()); -} - -PP_Bool DocumentCanRequest(PP_Instance instance, PP_Var url) { - scoped_refptr<StringVar> url_string(StringVar::FromPPVar(url)); - if (!url_string) - return PP_FALSE; - - WebKit::WebSecurityOrigin security_origin; - if (!SecurityOriginForInstance(instance, &security_origin)) - return PP_FALSE; - - GURL gurl(url_string->value()); - if (!gurl.is_valid()) - return PP_FALSE; - - return BoolToPPBool(security_origin.canRequest(gurl)); -} - -PP_Bool DocumentCanAccessDocument(PP_Instance active, PP_Instance target) { - WebKit::WebSecurityOrigin active_origin; - if (!SecurityOriginForInstance(active, &active_origin)) - return PP_FALSE; - - WebKit::WebSecurityOrigin target_origin; - if (!SecurityOriginForInstance(active, &target_origin)) - return PP_FALSE; - - return BoolToPPBool(active_origin.canAccess(target_origin)); -} - -} // namespace - -const PPB_UrlUtil_Dev ppb_url_util = { - &Canonicalize, - &ResolveRelativeToUrl, - &ResolveRelativeToDocument, - &IsSameSecurityOrigin, - &DocumentCanRequest, - &DocumentCanAccessDocument -}; - -// static -const PPB_UrlUtil_Dev* UrlUtil::GetInterface() { - return &ppb_url_util; -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_url_util.h b/webkit/glue/plugins/pepper_url_util.h deleted file mode 100644 index ffb7c76..0000000 --- a/webkit/glue/plugins/pepper_url_util.h +++ /dev/null @@ -1,19 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_URL_UTIL_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_URL_UTIL_H_ - -struct PPB_UrlUtil_Dev; - -namespace pepper { - -class UrlUtil { - public: - static const PPB_UrlUtil_Dev* GetInterface(); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_URL_UTIL_H_ diff --git a/webkit/glue/plugins/pepper_var.cc b/webkit/glue/plugins/pepper_var.cc deleted file mode 100644 index db83229..0000000 --- a/webkit/glue/plugins/pepper_var.cc +++ /dev/null @@ -1,853 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_var.h" - -#include <limits> - -#include "base/logging.h" -#include "base/scoped_ptr.h" -#include "base/string_util.h" -#include "ppapi/c/dev/ppb_var_deprecated.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/pp_var.h" -#include "third_party/WebKit/WebKit/chromium/public/WebBindings.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_plugin_object.h" -#include "v8/include/v8.h" - -using WebKit::WebBindings; - -namespace pepper { - -namespace { - -const char kInvalidObjectException[] = "Error: Invalid object"; -const char kInvalidPropertyException[] = "Error: Invalid property"; -const char kInvalidValueException[] = "Error: Invalid value"; -const char kUnableToGetPropertyException[] = "Error: Unable to get property"; -const char kUnableToSetPropertyException[] = "Error: Unable to set property"; -const char kUnableToRemovePropertyException[] = - "Error: Unable to remove property"; -const char kUnableToGetAllPropertiesException[] = - "Error: Unable to get all properties"; -const char kUnableToCallMethodException[] = "Error: Unable to call method"; -const char kUnableToConstructException[] = "Error: Unable to construct"; - -// --------------------------------------------------------------------------- -// Utilities - -// Converts the given PP_Var to an NPVariant, returning true on success. -// False means that the given variant is invalid. In this case, the result -// NPVariant will be set to a void one. -// -// The contents of the PP_Var will NOT be copied, so you need to ensure that -// the PP_Var remains valid while the resultant NPVariant is in use. -bool PPVarToNPVariantNoCopy(PP_Var var, NPVariant* result) { - switch (var.type) { - case PP_VARTYPE_UNDEFINED: - VOID_TO_NPVARIANT(*result); - break; - case PP_VARTYPE_NULL: - NULL_TO_NPVARIANT(*result); - break; - case PP_VARTYPE_BOOL: - BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); - break; - case PP_VARTYPE_INT32: - INT32_TO_NPVARIANT(var.value.as_int, *result); - break; - case PP_VARTYPE_DOUBLE: - DOUBLE_TO_NPVARIANT(var.value.as_double, *result); - break; - case PP_VARTYPE_STRING: { - scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); - if (!string) { - VOID_TO_NPVARIANT(*result); - return false; - } - const std::string& value = string->value(); - STRINGN_TO_NPVARIANT(value.c_str(), value.size(), *result); - break; - } - case PP_VARTYPE_OBJECT: { - scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); - if (!object) { - VOID_TO_NPVARIANT(*result); - return false; - } - OBJECT_TO_NPVARIANT(object->np_object(), *result); - break; - } - default: - VOID_TO_NPVARIANT(*result); - return false; - } - return true; -} - -// ObjectAccessorTryCatch ------------------------------------------------------ - -// Automatically sets up a TryCatch for accessing the object identified by the -// given PP_Var. The module from the object will be used for the exception -// strings generated by the TryCatch. -// -// This will automatically retrieve the ObjectVar from the object and throw -// an exception if it's invalid. At the end of construction, if there is no -// exception, you know that there is no previously set exception, that the -// object passed in is valid and ready to use (via the object() getter), and -// that the TryCatch's module() getter is also set up properly and ready to -// use. -class ObjectAccessorTryCatch : public TryCatch { - public: - ObjectAccessorTryCatch(PP_Var object, PP_Var* exception) - : TryCatch(NULL, exception), - object_(ObjectVar::FromPPVar(object)) { - if (!object_) { - // No object or an invalid object was given. This means we have no module - // to associated with the exception text, so use the magic invalid object - // exception. - SetInvalidObjectException(); - } else { - // When the object is valid, we have a valid module to associate - set_module(object_->module()); - } - } - - ObjectVar* object() { return object_.get(); } - - protected: - scoped_refptr<ObjectVar> object_; - - DISALLOW_COPY_AND_ASSIGN(ObjectAccessorTryCatch); -}; - -// ObjectAccessiorWithIdentifierTryCatch --------------------------------------- - -// Automatically sets up a TryCatch for accessing the identifier on the given -// object. This just extends ObjectAccessorTryCatch to additionally convert -// the given identifier to an NPIdentifier and validate it, throwing an -// exception if it's invalid. -// -// At the end of construction, if there is no exception, you know that there is -// no previously set exception, that the object passed in is valid and ready to -// use (via the object() getter), that the identifier is valid and ready to -// use (via the identifier() getter), and that the TryCatch's module() getter -// is also set up properly and ready to use. -class ObjectAccessorWithIdentifierTryCatch : public ObjectAccessorTryCatch { - public: - ObjectAccessorWithIdentifierTryCatch(PP_Var object, - PP_Var identifier, - PP_Var* exception) - : ObjectAccessorTryCatch(object, exception), - identifier_(0) { - if (!has_exception()) { - identifier_ = Var::PPVarToNPIdentifier(identifier); - if (!identifier_) - SetException(kInvalidPropertyException); - } - } - - NPIdentifier identifier() const { return identifier_; } - - private: - NPIdentifier identifier_; - - DISALLOW_COPY_AND_ASSIGN(ObjectAccessorWithIdentifierTryCatch); -}; - -PP_Var RunJSFunction(PP_Var scope_var, - const char* function_script, - PP_Var* argv, - unsigned argc, - PP_Var* exception) { - TryCatch try_catch(NULL, exception); - if (try_catch.has_exception()) - return PP_MakeUndefined(); - - scoped_refptr<ObjectVar> obj = ObjectVar::FromPPVar(scope_var); - if (!obj) { - try_catch.SetInvalidObjectException(); - return PP_MakeUndefined(); - } - - try_catch.set_module(obj->module()); - - scoped_array<NPVariant> args; - if (argc) { - args.reset(new NPVariant[argc]); - for (uint32_t i = 0; i < argc; ++i) { - if (!PPVarToNPVariantNoCopy(argv[i], &args[i])) { - // This argument was invalid, throw an exception & give up. - try_catch.SetException(kInvalidValueException); - return PP_MakeUndefined(); - } - } - } - - NPVariant function_var; - VOID_TO_NPVARIANT(function_var); - NPString function_string = { function_script, strlen(function_script) }; - if (!WebBindings::evaluate(NULL, obj->np_object(), &function_string, - &function_var)) { - try_catch.SetException(kInvalidValueException); - return PP_MakeUndefined(); - } - DCHECK(NPVARIANT_IS_OBJECT(function_var)); - DCHECK(!try_catch.has_exception()); - - NPVariant result_var; - VOID_TO_NPVARIANT(result_var); - PP_Var result; - - if (WebBindings::invokeDefault(NULL, NPVARIANT_TO_OBJECT(function_var), - args.get(), argc, &result_var)) { - result = Var::NPVariantToPPVar(obj->module(), &result_var); - } else { - DCHECK(try_catch.has_exception()); - result = PP_MakeUndefined(); - } - - WebBindings::releaseVariantValue(&function_var); - WebBindings::releaseVariantValue(&result_var); - return result; -} - -// PPB_Var methods ------------------------------------------------------------- - -PP_Var VarFromUtf8(PP_Module module_id, const char* data, uint32_t len) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return PP_MakeNull(); - return StringVar::StringToPPVar(module, data, len); -} - -const char* VarToUtf8(PP_Var var, uint32_t* len) { - scoped_refptr<StringVar> str(StringVar::FromPPVar(var)); - if (!str) { - *len = 0; - return NULL; - } - *len = static_cast<uint32_t>(str->value().size()); - if (str->value().empty()) - return ""; // Don't return NULL on success. - return str->value().data(); -} - -PP_Var ConvertType(PP_Instance instance, - struct PP_Var var, - PP_VarType new_type, - PP_Var* exception) { - TryCatch try_catch(NULL, exception); - if (try_catch.has_exception()) - return PP_MakeUndefined(); - - if (var.type == new_type) - return var; - - PluginInstance* plugin_instance = - ResourceTracker::Get()->GetInstance(instance); - if (!plugin_instance) { - try_catch.SetInvalidObjectException(); - return PP_MakeUndefined(); - } - - try_catch.set_module(plugin_instance->module()); - PP_Var object = plugin_instance->GetWindowObject(); - - PP_Var params[] = { - var, - PP_MakeInt32(new_type), - PP_MakeInt32(PP_VARTYPE_NULL), - PP_MakeInt32(PP_VARTYPE_BOOL), - PP_MakeInt32(PP_VARTYPE_INT32), - PP_MakeInt32(PP_VARTYPE_DOUBLE), - PP_MakeInt32(PP_VARTYPE_STRING), - PP_MakeInt32(PP_VARTYPE_OBJECT) - }; - PP_Var result = RunJSFunction(object, - "(function(v, new_type, type_null, type_bool, type_int32, type_double," - " type_string, type_object) {" - " switch(new_type) {" - " case type_null: return null;" - " case type_bool: return Boolean(v);" - " case type_int32: case type_double: return Number(v);" - " case type_string: return String(v);" - " case type_object: return Object(v);" - " default: return undefined;" - " }})", - params, sizeof(params) / sizeof(PP_Var), exception); - - // Massage Number into the correct type. - if (new_type == PP_VARTYPE_INT32 && result.type == PP_VARTYPE_DOUBLE) { - double value = result.value.as_double; - // Exclusive test wouldn't deal with NaNs correctly. - if (value >= std::numeric_limits<int32_t>::max() - && value <= std::numeric_limits<int32_t>::min()) - result = PP_MakeInt32(static_cast<int32_t>(value)); - else - result = PP_MakeInt32(0); - } else if (new_type == PP_VARTYPE_DOUBLE && result.type == PP_VARTYPE_INT32) { - result = PP_MakeDouble(result.value.as_int); - } - - Var::PluginReleasePPVar(object); - return result; -} - -PP_Var BoolToPPVar(bool value) { - return PP_MakeBool(BoolToPPBool(value)); -} - -void DefineProperty(struct PP_Var object, - struct PP_ObjectProperty property, - PP_Var* exception) { - PP_Var params[] = { - object, property.name, - BoolToPPVar(!!(property.modifiers & PP_OBJECTPROPERTY_MODIFIER_HASVALUE)), - property.value, - BoolToPPVar(property.getter.type == PP_VARTYPE_OBJECT), - property.getter, - BoolToPPVar(property.setter.type == PP_VARTYPE_OBJECT), - property.setter, - BoolToPPVar(!!(property.modifiers & PP_OBJECTPROPERTY_MODIFIER_READONLY)), - BoolToPPVar(!!(property.modifiers & PP_OBJECTPROPERTY_MODIFIER_DONTDELETE)), - BoolToPPVar(!!(property.modifiers & PP_OBJECTPROPERTY_MODIFIER_DONTENUM)) - }; - - RunJSFunction(object, - "(function(o, name," - " has_value, value," - " has_getter, getter," - " has_setter, setter," - " modifier_readonly, modifier_dontdelete, modifier_dontenum) {" - " prop = { 'enumerable': !modifier_dontenum," - " 'configurable': !modifier_dontdelete };" - " if (has_value && !modifier_readonly) prop.writable = true;" - " if (has_value) prop.value = value;" - " if (has_getter) prop.get = getter;" - " if (has_setter) prop.set = setter;" - " return Object.defineProperty(o, name, prop); })", - params, sizeof(params) / sizeof(PP_Var), exception); -} - -PP_Bool HasProperty(PP_Var var, - PP_Var name, - PP_Var* exception) { - ObjectAccessorWithIdentifierTryCatch accessor(var, name, exception); - if (accessor.has_exception()) - return PP_FALSE; - return BoolToPPBool(WebBindings::hasProperty(NULL, - accessor.object()->np_object(), - accessor.identifier())); -} - -bool HasPropertyDeprecated(PP_Var var, - PP_Var name, - PP_Var* exception) { - return PPBoolToBool(HasProperty(var, name, exception)); -} - -bool HasMethodDeprecated(PP_Var var, - PP_Var name, - PP_Var* exception) { - ObjectAccessorWithIdentifierTryCatch accessor(var, name, exception); - if (accessor.has_exception()) - return false; - return WebBindings::hasMethod(NULL, accessor.object()->np_object(), - accessor.identifier()); -} - -PP_Var GetProperty(PP_Var var, - PP_Var name, - PP_Var* exception) { - ObjectAccessorWithIdentifierTryCatch accessor(var, name, exception); - if (accessor.has_exception()) - return PP_MakeUndefined(); - - NPVariant result; - if (!WebBindings::getProperty(NULL, accessor.object()->np_object(), - accessor.identifier(), &result)) { - // An exception may have been raised. - accessor.SetException(kUnableToGetPropertyException); - return PP_MakeUndefined(); - } - - PP_Var ret = Var::NPVariantToPPVar(accessor.object()->module(), &result); - WebBindings::releaseVariantValue(&result); - return ret; -} - -void EnumerateProperties(PP_Var var, - uint32_t* property_count, - PP_Var** properties, - PP_Var* exception) { - *properties = NULL; - *property_count = 0; - - ObjectAccessorTryCatch accessor(var, exception); - if (accessor.has_exception()) - return; - - NPIdentifier* identifiers = NULL; - uint32_t count = 0; - if (!WebBindings::enumerate(NULL, accessor.object()->np_object(), - &identifiers, &count)) { - accessor.SetException(kUnableToGetAllPropertiesException); - return; - } - - if (count == 0) - return; - - *property_count = count; - *properties = static_cast<PP_Var*>(malloc(sizeof(PP_Var) * count)); - for (uint32_t i = 0; i < count; ++i) { - (*properties)[i] = Var::NPIdentifierToPPVar(accessor.object()->module(), - identifiers[i]); - } - free(identifiers); -} - -void SetPropertyDeprecated(PP_Var var, - PP_Var name, - PP_Var value, - PP_Var* exception) { - ObjectAccessorWithIdentifierTryCatch accessor(var, name, exception); - if (accessor.has_exception()) - return; - - NPVariant variant; - if (!PPVarToNPVariantNoCopy(value, &variant)) { - accessor.SetException(kInvalidValueException); - return; - } - if (!WebBindings::setProperty(NULL, accessor.object()->np_object(), - accessor.identifier(), &variant)) - accessor.SetException(kUnableToSetPropertyException); -} - -PP_Bool DeleteProperty(PP_Var var, - PP_Var name, - PP_Var* exception) { - ObjectAccessorWithIdentifierTryCatch accessor(var, name, exception); - if (accessor.has_exception()) - return PP_FALSE; - - return BoolToPPBool( - WebBindings::removeProperty(NULL, - accessor.object()->np_object(), - accessor.identifier())); -} - -void DeletePropertyDeprecated(PP_Var var, - PP_Var name, - PP_Var* exception) { - ObjectAccessorWithIdentifierTryCatch accessor(var, name, exception); - if (accessor.has_exception()) - return; - - if (!WebBindings::removeProperty(NULL, accessor.object()->np_object(), - accessor.identifier())) - accessor.SetException(kUnableToRemovePropertyException); -} - -PP_Bool IsCallable(struct PP_Var object) { - PP_Var result = RunJSFunction(object, - "(function() { return typeof(this) == 'function' })", NULL, 0, NULL); - if (result.type == PP_VARTYPE_BOOL) - return result.value.as_bool; - return PP_FALSE; -} - -struct PP_Var Call(struct PP_Var object, - struct PP_Var this_object, - uint32_t argc, - struct PP_Var* argv, - struct PP_Var* exception) { - ObjectAccessorTryCatch accessor(object, exception); - if (accessor.has_exception()) - return PP_MakeUndefined(); - - scoped_array<NPVariant> args; - if (argc) { - args.reset(new NPVariant[argc]); - for (uint32_t i = 0; i < argc; ++i) { - if (!PPVarToNPVariantNoCopy(argv[i], &args[i])) { - // This argument was invalid, throw an exception & give up. - accessor.SetException(kInvalidValueException); - return PP_MakeUndefined(); - } - } - } - - NPVariant result; - if (!WebBindings::invokeDefault(NULL, accessor.object()->np_object(), - args.get(), argc, &result)) { - // An exception may have been raised. - accessor.SetException(kUnableToCallMethodException); - return PP_MakeUndefined(); - } - - PP_Var ret = Var::NPVariantToPPVar(accessor.module(), &result); - WebBindings::releaseVariantValue(&result); - return ret; -} - -PP_Var CallDeprecated(PP_Var var, - PP_Var method_name, - uint32_t argc, - PP_Var* argv, - PP_Var* exception) { - ObjectAccessorTryCatch accessor(var, exception); - if (accessor.has_exception()) - return PP_MakeUndefined(); - - NPIdentifier identifier; - if (method_name.type == PP_VARTYPE_UNDEFINED) { - identifier = NULL; - } else if (method_name.type == PP_VARTYPE_STRING) { - // Specifically allow only string functions to be called. - identifier = Var::PPVarToNPIdentifier(method_name); - if (!identifier) { - accessor.SetException(kInvalidPropertyException); - return PP_MakeUndefined(); - } - } else { - accessor.SetException(kInvalidPropertyException); - return PP_MakeUndefined(); - } - - scoped_array<NPVariant> args; - if (argc) { - args.reset(new NPVariant[argc]); - for (uint32_t i = 0; i < argc; ++i) { - if (!PPVarToNPVariantNoCopy(argv[i], &args[i])) { - // This argument was invalid, throw an exception & give up. - accessor.SetException(kInvalidValueException); - return PP_MakeUndefined(); - } - } - } - - bool ok; - - NPVariant result; - if (identifier) { - ok = WebBindings::invoke(NULL, accessor.object()->np_object(), - identifier, args.get(), argc, &result); - } else { - ok = WebBindings::invokeDefault(NULL, accessor.object()->np_object(), - args.get(), argc, &result); - } - - if (!ok) { - // An exception may have been raised. - accessor.SetException(kUnableToCallMethodException); - return PP_MakeUndefined(); - } - - PP_Var ret = Var::NPVariantToPPVar(accessor.module(), &result); - WebBindings::releaseVariantValue(&result); - return ret; -} - -PP_Var Construct(PP_Var var, - uint32_t argc, - PP_Var* argv, - PP_Var* exception) { - ObjectAccessorTryCatch accessor(var, exception); - if (accessor.has_exception()) - return PP_MakeUndefined(); - - scoped_array<NPVariant> args; - if (argc) { - args.reset(new NPVariant[argc]); - for (uint32_t i = 0; i < argc; ++i) { - if (!PPVarToNPVariantNoCopy(argv[i], &args[i])) { - // This argument was invalid, throw an exception & give up. - accessor.SetException(kInvalidValueException); - return PP_MakeUndefined(); - } - } - } - - NPVariant result; - if (!WebBindings::construct(NULL, accessor.object()->np_object(), - args.get(), argc, &result)) { - // An exception may have been raised. - accessor.SetException(kUnableToConstructException); - return PP_MakeUndefined(); - } - - PP_Var ret = Var::NPVariantToPPVar(accessor.module(), &result); - WebBindings::releaseVariantValue(&result); - return ret; -} - -bool IsInstanceOfDeprecated(PP_Var var, - const PPP_Class_Deprecated* ppp_class, - void** ppp_class_data) { - scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); - if (!object) - return false; // Not an object at all. - - return PluginObject::IsInstanceOf(object->np_object(), - ppp_class, ppp_class_data); -} - -PP_Var CreateObjectDeprecated(PP_Module module_id, - const PPP_Class_Deprecated* ppp_class, - void* ppp_class_data) { - PluginModule* module = ResourceTracker::Get()->GetModule(module_id); - if (!module) - return PP_MakeNull(); - return PluginObject::Create(module, ppp_class, ppp_class_data); -} - -const PPB_Var_Deprecated var_deprecated_interface = { - &Var::PluginAddRefPPVar, - &Var::PluginReleasePPVar, - &VarFromUtf8, - &VarToUtf8, - &HasPropertyDeprecated, - &HasMethodDeprecated, - &GetProperty, - &EnumerateProperties, - &SetPropertyDeprecated, - &DeletePropertyDeprecated, - &CallDeprecated, - &Construct, - &IsInstanceOfDeprecated, - &CreateObjectDeprecated -}; - -const PPB_Var var_interface = { - &Var::PluginAddRefPPVar, - &Var::PluginReleasePPVar, - &VarFromUtf8, - &VarToUtf8, - &ConvertType, - &DefineProperty, - &HasProperty, - &GetProperty, - &DeleteProperty, - &EnumerateProperties, - &IsCallable, - &Call, - &Construct, -}; - - -} // namespace - -// Var ------------------------------------------------------------------------- - -Var::Var(PluginModule* module) : Resource(module) { -} - -Var::~Var() { -} - -// static -PP_Var Var::NPVariantToPPVar(PluginModule* module, const NPVariant* variant) { - switch (variant->type) { - case NPVariantType_Void: - return PP_MakeUndefined(); - case NPVariantType_Null: - return PP_MakeNull(); - case NPVariantType_Bool: - return BoolToPPVar(NPVARIANT_TO_BOOLEAN(*variant)); - case NPVariantType_Int32: - return PP_MakeInt32(NPVARIANT_TO_INT32(*variant)); - case NPVariantType_Double: - return PP_MakeDouble(NPVARIANT_TO_DOUBLE(*variant)); - case NPVariantType_String: - return StringVar::StringToPPVar( - module, - NPVARIANT_TO_STRING(*variant).UTF8Characters, - NPVARIANT_TO_STRING(*variant).UTF8Length); - case NPVariantType_Object: - return ObjectVar::NPObjectToPPVar(module, NPVARIANT_TO_OBJECT(*variant)); - } - NOTREACHED(); - return PP_MakeUndefined(); -} - -// static -NPIdentifier Var::PPVarToNPIdentifier(PP_Var var) { - switch (var.type) { - case PP_VARTYPE_STRING: { - scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); - if (!string) - return NULL; - return WebBindings::getStringIdentifier(string->value().c_str()); - } - case PP_VARTYPE_INT32: - return WebBindings::getIntIdentifier(var.value.as_int); - default: - return NULL; - } -} - -// static -PP_Var Var::NPIdentifierToPPVar(PluginModule* module, NPIdentifier id) { - const NPUTF8* string_value = NULL; - int32_t int_value = 0; - bool is_string = false; - WebBindings::extractIdentifierData(id, string_value, int_value, is_string); - if (is_string) - return StringVar::StringToPPVar(module, string_value); - - return PP_MakeInt32(int_value); -} - -// static -void Var::PluginAddRefPPVar(PP_Var var) { - if (var.type == PP_VARTYPE_STRING || var.type == PP_VARTYPE_OBJECT) { - // TODO(brettw) consider checking that the ID is actually a var ID rather - // than some random other resource ID. - if (!ResourceTracker::Get()->AddRefResource(var.value.as_id)) - DLOG(WARNING) << "AddRefVar()ing a nonexistant string/object var."; - } -} - -// static -void Var::PluginReleasePPVar(PP_Var var) { - if (var.type == PP_VARTYPE_STRING || var.type == PP_VARTYPE_OBJECT) { - // TODO(brettw) consider checking that the ID is actually a var ID rather - // than some random other resource ID. - if (!ResourceTracker::Get()->UnrefResource(var.value.as_id)) - DLOG(WARNING) << "ReleaseVar()ing a nonexistant string/object var."; - } -} - -// static -const PPB_Var_Deprecated* Var::GetDeprecatedInterface() { - return &var_deprecated_interface; -} - -const PPB_Var* Var::GetInterface() { - return &var_interface; -} - -// StringVar ------------------------------------------------------------------- - -StringVar::StringVar(PluginModule* module, const char* str, uint32 len) - : Var(module), - value_(str, len) { -} - -StringVar::~StringVar() { -} - -// static -PP_Var StringVar::StringToPPVar(PluginModule* module, const std::string& var) { - return StringToPPVar(module, var.c_str(), var.size()); -} - -// static -PP_Var StringVar::StringToPPVar(PluginModule* module, - const char* data, uint32 len) { - scoped_refptr<StringVar> str(new StringVar(module, data, len)); - if (!str || !IsStringUTF8(str->value())) - return PP_MakeNull(); - - PP_Var ret; - ret.type = PP_VARTYPE_STRING; - - // The caller takes ownership now. - ret.value.as_id = str->GetReference(); - return ret; -} - -// static -scoped_refptr<StringVar> StringVar::FromPPVar(PP_Var var) { - if (var.type != PP_VARTYPE_STRING) - return scoped_refptr<StringVar>(NULL); - return Resource::GetAs<StringVar>(var.value.as_id); -} - -// ObjectVar ------------------------------------------------------------- - -ObjectVar::ObjectVar(PluginModule* module, NPObject* np_object) - : Var(module), - np_object_(np_object) { - WebBindings::retainObject(np_object_); - module->AddNPObjectVar(this); -} - -ObjectVar::~ObjectVar() { - module()->RemoveNPObjectVar(this); - WebBindings::releaseObject(np_object_); -} - -// static -PP_Var ObjectVar::NPObjectToPPVar(PluginModule* module, NPObject* object) { - scoped_refptr<ObjectVar> object_var(module->ObjectVarForNPObject(object)); - if (!object_var) // No object for this module yet, make a new one. - object_var = new ObjectVar(module, object); - - if (!object_var) - return PP_MakeUndefined(); - - // Convert to a PP_Var, GetReference will AddRef for us. - PP_Var result; - result.type = PP_VARTYPE_OBJECT; - result.value.as_id = object_var->GetReference(); - return result; -} - -// static -scoped_refptr<ObjectVar> ObjectVar::FromPPVar(PP_Var var) { - if (var.type != PP_VARTYPE_OBJECT) - return scoped_refptr<ObjectVar>(NULL); - return Resource::GetAs<ObjectVar>(var.value.as_id); -} - -// TryCatch -------------------------------------------------------------------- - -TryCatch::TryCatch(PluginModule* module, PP_Var* exception) - : module_(module), - has_exception_(exception && exception->type != PP_VARTYPE_UNDEFINED), - exception_(exception) { - WebBindings::pushExceptionHandler(&TryCatch::Catch, this); -} - -TryCatch::~TryCatch() { - WebBindings::popExceptionHandler(); -} - -void TryCatch::SetException(const char* message) { - if (!module_) { - // Don't have a module to make the string. - SetInvalidObjectException(); - return; - } - - if (!has_exception()) { - has_exception_ = true; - if (exception_) - *exception_ = StringVar::StringToPPVar(module_, message, strlen(message)); - } -} - -void TryCatch::SetInvalidObjectException() { - if (!has_exception()) { - has_exception_ = true; - // TODO(brettw) bug 54504: Have a global singleton string that can hold - // a generic error message. - if (exception_) - *exception_ = PP_MakeInt32(1); - } -} - -// static -void TryCatch::Catch(void* self, const char* message) { - static_cast<TryCatch*>(self)->SetException(message); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_var.h b/webkit/glue/plugins/pepper_var.h deleted file mode 100644 index 8929448..0000000 --- a/webkit/glue/plugins/pepper_var.h +++ /dev/null @@ -1,251 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_VAR_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_VAR_H_ - -#include <string> - -#include "webkit/glue/plugins/pepper_resource.h" - -struct PP_Var; -struct PPB_Var; -struct PPB_Var_Deprecated; -typedef struct NPObject NPObject; -typedef struct _NPVariant NPVariant; -typedef void* NPIdentifier; - -namespace pepper { - -// Var ------------------------------------------------------------------------- - -// Represents a non-POD var. This is derived from a resource even though it -// isn't a resource from the plugin's perspective. This allows us to re-use -// the refcounting and the association with the module from the resource code. -class Var : public Resource { - public: - virtual ~Var(); - - // Resource overrides. - virtual Var* AsVar() { return this; } - - // Returns a PP_Var that corresponds to the given NPVariant. The contents of - // the NPVariant will be copied unless the NPVariant corresponds to an - // object. This will handle all Variant types including POD, strings, and - // objects. - // - // The returned PP_Var will have a refcount of 1, this passing ownership of - // the reference to the caller. This is suitable for returning to a plugin. - static PP_Var NPVariantToPPVar(PluginModule* module, - const NPVariant* variant); - - // Returns a NPIdentifier that corresponds to the given PP_Var. The contents - // of the PP_Var will be copied. Returns 0 if the given PP_Var is not a a - // string or integer type. - static NPIdentifier PPVarToNPIdentifier(PP_Var var); - - // Returns a PP_Var corresponding to the given identifier. In the case of - // a string identifier, the string will be allocated associated with the - // given module. A returned string will have a reference count of 1. - static PP_Var NPIdentifierToPPVar(PluginModule* module, NPIdentifier id); - - // Provides access to the manual refcounting of a PP_Var from the plugin's - // perspective. This is different than the AddRef/Release on this scoped - // object. This uses the ResourceTracker, which keeps a separate "plugin - // refcount" that prevents the plugin from messing up our refcounting or - // freeing something out from under us. - // - // You should not generally need to use these functions. However, if you - // call a plugin function that returns a var, it will transfer a ref to us - // (the caller) which in the case of a string or object var will need to - // be released. - // - // Example, assuming we're expecting the plugin to return a string: - // PP_Var rv = some_ppp_interface->DoSomething(a, b, c); - // - // // Get the string value. This will take a reference to the object which - // // will prevent it from being deleted out from under us when we call - // // PluginReleasePPVar(). - // scoped_refptr<StringVar> string(StringVar::FromPPVar(rv)); - // - // // Release the reference the plugin gave us when returning the value. - // // This is legal to do for all types of vars. - // Var::PluginReleasePPVar(rv); - // - // // Use the string. - // if (!string) - // return false; // It didn't return a proper string. - // UseTheString(string->value()); - static void PluginAddRefPPVar(PP_Var var); - static void PluginReleasePPVar(PP_Var var); - - // Returns the PPB_Var_Deprecated interface for the plugin to use. - static const PPB_Var_Deprecated* GetDeprecatedInterface(); - - // Returns the PPB_Var interface for the plugin to use. - static const PPB_Var* GetInterface(); - - protected: - // This can only be constructed as a StringVar or an ObjectVar. - explicit Var(PluginModule* module); - - private: - DISALLOW_COPY_AND_ASSIGN(Var); -}; - -// StringVar ------------------------------------------------------------------- - -// Represents a string-based Var. -// -// Returning a given string as a PP_Var: -// return StringVar::StringToPPVar(module, my_string); -// -// Converting a PP_Var to a string: -// scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); -// if (!string) -// return false; // Not a string or an invalid var. -// DoSomethingWithTheString(string->value()); -class StringVar : public Var { - public: - StringVar(PluginModule* module, const char* str, uint32 len); - virtual ~StringVar(); - - const std::string& value() const { return value_; } - - // Resource overrides. - virtual StringVar* AsStringVar() { return this; } - - // Helper function to create a PP_Var of type string that contains a copy of - // the given string. The input data must be valid UTF-8 encoded text, if it - // is not valid UTF-8, a NULL var will be returned. - // - // The return value will have a reference count of 1. Internally, this will - // create a StringVar, associate it with a module, and return the reference - // to it in the var. - static PP_Var StringToPPVar(PluginModule* module, const std::string& str); - static PP_Var StringToPPVar(PluginModule* module, - const char* str, uint32 len); - - // Helper function that converts a PP_Var to a string. This will return NULL - // if the PP_Var is not of string type or the string is invalid. - static scoped_refptr<StringVar> FromPPVar(PP_Var var); - - private: - std::string value_; - - DISALLOW_COPY_AND_ASSIGN(StringVar); -}; - -// ObjectVar ------------------------------------------------------------------- - -// Represents a JavaScript object Var. By itself, this represents random -// NPObjects that a given plugin (identified by the resource's module) wants to -// reference. If two different modules reference the same NPObject (like the -// "window" object), then there will be different ObjectVar's (and hence PP_Var -// IDs) for each module. This allows us to track all references owned by a -// given module and free them when the plugin exits independently of other -// plugins that may be running at the same time. -// -// See StringVar for examples, except obviously using NPObjects instead of -// strings. -class ObjectVar : public Var { - public: - virtual ~ObjectVar(); - - // Resource overrides. - virtual ObjectVar* AsObjectVar() { return this; } - - // Returns the underlying NPObject corresponding to this ObjectVar. - // Guaranteed non-NULL. - NPObject* np_object() const { return np_object_; } - - // Helper function to create a PP_Var of type object that contains the given - // NPObject for use byt he given module. Calling this function multiple times - // given the same module + NPObject results in the same PP_Var, assuming that - // there is still a PP_Var with a reference open to it from the previous - // call. - // - // The module is necessary because we can have different modules pointing to - // the same NPObject, and we want to keep their refs separate. - // - // If no ObjectVar currently exists corresponding to the NPObject, one is - // created associated with the given module. - static PP_Var NPObjectToPPVar(PluginModule* module, NPObject* object); - - // Helper function that converts a PP_Var to an object. This will return NULL - // if the PP_Var is not of object type or the object is invalid. - static scoped_refptr<ObjectVar> FromPPVar(PP_Var var); - - protected: - // You should always use FromNPObject to create an ObjectVar. This function - // guarantees that we maintain the 1:1 mapping between NPObject and - // ObjectVar. - ObjectVar(PluginModule* module, NPObject* np_object); - - private: - // Guaranteed non-NULL, this is the underlying object used by WebKit. We - // hold a reference to this object. - NPObject* np_object_; - - DISALLOW_COPY_AND_ASSIGN(ObjectVar); -}; - -// TryCatch -------------------------------------------------------------------- - -// Instantiate this object on the stack to catch V8 exceptions and pass them -// to an optional out parameter supplied by the plugin. -class TryCatch { - public: - // The given exception may be NULL if the consumer isn't interested in - // catching exceptions. If non-NULL, the given var will be updated if any - // exception is thrown (so it must outlive the TryCatch object). - // - // The module associated with the exception is passed so we know which module - // to associate any exception string with. It may be NULL if you don't know - // the module at construction time, in which case you should set it later - // by calling set_module(). - // - // If an exception is thrown when the module is NULL, setting *any* exception - // will result in using the InvalidObjectException. - TryCatch(PluginModule* module, PP_Var* exception); - ~TryCatch(); - - // Get and set the module. This may be NULL (see the constructor). - PluginModule* module() { return module_; } - void set_module(PluginModule* module) { module_ = module; } - - // Returns true is an exception has been thrown. This can be true immediately - // after construction if the var passed to the constructor is non-void. - bool has_exception() const { return has_exception_; } - - // Sets the given exception. If no module has been set yet, the message will - // be ignored (since we have no module to associate the string with) and the - // SetInvalidObjectException() will be used instead. - // - // If an exception has been previously set, this function will do nothing - // (normally you want only the first exception). - void SetException(const char* message); - - // Sets the exception to be a generic message contained in a magic string - // not associated with any module. - void SetInvalidObjectException(); - - private: - static void Catch(void* self, const char* message); - - PluginModule* module_; - - // True if an exception has been thrown. Since the exception itself may be - // NULL if the plugin isn't interested in getting the exception, this will - // always indicate if SetException has been called, regardless of whether - // the exception itself has been stored. - bool has_exception_; - - // May be null if the consumer isn't interesting in catching exceptions. - PP_Var* exception_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_VAR_H_ diff --git a/webkit/glue/plugins/pepper_video_decoder.cc b/webkit/glue/plugins/pepper_video_decoder.cc deleted file mode 100644 index cd4d3b5..0000000 --- a/webkit/glue/plugins/pepper_video_decoder.cc +++ /dev/null @@ -1,141 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_video_decoder.h" - -#include "base/logging.h" -#include "ppapi/c/dev/pp_video_dev.h" -#include "ppapi/c/dev/ppb_video_decoder_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_file_ref.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_resource_tracker.h" - -namespace pepper { - -namespace { - -PP_Bool GetConfig(PP_Instance instance_id, - PP_VideoCodecId_Dev codec, - PP_VideoConfig_Dev* configs, - int32_t config_size, - int32_t *num_config) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - *num_config = 0; - if (!instance) - return PP_FALSE; - - // Get configs based on codec. - - if (configs) { - // Fill in the array of configs. - } - - // Update *num_config. - - return PP_TRUE; -} - -PP_Resource Create(PP_Instance instance_id, - const PP_VideoDecoderConfig_Dev* decoder_config) { - PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id); - if (!instance) - return 0; - - scoped_refptr<VideoDecoder> decoder(new VideoDecoder(instance)); - - if (!decoder->Init(*decoder_config)) - return 0; - - return decoder->GetReference(); -} - -PP_Bool Decode(PP_Resource decoder_id, - PP_VideoCompressedDataBuffer_Dev* input_buffer) { - scoped_refptr<VideoDecoder> decoder( - Resource::GetAs<VideoDecoder>(decoder_id)); - if (!decoder) - return PP_FALSE; - - decoder->Decode(*input_buffer); - return PP_TRUE; -} - -int32_t Flush(PP_Resource decoder_id, PP_CompletionCallback callback) { - scoped_refptr<VideoDecoder> decoder( - Resource::GetAs<VideoDecoder>(decoder_id)); - if (!decoder) - return PP_ERROR_BADRESOURCE; - - return decoder->Flush(callback); -} - -PP_Bool ReturnUncompressedDataBuffer(PP_Resource decoder_id, - PP_VideoUncompressedDataBuffer_Dev* buffer) { - scoped_refptr<VideoDecoder> decoder( - Resource::GetAs<VideoDecoder>(decoder_id)); - if (!decoder) - return PP_FALSE; - - return BoolToPPBool(decoder->ReturnUncompressedDataBuffer(*buffer)); -} - -const PPB_VideoDecoder_Dev ppb_videodecoder = { - &GetConfig, - &Create, - &Decode, - &Flush, - &ReturnUncompressedDataBuffer -}; - -} // namespace - -VideoDecoder::VideoDecoder(PluginInstance* instance) - : Resource(instance->module()), - instance_(instance) { -} - -VideoDecoder::~VideoDecoder() { -} - -// static -const PPB_VideoDecoder_Dev* VideoDecoder::GetInterface() { - return &ppb_videodecoder; -} - -bool VideoDecoder::Init(const PP_VideoDecoderConfig_Dev& decoder_config) { - if (!instance()) - return false; - - platform_video_decoder_.reset( - instance()->delegate()->CreateVideoDecoder(decoder_config)); - - return platform_video_decoder_.get()? true : false; -} - -bool VideoDecoder::Decode(PP_VideoCompressedDataBuffer_Dev& input_buffer) { - if (!platform_video_decoder_.get()) - return false; - - return platform_video_decoder_->Decode(input_buffer); -} - -int32_t VideoDecoder::Flush(PP_CompletionCallback& callback) { - if (!platform_video_decoder_.get()) - return PP_ERROR_FAILED; - - return platform_video_decoder_->Flush(callback); -} - -bool VideoDecoder::ReturnUncompressedDataBuffer( - PP_VideoUncompressedDataBuffer_Dev& buffer) { - if (!platform_video_decoder_.get()) - return false; - - return platform_video_decoder_->ReturnUncompressedDataBuffer(buffer); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_video_decoder.h b/webkit/glue/plugins/pepper_video_decoder.h deleted file mode 100644 index c828709..0000000 --- a/webkit/glue/plugins/pepper_video_decoder.h +++ /dev/null @@ -1,50 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_VIDEO_DECODER_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_VIDEO_DECODER_H_ - -#include "base/scoped_ptr.h" -#include "webkit/glue/plugins/pepper_plugin_delegate.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PP_VideoDecoderConfig_Dev; -struct PP_VideoCompressedDataBuffer_Dev; -struct PP_VideoUncompressedDataBuffer_Dev; -struct PPB_VideoDecoder_Dev; - -namespace pepper { - -class PluginInstance; - -class VideoDecoder : public Resource { - public: - VideoDecoder(PluginInstance* instance); - virtual ~VideoDecoder(); - - // Returns a pointer to the interface implementing PPB_VideoDecoder that is - // exposed to the plugin. - static const PPB_VideoDecoder_Dev* GetInterface(); - - // Resource overrides. - VideoDecoder* AsVideoDecoder() { return this; } - - PluginInstance* instance() { return instance_.get(); } - - // PPB_VideoDecoder implementation. - bool Init(const PP_VideoDecoderConfig_Dev& decoder_config); - bool Decode(PP_VideoCompressedDataBuffer_Dev& input_buffer); - int32_t Flush(PP_CompletionCallback& callback); - bool ReturnUncompressedDataBuffer(PP_VideoUncompressedDataBuffer_Dev& buffer); - - private: - // This is NULL before initialization, and if this VideoDecoder is - // swapped with another. - scoped_ptr<PluginDelegate::PlatformVideoDecoder> platform_video_decoder_; - scoped_refptr<PluginInstance> instance_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_VIDEO_DECODER_H_ diff --git a/webkit/glue/plugins/pepper_webplugin_impl.cc b/webkit/glue/plugins/pepper_webplugin_impl.cc deleted file mode 100644 index 8da398f..0000000 --- a/webkit/glue/plugins/pepper_webplugin_impl.cc +++ /dev/null @@ -1,226 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_webplugin_impl.h" - -#include <cmath> - -#include "base/message_loop.h" -#include "ppapi/c/pp_var.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" -#include "webkit/glue/plugins/pepper_url_loader.h" -#include "webkit/glue/plugins/pepper_var.h" - -using WebKit::WebCanvas; -using WebKit::WebPluginContainer; -using WebKit::WebPluginParams; -using WebKit::WebPoint; -using WebKit::WebRect; -using WebKit::WebString; -using WebKit::WebURL; -using WebKit::WebVector; -using WebKit::WebView; - -namespace pepper { - -struct WebPluginImpl::InitData { - scoped_refptr<PluginModule> module; - base::WeakPtr<PluginDelegate> delegate; - std::vector<std::string> arg_names; - std::vector<std::string> arg_values; -}; - -WebPluginImpl::WebPluginImpl( - PluginModule* plugin_module, - const WebPluginParams& params, - const base::WeakPtr<PluginDelegate>& plugin_delegate) - : init_data_(new InitData()), - full_frame_(params.loadManually) { - DCHECK(plugin_module); - init_data_->module = plugin_module; - init_data_->delegate = plugin_delegate; - for (size_t i = 0; i < params.attributeNames.size(); ++i) { - init_data_->arg_names.push_back(params.attributeNames[i].utf8()); - init_data_->arg_values.push_back(params.attributeValues[i].utf8()); - } -} - -WebPluginImpl::~WebPluginImpl() { -} - -bool WebPluginImpl::initialize(WebPluginContainer* container) { - // The plugin delegate may have gone away. - if (!init_data_->delegate) - return false; - - instance_ = init_data_->module->CreateInstance(init_data_->delegate); - if (!instance_) - return false; - - bool success = instance_->Initialize(container, - init_data_->arg_names, - init_data_->arg_values, - full_frame_); - if (!success) { - instance_->Delete(); - instance_ = NULL; - return false; - } - - init_data_.reset(); - return true; -} - -void WebPluginImpl::destroy() { - if (instance_) { - instance_->Delete(); - instance_ = NULL; - } - - MessageLoop::current()->DeleteSoon(FROM_HERE, this); -} - -NPObject* WebPluginImpl::scriptableObject() { - scoped_refptr<ObjectVar> object( - ObjectVar::FromPPVar(instance_->GetInstanceObject())); - if (object) - return object->np_object(); - return NULL; -} - -void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& rect) { - if (!instance_->IsFullscreen()) - instance_->Paint(canvas, plugin_rect_, rect); -} - -void WebPluginImpl::updateGeometry( - const WebRect& window_rect, - const WebRect& clip_rect, - const WebVector<WebRect>& cut_outs_rects, - bool is_visible) { - plugin_rect_ = window_rect; - if (!instance_->IsFullscreen()) - instance_->ViewChanged(plugin_rect_, clip_rect); -} - -unsigned WebPluginImpl::getBackingTextureId() { - return instance_->GetBackingTextureId(); -} - -void WebPluginImpl::updateFocus(bool focused) { - instance_->SetWebKitFocus(focused); -} - -void WebPluginImpl::updateVisibility(bool visible) { -} - -bool WebPluginImpl::acceptsInputEvents() { - return true; -} - -bool WebPluginImpl::handleInputEvent(const WebKit::WebInputEvent& event, - WebKit::WebCursorInfo& cursor_info) { - if (instance_->IsFullscreen()) - return false; - return instance_->HandleInputEvent(event, &cursor_info); -} - -void WebPluginImpl::didReceiveResponse( - const WebKit::WebURLResponse& response) { - DCHECK(!document_loader_); - - document_loader_ = new URLLoader(instance_, true); - document_loader_->didReceiveResponse(NULL, response); - - if (!instance_->HandleDocumentLoad(document_loader_)) - document_loader_ = NULL; -} - -void WebPluginImpl::didReceiveData(const char* data, int data_length) { - if (document_loader_) - document_loader_->didReceiveData(NULL, data, data_length); -} - -void WebPluginImpl::didFinishLoading() { - if (document_loader_) { - document_loader_->didFinishLoading(NULL, 0); - document_loader_ = NULL; - } -} - -void WebPluginImpl::didFailLoading(const WebKit::WebURLError& error) { - if (document_loader_) { - document_loader_->didFail(NULL, error); - document_loader_ = NULL; - } -} - -void WebPluginImpl::didFinishLoadingFrameRequest(const WebKit::WebURL& url, - void* notify_data) { -} - -void WebPluginImpl::didFailLoadingFrameRequest( - const WebKit::WebURL& url, - void* notify_data, - const WebKit::WebURLError& error) { -} - -bool WebPluginImpl::hasSelection() const { - return !selectionAsText().isEmpty(); -} - -WebString WebPluginImpl::selectionAsText() const { - return instance_->GetSelectedText(false); -} - -WebString WebPluginImpl::selectionAsMarkup() const { - return instance_->GetSelectedText(true); -} - -WebURL WebPluginImpl::linkAtPosition(const WebPoint& position) const { - return GURL(instance_->GetLinkAtPosition(position)); -} - -void WebPluginImpl::setZoomLevel(double level, bool text_only) { - instance_->Zoom(WebView::zoomLevelToZoomFactor(level), text_only); -} - -bool WebPluginImpl::startFind(const WebKit::WebString& search_text, - bool case_sensitive, - int identifier) { - return instance_->StartFind(search_text, case_sensitive, identifier); -} - -void WebPluginImpl::selectFindResult(bool forward) { - instance_->SelectFindResult(forward); -} - -void WebPluginImpl::stopFind() { - instance_->StopFind(); -} - -bool WebPluginImpl::supportsPaginatedPrint() { - return instance_->SupportsPrintInterface(); -} - -int WebPluginImpl::printBegin(const WebKit::WebRect& printable_area, - int printer_dpi) { - return instance_->PrintBegin(printable_area, printer_dpi); -} - -bool WebPluginImpl::printPage(int page_number, - WebKit::WebCanvas* canvas) { - return instance_->PrintPage(page_number, canvas); -} - -void WebPluginImpl::printEnd() { - return instance_->PrintEnd(); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_webplugin_impl.h b/webkit/glue/plugins/pepper_webplugin_impl.h deleted file mode 100644 index 8922143..0000000 --- a/webkit/glue/plugins/pepper_webplugin_impl.h +++ /dev/null @@ -1,95 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_WEBPLUGIN_IMPL_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_WEBPLUGIN_IMPL_H_ - -#include <string> -#include <vector> - -#include "base/weak_ptr.h" -#include "base/scoped_ptr.h" -#include "base/task.h" -#include "gfx/rect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPlugin.h" - -namespace WebKit { -struct WebPluginParams; -} - -namespace pepper { - -class PluginDelegate; -class PluginInstance; -class PluginModule; -class URLLoader; - -class WebPluginImpl : public WebKit::WebPlugin { - public: - WebPluginImpl(PluginModule* module, - const WebKit::WebPluginParams& params, - const base::WeakPtr<PluginDelegate>& plugin_delegate); - - private: - friend class DeleteTask<WebPluginImpl>; - - ~WebPluginImpl(); - - // WebKit::WebPlugin implementation. - virtual bool initialize(WebKit::WebPluginContainer* container); - virtual void destroy(); - virtual NPObject* scriptableObject(); - virtual void paint(WebKit::WebCanvas* canvas, const WebKit::WebRect& rect); - virtual void updateGeometry( - const WebKit::WebRect& frame_rect, - const WebKit::WebRect& clip_rect, - const WebKit::WebVector<WebKit::WebRect>& cut_outs_rects, - bool is_visible); - virtual unsigned getBackingTextureId(); - virtual void updateFocus(bool focused); - virtual void updateVisibility(bool visible); - virtual bool acceptsInputEvents(); - virtual bool handleInputEvent(const WebKit::WebInputEvent& event, - WebKit::WebCursorInfo& cursor_info); - virtual void didReceiveResponse(const WebKit::WebURLResponse& response); - virtual void didReceiveData(const char* data, int data_length); - virtual void didFinishLoading(); - virtual void didFailLoading(const WebKit::WebURLError&); - virtual void didFinishLoadingFrameRequest(const WebKit::WebURL& url, - void* notify_data); - virtual void didFailLoadingFrameRequest(const WebKit::WebURL& url, - void* notify_data, - const WebKit::WebURLError& error); - virtual bool hasSelection() const; - virtual WebKit::WebString selectionAsText() const; - virtual WebKit::WebString selectionAsMarkup() const; - virtual WebKit::WebURL linkAtPosition(const WebKit::WebPoint& position) const; - virtual void setZoomLevel(double level, bool text_only); - virtual bool startFind(const WebKit::WebString& search_text, - bool case_sensitive, - int identifier); - virtual void selectFindResult(bool forward); - virtual void stopFind(); - virtual bool supportsPaginatedPrint(); - virtual int printBegin(const WebKit::WebRect& printable_area, - int printer_dpi); - virtual bool printPage(int page_number, WebKit::WebCanvas* canvas); - virtual void printEnd(); - - struct InitData; - - scoped_ptr<InitData> init_data_; // Cleared upon successful initialization. - // True if the instance represents the entire document in a frame instead of - // being an embedded resource. - bool full_frame_; - scoped_refptr<PluginInstance> instance_; - scoped_refptr<URLLoader> document_loader_; - gfx::Rect plugin_rect_; - - DISALLOW_COPY_AND_ASSIGN(WebPluginImpl); -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_WEBPLUGIN_IMPL_H_ diff --git a/webkit/glue/plugins/pepper_widget.cc b/webkit/glue/plugins/pepper_widget.cc deleted file mode 100644 index e704e8c..0000000 --- a/webkit/glue/plugins/pepper_widget.cc +++ /dev/null @@ -1,95 +0,0 @@ -// 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 "webkit/glue/plugins/pepper_widget.h" - -#include "base/logging.h" -#include "ppapi/c/dev/ppb_widget_dev.h" -#include "ppapi/c/dev/ppp_widget_dev.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "webkit/glue/plugins/pepper_common.h" -#include "webkit/glue/plugins/pepper_image_data.h" -#include "webkit/glue/plugins/pepper_plugin_instance.h" -#include "webkit/glue/plugins/pepper_plugin_module.h" - -namespace pepper { - -namespace { - -PP_Bool IsWidget(PP_Resource resource) { - return BoolToPPBool(!!Resource::GetAs<Widget>(resource)); -} - -PP_Bool Paint(PP_Resource resource, const PP_Rect* rect, PP_Resource image_id) { - scoped_refptr<Widget> widget(Resource::GetAs<Widget>(resource)); - if (!widget) - return PP_FALSE; - - scoped_refptr<ImageData> image(Resource::GetAs<ImageData>(image_id)); - if (!image) - return PP_FALSE; - - return BoolToPPBool(widget->Paint(rect, image)); -} - -PP_Bool HandleEvent(PP_Resource resource, const PP_InputEvent* event) { - scoped_refptr<Widget> widget(Resource::GetAs<Widget>(resource)); - return BoolToPPBool(widget && widget->HandleEvent(event)); -} - -PP_Bool GetLocation(PP_Resource resource, PP_Rect* location) { - scoped_refptr<Widget> widget(Resource::GetAs<Widget>(resource)); - return BoolToPPBool(widget && widget->GetLocation(location)); -} - -void SetLocation(PP_Resource resource, const PP_Rect* location) { - scoped_refptr<Widget> widget(Resource::GetAs<Widget>(resource)); - if (widget) - widget->SetLocation(location); -} - -const PPB_Widget_Dev ppb_widget = { - &IsWidget, - &Paint, - &HandleEvent, - &GetLocation, - &SetLocation, -}; - -} // namespace - -Widget::Widget(PluginInstance* instance) - : Resource(instance->module()), - instance_(instance) { -} - -Widget::~Widget() { -} - -// static -const PPB_Widget_Dev* Widget::GetInterface() { - return &ppb_widget; -} - -bool Widget::GetLocation(PP_Rect* location) { - *location = location_; - return true; -} - -void Widget::SetLocation(const PP_Rect* location) { - location_ = *location; - SetLocationInternal(location); -} - -void Widget::Invalidate(const PP_Rect* dirty) { - const PPP_Widget_Dev* widget = static_cast<const PPP_Widget_Dev*>( - module()->GetPluginInterface(PPP_WIDGET_DEV_INTERFACE)); - if (!widget) - return; - ScopedResourceId resource(this); - widget->Invalidate(instance_->pp_instance(), resource.id, dirty); -} - -} // namespace pepper diff --git a/webkit/glue/plugins/pepper_widget.h b/webkit/glue/plugins/pepper_widget.h deleted file mode 100644 index cf937bd..0000000 --- a/webkit/glue/plugins/pepper_widget.h +++ /dev/null @@ -1,53 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PEPPER_WIDGET_H_ -#define WEBKIT_GLUE_PLUGINS_PEPPER_WIDGET_H_ - -#include "base/scoped_ptr.h" -#include "ppapi/c/pp_rect.h" -#include "webkit/glue/plugins/pepper_resource.h" - -struct PPB_Widget_Dev; -struct PP_InputEvent; - -namespace pepper { - -class ImageData; -class PluginInstance; - -class Widget : public Resource { - public: - explicit Widget(PluginInstance* instance); - virtual ~Widget(); - - // Returns a pointer to the interface implementing PPB_Widget that is - // exposed to the plugin. - static const PPB_Widget_Dev* GetInterface(); - - // Resource overrides. - Widget* AsWidget() { return this; } - - // PPB_Widget implementation. - virtual bool Paint(const PP_Rect* rect, ImageData* image) = 0; - virtual bool HandleEvent(const PP_InputEvent* event) = 0; - bool GetLocation(PP_Rect* location); - void SetLocation(const PP_Rect* location); - - // Notifies the plugin instance that the given rect needs to be repainted. - void Invalidate(const PP_Rect* dirty); - PluginInstance* instance() { return instance_; } - - protected: - virtual void SetLocationInternal(const PP_Rect* location) = 0; - PP_Rect location() const { return location_; } - - private: - scoped_refptr<PluginInstance> instance_; - PP_Rect location_; -}; - -} // namespace pepper - -#endif // WEBKIT_GLUE_PLUGINS_PEPPER_WIDGET_H_ diff --git a/webkit/glue/plugins/plugin_constants_win.h b/webkit/glue/plugins/plugin_constants_win.h deleted file mode 100644 index 9913e5d..0000000 --- a/webkit/glue/plugins/plugin_constants_win.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGIN_CONSTANTS_WIN_H_ -#define WEBKIT_GLUE_PLUGIN_CONSTANTS_WIN_H_ - -// Used by the plugins_test when testing the older WMP plugin to force the new -// plugin to not get loaded. -#define kUseOldWMPPluginSwitch "use-old-wmp" - -// The window class name for a plugin window. -#define kNativeWindowClassName L"NativeWindowClass" - -// The name of the window class name for the wrapper HWND around the actual -// plugin window that's used when running in multi-process mode. This window -// is created on the browser UI thread. -#define kWrapperNativeWindowClassName L"WrapperNativeWindowClass" - -// The name of the custom window message that the browser uses to tell the -// plugin process to paint a window. -#define kPaintMessageName L"Chrome_CustomPaint" - -// The name of the registry key which NPAPI plugins update on installation. -#define kRegistryMozillaPlugins L"SOFTWARE\\MozillaPlugins" - -#define kMozillaActiveXPlugin L"npmozax.dll" -#define kNewWMPPlugin L"np-mswmp.dll" -#define kOldWMPPlugin L"npdsplay.dll" -#define kYahooApplicationStatePlugin L"npystate.dll" -#define kWanWangProtocolHandlerPlugin L"npww.dll" -#define kFlashPlugin L"npswf32.dll" -#define kAcrobatReaderPlugin L"nppdf32.dll" -#define kRealPlayerPlugin L"nppl3260.dll" -#define kSilverlightPlugin L"npctrl.dll" -#define kJavaPlugin1 L"npjp2.dll" -#define kJavaPlugin2 L"npdeploytk.dll" - -#define kGPUPluginMimeType "application/vnd.google.chrome.gpu-plugin" - -#endif // WEBKIT_GLUE_PLUGIN_PLUGIN_LIST_H_ diff --git a/webkit/glue/plugins/plugin_group.cc b/webkit/glue/plugins/plugin_group.cc deleted file mode 100644 index e68649c..0000000 --- a/webkit/glue/plugins/plugin_group.cc +++ /dev/null @@ -1,419 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_group.h" - -#include "base/linked_ptr.h" -#include "base/string_util.h" -#include "base/sys_string_conversions.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "base/version.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/webplugininfo.h" - -const char* PluginGroup::kAdobeReader8GroupName = "Adobe Reader 8"; -const char* PluginGroup::kAdobeReader9GroupName = "Adobe Reader 9"; - -#if defined(OS_MACOSX) -// Plugin Groups for Mac. -// Plugins are listed here as soon as vulnerabilities and solutions -// (new versions) are published. -// TODO(panayiotis): Get the Real Player version on Mac, somehow. -static const PluginGroupDefinition kGroupDefinitions[] = { - { "apple-quicktime", "Quicktime", "QuickTime Plug-in", "", "", "7.6.6", - "http://www.apple.com/quicktime/download/" }, - { "java-runtime-environment", "Java", "Java", "", "", "", - "http://support.apple.com/kb/HT1338" }, - { "adobe-flash-player", "Flash", "Shockwave Flash", "", "", "10.1.102", - "http://get.adobe.com/flashplayer/" }, - { "silverlight-3", "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", - "http://www.microsoft.com/getsilverlight/" }, - { "silverlight-4", "Silverlight 4", "Silverlight", "4", "5", "", - "http://www.microsoft.com/getsilverlight/" }, - { "flip4mac", "Flip4Mac", "Flip4Mac", "", "", "2.2.1", - "http://www.telestream.net/flip4mac-wmv/overview.htm" }, - { "shockwave", "Shockwave", "Shockwave for Director", "", "", "11.5.9.615", - "http://www.adobe.com/shockwave/download/" } -}; - -#elif defined(OS_WIN) -// TODO(panayiotis): We should group "RealJukebox NS Plugin" with the rest of -// the RealPlayer files. -static const PluginGroupDefinition kGroupDefinitions[] = { - { "apple-quicktime", "Quicktime", "QuickTime Plug-in", "", "", "7.6.8", - "http://www.apple.com/quicktime/download/" }, - { "java-runtime-environment", "Java 6", "Java", "", "6", "6.0.220", - "http://www.java.com/" }, - { "adobe-reader", PluginGroup::kAdobeReader9GroupName, "Adobe Acrobat", "9", - "10", "9.4.1", "http://get.adobe.com/reader/" }, - { "adobe-reader-8", PluginGroup::kAdobeReader8GroupName, "Adobe Acrobat", "0", - "9", "8.2.5", "http://get.adobe.com/reader/" }, - { "adobe-flash-player", "Flash", "Shockwave Flash", "", "", "10.1.102", - "http://get.adobe.com/flashplayer/" }, - { "silverlight-3", "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", - "http://www.microsoft.com/getsilverlight/" }, - { "silverlight-4", "Silverlight 4", "Silverlight", "4", "5", "", - "http://www.microsoft.com/getsilverlight/" }, - { "shockwave", "Shockwave", "Shockwave for Director", "", "", "11.5.9.615", - "http://www.adobe.com/shockwave/download/" }, - { "divx-player", "DivX Player", "DivX Web Player", "", "", "1.4.3.4", - "http://download.divx.com/divx/autoupdate/player/" - "DivXWebPlayerInstaller.exe" }, - // These are here for grouping, no vulnerabilies known. - { "windows-media-player", "Windows Media Player", "Windows Media Player", - "", "", "", "" }, - { "microsoft-office", "Microsoft Office", "Microsoft Office", - "", "", "", "" }, - // TODO(panayiotis): The vulnerable versions are - // (v >= 6.0.12.1040 && v <= 6.0.12.1663) - // || v == 6.0.12.1698 || v == 6.0.12.1741 - { "realplayer", "RealPlayer", "RealPlayer", "", "", "", - "http://www.adobe.com/shockwave/download/" }, -}; - -#else -static const PluginGroupDefinition kGroupDefinitions[] = {}; -#endif - -/*static*/ -std::set<string16>* PluginGroup::policy_disabled_plugin_patterns_; - -/*static*/ -const PluginGroupDefinition* PluginGroup::GetPluginGroupDefinitions() { - return kGroupDefinitions; -} - -/*static*/ -size_t PluginGroup::GetPluginGroupDefinitionsSize() { - // TODO(viettrungluu): |arraysize()| doesn't work with zero-size arrays. - return ARRAYSIZE_UNSAFE(kGroupDefinitions); -} - -/*static*/ -void PluginGroup::SetPolicyDisabledPluginPatterns( - const std::set<string16>& set) { - if (!policy_disabled_plugin_patterns_) - policy_disabled_plugin_patterns_ = new std::set<string16>(set); - else - *policy_disabled_plugin_patterns_ = set; -} - -/*static*/ -bool PluginGroup::IsPluginNameDisabledByPolicy(const string16& plugin_name) { - if (!policy_disabled_plugin_patterns_) - return false; - - std::set<string16>::const_iterator pattern( - policy_disabled_plugin_patterns_->begin()); - while (pattern != policy_disabled_plugin_patterns_->end()) { - if (MatchPattern(plugin_name, *pattern)) - return true; - ++pattern; - } - - return false; -} - -/*static*/ -bool PluginGroup::IsPluginPathDisabledByPolicy(const FilePath& plugin_path) { - std::vector<WebPluginInfo> plugins; - NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); - for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); - it != plugins.end(); - ++it) { - if (FilePath::CompareEqualIgnoreCase(it->path.value(), - plugin_path.value()) && IsPluginNameDisabledByPolicy(it->name)) { - return true; - } - } - return false; -} - -PluginGroup::PluginGroup(const string16& group_name, - const string16& name_matcher, - const std::string& version_range_low, - const std::string& version_range_high, - const std::string& min_version, - const std::string& update_url, - const std::string& identifier) - : identifier_(identifier), - group_name_(group_name), - name_matcher_(name_matcher), - version_range_low_str_(version_range_low), - version_range_high_str_(version_range_high), - update_url_(update_url), - enabled_(false), - min_version_str_(min_version), - version_(Version::GetVersionFromString("0")) { - if (!version_range_low.empty()) - version_range_low_.reset(Version::GetVersionFromString(version_range_low)); - if (!version_range_high.empty()) { - version_range_high_.reset( - Version::GetVersionFromString(version_range_high)); - } - if (!min_version.empty()) - min_version_.reset(Version::GetVersionFromString(min_version)); -} - -PluginGroup* PluginGroup::FromPluginGroupDefinition( - const PluginGroupDefinition& definition) { - return new PluginGroup(ASCIIToUTF16(definition.name), - ASCIIToUTF16(definition.name_matcher), - definition.version_matcher_low, - definition.version_matcher_high, - definition.min_version, - definition.update_url, - definition.identifier); -} - -PluginGroup::~PluginGroup() { } - -PluginGroup* PluginGroup::FromWebPluginInfo(const WebPluginInfo& wpi) { - // Create a matcher from the name of this plugin. -#if defined(OS_POSIX) - std::string identifier = wpi.path.BaseName().value(); -#elif defined(OS_WIN) - std::string identifier = base::SysWideToUTF8(wpi.path.BaseName().value()); -#endif - return new PluginGroup(wpi.name, wpi.name, std::string(), std::string(), - std::string(), std::string(), identifier); -} - -PluginGroup* PluginGroup::CopyOrCreatePluginGroup( - const WebPluginInfo& info) { - static PluginMap* hardcoded_plugin_groups = NULL; - if (!hardcoded_plugin_groups) { - PluginMap* groups = new PluginMap(); - const PluginGroupDefinition* definitions = GetPluginGroupDefinitions(); - for (size_t i = 0; i < GetPluginGroupDefinitionsSize(); ++i) { - PluginGroup* definition_group = PluginGroup::FromPluginGroupDefinition( - definitions[i]); - std::string identifier = definition_group->identifier(); - DCHECK(groups->find(identifier) == groups->end()); - (*groups)[identifier] = linked_ptr<PluginGroup>(definition_group); - } - hardcoded_plugin_groups = groups; - } - - // See if this plugin matches any of the hardcoded groups. - PluginGroup* hardcoded_group = FindGroupMatchingPlugin( - *hardcoded_plugin_groups, info); - if (hardcoded_group) { - // Make a copy. - return hardcoded_group->Copy(); - } else { - // Not found in our hardcoded list, create a new one. - return PluginGroup::FromWebPluginInfo(info); - } -} - -PluginGroup* PluginGroup::FindGroupMatchingPlugin( - const PluginMap& plugin_groups, - const WebPluginInfo& plugin) { - for (std::map<std::string, linked_ptr<PluginGroup> >::const_iterator it = - plugin_groups.begin(); - it != plugin_groups.end(); - ++it) { - if (it->second->Match(plugin)) - return it->second.get(); - } - return NULL; -} - -bool PluginGroup::Match(const WebPluginInfo& plugin) const { - if (name_matcher_.empty()) { - return false; - } - - // Look for the name matcher anywhere in the plugin name. - if (plugin.name.find(name_matcher_) == string16::npos) { - return false; - } - - if (version_range_low_.get() == NULL || - version_range_high_.get() == NULL) { - return true; - } - - // There's a version range, we must be in it. - scoped_ptr<Version> plugin_version( - Version::GetVersionFromString(UTF16ToWide(plugin.version))); - if (plugin_version.get() == NULL) { - // No version could be extracted, assume we don't match the range. - return false; - } - - // We match if we are in the range: [low, high) - return (version_range_low_->CompareTo(*plugin_version) <= 0 && - version_range_high_->CompareTo(*plugin_version) > 0); -} - -Version* PluginGroup::CreateVersionFromString(const string16& version_string) { - // Remove spaces and ')' from the version string, - // Replace any instances of 'r', ',' or '(' with a dot. - std::wstring version = UTF16ToWide(version_string); - RemoveChars(version, L") ", &version); - std::replace(version.begin(), version.end(), 'r', '.'); - std::replace(version.begin(), version.end(), ',', '.'); - std::replace(version.begin(), version.end(), '(', '.'); - - return Version::GetVersionFromString(version); -} - -void PluginGroup::UpdateActivePlugin(const WebPluginInfo& plugin) { - // A group is enabled if any of the files are enabled. - if (plugin.enabled) { - if (!enabled_) { - // If this is the first enabled plugin, use its description. - enabled_ = true; - UpdateDescriptionAndVersion(plugin); - } - } else { - // If this is the first plugin and it's disabled, - // use its description for now. - if (description_.empty()) - UpdateDescriptionAndVersion(plugin); - } -} - -void PluginGroup::UpdateDescriptionAndVersion(const WebPluginInfo& plugin) { - description_ = plugin.desc; - if (Version* new_version = CreateVersionFromString(plugin.version)) - version_.reset(new_version); - else - version_.reset(Version::GetVersionFromString("0")); -} - -void PluginGroup::AddPlugin(const WebPluginInfo& plugin, int position) { - web_plugin_infos_.push_back(plugin); - // The position of this plugin relative to the global list of plugins. - web_plugin_positions_.push_back(position); - UpdateActivePlugin(plugin); -} - -string16 PluginGroup::GetGroupName() const { - if (!group_name_.empty()) - return group_name_; - DCHECK_EQ(1u, web_plugin_infos_.size()); - FilePath::StringType path = - web_plugin_infos_[0].path.BaseName().RemoveExtension().value(); -#if defined(OS_POSIX) - return UTF8ToUTF16(path); -#elif defined(OS_WIN) - return WideToUTF16(path); -#endif -} - -DictionaryValue* PluginGroup::GetSummary() const { - DictionaryValue* result = new DictionaryValue(); - result->SetString("name", GetGroupName()); - result->SetBoolean("enabled", enabled_); - return result; -} - -DictionaryValue* PluginGroup::GetDataForUI() const { - string16 name = GetGroupName(); - DictionaryValue* result = new DictionaryValue(); - result->SetString("name", name); - result->SetString("description", description_); - result->SetString("version", version_->GetString()); - result->SetString("update_url", update_url_); - result->SetBoolean("critical", IsVulnerable()); - - bool group_disabled_by_policy = IsPluginNameDisabledByPolicy(name); - ListValue* plugin_files = new ListValue(); - bool all_plugins_disabled_by_policy = true; - for (size_t i = 0; i < web_plugin_infos_.size(); ++i) { - const WebPluginInfo& web_plugin = web_plugin_infos_[i]; - int priority = web_plugin_positions_[i]; - DictionaryValue* plugin_file = new DictionaryValue(); - plugin_file->SetString("name", web_plugin.name); - plugin_file->SetString("description", web_plugin.desc); - plugin_file->SetString("path", web_plugin.path.value()); - plugin_file->SetString("version", web_plugin.version); - bool plugin_disabled_by_policy = group_disabled_by_policy || - IsPluginNameDisabledByPolicy(web_plugin.name); - if (plugin_disabled_by_policy) { - plugin_file->SetString("enabledMode", "disabledByPolicy"); - } else { - all_plugins_disabled_by_policy = false; - plugin_file->SetString("enabledMode", - web_plugin.enabled ? "enabled" : "disabledByUser"); - } - plugin_file->SetInteger("priority", priority); - - ListValue* mime_types = new ListValue(); - for (std::vector<WebPluginMimeType>::const_iterator type_it = - web_plugin.mime_types.begin(); - type_it != web_plugin.mime_types.end(); - ++type_it) { - DictionaryValue* mime_type = new DictionaryValue(); - mime_type->SetString("mimeType", type_it->mime_type); - mime_type->SetString("description", type_it->description); - - ListValue* file_extensions = new ListValue(); - for (std::vector<std::string>::const_iterator ext_it = - type_it->file_extensions.begin(); - ext_it != type_it->file_extensions.end(); - ++ext_it) { - file_extensions->Append(new StringValue(*ext_it)); - } - mime_type->Set("fileExtensions", file_extensions); - - mime_types->Append(mime_type); - } - plugin_file->Set("mimeTypes", mime_types); - - plugin_files->Append(plugin_file); - } - - if (group_disabled_by_policy || all_plugins_disabled_by_policy) { - result->SetString("enabledMode", "disabledByPolicy"); - } else { - result->SetString("enabledMode", enabled_ ? "enabled" : "disabledByUser"); - } - result->Set("plugin_files", plugin_files); - - return result; -} - -// Returns true if the latest version of this plugin group is vulnerable. -bool PluginGroup::IsVulnerable() const { - if (min_version_.get() == NULL || version_->GetString() == "0") { - return false; - } - return version_->CompareTo(*min_version_) < 0; -} - -void PluginGroup::DisableOutdatedPlugins() { - if (!min_version_.get()) - return; - - description_ = string16(); - enabled_ = false; - - for (std::vector<WebPluginInfo>::iterator it = - web_plugin_infos_.begin(); - it != web_plugin_infos_.end(); ++it) { - scoped_ptr<Version> version(CreateVersionFromString(it->version)); - if (version.get() && version->CompareTo(*min_version_) < 0) { - it->enabled = false; - NPAPI::PluginList::Singleton()->DisablePlugin(it->path); - } - UpdateActivePlugin(*it); - } -} - -void PluginGroup::Enable(bool enable) { - for (std::vector<WebPluginInfo>::const_iterator it = - web_plugin_infos_.begin(); - it != web_plugin_infos_.end(); ++it) { - if (enable && !IsPluginNameDisabledByPolicy(it->name)) { - NPAPI::PluginList::Singleton()->EnablePlugin(it->path); - } else { - NPAPI::PluginList::Singleton()->DisablePlugin(it->path); - } - } -} diff --git a/webkit/glue/plugins/plugin_group.h b/webkit/glue/plugins/plugin_group.h deleted file mode 100644 index 2281437..0000000 --- a/webkit/glue/plugins/plugin_group.h +++ /dev/null @@ -1,184 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PLUGIN_GROUP_H_ -#define WEBKIT_GLUE_PLUGINS_PLUGIN_GROUP_H_ -#pragma once - -#include <map> -#include <set> -#include <vector> - -#include "base/gtest_prod_util.h" -#include "base/scoped_ptr.h" -#include "base/string16.h" - -class DictionaryValue; -class FilePath; -class Version; -struct WebPluginInfo; - -namespace NPAPI { - class PluginList; -}; - -template <typename T> -class linked_ptr; - -// Hard-coded definitions of plugin groups. -struct PluginGroupDefinition { - const char* identifier; // Unique identifier for this group. - const char* name; // Name of this group. - const char* name_matcher; // Substring matcher for the plugin name. - const char* version_matcher_low; // Matchers for the plugin version. - const char* version_matcher_high; - const char* min_version; // Minimum secure version. - const char* update_url; // Location of latest secure version. -}; - -// A PluginGroup can match a range of versions of a specific plugin (as defined -// by matching a substring of its name). -// It contains all WebPluginInfo structs (at least one) matching its definition. -// In addition, it knows about a security "baseline", i.e. the minimum version -// of a plugin that is needed in order not to exhibit known security -// vulnerabilities. - -class PluginGroup { - public: - // Used by about:plugins to disable Reader plugin when internal PDF viewer is - // enabled. - static const char* kAdobeReader8GroupName; - static const char* kAdobeReader9GroupName; - - typedef std::map<std::string, linked_ptr<PluginGroup> > PluginMap; - - // Creates a PluginGroup from a PluginGroupDefinition. - static PluginGroup* FromPluginGroupDefinition( - const PluginGroupDefinition& definition); - - ~PluginGroup(); - - // Creates a PluginGroup from a WebPluginInfo -- when no hard-coded - // definition is found. - static PluginGroup* FromWebPluginInfo(const WebPluginInfo& wpi); - - // Find a plugin group matching |info| in the list of hardcoded plugins and - // returns a copy of it if found, or a new group matching exactly this plugin - // otherwise. - // The caller should take ownership of the return PluginGroup. - static PluginGroup* CopyOrCreatePluginGroup(const WebPluginInfo& info); - - // Configures the set of plugin name patterns for disabling plugins via - // enterprise configuration management. - static void SetPolicyDisabledPluginPatterns(const std::set<string16>& set); - - // Tests to see if a plugin is on the blacklist using its name as - // the lookup key. - static bool IsPluginNameDisabledByPolicy(const string16& plugin_name); - - // Tests to see if a plugin is on the blacklist using its path as - // the lookup key. - static bool IsPluginPathDisabledByPolicy(const FilePath& plugin_path); - - // Find the PluginGroup matching a Plugin in a list of plugin groups. Returns - // NULL if no matching PluginGroup is found. - static PluginGroup* FindGroupMatchingPlugin( - const std::map<std::string, linked_ptr<PluginGroup> >& plugin_groups, - const WebPluginInfo& plugin); - - // Creates a copy of this plugin group. - PluginGroup* Copy() { - return new PluginGroup(group_name_, name_matcher_, version_range_low_str_, - version_range_high_str_, min_version_str_, - update_url_, identifier_); - } - - // Returns true if the given plugin matches this group. - bool Match(const WebPluginInfo& plugin) const; - - // Adds the given plugin to this group. Provide the position of the - // plugin as given by PluginList so we can display its priority. - void AddPlugin(const WebPluginInfo& plugin, int position); - - // Enables/disables this group. This enables/disables all plugins in the - // group. - void Enable(bool enable); - - // Returns whether the plugin group is enabled or not. - bool Enabled() const { return enabled_; } - - // Returns a unique identifier for this group, if one is defined, or the empty - // string otherwise. - const std::string& identifier() const { return identifier_; } - - // Returns this group's name, or the filename without extension if the name - // is empty. - string16 GetGroupName() const; - - // Returns the description of the highest-priority plug-in in the group. - const string16& description() const { return description_; } - - // Returns a DictionaryValue with data to display in the UI. - DictionaryValue* GetDataForUI() const; - - // Returns a DictionaryValue with data to save in the preferences. - DictionaryValue* GetSummary() const; - - // Returns the update URL. - std::string GetUpdateURL() const { return update_url_; } - - // Returns true if the highest-priority plugin in this group has known - // security problems. - bool IsVulnerable() const; - - // Disables all plugins in this group that are older than the - // minimum version. - void DisableOutdatedPlugins(); - - private: - FRIEND_TEST_ALL_PREFIXES(PluginGroupTest, PluginGroupDefinition); - - static const PluginGroupDefinition* GetPluginGroupDefinitions(); - static size_t GetPluginGroupDefinitionsSize(); - - PluginGroup(const string16& group_name, - const string16& name_matcher, - const std::string& version_range_low, - const std::string& version_range_high, - const std::string& min_version, - const std::string& update_url, - const std::string& identifier); - - Version* CreateVersionFromString(const string16& version_string); - - // Set the description and version for this plugin group from the - // given plug-in. - void UpdateDescriptionAndVersion(const WebPluginInfo& plugin); - - // Updates the active plugin in the group. The active plugin is the first - // enabled one, or if all plugins are disabled, simply the first one. - void UpdateActivePlugin(const WebPluginInfo& plugin); - - static std::set<string16>* policy_disabled_plugin_patterns_; - - std::string identifier_; - string16 group_name_; - string16 name_matcher_; - std::string version_range_low_str_; - std::string version_range_high_str_; - scoped_ptr<Version> version_range_low_; - scoped_ptr<Version> version_range_high_; - string16 description_; - std::string update_url_; - bool enabled_; - std::string min_version_str_; - scoped_ptr<Version> min_version_; - scoped_ptr<Version> version_; - std::vector<WebPluginInfo> web_plugin_infos_; - std::vector<int> web_plugin_positions_; - - DISALLOW_COPY_AND_ASSIGN(PluginGroup); -}; - -#endif // WEBKIT_GLUE_PLUGINS_PLUGIN_GROUP_H_ diff --git a/webkit/glue/plugins/plugin_group_unittest.cc b/webkit/glue/plugins/plugin_group_unittest.cc deleted file mode 100644 index 467c273..0000000 --- a/webkit/glue/plugins/plugin_group_unittest.cc +++ /dev/null @@ -1,181 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_group.h" - -#include <string> -#include <vector> - -#include "base/scoped_ptr.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "base/version.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "webkit/glue/plugins/webplugininfo.h" - -static const PluginGroupDefinition kPluginDef = { - "myplugin", "MyPlugin", "MyPlugin", "", "", "3.0.44", "http://latest/" }; -static const PluginGroupDefinition kPluginDef3 = { - "myplugin-3", "MyPlugin 3", "MyPlugin", "0", "4", "3.0.44", "http://latest" }; -static const PluginGroupDefinition kPluginDef4 = { - "myplugin-4", "MyPlugin 4", "MyPlugin", "4", "5", "4.0.44", "http://latest" }; -static const PluginGroupDefinition kPluginDefNotVulnerable = { - "myplugin-latest", "MyPlugin", "MyPlugin", "", "", "", "http://latest" }; - -// name, path, version, desc, mime_types, enabled. -static WebPluginInfo kPlugin2043 = WebPluginInfo( - ASCIIToUTF16("MyPlugin"), ASCIIToUTF16("2.0.43"), - ASCIIToUTF16("MyPlugin version 2.0.43")); -static WebPluginInfo kPlugin3043 = WebPluginInfo( - ASCIIToUTF16("MyPlugin"), ASCIIToUTF16("3.0.43"), - ASCIIToUTF16("MyPlugin version 3.0.43")); -static WebPluginInfo kPlugin3044 = WebPluginInfo( - ASCIIToUTF16("MyPlugin"), ASCIIToUTF16("3.0.44"), - ASCIIToUTF16("MyPlugin version 3.0.44")); -static WebPluginInfo kPlugin3045 = WebPluginInfo( - ASCIIToUTF16("MyPlugin"), ASCIIToUTF16("3.0.45"), - ASCIIToUTF16("MyPlugin version 3.0.45")); -static WebPluginInfo kPlugin4043 = WebPluginInfo( - ASCIIToUTF16("MyPlugin"), ASCIIToUTF16("4.0.43"), - ASCIIToUTF16("MyPlugin version 4.0.43")); - -class PluginGroupTest : public testing::Test { - protected: - virtual void TearDown() { - PluginGroup::SetPolicyDisabledPluginPatterns(std::set<string16>()); - } -}; - -TEST(PluginGroupTest, PluginGroupMatch) { - scoped_ptr<PluginGroup> group(PluginGroup::FromPluginGroupDefinition( - kPluginDef3)); - EXPECT_TRUE(group->Match(kPlugin3045)); - group->AddPlugin(kPlugin3045, 0); - EXPECT_FALSE(group->IsVulnerable()); -} - -TEST(PluginGroupTest, PluginGroupMatchCorrectVersion) { - scoped_ptr<PluginGroup> group(PluginGroup::FromPluginGroupDefinition( - kPluginDef3)); - EXPECT_TRUE(group->Match(kPlugin2043)); - EXPECT_TRUE(group->Match(kPlugin3043)); - EXPECT_FALSE(group->Match(kPlugin4043)); - - group.reset(PluginGroup::FromPluginGroupDefinition(kPluginDef4)); - EXPECT_FALSE(group->Match(kPlugin2043)); - EXPECT_FALSE(group->Match(kPlugin3043)); - EXPECT_TRUE(group->Match(kPlugin4043)); -} - -TEST(PluginGroupTest, PluginGroupDescription) { - string16 desc3043(ASCIIToUTF16("MyPlugin version 3.0.43")); - string16 desc3045(ASCIIToUTF16("MyPlugin version 3.0.45")); - WebPluginInfo plugin3043(kPlugin3043); - WebPluginInfo plugin3045(kPlugin3045); - - { - scoped_ptr<PluginGroup> group(PluginGroup::FromPluginGroupDefinition( - kPluginDef3)); - EXPECT_TRUE(group->Match(plugin3043)); - group->AddPlugin(plugin3043, 0); - EXPECT_EQ(desc3043, group->description()); - EXPECT_TRUE(group->IsVulnerable()); - EXPECT_TRUE(group->Match(plugin3045)); - group->AddPlugin(plugin3045, 1); - EXPECT_EQ(desc3043, group->description()); - EXPECT_TRUE(group->IsVulnerable()); - } - - { - // Disable the first plugin. - plugin3043.enabled = false; - scoped_ptr<PluginGroup> group(PluginGroup::FromPluginGroupDefinition( - kPluginDef3)); - EXPECT_TRUE(group->Match(plugin3043)); - group->AddPlugin(plugin3043, 0); - EXPECT_EQ(desc3043, group->description()); - EXPECT_TRUE(group->IsVulnerable()); - EXPECT_TRUE(group->Match(plugin3045)); - group->AddPlugin(plugin3045, 1); - EXPECT_EQ(desc3045, group->description()); - EXPECT_FALSE(group->IsVulnerable()); - } - - { - // Disable the second plugin. - plugin3045.enabled = false; - scoped_ptr<PluginGroup> group(PluginGroup::FromPluginGroupDefinition( - kPluginDef3)); - EXPECT_TRUE(group->Match(plugin3043)); - group->AddPlugin(plugin3043, 1); - EXPECT_EQ(desc3043, group->description()); - EXPECT_TRUE(group->IsVulnerable()); - EXPECT_TRUE(group->Match(plugin3045)); - group->AddPlugin(plugin3045, 0); - EXPECT_EQ(desc3043, group->description()); - EXPECT_TRUE(group->IsVulnerable()); - } -} - -TEST(PluginGroupTest, PluginGroupDefinition) { - const PluginGroupDefinition* definitions = - PluginGroup::GetPluginGroupDefinitions(); - for (size_t i = 0; i < PluginGroup::GetPluginGroupDefinitionsSize(); ++i) { - scoped_ptr<PluginGroup> def_group( - PluginGroup::FromPluginGroupDefinition(definitions[i])); - ASSERT_TRUE(def_group.get() != NULL); - EXPECT_FALSE(def_group->Match(kPlugin2043)); - } -} - -TEST(PluginGroupTest, DisableOutdated) { - scoped_ptr<PluginGroup> group(PluginGroup::FromPluginGroupDefinition( - kPluginDef3)); - group->AddPlugin(kPlugin3043, 0); - group->AddPlugin(kPlugin3045, 1); - EXPECT_EQ(ASCIIToUTF16("MyPlugin version 3.0.43"), group->description()); - EXPECT_TRUE(group->IsVulnerable()); - - group->DisableOutdatedPlugins(); - EXPECT_EQ(ASCIIToUTF16("MyPlugin version 3.0.45"), group->description()); - EXPECT_FALSE(group->IsVulnerable()); -} - -TEST(PluginGroupTest, VersionExtraction) { - // Some real-world plugin versions (spaces, commata, parentheses, 'r', oh my) - const char* versions[][2] = { - { "7.6.6 (1671)", "7.6.6.1671" }, // Quicktime - { "2, 0, 0, 254", "2.0.0.254" }, // DivX - { "3, 0, 0, 0", "3.0.0.0" }, // Picasa - { "1, 0, 0, 1", "1.0.0.1" }, // Earth - { "10,0,45,2", "10.0.45.2" }, // Flash - { "11.5.7r609", "11.5.7.609"} // Shockwave - }; - - for (size_t i = 0; i < arraysize(versions); i++) { - const WebPluginInfo plugin = WebPluginInfo( - ASCIIToUTF16("Blah Plugin"), ASCIIToUTF16(versions[i][0]), string16()); - scoped_ptr<PluginGroup> group(PluginGroup::FromWebPluginInfo(plugin)); - EXPECT_TRUE(group->Match(plugin)); - group->AddPlugin(plugin, 0); - scoped_ptr<DictionaryValue> data(group->GetDataForUI()); - std::string version; - data->GetString("version", &version); - EXPECT_EQ(versions[i][1], version); - } -} - -TEST(PluginGroupTest, DisabledByPolicy) { - std::set<string16> disabled_plugins; - disabled_plugins.insert(ASCIIToUTF16("Disable this!")); - disabled_plugins.insert(ASCIIToUTF16("*Google*")); - PluginGroup::SetPolicyDisabledPluginPatterns(disabled_plugins); - - EXPECT_FALSE(PluginGroup::IsPluginNameDisabledByPolicy(ASCIIToUTF16("42"))); - EXPECT_TRUE(PluginGroup::IsPluginNameDisabledByPolicy( - ASCIIToUTF16("Disable this!"))); - EXPECT_TRUE(PluginGroup::IsPluginNameDisabledByPolicy( - ASCIIToUTF16("Google Earth"))); -} diff --git a/webkit/glue/plugins/plugin_host.cc b/webkit/glue/plugins/plugin_host.cc deleted file mode 100644 index 670f589..0000000 --- a/webkit/glue/plugins/plugin_host.cc +++ /dev/null @@ -1,1104 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_host.h" - -#include "base/file_util.h" -#include "base/logging.h" -#include "base/scoped_ptr.h" -#include "base/string_piece.h" -#include "base/string_util.h" -#if defined(OS_MACOSX) -#include "base/sys_info.h" -#endif -#include "base/sys_string_conversions.h" -#include "base/utf_string_conversions.h" -#include "net/base/net_util.h" -#include "third_party/npapi/bindings/npapi_extensions.h" -#include "third_party/npapi/bindings/npruntime.h" -#include "third_party/WebKit/WebKit/chromium/public/WebBindings.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/plugins/default_plugin_shared.h" -#include "webkit/glue/plugins/npapi_extension_thunk.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/plugin_stream_url.h" -#include "webkit/glue/plugins/webplugin_delegate.h" -#include "webkit/glue/plugins/webplugininfo.h" - -using WebKit::WebBindings; - -// Finds a PluginInstance from an NPP. -// The caller must take a reference if needed. -static NPAPI::PluginInstance* FindInstance(NPP id) { - if (id == NULL) { - return NULL; - } - return reinterpret_cast<NPAPI::PluginInstance*>(id->ndata); -} - -#if defined(OS_MACOSX) -// Returns true if the OS supports shared accelerated surfaces via IOSurface. -// This is true on Snow Leopard and higher. -static bool SupportsSharingAcceleratedSurfaces() { - int32 major, minor, bugfix; - base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &bugfix); - return major > 10 || (major == 10 && minor > 5); -} -#endif - -namespace NPAPI { - -scoped_refptr<PluginHost> PluginHost::singleton_; - -PluginHost::PluginHost() { - InitializeHostFuncs(); -} - -PluginHost::~PluginHost() { -} - -PluginHost *PluginHost::Singleton() { - if (singleton_.get() == NULL) { - singleton_ = new PluginHost(); - } - - DCHECK(singleton_.get() != NULL); - return singleton_; -} - -void PluginHost::InitializeHostFuncs() { - memset(&host_funcs_, 0, sizeof(host_funcs_)); - host_funcs_.size = sizeof(host_funcs_); - host_funcs_.version = (NP_VERSION_MAJOR << 8) | (NP_VERSION_MINOR); - - // The "basic" functions - host_funcs_.geturl = &NPN_GetURL; - host_funcs_.posturl = &NPN_PostURL; - host_funcs_.requestread = &NPN_RequestRead; - host_funcs_.newstream = &NPN_NewStream; - host_funcs_.write = &NPN_Write; - host_funcs_.destroystream = &NPN_DestroyStream; - host_funcs_.status = &NPN_Status; - host_funcs_.uagent = &NPN_UserAgent; - host_funcs_.memalloc = &NPN_MemAlloc; - host_funcs_.memfree = &NPN_MemFree; - host_funcs_.memflush = &NPN_MemFlush; - host_funcs_.reloadplugins = &NPN_ReloadPlugins; - - // We don't implement java yet - host_funcs_.getJavaEnv = &NPN_GetJavaEnv; - host_funcs_.getJavaPeer = &NPN_GetJavaPeer; - - // Advanced functions we implement - host_funcs_.geturlnotify = &NPN_GetURLNotify; - host_funcs_.posturlnotify = &NPN_PostURLNotify; - host_funcs_.getvalue = &NPN_GetValue; - host_funcs_.setvalue = &NPN_SetValue; - host_funcs_.invalidaterect = &NPN_InvalidateRect; - host_funcs_.invalidateregion = &NPN_InvalidateRegion; - host_funcs_.forceredraw = &NPN_ForceRedraw; - - // These come from the Javascript Engine - host_funcs_.getstringidentifier = WebBindings::getStringIdentifier; - host_funcs_.getstringidentifiers = WebBindings::getStringIdentifiers; - host_funcs_.getintidentifier = WebBindings::getIntIdentifier; - host_funcs_.identifierisstring = WebBindings::identifierIsString; - host_funcs_.utf8fromidentifier = WebBindings::utf8FromIdentifier; - host_funcs_.intfromidentifier = WebBindings::intFromIdentifier; - host_funcs_.createobject = WebBindings::createObject; - host_funcs_.retainobject = WebBindings::retainObject; - host_funcs_.releaseobject = WebBindings::releaseObject; - host_funcs_.invoke = WebBindings::invoke; - host_funcs_.invokeDefault = WebBindings::invokeDefault; - host_funcs_.evaluate = WebBindings::evaluate; - host_funcs_.getproperty = WebBindings::getProperty; - host_funcs_.setproperty = WebBindings::setProperty; - host_funcs_.removeproperty = WebBindings::removeProperty; - host_funcs_.hasproperty = WebBindings::hasProperty; - host_funcs_.hasmethod = WebBindings::hasMethod; - host_funcs_.releasevariantvalue = WebBindings::releaseVariantValue; - host_funcs_.setexception = WebBindings::setException; - host_funcs_.pushpopupsenabledstate = NPN_PushPopupsEnabledState; - host_funcs_.poppopupsenabledstate = NPN_PopPopupsEnabledState; - host_funcs_.enumerate = WebBindings::enumerate; - host_funcs_.pluginthreadasynccall = NPN_PluginThreadAsyncCall; - host_funcs_.construct = WebBindings::construct; - host_funcs_.getvalueforurl = NPN_GetValueForURL; - host_funcs_.setvalueforurl = NPN_SetValueForURL; - host_funcs_.getauthenticationinfo = NPN_GetAuthenticationInfo; - host_funcs_.scheduletimer = NPN_ScheduleTimer; - host_funcs_.unscheduletimer = NPN_UnscheduleTimer; - host_funcs_.popupcontextmenu = NPN_PopUpContextMenu; - host_funcs_.convertpoint = NPN_ConvertPoint; - host_funcs_.handleevent = NPN_HandleEvent; - host_funcs_.unfocusinstance = NPN_UnfocusInstance; - host_funcs_.urlredirectresponse = NPN_URLRedirectResponse; -} - -void PluginHost::PatchNPNetscapeFuncs(NPNetscapeFuncs* overrides) { - // When running in the plugin process, we need to patch the NPN functions - // that the plugin calls to interact with NPObjects that we give. Otherwise - // the plugin will call the v8 NPN functions, which won't work since we have - // an NPObjectProxy and not a real v8 implementation. - if (overrides->invoke) - host_funcs_.invoke = overrides->invoke; - - if (overrides->invokeDefault) - host_funcs_.invokeDefault = overrides->invokeDefault; - - if (overrides->evaluate) - host_funcs_.evaluate = overrides->evaluate; - - if (overrides->getproperty) - host_funcs_.getproperty = overrides->getproperty; - - if (overrides->setproperty) - host_funcs_.setproperty = overrides->setproperty; - - if (overrides->removeproperty) - host_funcs_.removeproperty = overrides->removeproperty; - - if (overrides->hasproperty) - host_funcs_.hasproperty = overrides->hasproperty; - - if (overrides->hasmethod) - host_funcs_.hasmethod = overrides->hasmethod; - - if (overrides->setexception) - host_funcs_.setexception = overrides->setexception; - - if (overrides->enumerate) - host_funcs_.enumerate = overrides->enumerate; -} - -bool PluginHost::SetPostData(const char* buf, - uint32 length, - std::vector<std::string>* names, - std::vector<std::string>* values, - std::vector<char>* body) { - // Use a state table to do the parsing. Whitespace must be - // trimmed after the fact if desired. In our case, we actually - // don't care about the whitespace, because we're just going to - // pass this back into another POST. This function strips out the - // "Content-length" header and does not append it to the request. - - // - // This parser takes action only on state changes. - // - // Transition table: - // : \n NULL Other - // 0 GetHeader 1 2 4 0 - // 1 GetValue 1 0 3 1 - // 2 GetData 2 2 3 2 - // 3 DONE - // 4 ERR - // - enum { INPUT_COLON=0, INPUT_NEWLINE, INPUT_NULL, INPUT_OTHER }; - enum { GETNAME, GETVALUE, GETDATA, DONE, ERR }; - int statemachine[3][4] = { { GETVALUE, GETDATA, GETDATA, GETNAME }, - { GETVALUE, GETNAME, DONE, GETVALUE }, - { GETDATA, GETDATA, DONE, GETDATA } }; - std::string name, value; - const char* ptr = static_cast<const char*>(buf); - const char* start = ptr; - int state = GETNAME; // initial state - bool done = false; - bool err = false; - do { - int input; - - // Translate the current character into an input - // for the state table. - switch (*ptr) { - case ':' : - input = INPUT_COLON; - break; - case '\n': - input = INPUT_NEWLINE; - break; - case 0 : - input = INPUT_NULL; - break; - default : - input = INPUT_OTHER; - break; - } - - int newstate = statemachine[state][input]; - - // Take action based on the new state. - if (state != newstate) { - switch (newstate) { - case GETNAME: - // Got a value. - value = std::string(start, ptr - start); - TrimWhitespace(value, TRIM_ALL, &value); - // If the name field is empty, we'll skip this header - // but we won't error out. - if (!name.empty() && name != "content-length") { - names->push_back(name); - values->push_back(value); - } - start = ptr + 1; - break; - case GETVALUE: - // Got a header. - name = StringToLowerASCII(std::string(start, ptr - start)); - TrimWhitespace(name, TRIM_ALL, &name); - start = ptr + 1; - break; - case GETDATA: { - // Finished headers, now get body - if (*ptr) - start = ptr + 1; - size_t previous_size = body->size(); - size_t new_body_size = length - static_cast<int>(start - buf); - body->resize(previous_size + new_body_size); - if (!body->empty()) - memcpy(&body->front() + previous_size, start, new_body_size); - done = true; - break; - } - case ERR: - // error - err = true; - done = true; - break; - } - } - state = newstate; - ptr++; - } while (!done); - - return !err; -} - -} // namespace NPAPI - -extern "C" { - -// Allocates memory from the host's memory space. -void* NPN_MemAlloc(uint32_t size) { - // Note: We must use the same allocator/deallocator - // that is used by the javascript library, as some of the - // JS APIs will pass memory to the plugin which the plugin - // will attempt to free. - return malloc(size); -} - -// Deallocates memory from the host's memory space -void NPN_MemFree(void* ptr) { - if (ptr != NULL && ptr != reinterpret_cast<void*>(-1)) - free(ptr); -} - -// Requests that the host free a specified amount of memory. -uint32_t NPN_MemFlush(uint32_t size) { - // This is not relevant on Windows; MAC specific - return size; -} - -// This is for dynamic discovery of new plugins. -// Should force a re-scan of the plugins directory to load new ones. -void NPN_ReloadPlugins(NPBool reload_pages) { - WebKit::resetPluginCache(reload_pages ? true : false); -} - -// Requests a range of bytes for a seekable stream. -NPError NPN_RequestRead(NPStream* stream, NPByteRange* range_list) { - if (!stream || !range_list) - return NPERR_GENERIC_ERROR; - - scoped_refptr<NPAPI::PluginInstance> plugin( - reinterpret_cast<NPAPI::PluginInstance*>(stream->ndata)); - if (!plugin.get()) - return NPERR_GENERIC_ERROR; - - plugin->RequestRead(stream, range_list); - return NPERR_NO_ERROR; -} - -// Generic form of GetURL for common code between GetURL and GetURLNotify. -static NPError GetURLNotify(NPP id, - const char* url, - const char* target, - bool notify, - void* notify_data) { - if (!url) - return NPERR_INVALID_URL; - - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin.get()) { - return NPERR_GENERIC_ERROR; - } - - plugin->RequestURL(url, "GET", target, NULL, 0, notify, notify_data); - return NPERR_NO_ERROR; -} - -// Requests creation of a new stream with the contents of the -// specified URL; gets notification of the result. -NPError NPN_GetURLNotify(NPP id, - const char* url, - const char* target, - void* notify_data) { - // This is identical to NPN_GetURL, but after finishing, the - // browser will call NPP_URLNotify to inform the plugin that - // it has completed. - - // According to the NPAPI documentation, if target == _self - // or a parent to _self, the browser should return NPERR_INVALID_PARAM, - // because it can't notify the plugin once deleted. This is - // absolutely false; firefox doesn't do this, and Flash relies on - // being able to use this. - - // Also according to the NPAPI documentation, we should return - // NPERR_INVALID_URL if the url requested is not valid. However, - // this would require that we synchronously start fetching the - // URL. That just isn't practical. As such, there really is - // no way to return this error. From looking at the Firefox - // implementation, it doesn't look like Firefox does this either. - - return GetURLNotify(id, url, target, true, notify_data); -} - -NPError NPN_GetURL(NPP id, const char* url, const char* target) { - // Notes: - // Request from the Plugin to fetch content either for the plugin - // or to be placed into a browser window. - // - // If target == null, the browser fetches content and streams to plugin. - // otherwise, the browser loads content into an existing browser frame. - // If the target is the window/frame containing the plugin, the plugin - // may be destroyed. - // If the target is _blank, a mailto: or news: url open content in a new - // browser window - // If the target is _self, no other instance of the plugin is created. The - // plugin continues to operate in its own window - - return GetURLNotify(id, url, target, false, 0); -} - -// Generic form of PostURL for common code between PostURL and PostURLNotify. -static NPError PostURLNotify(NPP id, - const char* url, - const char* target, - uint32_t len, - const char* buf, - NPBool file, - bool notify, - void* notify_data) { - if (!url) - return NPERR_INVALID_URL; - - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin.get()) { - NOTREACHED(); - return NPERR_GENERIC_ERROR; - } - - std::string post_file_contents; - - if (file) { - // Post data to be uploaded from a file. This can be handled in two - // ways. - // 1. Read entire file and send the contents as if it was a post data - // specified in the argument - // 2. Send just the file details and read them in the browser at the - // time of sending the request. - // Approach 2 is more efficient but complicated. Approach 1 has a major - // drawback of sending potentially large data over two IPC hops. In a way - // 'large data over IPC' problem exists as it is in case of plugin giving - // the data directly instead of in a file. - // Currently we are going with the approach 1 to get the feature working. - // We can optimize this later with approach 2. - - // TODO(joshia): Design a scheme to send a file descriptor instead of - // entire file contents across. - - // Security alert: - // --------------- - // Here we are blindly uploading whatever file requested by a plugin. - // This is risky as someone could exploit a plugin to send private - // data in arbitrary locations. - // A malicious (non-sandboxed) plugin has unfeterred access to OS - // resources and can do this anyway without using browser's HTTP stack. - // FWIW, Firefox and Safari don't perform any security checks. - - if (!buf) - return NPERR_FILE_NOT_FOUND; - - std::string file_path_ascii(buf); - FilePath file_path; - static const char kFileUrlPrefix[] = "file:"; - if (StartsWithASCII(file_path_ascii, kFileUrlPrefix, false)) { - GURL file_url(file_path_ascii); - DCHECK(file_url.SchemeIsFile()); - net::FileURLToFilePath(file_url, &file_path); - } else { - file_path = FilePath::FromWStringHack( - base::SysNativeMBToWide(file_path_ascii)); - } - - base::PlatformFileInfo post_file_info = {0}; - if (!file_util::GetFileInfo(file_path, &post_file_info) || - post_file_info.is_directory) - return NPERR_FILE_NOT_FOUND; - - if (!file_util::ReadFileToString(file_path, &post_file_contents)) - return NPERR_FILE_NOT_FOUND; - - buf = post_file_contents.c_str(); - len = post_file_contents.size(); - } - - // The post data sent by a plugin contains both headers - // and post data. Example: - // Content-type: text/html - // Content-length: 200 - // - // <200 bytes of content here> - // - // Unfortunately, our stream needs these broken apart, - // so we need to parse the data and set headers and data - // separately. - plugin->RequestURL(url, "POST", target, buf, len, notify, notify_data); - return NPERR_NO_ERROR; -} - -NPError NPN_PostURLNotify(NPP id, - const char* url, - const char* target, - uint32_t len, - const char* buf, - NPBool file, - void* notify_data) { - return PostURLNotify(id, url, target, len, buf, file, true, notify_data); -} - -NPError NPN_PostURL(NPP id, - const char* url, - const char* target, - uint32_t len, - const char* buf, - NPBool file) { - // POSTs data to an URL, either from a temp file or a buffer. - // If file is true, buf contains a temp file (which host will delete after - // completing), and len contains the length of the filename. - // If file is false, buf contains the data to send, and len contains the - // length of the buffer - // - // If target is null, - // server response is returned to the plugin - // If target is _current, _self, or _top, - // server response is written to the plugin window and plugin is unloaded. - // If target is _new or _blank, - // server response is written to a new browser window - // If target is an existing frame, - // server response goes to that frame. - // - // For protocols other than FTP - // file uploads must be line-end converted from \r\n to \n - // - // Note: you cannot specify headers (even a blank line) in a memory buffer, - // use NPN_PostURLNotify - - return PostURLNotify(id, url, target, len, buf, file, false, 0); -} - -NPError NPN_NewStream(NPP id, - NPMIMEType type, - const char* target, - NPStream** stream) { - // Requests creation of a new data stream produced by the plugin, - // consumed by the browser. - // - // Browser should put this stream into a window target. - // - // TODO: implement me - DVLOG(1) << "NPN_NewStream is not implemented yet."; - return NPERR_GENERIC_ERROR; -} - -int32_t NPN_Write(NPP id, NPStream* stream, int32_t len, void* buffer) { - // Writes data to an existing Plugin-created stream. - - // TODO: implement me - DVLOG(1) << "NPN_Write is not implemented yet."; - return NPERR_GENERIC_ERROR; -} - -NPError NPN_DestroyStream(NPP id, NPStream* stream, NPReason reason) { - // Destroys a stream (could be created by plugin or browser). - // - // Reasons: - // NPRES_DONE - normal completion - // NPRES_USER_BREAK - user terminated - // NPRES_NETWORK_ERROR - network error (all errors fit here?) - // - // - - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin.get() == NULL) { - NOTREACHED(); - return NPERR_GENERIC_ERROR; - } - - return plugin->NPP_DestroyStream(stream, reason); -} - -const char* NPN_UserAgent(NPP id) { -#if defined(OS_WIN) - // Flash passes in a null id during the NP_initialize call. We need to - // default to the Mozilla user agent if we don't have an NPP instance or - // else Flash won't request windowless mode. - bool use_mozilla_user_agent = true; - if (id) { - scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id); - if (plugin.get() && !plugin->use_mozilla_user_agent()) - use_mozilla_user_agent = false; - } - - if (use_mozilla_user_agent) - return "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) " - "Gecko/20061103 Firefox/2.0a1"; -#elif defined(OS_MACOSX) - // Silverlight 4 doesn't handle events correctly unless we claim to be Safari. - scoped_refptr<NPAPI::PluginInstance> plugin; - if (id) - plugin = FindInstance(id); - if (plugin.get()) { - WebPluginInfo plugin_info = plugin->plugin_lib()->plugin_info(); - if (plugin_info.name == ASCIIToUTF16("Silverlight Plug-In") && - StartsWith(plugin_info.version, ASCIIToUTF16("4."), false)) { - return "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-us) " - "AppleWebKit/534.1+ (KHTML, like Gecko) Version/5.0 Safari/533.16"; - } - } -#endif - - return webkit_glue::GetUserAgent(GURL()).c_str(); -} - -void NPN_Status(NPP id, const char* message) { - // Displays a message on the status line of the browser window. - - // TODO: implement me - DVLOG(1) << "NPN_Status is not implemented yet."; -} - -void NPN_InvalidateRect(NPP id, NPRect *invalidRect) { - // Invalidates specified drawing area prior to repainting or refreshing a - // windowless plugin - - // Before a windowless plugin can refresh part of its drawing area, it must - // first invalidate it. This function causes the NPP_HandleEvent method to - // pass an update event or a paint message to the plug-in. After calling - // this method, the plug-in recieves a paint message asynchronously. - - // The browser redraws invalid areas of the document and any windowless - // plug-ins at regularly timed intervals. To force a paint message, the - // plug-in can call NPN_ForceRedraw after calling this method. - - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin.get() && plugin->webplugin()) { - if (invalidRect) { -#if defined(OS_WIN) - if (!plugin->windowless()) { - RECT rect = {0}; - rect.left = invalidRect->left; - rect.right = invalidRect->right; - rect.top = invalidRect->top; - rect.bottom = invalidRect->bottom; - ::InvalidateRect(plugin->window_handle(), &rect, false); - return; - } -#endif - gfx::Rect rect(invalidRect->left, - invalidRect->top, - invalidRect->right - invalidRect->left, - invalidRect->bottom - invalidRect->top); - plugin->webplugin()->InvalidateRect(rect); - } else { - plugin->webplugin()->Invalidate(); - } - } -} - -void NPN_InvalidateRegion(NPP id, NPRegion invalidRegion) { - // Invalidates a specified drawing region prior to repainting - // or refreshing a window-less plugin. - // - // Similar to NPN_InvalidateRect. - - // TODO: this is overkill--add platform-specific region handling (at the - // very least, fetch the region's bounding box and pass it to InvalidateRect). - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - DCHECK(plugin.get() != NULL); - if (plugin.get() && plugin->webplugin()) - plugin->webplugin()->Invalidate(); -} - -void NPN_ForceRedraw(NPP id) { - // Forces repaint for a windowless plug-in. - // - // We deliberately do not implement this; we don't want plugins forcing - // synchronous paints. -} - -NPError NPN_GetValue(NPP id, NPNVariable variable, void* value) { - // Allows the plugin to query the browser for information - // - // Variables: - // NPNVxDisplay (unix only) - // NPNVxtAppContext (unix only) - // NPNVnetscapeWindow (win only) - Gets the native window on which the - // plug-in drawing occurs, returns HWND - // NPNVjavascriptEnabledBool: tells whether Javascript is enabled - // NPNVasdEnabledBool: tells whether SmartUpdate is enabled - // NPNVOfflineBool: tells whether offline-mode is enabled - - NPError rv = NPERR_GENERIC_ERROR; - - switch (static_cast<int>(variable)) { - case NPNVWindowNPObject: { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - NPObject *np_object = plugin->webplugin()->GetWindowScriptNPObject(); - // Return value is expected to be retained, as - // described here: - // <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess> - if (np_object) { - WebBindings::retainObject(np_object); - void **v = (void **)value; - *v = np_object; - rv = NPERR_NO_ERROR; - } else { - NOTREACHED(); - } - break; - } - case NPNVPluginElementNPObject: { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - NPObject *np_object = plugin->webplugin()->GetPluginElement(); - // Return value is expected to be retained, as - // described here: - // <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess> - if (np_object) { - WebBindings::retainObject(np_object); - void** v = static_cast<void**>(value); - *v = np_object; - rv = NPERR_NO_ERROR; - } else { - NOTREACHED(); - } - break; - } - #if !defined(OS_MACOSX) // OS X doesn't have windowed plugins. - case NPNVnetscapeWindow: { - scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id); - if (!plugin.get()) { - NOTREACHED(); - return NPERR_GENERIC_ERROR; - } - gfx::PluginWindowHandle handle = plugin->window_handle(); - *((void**)value) = (void*)handle; - rv = NPERR_NO_ERROR; - break; - } - #endif - case NPNVjavascriptEnabledBool: { - // yes, JS is enabled. - *((void**)value) = (void*)1; - rv = NPERR_NO_ERROR; - break; - } - #if defined(TOOLKIT_USES_GTK) - case NPNVToolkit: - // Tell them we are GTK2. (The alternative is GTK 1.2.) - *reinterpret_cast<int*>(value) = NPNVGtk2; - rv = NPERR_NO_ERROR; - break; - - case NPNVSupportsXEmbedBool: - *reinterpret_cast<NPBool*>(value) = true; - rv = NPERR_NO_ERROR; - break; - #endif - case NPNVSupportsWindowless: { - NPBool* supports_windowless = reinterpret_cast<NPBool*>(value); - *supports_windowless = true; - rv = NPERR_NO_ERROR; - break; - } - case NPNVprivateModeBool: { - NPBool* private_mode = reinterpret_cast<NPBool*>(value); - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - *private_mode = plugin->webplugin()->IsOffTheRecord(); - rv = NPERR_NO_ERROR; - break; - } - case default_plugin::kMissingPluginStatusStart + - default_plugin::MISSING_PLUGIN_AVAILABLE: - // fall through - case default_plugin::kMissingPluginStatusStart + - default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD: { - // This is a hack for the default plugin to send notification to - // renderer. Even though we check if the plugin is the default plugin, - // we still need to worry about future standard change that may conflict - // with the variable definition, in order to avoid duplicate case clauses - // in this big switch statement. - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin->plugin_lib()->plugin_info().path.value() == - kDefaultPluginLibraryName) { - plugin->webplugin()->OnMissingPluginStatus( - variable - default_plugin::kMissingPluginStatusStart); - } - break; - } - #if defined(OS_MACOSX) - case NPNVpluginDrawingModel: { - // return the drawing model that was negotiated when we initialized. - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - *reinterpret_cast<int*>(value) = plugin->drawing_model(); - rv = NPERR_NO_ERROR; - break; - } -#ifndef NP_NO_QUICKDRAW - case NPNVsupportsQuickDrawBool: { - // We do not admit to supporting the QuickDraw drawing model. The logic - // here is that our QuickDraw plugin support is so rudimentary that we - // only want to use it as a fallback to keep plugins from crashing: if a - // plugin knows enough to ask, we want them to use CoreGraphics. - NPBool* supports_qd = reinterpret_cast<NPBool*>(value); - *supports_qd = false; - rv = NPERR_NO_ERROR; - break; - } -#endif - case NPNVsupportsCoreGraphicsBool: -#ifndef NP_NO_CARBON - case NPNVsupportsCarbonBool: -#endif - case NPNVsupportsCocoaBool: { - // we do support these drawing and event models. - NPBool* supports_model = reinterpret_cast<NPBool*>(value); - *supports_model = true; - rv = NPERR_NO_ERROR; - break; - } - case NPNVsupportsCoreAnimationBool: { - // We only support the Core Animation model on 10.6 and higher - // TODO(stuartmorgan): Once existing CA plugins have implemented the - // invalidating version, remove support for this one. - NPBool* supports_model = reinterpret_cast<NPBool*>(value); - *supports_model = SupportsSharingAcceleratedSurfaces() ? true : false; - rv = NPERR_NO_ERROR; - break; - } - case NPNVsupportsInvalidatingCoreAnimationBool: { - NPBool* supports_model = reinterpret_cast<NPBool*>(value); - *supports_model = true; - rv = NPERR_NO_ERROR; - break; - } - case NPNVsupportsOpenGLBool: { - // This drawing model was never widely supported, and we don't plan to - // support it. - NPBool* supports_model = reinterpret_cast<NPBool*>(value); - *supports_model = false; - rv = NPERR_NO_ERROR; - break; - } - #endif // OS_MACOSX - case NPNVPepperExtensions: - // Available for any plugin that attempts to get it. - // If the plugin is not started in a Pepper implementation, it - // will likely fail when it tries to use any of the functions - // attached to the extension vector. - rv = NPAPI::GetPepperExtensionsFunctions(value); - break; - default: - DVLOG(1) << "NPN_GetValue(" << variable << ") is not implemented yet."; - break; - } - return rv; -} - -NPError NPN_SetValue(NPP id, NPPVariable variable, void* value) { - // Allows the plugin to set various modes - - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - switch(variable) { - case NPPVpluginWindowBool: { - // Sets windowless mode for display of the plugin - // Note: the documentation at - // http://developer.mozilla.org/en/docs/NPN_SetValue is wrong. When - // value is NULL, the mode is set to true. This is the same way Mozilla - // works. - plugin->set_windowless(value == 0); - return NPERR_NO_ERROR; - } - case NPPVpluginTransparentBool: { - // Sets transparent mode for display of the plugin - // - // Transparent plugins require the browser to paint the background - // before having the plugin paint. By default, windowless plugins - // are transparent. Making a windowless plugin opaque means that - // the plugin does not require the browser to paint the background. - bool mode = (value != 0); - plugin->set_transparent(mode); - return NPERR_NO_ERROR; - } - case NPPVjavascriptPushCallerBool: - // Specifies whether you are pushing or popping the JSContext off. - // the stack - // TODO: implement me - DVLOG(1) << "NPN_SetValue(NPPVJavascriptPushCallerBool) is not " - "implemented."; - return NPERR_GENERIC_ERROR; - case NPPVpluginKeepLibraryInMemory: - // Tells browser that plugin library should live longer than usual. - // TODO: implement me - DVLOG(1) << "NPN_SetValue(NPPVpluginKeepLibraryInMemory) is not " - "implemented."; - return NPERR_GENERIC_ERROR; - #if defined(OS_MACOSX) - case NPPVpluginDrawingModel: { - int model = reinterpret_cast<int>(value); - if (model == NPDrawingModelCoreGraphics || - model == NPDrawingModelInvalidatingCoreAnimation || - (model == NPDrawingModelCoreAnimation && - SupportsSharingAcceleratedSurfaces())) { - plugin->set_drawing_model(static_cast<NPDrawingModel>(model)); - return NPERR_NO_ERROR; - } - return NPERR_GENERIC_ERROR; - } - case NPPVpluginEventModel: { - // we support Carbon and Cocoa event models - int model = reinterpret_cast<int>(value); - switch (model) { -#ifndef NP_NO_CARBON - case NPEventModelCarbon: -#endif - case NPEventModelCocoa: - plugin->set_event_model(static_cast<NPEventModel>(model)); - return NPERR_NO_ERROR; - break; - } - return NPERR_GENERIC_ERROR; - } - #endif - default: - // TODO: implement me - DVLOG(1) << "NPN_SetValue(" << variable << ") is not implemented."; - break; - } - - NOTREACHED(); - return NPERR_GENERIC_ERROR; -} - -void* NPN_GetJavaEnv() { - // TODO: implement me - DVLOG(1) << "NPN_GetJavaEnv is not implemented."; - return NULL; -} - -void* NPN_GetJavaPeer(NPP) { - // TODO: implement me - DVLOG(1) << "NPN_GetJavaPeer is not implemented."; - return NULL; -} - -void NPN_PushPopupsEnabledState(NPP id, NPBool enabled) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) - plugin->PushPopupsEnabledState(enabled ? true : false); -} - -void NPN_PopPopupsEnabledState(NPP id) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) - plugin->PopPopupsEnabledState(); -} - -void NPN_PluginThreadAsyncCall(NPP id, - void (*func)(void*), - void* user_data) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) - plugin->PluginThreadAsyncCall(func, user_data); -} - -NPError NPN_GetValueForURL(NPP id, - NPNURLVariable variable, - const char* url, - char** value, - uint32_t* len) { - if (!id) - return NPERR_INVALID_PARAM; - - if (!url || !*url || !len) - return NPERR_INVALID_URL; - - *len = 0; - std::string result; - - switch (variable) { - case NPNURLVProxy: { - result = "DIRECT"; - if (!webkit_glue::FindProxyForUrl(GURL((std::string(url))), &result)) - return NPERR_GENERIC_ERROR; - - break; - } - case NPNURLVCookie: { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin) - return NPERR_GENERIC_ERROR; - - webkit_glue::WebPlugin* webplugin = plugin->webplugin(); - if (!webplugin) - return NPERR_GENERIC_ERROR; - - // Bypass third-party cookie blocking by using the url as the - // first_party_for_cookies. - GURL cookies_url((std::string(url))); - result = webplugin->GetCookies(cookies_url, cookies_url); - break; - } - default: - return NPERR_GENERIC_ERROR; - } - - // Allocate this using the NPAPI allocator. The plugin will call - // NPN_Free to free this. - *value = static_cast<char*>(NPN_MemAlloc(result.length() + 1)); - base::strlcpy(*value, result.c_str(), result.length() + 1); - *len = result.length(); - - return NPERR_NO_ERROR; -} - -NPError NPN_SetValueForURL(NPP id, - NPNURLVariable variable, - const char* url, - const char* value, - uint32_t len) { - if (!id) - return NPERR_INVALID_PARAM; - - if (!url || !*url) - return NPERR_INVALID_URL; - - switch (variable) { - case NPNURLVCookie: { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin) - return NPERR_GENERIC_ERROR; - - webkit_glue::WebPlugin* webplugin = plugin->webplugin(); - if (!webplugin) - return NPERR_GENERIC_ERROR; - - std::string cookie(value, len); - GURL cookies_url((std::string(url))); - webplugin->SetCookie(cookies_url, cookies_url, cookie); - return NPERR_NO_ERROR; - } - case NPNURLVProxy: - // We don't support setting proxy values, fall through... - break; - default: - // Fall through and return an error... - break; - } - - return NPERR_GENERIC_ERROR; -} - -NPError NPN_GetAuthenticationInfo(NPP id, - const char* protocol, - const char* host, - int32_t port, - const char* scheme, - const char* realm, - char** username, - uint32_t* ulen, - char** password, - uint32_t* plen) { - if (!id || !protocol || !host || !scheme || !realm || !username || - !ulen || !password || !plen) - return NPERR_INVALID_PARAM; - - // TODO: implement me (bug 23928) - return NPERR_GENERIC_ERROR; -} - -uint32_t NPN_ScheduleTimer(NPP id, - uint32_t interval, - NPBool repeat, - void (*func)(NPP id, uint32_t timer_id)) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (!plugin) - return 0; - - return plugin->ScheduleTimer(interval, repeat, func); -} - -void NPN_UnscheduleTimer(NPP id, uint32_t timer_id) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin) - plugin->UnscheduleTimer(timer_id); -} - -NPError NPN_PopUpContextMenu(NPP id, NPMenu* menu) { - if (!menu) - return NPERR_INVALID_PARAM; - - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin.get()) { - return plugin->PopUpContextMenu(menu); - } - NOTREACHED(); - return NPERR_GENERIC_ERROR; -} - -NPBool NPN_ConvertPoint(NPP id, double sourceX, double sourceY, - NPCoordinateSpace sourceSpace, - double *destX, double *destY, - NPCoordinateSpace destSpace) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(id)); - if (plugin.get()) { - return plugin->ConvertPoint(sourceX, sourceY, sourceSpace, - destX, destY, destSpace); - } - NOTREACHED(); - return false; -} - -NPBool NPN_HandleEvent(NPP id, void *event, NPBool handled) { - // TODO: Implement advanced key handling: http://crbug.com/46578 - NOTIMPLEMENTED(); - return false; -} - -NPBool NPN_UnfocusInstance(NPP id, NPFocusDirection direction) { - // TODO: Implement advanced key handling: http://crbug.com/46578 - NOTIMPLEMENTED(); - return false; -} - -void NPN_URLRedirectResponse(NPP instance, void* notify_data, NPBool allow) { - scoped_refptr<NPAPI::PluginInstance> plugin(FindInstance(instance)); - if (plugin.get()) { - plugin->URLRedirectResponse(!!allow, notify_data); - } -} - -} // extern "C" diff --git a/webkit/glue/plugins/plugin_host.h b/webkit/glue/plugins/plugin_host.h deleted file mode 100644 index 4763df1..0000000 --- a/webkit/glue/plugins/plugin_host.h +++ /dev/null @@ -1,63 +0,0 @@ -// 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. - -// TODO: Need mechanism to cleanup the static instance - -#ifndef WEBKIT_GLUE_PLUGIN_PLUGIN_HOST_H__ -#define WEBKIT_GLUE_PLUGIN_PLUGIN_HOST_H__ - -#include <string> -#include <vector> - -#include "base/ref_counted.h" -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/nphostapi.h" - -namespace NPAPI -{ -class PluginInstance; - -// The Plugin Host implements the NPN_xxx functions for NPAPI plugins. -// These are the functions exposed from the Plugin Host for use -// by the Plugin. -// -// The PluginHost is managed as a singleton. This isn't strictly -// necessary, but since the callback functions are all global C -// functions, there is really no point in having per-instance PluginHosts. -class PluginHost : public base::RefCounted<PluginHost> { - public: - // Access the single PluginHost instance. Callers - // must call deref() when finished with the object. - static PluginHost *Singleton(); - - // The table of functions provided to the plugin. - NPNetscapeFuncs *host_functions() { return &host_funcs_; } - - // Helper function for parsing post headers, and applying attributes - // to the stream. NPAPI post data include headers + data combined. - // This function parses it out and adds it to the stream in a WebKit - // style. - static bool SetPostData(const char *buf, - uint32 length, - std::vector<std::string>* names, - std::vector<std::string>* values, - std::vector<char>* body); - - void PatchNPNetscapeFuncs(NPNetscapeFuncs* overrides); - - private: - friend class base::RefCounted<PluginHost>; - - virtual ~PluginHost(); - - PluginHost(); - void InitializeHostFuncs(); - static scoped_refptr<PluginHost> singleton_; - NPNetscapeFuncs host_funcs_; - DISALLOW_COPY_AND_ASSIGN(PluginHost); -}; - -} // namespace NPAPI - -#endif // WEBKIT_GLUE_PLUGIN_PLUGIN_HOST_H__ diff --git a/webkit/glue/plugins/plugin_instance.cc b/webkit/glue/plugins/plugin_instance.cc deleted file mode 100644 index 4ccbadf..0000000 --- a/webkit/glue/plugins/plugin_instance.cc +++ /dev/null @@ -1,680 +0,0 @@ -// 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 "build/build_config.h" - -#include "webkit/glue/plugins/plugin_instance.h" - -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/string_number_conversions.h" -#include "base/utf_string_conversions.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/plugins/plugin_host.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_stream_url.h" -#include "webkit/glue/plugins/plugin_string_stream.h" -#include "webkit/glue/plugins/webplugin.h" -#include "webkit/glue/plugins/webplugin_delegate.h" -#include "net/base/escape.h" - -#if defined(OS_MACOSX) -#include <ApplicationServices/ApplicationServices.h> -#endif - -namespace NPAPI { - -PluginInstance::PluginInstance(PluginLib *plugin, const std::string &mime_type) - : plugin_(plugin), - npp_(0), - host_(PluginHost::Singleton()), - npp_functions_(plugin->functions()), - window_handle_(0), - windowless_(false), - transparent_(true), - webplugin_(0), - mime_type_(mime_type), - use_mozilla_user_agent_(false), -#if defined (OS_MACOSX) -#ifdef NP_NO_QUICKDRAW - drawing_model_(NPDrawingModelCoreGraphics), -#else - drawing_model_(NPDrawingModelQuickDraw), -#endif -#ifdef NP_NO_CARBON - event_model_(NPEventModelCocoa), -#else - event_model_(NPEventModelCarbon), -#endif - currently_handled_event_(NULL), -#endif - message_loop_(MessageLoop::current()), - load_manually_(false), - in_close_streams_(false), - next_timer_id_(1), - next_notify_id_(0), - next_range_request_id_(0), - handles_url_redirects_(false) { - npp_ = new NPP_t(); - npp_->ndata = 0; - npp_->pdata = 0; - - memset(&zero_padding_, 0, sizeof(zero_padding_)); - DCHECK(message_loop_); -} - -PluginInstance::~PluginInstance() { - CloseStreams(); - - if (npp_ != 0) { - delete npp_; - npp_ = 0; - } - - if (plugin_) - plugin_->CloseInstance(); -} - -PluginStreamUrl* PluginInstance::CreateStream(unsigned long resource_id, - const GURL& url, - const std::string& mime_type, - int notify_id) { - - bool notify; - void* notify_data; - GetNotifyData(notify_id, ¬ify, ¬ify_data); - PluginStreamUrl* stream = new PluginStreamUrl( - resource_id, url, this, notify, notify_data); - - AddStream(stream); - return stream; -} - -void PluginInstance::AddStream(PluginStream* stream) { - open_streams_.push_back(make_scoped_refptr(stream)); -} - -void PluginInstance::RemoveStream(PluginStream* stream) { - if (in_close_streams_) - return; - - std::vector<scoped_refptr<PluginStream> >::iterator stream_index; - for (stream_index = open_streams_.begin(); - stream_index != open_streams_.end(); ++stream_index) { - if (*stream_index == stream) { - open_streams_.erase(stream_index); - break; - } - } -} - -bool PluginInstance::IsValidStream(const NPStream* stream) { - std::vector<scoped_refptr<PluginStream> >::iterator stream_index; - for (stream_index = open_streams_.begin(); - stream_index != open_streams_.end(); ++stream_index) { - if ((*stream_index)->stream() == stream) - return true; - } - - return false; -} - -void PluginInstance::CloseStreams() { - in_close_streams_ = true; - for (unsigned int index = 0; index < open_streams_.size(); ++index) { - // Close all streams on the way down. - open_streams_[index]->Close(NPRES_USER_BREAK); - } - open_streams_.clear(); - in_close_streams_ = false; -} - -webkit_glue::WebPluginResourceClient* PluginInstance::GetRangeRequest( - int id) { - PendingRangeRequestMap::iterator iter = pending_range_requests_.find(id); - if (iter == pending_range_requests_.end()) { - NOTREACHED(); - return NULL; - } - - webkit_glue::WebPluginResourceClient* rv = iter->second->AsResourceClient(); - pending_range_requests_.erase(iter); - return rv; -} - -bool PluginInstance::Start(const GURL& url, - char** const param_names, - char** const param_values, - int param_count, - bool load_manually) { - load_manually_ = load_manually; - unsigned short mode = load_manually_ ? NP_FULL : NP_EMBED; - npp_->ndata = this; - - NPError err = NPP_New(mode, param_count, - const_cast<char **>(param_names), const_cast<char **>(param_values)); - - if (err == NPERR_NO_ERROR) { - handles_url_redirects_ = - ((npp_functions_->version >= NPVERS_HAS_URL_REDIRECT_HANDLING) && - (npp_functions_->urlredirectnotify)); - } - return err == NPERR_NO_ERROR; -} - -NPObject *PluginInstance::GetPluginScriptableObject() { - NPObject *value = NULL; - NPError error = NPP_GetValue(NPPVpluginScriptableNPObject, &value); - if (error != NPERR_NO_ERROR || value == NULL) - return NULL; - return value; -} - -// WebPluginLoadDelegate methods -void PluginInstance::DidFinishLoadWithReason( - const GURL& url, NPReason reason, int notify_id) { - bool notify; - void* notify_data; - GetNotifyData(notify_id, ¬ify, ¬ify_data); - if (!notify) { - NOTREACHED(); - return; - } - - NPP_URLNotify(url.spec().c_str(), reason, notify_data); -} - -unsigned PluginInstance::GetBackingTextureId() { - // By default the plugin instance is not backed by an OpenGL texture. - return 0; -} - -// NPAPI methods -NPError PluginInstance::NPP_New(unsigned short mode, - short argc, - char *argn[], - char *argv[]) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->newp != 0); - DCHECK(argc >= 0); - - if (npp_functions_->newp != 0) { - return npp_functions_->newp( - (NPMIMEType)mime_type_.c_str(), npp_, mode, argc, argn, argv, NULL); - } - return NPERR_INVALID_FUNCTABLE_ERROR; -} - -void PluginInstance::NPP_Destroy() { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->destroy != 0); - - if (npp_functions_->destroy != 0) { - NPSavedData *savedData = 0; - npp_functions_->destroy(npp_, &savedData); - - // TODO: Support savedData. Technically, these need to be - // saved on a per-URL basis, and then only passed - // to new instances of the plugin at the same URL. - // Sounds like a huge security risk. When we do support - // these, we should pass them back to the PluginLib - // to be stored there. - DCHECK(savedData == 0); - } - - for (unsigned int file_index = 0; file_index < files_created_.size(); - file_index++) { - file_util::Delete(files_created_[file_index], false); - } - - // Ensure that no timer callbacks are invoked after NPP_Destroy. - timers_.clear(); -} - -NPError PluginInstance::NPP_SetWindow(NPWindow *window) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->setwindow != 0); - - if (npp_functions_->setwindow != 0) { - return npp_functions_->setwindow(npp_, window); - } - return NPERR_INVALID_FUNCTABLE_ERROR; -} - -NPError PluginInstance::NPP_NewStream(NPMIMEType type, - NPStream *stream, - NPBool seekable, - unsigned short *stype) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->newstream != 0); - if (npp_functions_->newstream != 0) { - return npp_functions_->newstream(npp_, type, stream, seekable, stype); - } - return NPERR_INVALID_FUNCTABLE_ERROR; -} - -NPError PluginInstance::NPP_DestroyStream(NPStream *stream, NPReason reason) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->destroystream != 0); - - if (stream == NULL || !IsValidStream(stream) || (stream->ndata == NULL)) - return NPERR_INVALID_INSTANCE_ERROR; - - if (npp_functions_->destroystream != 0) { - NPError result = npp_functions_->destroystream(npp_, stream, reason); - stream->ndata = NULL; - return result; - } - return NPERR_INVALID_FUNCTABLE_ERROR; -} - -int PluginInstance::NPP_WriteReady(NPStream *stream) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->writeready != 0); - if (npp_functions_->writeready != 0) { - return npp_functions_->writeready(npp_, stream); - } - return 0; -} - -int PluginInstance::NPP_Write(NPStream *stream, - int offset, - int len, - void *buffer) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->write != 0); - if (npp_functions_->write != 0) { - return npp_functions_->write(npp_, stream, offset, len, buffer); - } - return 0; -} - -void PluginInstance::NPP_StreamAsFile(NPStream *stream, const char *fname) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->asfile != 0); - if (npp_functions_->asfile != 0) { - npp_functions_->asfile(npp_, stream, fname); - } - - // Creating a temporary FilePath instance on the stack as the explicit - // FilePath constructor with StringType as an argument causes a compiler - // error when invoked via vector push back. - FilePath file_name = FilePath::FromWStringHack(UTF8ToWide(fname)); - files_created_.push_back(file_name); -} - -void PluginInstance::NPP_URLNotify(const char *url, - NPReason reason, - void *notifyData) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->urlnotify != 0); - if (npp_functions_->urlnotify != 0) { - npp_functions_->urlnotify(npp_, url, reason, notifyData); - } -} - -NPError PluginInstance::NPP_GetValue(NPPVariable variable, void *value) { - DCHECK(npp_functions_ != 0); - // getvalue is NULL for Shockwave - if (npp_functions_->getvalue != 0) { - return npp_functions_->getvalue(npp_, variable, value); - } - return NPERR_INVALID_FUNCTABLE_ERROR; -} - -NPError PluginInstance::NPP_SetValue(NPNVariable variable, void *value) { - DCHECK(npp_functions_ != 0); - if (npp_functions_->setvalue != 0) { - return npp_functions_->setvalue(npp_, variable, value); - } - return NPERR_INVALID_FUNCTABLE_ERROR; -} - -short PluginInstance::NPP_HandleEvent(void* event) { - DCHECK(npp_functions_ != 0); - DCHECK(npp_functions_->event != 0); - if (npp_functions_->event != 0) { - return npp_functions_->event(npp_, (void*)event); - } - return false; -} - -bool PluginInstance::NPP_Print(NPPrint* platform_print) { - DCHECK(npp_functions_ != 0); - if (npp_functions_->print != 0) { - npp_functions_->print(npp_, platform_print); - return true; - } - return false; -} - -NPError PluginInstance::NPP_ClearSiteData(uint64 flags, - const char* domain, - uint64 max_age) { - DCHECK(npp_functions_ != 0); - // TODO(bauerb): Call NPAPI function when it is defined in the header. - return NPERR_NO_ERROR; -} - -void PluginInstance::NPP_URLRedirectNotify(const char* url, int32_t status, - void* notify_data) { - DCHECK(npp_functions_ != 0); - if (npp_functions_->urlredirectnotify != 0) { - npp_functions_->urlredirectnotify(npp_, url, status, notify_data); - } -} - -void PluginInstance::SendJavaScriptStream(const GURL& url, - const std::string& result, - bool success, - int notify_id) { - bool notify; - void* notify_data; - GetNotifyData(notify_id, ¬ify, ¬ify_data); - - if (success) { - PluginStringStream *stream = - new PluginStringStream(this, url, notify, notify_data); - AddStream(stream); - stream->SendToPlugin(result, "text/html"); - } else { - // NOTE: Sending an empty stream here will crash MacroMedia - // Flash 9. Just send the URL Notify. - if (notify) - NPP_URLNotify(url.spec().c_str(), NPRES_DONE, notify_data); - } -} - -void PluginInstance::DidReceiveManualResponse(const GURL& url, - const std::string& mime_type, - const std::string& headers, - uint32 expected_length, - uint32 last_modified) { - DCHECK(load_manually_); - - plugin_data_stream_ = CreateStream(-1, url, mime_type, 0); - plugin_data_stream_->DidReceiveResponse(mime_type, headers, expected_length, - last_modified, true); -} - -void PluginInstance::DidReceiveManualData(const char* buffer, int length) { - DCHECK(load_manually_); - if (plugin_data_stream_.get() != NULL) { - plugin_data_stream_->DidReceiveData(buffer, length, 0); - } -} - -void PluginInstance::DidFinishManualLoading() { - DCHECK(load_manually_); - if (plugin_data_stream_.get() != NULL) { - plugin_data_stream_->DidFinishLoading(); - plugin_data_stream_->Close(NPRES_DONE); - plugin_data_stream_ = NULL; - } -} - -void PluginInstance::DidManualLoadFail() { - DCHECK(load_manually_); - if (plugin_data_stream_.get() != NULL) { - plugin_data_stream_->DidFail(); - plugin_data_stream_ = NULL; - } -} - -void PluginInstance::PluginThreadAsyncCall(void (*func)(void *), - void *user_data) { - message_loop_->PostTask( - FROM_HERE, NewRunnableMethod( - this, &PluginInstance::OnPluginThreadAsyncCall, func, user_data)); -} - -void PluginInstance::OnPluginThreadAsyncCall(void (*func)(void *), - void *user_data) { - // Do not invoke the callback if NPP_Destroy has already been invoked. - if (webplugin_) - func(user_data); -} - -uint32 PluginInstance::ScheduleTimer(uint32 interval, - NPBool repeat, - void (*func)(NPP id, uint32 timer_id)) { - // Use next timer id. - uint32 timer_id; - timer_id = next_timer_id_; - ++next_timer_id_; - DCHECK(next_timer_id_ != 0); - - // Record timer interval and repeat. - TimerInfo info; - info.interval = interval; - info.repeat = repeat ? true : false; - timers_[timer_id] = info; - - // Schedule the callback. - MessageLoop::current()->PostDelayedTask( - FROM_HERE, - NewRunnableMethod( - this, &PluginInstance::OnTimerCall, func, npp_, timer_id), - interval); - return timer_id; -} - -void PluginInstance::UnscheduleTimer(uint32 timer_id) { - // Remove info about the timer. - TimerMap::iterator it = timers_.find(timer_id); - if (it != timers_.end()) - timers_.erase(it); -} - -#if !defined(OS_MACOSX) -NPError PluginInstance::PopUpContextMenu(NPMenu* menu) { - NOTIMPLEMENTED(); - return NPERR_GENERIC_ERROR; -} -#endif - -void PluginInstance::OnTimerCall(void (*func)(NPP id, uint32 timer_id), - NPP id, - uint32 timer_id) { - // Do not invoke callback if the timer has been unscheduled. - TimerMap::iterator it = timers_.find(timer_id); - if (it == timers_.end()) - return; - - // Get all information about the timer before invoking the callback. The - // callback might unschedule the timer. - TimerInfo info = it->second; - - func(id, timer_id); - - // If the timer was unscheduled by the callback, just free up the timer id. - if (timers_.find(timer_id) == timers_.end()) - return; - - // Reschedule repeating timers after invoking the callback so callback is not - // re-entered if it pumps the messager loop. - if (info.repeat) { - MessageLoop::current()->PostDelayedTask( - FROM_HERE, - NewRunnableMethod( - this, &PluginInstance::OnTimerCall, func, npp_, timer_id), - info.interval); - } else { - timers_.erase(it); - } -} - -void PluginInstance::PushPopupsEnabledState(bool enabled) { - popups_enabled_stack_.push(enabled); -} - -void PluginInstance::PopPopupsEnabledState() { - popups_enabled_stack_.pop(); -} - -void PluginInstance::RequestRead(NPStream* stream, NPByteRange* range_list) { - std::string range_info = "bytes="; - - while (range_list) { - range_info += base::IntToString(range_list->offset); - range_info.push_back('-'); - range_info += - base::IntToString(range_list->offset + range_list->length - 1); - range_list = range_list->next; - if (range_list) - range_info.push_back(','); - } - - if (plugin_data_stream_) { - if (plugin_data_stream_->stream() == stream) { - webplugin_->CancelDocumentLoad(); - plugin_data_stream_ = NULL; - } - } - - // The lifetime of a NPStream instance depends on the PluginStream instance - // which owns it. When a plugin invokes NPN_RequestRead on a seekable stream, - // we don't want to create a new stream when the corresponding response is - // received. We send over a cookie which represents the PluginStream - // instance which is sent back from the renderer when the response is - // received. - std::vector<scoped_refptr<PluginStream> >::iterator stream_index; - for (stream_index = open_streams_.begin(); - stream_index != open_streams_.end(); ++stream_index) { - PluginStream* plugin_stream = *stream_index; - if (plugin_stream->stream() == stream) { - // A stream becomes seekable the first time NPN_RequestRead - // is called on it. - plugin_stream->set_seekable(true); - - pending_range_requests_[++next_range_request_id_] = plugin_stream; - webplugin_->InitiateHTTPRangeRequest( - stream->url, range_info.c_str(), next_range_request_id_); - return; - } - } - NOTREACHED(); -} - -void PluginInstance::RequestURL(const char* url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - bool notify, - void* notify_data) { - int notify_id = 0; - if (notify) { - notify_id = ++next_notify_id_; - pending_requests_[notify_id] = notify_data; - } - - webplugin_->HandleURLRequest( - url, method, target, buf, len, notify_id, popups_allowed(), - notify ? handles_url_redirects_ : false); -} - -bool PluginInstance::ConvertPoint(double source_x, double source_y, - NPCoordinateSpace source_space, - double* dest_x, double* dest_y, - NPCoordinateSpace dest_space) { -#if defined(OS_MACOSX) - CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID()); - - double flipped_screen_x = source_x; - double flipped_screen_y = source_y; - switch(source_space) { - case NPCoordinateSpacePlugin: - flipped_screen_x += plugin_origin_.x(); - flipped_screen_y += plugin_origin_.y(); - break; - case NPCoordinateSpaceWindow: - flipped_screen_x += containing_window_frame_.x(); - flipped_screen_y = containing_window_frame_.height() - source_y + - containing_window_frame_.y(); - break; - case NPCoordinateSpaceFlippedWindow: - flipped_screen_x += containing_window_frame_.x(); - flipped_screen_y += containing_window_frame_.y(); - break; - case NPCoordinateSpaceScreen: - flipped_screen_y = main_display_bounds.size.height - flipped_screen_y; - break; - case NPCoordinateSpaceFlippedScreen: - break; - default: - NOTREACHED(); - return false; - } - - double target_x = flipped_screen_x; - double target_y = flipped_screen_y; - switch(dest_space) { - case NPCoordinateSpacePlugin: - target_x -= plugin_origin_.x(); - target_y -= plugin_origin_.y(); - break; - case NPCoordinateSpaceWindow: - target_x -= containing_window_frame_.x(); - target_y -= containing_window_frame_.y(); - target_y = containing_window_frame_.height() - target_y; - break; - case NPCoordinateSpaceFlippedWindow: - target_x -= containing_window_frame_.x(); - target_y -= containing_window_frame_.y(); - break; - case NPCoordinateSpaceScreen: - target_y = main_display_bounds.size.height - flipped_screen_y; - break; - case NPCoordinateSpaceFlippedScreen: - break; - default: - NOTREACHED(); - return false; - } - - if (dest_x) - *dest_x = target_x; - if (dest_y) - *dest_y = target_y; - return true; -#else - NOTIMPLEMENTED(); - return false; -#endif -} - -void PluginInstance::GetNotifyData( - int notify_id, bool* notify, void** notify_data) { - PendingRequestMap::iterator iter = pending_requests_.find(notify_id); - if (iter != pending_requests_.end()) { - *notify = true; - *notify_data = iter->second; - pending_requests_.erase(iter); - } else { - *notify = false; - *notify_data = NULL; - } -} - -void PluginInstance::URLRedirectResponse(bool allow, void* notify_data) { - // The notify_data passed in allows us to identify the matching stream. - std::vector<scoped_refptr<PluginStream> >::iterator stream_index; - for (stream_index = open_streams_.begin(); - stream_index != open_streams_.end(); ++stream_index) { - PluginStream* plugin_stream = *stream_index; - if (plugin_stream->notify_data() == notify_data) { - webkit_glue::WebPluginResourceClient* resource_client = - plugin_stream->AsResourceClient(); - webplugin_->URLRedirectResponse(allow, resource_client->ResourceId()); - if (allow) { - plugin_stream->UpdateUrl( - plugin_stream->pending_redirect_url().c_str()); - } - break; - } - } -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_instance.h b/webkit/glue/plugins/plugin_instance.h deleted file mode 100644 index fa0320e..0000000 --- a/webkit/glue/plugins/plugin_instance.h +++ /dev/null @@ -1,375 +0,0 @@ -// 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. - -// TODO: Need to deal with NPAPI's NPSavedData. -// I haven't seen plugins use it yet. - -#ifndef WEBKIT_GLUE_PLUGIN_PLUGIN_INSTANCE_H__ -#define WEBKIT_GLUE_PLUGIN_PLUGIN_INSTANCE_H__ - -#include <map> -#include <stack> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/file_path.h" -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "gfx/native_widget_types.h" -#include "gfx/point.h" -#include "gfx/rect.h" -#include "googleurl/src/gurl.h" -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/nphostapi.h" - -class MessageLoop; - -namespace webkit_glue { -class WebPlugin; -class WebPluginResourceClient; -} - -namespace NPAPI -{ -class PluginLib; -class PluginHost; -class PluginStream; -class PluginStreamUrl; -class PluginDataStream; -#if defined(OS_MACOSX) -class ScopedCurrentPluginEvent; -#endif - -// A PluginInstance is an active, running instance of a Plugin. -// A single plugin may have many PluginInstances. -class PluginInstance : public base::RefCountedThreadSafe<PluginInstance> { - public: - // Create a new instance of a plugin. The PluginInstance - // will hold a reference to the plugin. - PluginInstance(PluginLib *plugin, const std::string &mime_type); - - // Activates the instance by calling NPP_New. - // This should be called after our instance is all - // setup from the host side and we are ready to receive - // requests from the plugin. We must not call any - // functions on the plugin instance until start has - // been called. - // - // url: The instance URL. - // param_names: the list of names of attributes passed via the - // element. - // param_values: the list of values corresponding to param_names - // param_count: number of attributes - // load_manually: if true indicates that the plugin data would be passed - // from webkit. if false indicates that the plugin should - // download the data. - // This also controls whether the plugin is instantiated as - // a full page plugin (NP_FULL) or embedded (NP_EMBED) - // - bool Start(const GURL& url, - char** const param_names, - char** const param_values, - int param_count, - bool load_manually); - - // NPAPI's instance identifier for this instance - NPP npp() { return npp_; } - - // Get/Set for the instance's window handle. - gfx::PluginWindowHandle window_handle() const { return window_handle_; } - void set_window_handle(gfx::PluginWindowHandle value) { - window_handle_ = value; - } - - // Get/Set whether this instance is in Windowless mode. - // Default is false. - bool windowless() { return windowless_; } - void set_windowless(bool value) { windowless_ = value; } - - // Get/Set whether this instance is transparent. - // This only applies to windowless plugins. Transparent - // plugins require that webkit paint the background. - // Default is true. - bool transparent() { return transparent_; } - void set_transparent(bool value) { transparent_ = value; } - - // Get/Set the WebPlugin associated with this instance - webkit_glue::WebPlugin* webplugin() { return webplugin_; } - void set_web_plugin(webkit_glue::WebPlugin* webplugin) { - webplugin_ = webplugin; - } - - // Get the mimeType for this plugin stream - const std::string &mime_type() { return mime_type_; } - - NPAPI::PluginLib* plugin_lib() { return plugin_; } - -#if defined(OS_MACOSX) - // Get/Set the Mac NPAPI drawing and event models - NPDrawingModel drawing_model() { return drawing_model_; } - void set_drawing_model(NPDrawingModel value) { drawing_model_ = value; } - NPEventModel event_model() { return event_model_; } - void set_event_model(NPEventModel value) { event_model_ = value; } - // Updates the instance's tracking of the location of the plugin location - // relative to the upper left of the screen. - void set_plugin_origin(const gfx::Point& origin) { plugin_origin_ = origin; } - // Updates the instance's tracking of the frame of the containing window - // relative to the upper left of the screen. - void set_window_frame(const gfx::Rect& frame) { - containing_window_frame_ = frame; - } -#endif - - // Creates a stream for sending an URL. If notify_id is non-zero, it will - // send a notification to the plugin when the stream is complete; otherwise it - // will not. Set object_url to true if the load is for the object tag's url, - // or false if it's for a url that the plugin fetched through - // NPN_GetUrl[Notify]. - PluginStreamUrl* CreateStream(unsigned long resource_id, - const GURL& url, - const std::string& mime_type, - int notify_id); - - // For each instance, we track all streams. When the - // instance closes, all remaining streams are also - // closed. All streams associated with this instance - // should call AddStream so that they can be cleaned - // up when the instance shuts down. - void AddStream(PluginStream* stream); - - // This is called when a stream is closed. We remove the stream from the - // list, which releases the reference maintained to the stream. - void RemoveStream(PluginStream* stream); - - // Closes all open streams on this instance. - void CloseStreams(); - - // Returns the WebPluginResourceClient object for a stream that has become - // seekable. - webkit_glue::WebPluginResourceClient* GetRangeRequest(int id); - - // Have the plugin create it's script object. - NPObject *GetPluginScriptableObject(); - - // WebViewDelegate methods that we implement. This is for handling - // callbacks during getURLNotify. - void DidFinishLoadWithReason(const GURL& url, NPReason reason, int notify_id); - - // If true, send the Mozilla user agent instead of Chrome's to the plugin. - bool use_mozilla_user_agent() { return use_mozilla_user_agent_; } - void set_use_mozilla_user_agent() { use_mozilla_user_agent_ = true; } - - // If the plugin instance is backed by a texture, return its ID in the - // compositor's namespace. Otherwise return 0. Returns 0 by default. - virtual unsigned GetBackingTextureId(); - - // Helper that implements NPN_PluginThreadAsyncCall semantics - void PluginThreadAsyncCall(void (*func)(void *), - void *userData); - - uint32 ScheduleTimer(uint32 interval, - NPBool repeat, - void (*func)(NPP id, uint32 timer_id)); - - void UnscheduleTimer(uint32 timer_id); - - bool ConvertPoint(double source_x, double source_y, - NPCoordinateSpace source_space, - double* dest_x, double* dest_y, - NPCoordinateSpace dest_space); - - NPError PopUpContextMenu(NPMenu* menu); - - // - // NPAPI methods for calling the Plugin Instance - // - NPError NPP_New(unsigned short, short, char *[], char *[]); - NPError NPP_SetWindow(NPWindow *); - NPError NPP_NewStream(NPMIMEType, NPStream *, NPBool, unsigned short *); - NPError NPP_DestroyStream(NPStream *, NPReason); - int NPP_WriteReady(NPStream *); - int NPP_Write(NPStream *, int, int, void *); - void NPP_StreamAsFile(NPStream *, const char *); - void NPP_URLNotify(const char *, NPReason, void *); - NPError NPP_GetValue(NPPVariable, void *); - NPError NPP_SetValue(NPNVariable, void *); - short NPP_HandleEvent(void*); - void NPP_Destroy(); - bool NPP_Print(NPPrint* platform_print); - NPError NPP_ClearSiteData(uint64, const char*, uint64); - void NPP_URLRedirectNotify(const char* url, int32_t status, - void* notify_data); - - void SendJavaScriptStream(const GURL& url, - const std::string& result, - bool success, - int notify_id); - - void DidReceiveManualResponse(const GURL& url, - const std::string& mime_type, - const std::string& headers, - uint32 expected_length, - uint32 last_modified); - void DidReceiveManualData(const char* buffer, int length); - void DidFinishManualLoading(); - void DidManualLoadFail(); - - void PushPopupsEnabledState(bool enabled); - void PopPopupsEnabledState(); - - bool popups_allowed() const { - return popups_enabled_stack_.empty() ? false : popups_enabled_stack_.top(); - } - - // Initiates byte range reads for plugins. - void RequestRead(NPStream* stream, NPByteRange* range_list); - - // Handles GetURL/GetURLNotify/PostURL/PostURLNotify requests initiated - // by plugins. - void RequestURL(const char* url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - bool notify, - void* notify_data); - - // Handles NPN_URLRedirectResponse calls issued by plugins in response to - // HTTP URL redirect notifications. - void URLRedirectResponse(bool allow, void* notify_data); - - bool handles_url_redirects() const { return handles_url_redirects_; } - - private: - friend class base::RefCountedThreadSafe<PluginInstance>; - -#if defined(OS_MACOSX) - friend class ScopedCurrentPluginEvent; - // Sets the event that the plugin is currently handling. The object is not - // owned or copied, so the caller must call this again with NULL before the - // event pointer becomes invalid. Clients use ScopedCurrentPluginEvent rather - // than calling this directly. - void set_currently_handled_event(NPCocoaEvent* event) { - currently_handled_event_ = event; - } -#endif - - ~PluginInstance(); - void OnPluginThreadAsyncCall(void (*func)(void *), void *userData); - void OnTimerCall(void (*func)(NPP id, uint32 timer_id), - NPP id, uint32 timer_id); - bool IsValidStream(const NPStream* stream); - void GetNotifyData(int notify_id, bool* notify, void** notify_data); - - // This is a hack to get the real player plugin to work with chrome - // The real player plugin dll(nppl3260) when loaded by firefox is loaded via - // the NS COM API which is analogous to win32 COM. So the NPAPI functions in - // the plugin are invoked via an interface by firefox. The plugin instance - // handle which is passed to every NPAPI method is owned by the real player - // plugin, i.e. it expects the ndata member to point to a structure which - // it knows about. Eventually it dereferences this structure and compares - // a member variable at offset 0x24(Version 6.0.11.2888) /2D (Version - // 6.0.11.3088) with 0 and on failing this check, takes a different code - // path which causes a crash. Safari and Opera work with version 6.0.11.2888 - // by chance as their ndata structure contains a 0 at the location which real - // player checks:(. They crash with version 6.0.11.3088 as well. The - // following member just adds a 96 byte padding to our PluginInstance class - // which is passed in the ndata member. This magic number works correctly on - // Vista with UAC on or off :(. - // NOTE: Please dont change the ordering of the member variables - // New members should be added after this padding array. - // TODO(iyengar) : Disassemble the Realplayer ndata structure and look into - // the possiblity of conforming to it (http://b/issue?id=936667). We - // could also log a bug with Real, which would save the effort. - uint8 zero_padding_[96]; - scoped_refptr<NPAPI::PluginLib> plugin_; - NPP npp_; - scoped_refptr<PluginHost> host_; - NPPluginFuncs* npp_functions_; - std::vector<scoped_refptr<PluginStream> > open_streams_; - gfx::PluginWindowHandle window_handle_; - bool windowless_; - bool transparent_; - webkit_glue::WebPlugin* webplugin_; - std::string mime_type_; - GURL get_url_; - intptr_t get_notify_data_; - bool use_mozilla_user_agent_; -#if defined(OS_MACOSX) - NPDrawingModel drawing_model_; - NPEventModel event_model_; - gfx::Point plugin_origin_; - gfx::Rect containing_window_frame_; - NPCocoaEvent* currently_handled_event_; // weak -#endif - MessageLoop* message_loop_; - scoped_refptr<PluginStreamUrl> plugin_data_stream_; - - // This flag if true indicates that the plugin data would be passed from - // webkit. if false indicates that the plugin should download the data. - bool load_manually_; - - // Stack indicating if popups are to be enabled for the outgoing - // NPN_GetURL/NPN_GetURLNotify calls. - std::stack<bool> popups_enabled_stack_; - - // True if in CloseStreams(). - bool in_close_streams_; - - // List of files created for the current plugin instance. File names are - // added to the list every time the NPP_StreamAsFile function is called. - std::vector<FilePath> files_created_; - - // Next unusued timer id. - uint32 next_timer_id_; - - // Map of timer id to settings for timer. - struct TimerInfo { - uint32 interval; - bool repeat; - }; - typedef std::map<uint32, TimerInfo> TimerMap; - TimerMap timers_; - - // Tracks pending GET/POST requests so that the plugin-given data doesn't - // cross process boundaries to an untrusted process. - typedef std::map<int, void*> PendingRequestMap; - PendingRequestMap pending_requests_; - int next_notify_id_; - - // Used to track pending range requests so that when WebPlugin replies to us - // we can match the reply to the stream. - typedef std::map<int, scoped_refptr<PluginStream> > PendingRangeRequestMap; - PendingRangeRequestMap pending_range_requests_; - int next_range_request_id_; - // The plugin handles the NPAPI URL redirect notification API. - // See here https://wiki.mozilla.org/NPAPI:HTTPRedirectHandling - bool handles_url_redirects_; - - DISALLOW_COPY_AND_ASSIGN(PluginInstance); -}; - -#if defined(OS_MACOSX) -// Helper to simplify correct usage of set_currently_handled_event. -// Instantiating will set |instance|'s currently handled to |event| for the -// lifetime of the object, then NULL when it goes out of scope. -class ScopedCurrentPluginEvent { - public: - ScopedCurrentPluginEvent(PluginInstance* instance, NPCocoaEvent* event) - : instance_(instance) { - instance_->set_currently_handled_event(event); - } - ~ScopedCurrentPluginEvent() { - instance_->set_currently_handled_event(NULL); - } - private: - scoped_refptr<PluginInstance> instance_; - DISALLOW_COPY_AND_ASSIGN(ScopedCurrentPluginEvent); -}; -#endif - -} // namespace NPAPI - -#endif // WEBKIT_GLUE_PLUGIN_PLUGIN_INSTANCE_H__ diff --git a/webkit/glue/plugins/plugin_instance_mac.mm b/webkit/glue/plugins/plugin_instance_mac.mm deleted file mode 100644 index 9800198..0000000 --- a/webkit/glue/plugins/plugin_instance_mac.mm +++ /dev/null @@ -1,133 +0,0 @@ -// 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 "build/build_config.h" - -#import <AppKit/AppKit.h> - -#include "base/logging.h" -#include "webkit/glue/plugins/plugin_instance.h" - -// When C++ exceptions are disabled, the C++ library defines |try| and -// |catch| so as to allow exception-expecting C++ code to build properly when -// language support for exceptions is not present. These macros interfere -// with the use of |@try| and |@catch| in Objective-C files such as this one. -// Undefine these macros here, after everything has been #included, since -// there will be no C++ uses and only Objective-C uses from this point on. -#undef try -#undef catch - -#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5 -@interface NSMenu (SnowLeopardMenuPopUpDeclaration) -- (BOOL)popUpMenuPositioningItem:(NSMenuItem*)item - atLocation:(NSPoint)location - inView:(NSView*)view; -@end -#endif - -namespace { - -// Returns an autoreleased NSEvent constructed from the given np_event, -// targeting the given window. -NSEvent* NSEventForNPCocoaEvent(NPCocoaEvent* np_event, NSWindow* window) { - bool mouse_down = 1; - switch (np_event->type) { - case NPCocoaEventMouseDown: - mouse_down = 1; - break; - case NPCocoaEventMouseUp: - mouse_down = 0; - break; - default: - // If plugins start bringing up context menus for things other than - // clicks, this will need more plumbing; for now just log it and proceed - // as if it were a mouse down. - NOTREACHED(); - } - NSEventType event_type = NSLeftMouseDown; - switch (np_event->data.mouse.buttonNumber) { - case 0: - event_type = mouse_down ? NSLeftMouseDown : NSLeftMouseUp; - break; - case 1: - event_type = mouse_down ? NSRightMouseDown : NSRightMouseUp; - break; - default: - event_type = mouse_down ? NSOtherMouseDown : NSOtherMouseUp; - break; - } - - NSInteger click_count = np_event->data.mouse.clickCount; - NSInteger modifiers = np_event->data.mouse.modifierFlags; - // NPCocoaEvent doesn't have a timestamp, so just use the current time. - NSEvent* event = - [NSEvent mouseEventWithType:event_type - location:NSMakePoint(0, 0) - modifierFlags:modifiers - timestamp:[[NSApp currentEvent] timestamp] - windowNumber:[window windowNumber] - context:[NSGraphicsContext currentContext] - eventNumber:0 - clickCount:click_count - pressure:1.0]; - return event; -} - -} // namespace - -namespace NPAPI { - -NPError PluginInstance::PopUpContextMenu(NPMenu* menu) { - if (!currently_handled_event_) - return NPERR_GENERIC_ERROR; - - CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID()); - NSPoint screen_point = NSMakePoint( - plugin_origin_.x() + currently_handled_event_->data.mouse.pluginX, - plugin_origin_.y() + currently_handled_event_->data.mouse.pluginY); - // Plugin offsets are upper-left based, so flip vertically for Cocoa. - screen_point.y = main_display_bounds.size.height - screen_point.y; - - NSMenu* nsmenu = reinterpret_cast<NSMenu*>(menu); - NPError return_val = NPERR_NO_ERROR; - NSWindow* window = nil; - @try { - if ([nsmenu respondsToSelector: - @selector(popUpMenuPositioningItem:atLocation:inView:)]) { - [nsmenu popUpMenuPositioningItem:nil atLocation:screen_point inView:nil]; - } else { - NSRect dummy_window_rect = NSMakeRect(screen_point.x, screen_point.y, - 1, 1); - window = [[NSWindow alloc] initWithContentRect:dummy_window_rect - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreNonretained - defer:YES]; - [window setTitle:@"PopupMenuDummy"]; // Lets interposing identify it. - [window setAlphaValue:0]; - [window makeKeyAndOrderFront:nil]; - [NSMenu popUpContextMenu:nsmenu - withEvent:NSEventForNPCocoaEvent(currently_handled_event_, - window) - forView:[window contentView]]; - } - } - @catch (NSException* e) { - NSLog(@"Caught exception while handling PopUpContextMenu: %@", e); - return_val = NPERR_GENERIC_ERROR; - } - - if (window) { - @try { - [window orderOut:nil]; - [window release]; - } - @catch (NSException* e) { - NSLog(@"Caught exception while cleaning up in PopUpContextMenu: %@", e); - } - } - - return return_val; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_lib.cc b/webkit/glue/plugins/plugin_lib.cc deleted file mode 100644 index 4ae4da4..0000000 --- a/webkit/glue/plugins/plugin_lib.cc +++ /dev/null @@ -1,349 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_lib.h" - -#include "base/logging.h" -#include "base/message_loop.h" -#include "base/metrics/stats_counters.h" -#include "base/string_util.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_host.h" -#include "webkit/glue/plugins/plugin_list.h" - -namespace NPAPI { - -const char kPluginLibrariesLoadedCounter[] = "PluginLibrariesLoaded"; -const char kPluginInstancesActiveCounter[] = "PluginInstancesActive"; - -// A list of all the instantiated plugins. -static std::vector<scoped_refptr<PluginLib> >* g_loaded_libs; - -PluginLib* PluginLib::CreatePluginLib(const FilePath& filename) { - // We can only have one PluginLib object per plugin as it controls the per - // instance function calls (i.e. NP_Initialize and NP_Shutdown). So we keep - // a map of PluginLib objects. - if (!g_loaded_libs) - g_loaded_libs = new std::vector<scoped_refptr<PluginLib> >; - - for (size_t i = 0; i < g_loaded_libs->size(); ++i) { - if ((*g_loaded_libs)[i]->plugin_info().path == filename) - return (*g_loaded_libs)[i]; - } - - WebPluginInfo info; - const PluginEntryPoints* entry_points = NULL; - if (!PluginList::Singleton()->ReadPluginInfo(filename, &info, &entry_points)) - return NULL; - - return new PluginLib(info, entry_points); -} - -void PluginLib::UnloadAllPlugins() { - if (g_loaded_libs) { - // PluginLib::Unload() can remove items from the list and even delete - // the list when it removes the last item, so we must work with a copy - // of the list so that we don't get the carpet removed under our feet. - std::vector<scoped_refptr<PluginLib> > loaded_libs(*g_loaded_libs); - for (size_t i = 0; i < loaded_libs.size(); ++i) - loaded_libs[i]->Unload(); - - if (g_loaded_libs && g_loaded_libs->empty()) { - delete g_loaded_libs; - g_loaded_libs = NULL; - } - } -} - -void PluginLib::ShutdownAllPlugins() { - if (g_loaded_libs) { - for (size_t i = 0; i < g_loaded_libs->size(); ++i) - (*g_loaded_libs)[i]->Shutdown(); - } -} - -PluginLib::PluginLib(const WebPluginInfo& info, - const PluginEntryPoints* entry_points) - : web_plugin_info_(info), - library_(NULL), - initialized_(false), - saved_data_(0), - instance_count_(0), - skip_unload_(false) { - base::StatsCounter(kPluginLibrariesLoadedCounter).Increment(); - memset(static_cast<void*>(&plugin_funcs_), 0, sizeof(plugin_funcs_)); - g_loaded_libs->push_back(make_scoped_refptr(this)); - - if (entry_points) { - internal_ = true; - entry_points_ = *entry_points; - } else { - internal_ = false; - // We will read the entry points from the plugin directly. - memset(&entry_points_, 0, sizeof(entry_points_)); - } -} - -PluginLib::~PluginLib() { - base::StatsCounter(kPluginLibrariesLoadedCounter).Decrement(); - if (saved_data_ != 0) { - // TODO - delete the savedData object here - } -} - -NPPluginFuncs* PluginLib::functions() { - return &plugin_funcs_; -} - -NPError PluginLib::NP_Initialize() { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "PluginLib::NP_Initialize(" << web_plugin_info_.path.value() - << "): initialized=" << initialized_; - if (initialized_) - return NPERR_NO_ERROR; - - if (!Load()) - return NPERR_MODULE_LOAD_FAILED_ERROR; - - PluginHost* host = PluginHost::Singleton(); - if (host == 0) - return NPERR_GENERIC_ERROR; - -#if defined(OS_POSIX) && !defined(OS_MACOSX) - NPError rv = entry_points_.np_initialize(host->host_functions(), - &plugin_funcs_); -#else - NPError rv = entry_points_.np_initialize(host->host_functions()); -#if defined(OS_MACOSX) - // On the Mac, we need to get entry points after calling np_initialize to - // match the behavior of other browsers. - if (rv == NPERR_NO_ERROR) { - rv = entry_points_.np_getentrypoints(&plugin_funcs_); - } -#endif // OS_MACOSX -#endif - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "PluginLib::NP_Initialize(" << web_plugin_info_.path.value() - << "): result=" << rv; - initialized_ = (rv == NPERR_NO_ERROR); - return rv; -} - -void PluginLib::NP_Shutdown(void) { - DCHECK(initialized_); - entry_points_.np_shutdown(); -} - -void PluginLib::PreventLibraryUnload() { - skip_unload_ = true; -} - -PluginInstance* PluginLib::CreateInstance(const std::string& mime_type) { - PluginInstance* new_instance = new PluginInstance(this, mime_type); - instance_count_++; - base::StatsCounter(kPluginInstancesActiveCounter).Increment(); - DCHECK_NE(static_cast<PluginInstance*>(NULL), new_instance); - return new_instance; -} - -void PluginLib::CloseInstance() { - base::StatsCounter(kPluginInstancesActiveCounter).Decrement(); - instance_count_--; - // If a plugin is running in its own process it will get unloaded on process - // shutdown. - if ((instance_count_ == 0) && webkit_glue::IsPluginRunningInRendererProcess()) - Unload(); -} - -bool PluginLib::Load() { - if (library_) - return true; - - bool rv = false; - base::NativeLibrary library = 0; - - if (!internal_) { -#if defined(OS_WIN) - // This is to work around a bug in the Real player recorder plugin which - // intercepts LoadLibrary calls from chrome.dll and wraps NPAPI functions - // provided by the plugin. It crashes if the media player plugin is being - // loaded. Workaround is to load the dll dynamically by getting the - // LoadLibrary API address from kernel32.dll which bypasses the recorder - // plugin. - if (web_plugin_info_.name.find(L"Windows Media Player") != - std::wstring::npos) { - library = base::LoadNativeLibraryDynamically(web_plugin_info_.path); - } else { - library = base::LoadNativeLibrary(web_plugin_info_.path); - } -#else // OS_WIN - library = base::LoadNativeLibrary(web_plugin_info_.path); -#endif // OS_WIN - if (library == 0) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Couldn't load plugin " << web_plugin_info_.path.value(); - return rv; - } - -#if defined(OS_MACOSX) - // According to the WebKit source, QuickTime at least requires us to call - // UseResFile on the plugin resources before loading. - if (library->bundle_resource_ref != -1) - UseResFile(library->bundle_resource_ref); -#endif - - rv = true; // assume success now - - entry_points_.np_initialize = - (NP_InitializeFunc)base::GetFunctionPointerFromNativeLibrary(library, - "NP_Initialize"); - if (entry_points_.np_initialize == 0) - rv = false; - -#if defined(OS_WIN) || defined(OS_MACOSX) - entry_points_.np_getentrypoints = - (NP_GetEntryPointsFunc)base::GetFunctionPointerFromNativeLibrary( - library, "NP_GetEntryPoints"); - if (entry_points_.np_getentrypoints == 0) - rv = false; -#endif - - entry_points_.np_shutdown = - (NP_ShutdownFunc)base::GetFunctionPointerFromNativeLibrary(library, - "NP_Shutdown"); - if (entry_points_.np_shutdown == 0) - rv = false; - } else { - rv = true; - } - - if (rv) { - plugin_funcs_.size = sizeof(plugin_funcs_); - plugin_funcs_.version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; -#if !defined(OS_POSIX) - if (entry_points_.np_getentrypoints(&plugin_funcs_) != NPERR_NO_ERROR) - rv = false; -#else - // On Linux and Mac, we get the plugin entry points during NP_Initialize. -#endif - } - - if (!internal_) { - if (rv) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Plugin " << web_plugin_info_.path.value() - << " loaded successfully."; - library_ = library; - } else { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Plugin " << web_plugin_info_.path.value() - << " failed to load, unloading."; - base::UnloadNativeLibrary(library); - } - } - - return rv; -} - -// This class implements delayed NP_Shutdown and FreeLibrary on the plugin dll. -class FreePluginLibraryTask : public Task { - public: - FreePluginLibraryTask(const FilePath& path, - base::NativeLibrary library, - NP_ShutdownFunc shutdown_func) - : path_(path), - library_(library), - NP_Shutdown_(shutdown_func) { - } - - ~FreePluginLibraryTask() {} - - void Run() { - if (NP_Shutdown_) { - // Don't call NP_Shutdown if the library has been reloaded since this task - // was posted. - bool reloaded = false; - if (g_loaded_libs) { - for (size_t i = 0; i < g_loaded_libs->size(); ++i) { - if ((*g_loaded_libs)[i]->plugin_info().path == path_) - reloaded = true; - } - } - if (!reloaded) - NP_Shutdown_(); - } - - if (library_) { - // Always call base::UnloadNativeLibrary so that the system reference - // count is decremented. - base::UnloadNativeLibrary(library_); - library_ = NULL; - } - } - - private: - FilePath path_; - base::NativeLibrary library_; - NP_ShutdownFunc NP_Shutdown_; - DISALLOW_COPY_AND_ASSIGN(FreePluginLibraryTask); -}; - -void PluginLib::Unload() { - if (!internal_ && library_) { - // In case of single process mode, a plugin can delete itself - // by executing a script. So delay the unloading of the library - // so that the plugin will have a chance to unwind. - bool defer_unload = webkit_glue::IsPluginRunningInRendererProcess(); - -/* TODO(dglazkov): Revisit when re-enabling the JSC build. -#if USE(JSC) - // The plugin NPAPI instances may still be around. Delay the - // NP_Shutdown and FreeLibrary calls at least till the next - // peek message. - defer_unload = true; -#endif -*/ - - if (defer_unload) { - FreePluginLibraryTask* free_library_task = - new FreePluginLibraryTask(web_plugin_info_.path, - skip_unload_ ? NULL : library_, - entry_points_.np_shutdown); - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Scheduling delayed unload for plugin " - << web_plugin_info_.path.value(); - MessageLoop::current()->PostTask(FROM_HERE, free_library_task); - } else { - Shutdown(); - if (!skip_unload_) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Unloading plugin " << web_plugin_info_.path.value(); - base::UnloadNativeLibrary(library_); - } - } - - library_ = NULL; - } - - for (size_t i = 0; i < g_loaded_libs->size(); ++i) { - if ((*g_loaded_libs)[i].get() == this) { - g_loaded_libs->erase(g_loaded_libs->begin() + i); - break; - } - } - if (g_loaded_libs->empty()) { - delete g_loaded_libs; - g_loaded_libs = NULL; - } -} - -void PluginLib::Shutdown() { - if (initialized_ && !internal_) { - NP_Shutdown(); - initialized_ = false; - } -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_lib.h b/webkit/glue/plugins/plugin_lib.h deleted file mode 100644 index ca46e41..0000000 --- a/webkit/glue/plugins/plugin_lib.h +++ /dev/null @@ -1,120 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PLUGIN_LIB_H_ -#define WEBKIT_GLUE_PLUGINS_PLUGIN_LIB_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/native_library.h" -#include "base/ref_counted.h" -#include "build/build_config.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/webplugin.h" - -class FilePath; -struct WebPluginInfo; - -namespace NPAPI { - -class PluginInstance; - -// A PluginLib is a single NPAPI Plugin Library, and is the lifecycle -// manager for new PluginInstances. -class PluginLib : public base::RefCounted<PluginLib> { - public: - static PluginLib* CreatePluginLib(const FilePath& filename); - - // Creates a WebPluginInfo structure given a plugin's path. On success - // returns true, with the information being put into "info". - // Returns false if the library couldn't be found, or if it's not a plugin. - static bool ReadWebPluginInfo(const FilePath& filename, WebPluginInfo* info); - -#if defined(OS_POSIX) && !defined(OS_MACOSX) - // Parse the result of an NP_GetMIMEDescription() call. - // This API is only used on Unixes, and is exposed here for testing. - static void ParseMIMEDescription(const std::string& description, - std::vector<WebPluginMimeType>* mime_types); -#endif - - // Unloads all the loaded plugin libraries and cleans up the plugin map. - static void UnloadAllPlugins(); - - // Shuts down all loaded plugin instances. - static void ShutdownAllPlugins(); - - // Get the Plugin's function pointer table. - NPPluginFuncs* functions(); - - // Creates a new instance of this plugin. - PluginInstance* CreateInstance(const std::string& mime_type); - - // Called by the instance when the instance is tearing down. - void CloseInstance(); - - // Gets information about this plugin and the mime types that it - // supports. - const WebPluginInfo& plugin_info() { return web_plugin_info_; } - - bool internal() { return internal_; } - - // - // NPAPI functions - // - - // NPAPI method to initialize a Plugin. - // Initialize can be safely called multiple times - NPError NP_Initialize(); - - // NPAPI method to shutdown a Plugin. - void NP_Shutdown(void); - - int instance_count() const { return instance_count_; } - - // Prevents the library code from being unload when Unload() is called (since - // some plugins crash if unloaded). - void PreventLibraryUnload(); - - // protected for testability. - protected: - friend class base::RefCounted<PluginLib>; - - // Creates a new PluginLib. - // |entry_points| is non-NULL for internal plugins. - PluginLib(const WebPluginInfo& info, - const PluginEntryPoints* entry_points); - - virtual ~PluginLib(); - - // Attempts to load the plugin from the library. - // Returns true if it is a legitimate plugin, false otherwise - bool Load(); - - // Unloads the plugin library. - void Unload(); - - // Shutdown the plugin library. - void Shutdown(); - - private: - bool internal_; // True for plugins that are built-in into chrome binaries. - WebPluginInfo web_plugin_info_; // Supported mime types, description - base::NativeLibrary library_; // The opened library reference. - NPPluginFuncs plugin_funcs_; // The struct of plugin side functions. - bool initialized_; // Is the plugin initialized? - NPSavedData *saved_data_; // Persisted plugin info for NPAPI. - int instance_count_; // Count of plugins in use. - bool skip_unload_; // True if library_ should not be unloaded. - - // Function pointers to entry points into the plugin. - PluginEntryPoints entry_points_; - - DISALLOW_COPY_AND_ASSIGN(PluginLib); -}; - -} // namespace NPAPI - -#endif // WEBKIT_GLUE_PLUGINS_PLUGIN_LIB_H_ diff --git a/webkit/glue/plugins/plugin_lib_mac.mm b/webkit/glue/plugins/plugin_lib_mac.mm deleted file mode 100644 index 89444c8..0000000 --- a/webkit/glue/plugins/plugin_lib_mac.mm +++ /dev/null @@ -1,348 +0,0 @@ -// 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. - -#import <Carbon/Carbon.h> - -#include "webkit/glue/plugins/plugin_lib.h" - -#include "base/mac/scoped_cftyperef.h" -#include "base/native_library.h" -#include "base/scoped_ptr.h" -#include "base/string_split.h" -#include "base/string_util.h" -#include "base/sys_string_conversions.h" -#include "base/utf_string_conversions.h" -#include "webkit/glue/plugins/plugin_list.h" - -static const short kSTRTypeDefinitionResourceID = 128; -static const short kSTRTypeDescriptionResourceID = 127; -static const short kSTRPluginDescriptionResourceID = 126; - -using base::mac::ScopedCFTypeRef; - -namespace NPAPI { - -namespace { - -NSDictionary* GetMIMETypes(CFBundleRef bundle) { - NSString* mime_filename = - (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle, - CFSTR("WebPluginMIMETypesFilename")); - - if (mime_filename) { - - // get the file - - NSString* mime_path = - [NSString stringWithFormat:@"%@/Library/Preferences/%@", - NSHomeDirectory(), mime_filename]; - NSDictionary* mime_file_dict = - [NSDictionary dictionaryWithContentsOfFile:mime_path]; - - // is it valid? - - bool valid_file = false; - if (mime_file_dict) { - NSString* l10n_name = - [mime_file_dict objectForKey:@"WebPluginLocalizationName"]; - NSString* preferred_l10n = [[NSLocale currentLocale] localeIdentifier]; - if ([l10n_name isEqualToString:preferred_l10n]) - valid_file = true; - } - - if (valid_file) - return [mime_file_dict objectForKey:@"WebPluginMIMETypes"]; - - // dammit, I didn't want to have to do this - - typedef void (*CreateMIMETypesPrefsPtr)(void); - CreateMIMETypesPrefsPtr create_prefs_file = - (CreateMIMETypesPrefsPtr)CFBundleGetFunctionPointerForName( - bundle, CFSTR("BP_CreatePluginMIMETypesPreferences")); - if (!create_prefs_file) - return nil; - create_prefs_file(); - - // one more time - - mime_file_dict = [NSDictionary dictionaryWithContentsOfFile:mime_path]; - if (mime_file_dict) - return [mime_file_dict objectForKey:@"WebPluginMIMETypes"]; - else - return nil; - - } else { - return (NSDictionary*)CFBundleGetValueForInfoDictionaryKey(bundle, - CFSTR("WebPluginMIMETypes")); - } -} - -bool ReadPlistPluginInfo(const FilePath& filename, CFBundleRef bundle, - WebPluginInfo* info) { - NSDictionary* mime_types = GetMIMETypes(bundle); - if (!mime_types) - return false; // no type info here; try elsewhere - - for (NSString* mime_type in [mime_types allKeys]) { - NSDictionary* mime_dict = [mime_types objectForKey:mime_type]; - NSString* mime_desc = [mime_dict objectForKey:@"WebPluginTypeDescription"]; - NSArray* mime_exts = [mime_dict objectForKey:@"WebPluginExtensions"]; - - WebPluginMimeType mime; - mime.mime_type = base::SysNSStringToUTF8([mime_type lowercaseString]); - // Remove PDF from the list of types handled by QuickTime, since it provides - // a worse experience than just downloading the PDF. - if (mime.mime_type == "application/pdf" && - StartsWithASCII(filename.BaseName().value(), "QuickTime", false)) { - continue; - } - - if (mime_desc) - mime.description = base::SysNSStringToUTF16(mime_desc); - for (NSString* ext in mime_exts) - mime.file_extensions.push_back( - base::SysNSStringToUTF8([ext lowercaseString])); - - info->mime_types.push_back(mime); - } - - NSString* plugin_name = - (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle, - CFSTR("WebPluginName")); - NSString* plugin_vers = - (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle, - CFSTR("CFBundleShortVersionString")); - NSString* plugin_desc = - (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle, - CFSTR("WebPluginDescription")); - - if (plugin_name) - info->name = base::SysNSStringToUTF16(plugin_name); - else - info->name = UTF8ToUTF16(filename.BaseName().value()); - info->path = filename; - if (plugin_vers) - info->version = base::SysNSStringToUTF16(plugin_vers); - if (plugin_desc) - info->desc = base::SysNSStringToUTF16(plugin_desc); - else - info->desc = UTF8ToUTF16(filename.BaseName().value()); - info->enabled = true; - - return true; -} - -class ScopedBundleResourceFile { - public: - ScopedBundleResourceFile(CFBundleRef bundle) : bundle_(bundle) { - old_ref_num_ = CurResFile(); - bundle_ref_num_ = CFBundleOpenBundleResourceMap(bundle); - UseResFile(bundle_ref_num_); - } - ~ScopedBundleResourceFile() { - UseResFile(old_ref_num_); - CFBundleCloseBundleResourceMap(bundle_, bundle_ref_num_); - } - - private: - CFBundleRef bundle_; - CFBundleRefNum bundle_ref_num_; - ResFileRefNum old_ref_num_; -}; - -bool GetSTRResource(CFBundleRef bundle, short res_id, - std::vector<std::string>* contents) { - Handle res_handle = Get1Resource('STR#', res_id); - if (!res_handle || !*res_handle) - return false; - - char* pointer = *res_handle; - short num_strings = *(short*)pointer; - pointer += sizeof(short); - for (short i = 0; i < num_strings; ++i) { - // Despite being 8-bits wide, these are legacy encoded. Make a round trip. - ScopedCFTypeRef<CFStringRef> str(CFStringCreateWithPascalStringNoCopy( - kCFAllocatorDefault, - (unsigned char*)pointer, - GetApplicationTextEncoding(), // is this right? - kCFAllocatorNull)); // perhaps CFStringGetSystemEncoding? - if (!str.get()) - return false; - contents->push_back(base::SysCFStringRefToUTF8(str.get())); - pointer += 1+*reinterpret_cast<unsigned char*>(pointer); - } - - return true; -} - -bool ReadSTRPluginInfo(const FilePath& filename, CFBundleRef bundle, - WebPluginInfo* info) { - ScopedBundleResourceFile res_file(bundle); - - std::vector<std::string> type_strings; - if (!GetSTRResource(bundle, kSTRTypeDefinitionResourceID, &type_strings)) - return false; - - std::vector<std::string> type_descs; - bool have_type_descs = GetSTRResource(bundle, - kSTRTypeDescriptionResourceID, - &type_descs); - - std::vector<std::string> plugin_descs; - bool have_plugin_descs = GetSTRResource(bundle, - kSTRPluginDescriptionResourceID, - &plugin_descs); - - size_t num_types = type_strings.size()/2; - - for (size_t i = 0; i < num_types; ++i) { - WebPluginMimeType mime; - mime.mime_type = StringToLowerASCII(type_strings[2*i]); - if (have_type_descs && i < type_descs.size()) - mime.description = UTF8ToUTF16(type_descs[i]); - base::SplitString( - StringToLowerASCII(type_strings[2*i+1]), ',', &mime.file_extensions); - - info->mime_types.push_back(mime); - } - - NSString* plugin_vers = - (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle, - CFSTR("CFBundleShortVersionString")); - - if (have_plugin_descs && plugin_descs.size() > 1) - info->name = UTF8ToUTF16(plugin_descs[1]); - else - info->name = UTF8ToUTF16(filename.BaseName().value()); - info->path = filename; - if (plugin_vers) - info->version = base::SysNSStringToUTF16(plugin_vers); - if (have_plugin_descs && plugin_descs.size() > 0) - info->desc = UTF8ToUTF16(plugin_descs[0]); - else - info->desc = UTF8ToUTF16(filename.BaseName().value()); - info->enabled = true; - - return true; -} - -} // anonymous namespace - -bool PluginLib::ReadWebPluginInfo(const FilePath &filename, - WebPluginInfo* info) { - // There are two ways to get information about plugin capabilities. One is an - // Info.plist set of keys, documented at - // http://developer.apple.com/documentation/InternetWeb/Conceptual/WebKit_PluginProgTopic/Concepts/AboutPlugins.html . - // The other is a set of STR# resources, documented at - // https://developer.mozilla.org/En/Gecko_Plugin_API_Reference/Plug-in_Development_Overview . - // - // Historically, the data was maintained in the STR# resources. Apple, with - // the introduction of WebKit, noted the weaknesses of resources and moved the - // information into the Info.plist. Mozilla had always supported a - // NP_GetMIMEDescription() entry point for Unix plugins and also supports it - // on the Mac to supplement the STR# format. WebKit does not support - // NP_GetMIMEDescription() and neither do we. (That entry point is documented - // at https://developer.mozilla.org/en/NP_GetMIMEDescription .) We prefer the - // Info.plist format because it's more extensible and has a defined encoding, - // but will fall back to the STR# format of the data if it is not present in - // the Info.plist. - // - // The parsing of the data lives in the two functions ReadSTRPluginInfo() and - // ReadPlistPluginInfo(), but a summary of the formats follows. - // - // Each data type handled by a plugin has several properties: - // - <<type0mimetype>> - // - <<type0fileextension0>>..<<type0fileextensionk>> - // - <<type0description>> - // - // Each plugin may have any number of types defined. In addition, the plugin - // itself has properties: - // - <<plugindescription>> - // - <<pluginname>> - // - // For the Info.plist version, the data is formatted as follows (in text plist - // format): - // { - // ... the usual plist keys ... - // WebPluginDescription = <<plugindescription>>; - // WebPluginMIMETypes = { - // <<type0mimetype>> = { - // WebPluginExtensions = ( - // <<type0fileextension0>>, - // ... - // <<type0fileextensionk>>, - // ); - // WebPluginTypeDescription = <<type0description>>; - // }; - // <<type1mimetype>> = { ... }; - // ... - // <<typenmimetype>> = { ... }; - // }; - // WebPluginName = <<pluginname>>; - // } - // - // Alternatively (and this is undocumented), rather than a WebPluginMIMETypes - // key, there may be a WebPluginMIMETypesFilename key. If it is present, then - // it is the name of a file in the user's preferences folder in which to find - // the WebPluginMIMETypes key. If the key is present but the file doesn't - // exist, we must load the plugin and call a specific function to have the - // plugin create the file. - // - // If we do not find those keys in the Info.plist, we fall back to the STR# - // resources. In them, the data is formatted as follows: - // STR# 128 - // (1) <<type0mimetype>> - // (2) <<type0fileextension0>>,...,<<type0fileextensionk>> - // (3) <<type1mimetype>> - // (4) <<type1fileextension0>>,...,<<type1fileextensionk>> - // (...) - // (2n+1) <<typenmimetype>> - // (2n+2) <<typenfileextension0>>,...,<<typenfileextensionk>> - // STR# 127 - // (1) <<type0description>> - // (2) <<type1description>> - // (...) - // (n+1) <<typendescription>> - // STR# 126 - // (1) <<plugindescription>> - // (2) <<pluginname>> - // - // Strictly speaking, only STR# 128 is required. - - ScopedCFTypeRef<CFURLRef> bundle_url(CFURLCreateFromFileSystemRepresentation( - kCFAllocatorDefault, (const UInt8*)filename.value().c_str(), - filename.value().length(), true)); - if (!bundle_url) - return false; - ScopedCFTypeRef<CFBundleRef> bundle(CFBundleCreate(kCFAllocatorDefault, - bundle_url.get())); - if (!bundle) - return false; - - // preflight - - OSType type = 0; - CFBundleGetPackageInfo(bundle.get(), &type, NULL); - if (type != FOUR_CHAR_CODE('BRPL')) - return false; - - CFErrorRef error; - Boolean would_load = CFBundlePreflightExecutable(bundle.get(), &error); - if (!would_load) - return false; - - // get the info - - if (ReadPlistPluginInfo(filename, bundle.get(), info)) - return true; - - if (ReadSTRPluginInfo(filename, bundle.get(), info)) - return true; - - // ... or not - - return false; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_lib_posix.cc b/webkit/glue/plugins/plugin_lib_posix.cc deleted file mode 100644 index ac937e1..0000000 --- a/webkit/glue/plugins/plugin_lib_posix.cc +++ /dev/null @@ -1,256 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_lib.h" - -#include <dlfcn.h> -#if defined(OS_OPENBSD) -#include <sys/exec_elf.h> -#else -#include <elf.h> -#include <fcntl.h> -#endif -#include <sys/stat.h> -#include <sys/types.h> -#include <unistd.h> - -#include "base/eintr_wrapper.h" -#include "base/file_util.h" -#include "base/string_split.h" -#include "base/string_util.h" -#include "base/sys_string_conversions.h" -#include "base/utf_string_conversions.h" -#include "webkit/glue/plugins/plugin_list.h" - -// These headers must be included in this order to make the declaration gods -// happy. -#include "base/third_party/nspr/prcpucfg_linux.h" - -namespace { - -using NPAPI::PluginList; - -// Copied from nsplugindefs.h instead of including the file since it has a bunch -// of dependencies. -enum nsPluginVariable { - nsPluginVariable_NameString = 1, - nsPluginVariable_DescriptionString = 2 -}; - -// Read the ELF header and return true if it is usable on -// the current architecture (e.g. 32-bit ELF on 32-bit build). -// Returns false on other errors as well. -bool ELFMatchesCurrentArchitecture(const FilePath& filename) { - // First make sure we can open the file and it is in fact, a regular file. - struct stat stat_buf; - // Open with O_NONBLOCK so we don't block on pipes. - int fd = open(filename.value().c_str(), O_RDONLY|O_NONBLOCK); - if (fd < 0) - return false; - bool ret = (fstat(fd, &stat_buf) >= 0 && S_ISREG(stat_buf.st_mode)); - if (HANDLE_EINTR(close(fd)) < 0) - return false; - if (!ret) - return false; - - const size_t kELFBufferSize = 5; - char buffer[kELFBufferSize]; - if (!file_util::ReadFile(filename, buffer, kELFBufferSize)) - return false; - - if (buffer[0] != ELFMAG0 || - buffer[1] != ELFMAG1 || - buffer[2] != ELFMAG2 || - buffer[3] != ELFMAG3) { - // Not an ELF file, perhaps? - return false; - } - - int elf_class = buffer[EI_CLASS]; -#if defined(ARCH_CPU_32_BITS) - if (elf_class == ELFCLASS32) - return true; -#elif defined(ARCH_CPU_64_BITS) - if (elf_class == ELFCLASS64) - return true; -#endif - - return false; -} - -// This structure matches enough of nspluginwrapper's NPW_PluginInfo -// for us to extract the real plugin path. -struct __attribute__((packed)) NSPluginWrapperInfo { - char ident[32]; // NSPluginWrapper magic identifier (includes version). - char path[PATH_MAX]; // Path to wrapped plugin. -}; - -// Test a plugin for whether it's been wrapped by NSPluginWrapper, and -// if so attempt to unwrap it. Pass in an opened plugin handle; on -// success, |dl| and |unwrapped_path| will be filled in with the newly -// opened plugin. On failure, params are left unmodified. -void UnwrapNSPluginWrapper(void **dl, FilePath* unwrapped_path) { - NSPluginWrapperInfo* info = - reinterpret_cast<NSPluginWrapperInfo*>(dlsym(*dl, "NPW_Plugin")); - if (!info) - return; // Not a NSPW plugin. - - // Here we could check the NSPW ident field for the versioning - // information, but the path field is available in all versions - // anyway. - - // Grab the path to the wrapped plugin. Just in case the structure - // format changes, protect against the path not being null-terminated. - char* path_end = static_cast<char*>(memchr(info->path, '\0', - sizeof(info->path))); - if (!path_end) - path_end = info->path + sizeof(info->path); - FilePath path = FilePath(std::string(info->path, path_end - info->path)); - - if (!ELFMatchesCurrentArchitecture(path)) { - LOG(WARNING) << path.value() << " is nspluginwrapper wrapping a " - << "plugin for a different architecture; it will " - << "work better if you instead use a native plugin."; - return; - } - - void* newdl = base::LoadNativeLibrary(path); - if (!newdl) { - // We couldn't load the unwrapped plugin for some reason, despite - // being able to load the wrapped one. Just use the wrapped one. - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Could not use unwrapped nspluginwrapper plugin " - << unwrapped_path->value() << ", using the wrapped one."; - return; - } - - // Unload the wrapped plugin, and use the wrapped plugin instead. - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Using unwrapped version " << unwrapped_path->value() - << " of nspluginwrapper-wrapped plugin."; - base::UnloadNativeLibrary(*dl); - *dl = newdl; - *unwrapped_path = path; -} - -} // anonymous namespace - -namespace NPAPI { - -bool PluginLib::ReadWebPluginInfo(const FilePath& filename, - WebPluginInfo* info) { - // The file to reference is: - // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp - - // Skip files that aren't appropriate for our architecture. - if (!ELFMatchesCurrentArchitecture(filename)) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Skipping plugin " << filename.value() - << " because it doesn't match the current architecture."; - return false; - } - - void* dl = base::LoadNativeLibrary(filename); - if (!dl) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "While reading plugin info, unable to load library " - << filename.value() << ", skipping."; - return false; - } - - info->path = filename; - info->enabled = true; - - // Attempt to swap in the wrapped plugin if this is nspluginwrapper. - UnwrapNSPluginWrapper(&dl, &info->path); - - // See comments in plugin_lib_mac regarding this symbol. - typedef const char* (*NP_GetMimeDescriptionType)(); - NP_GetMimeDescriptionType NP_GetMIMEDescription = - reinterpret_cast<NP_GetMimeDescriptionType>( - dlsym(dl, "NP_GetMIMEDescription")); - const char* mime_description = NULL; - if (NP_GetMIMEDescription) - mime_description = NP_GetMIMEDescription(); - - if (mime_description) - ParseMIMEDescription(mime_description, &info->mime_types); - - // The plugin name and description live behind NP_GetValue calls. - typedef NPError (*NP_GetValueType)(void* unused, - nsPluginVariable variable, - void* value_out); - NP_GetValueType NP_GetValue = - reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue")); - if (NP_GetValue) { - const char* name = NULL; - NP_GetValue(NULL, nsPluginVariable_NameString, &name); - if (name) - info->name = UTF8ToUTF16(name); - - const char* description = NULL; - NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description); - if (description) - info->desc = UTF8ToUTF16(description); - - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Got info for plugin " << filename.value() - << " Name = \"" << UTF16ToUTF8(info->name) - << "\", Description = \"" << UTF16ToUTF8(info->desc) << "\"."; - } else { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Plugin " << filename.value() - << " has no GetValue() and probably won't work."; - } - - // Intentionally not unloading the plugin here, it can lead to crashes. - - return true; -} - -// static -void PluginLib::ParseMIMEDescription( - const std::string& description, - std::vector<WebPluginMimeType>* mime_types) { - // We parse the description here into WebPluginMimeType structures. - // Naively from the NPAPI docs you'd think you could use - // string-splitting, but the Firefox parser turns out to do something - // different: find the first colon, then the second, then a semi. - // - // See ParsePluginMimeDescription near - // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUtils.h#53 - - std::string::size_type ofs = 0; - for (;;) { - WebPluginMimeType mime_type; - - std::string::size_type end = description.find(':', ofs); - if (end == std::string::npos) - break; - mime_type.mime_type = description.substr(ofs, end - ofs); - ofs = end + 1; - - end = description.find(':', ofs); - if (end == std::string::npos) - break; - const std::string extensions = description.substr(ofs, end - ofs); - base::SplitString(extensions, ',', &mime_type.file_extensions); - ofs = end + 1; - - end = description.find(';', ofs); - // It's ok for end to run off the string here. If there's no - // trailing semicolon we consume the remainder of the string. - if (end != std::string::npos) { - mime_type.description = UTF8ToUTF16(description.substr(ofs, end - ofs)); - } else { - mime_type.description = UTF8ToUTF16(description.substr(ofs)); - } - mime_types->push_back(mime_type); - if (end == std::string::npos) - break; - ofs = end + 1; - } -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_lib_unittest.cc b/webkit/glue/plugins/plugin_lib_unittest.cc deleted file mode 100644 index 45c4bb6..0000000 --- a/webkit/glue/plugins/plugin_lib_unittest.cc +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/plugin_lib.h" - -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "build/build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -// Test the unloading of plugin libs. Bug http://crbug.com/46526 showed that -// if UnloadAllPlugins() simply iterates through the g_loaded_libs global -// variable, we can get a crash if no plugin libs were marked as always loaded. -class PluginLibTest : public NPAPI::PluginLib { - public: - PluginLibTest() : NPAPI::PluginLib(WebPluginInfo(), NULL) { - } - using NPAPI::PluginLib::Unload; -}; - -TEST(PluginLibLoading, UnloadAllPlugins) { - // For the creation of the g_loaded_libs global variable. - ASSERT_EQ(static_cast<PluginLibTest*>(NULL), - PluginLibTest::CreatePluginLib(FilePath())); - - // Try with a single plugin lib. - scoped_refptr<PluginLibTest> plugin_lib1(new PluginLibTest()); - NPAPI::PluginLib::UnloadAllPlugins(); - - // Need to create it again, it should have been destroyed above. - ASSERT_EQ(static_cast<PluginLibTest*>(NULL), - PluginLibTest::CreatePluginLib(FilePath())); - - // Try with two plugin libs. - plugin_lib1 = new PluginLibTest(); - scoped_refptr<PluginLibTest> plugin_lib2(new PluginLibTest()); - NPAPI::PluginLib::UnloadAllPlugins(); - - // Need to create it again, it should have been destroyed above. - ASSERT_EQ(static_cast<PluginLibTest*>(NULL), - PluginLibTest::CreatePluginLib(FilePath())); - - // Now try to manually Unload one and then UnloadAll. - plugin_lib1 = new PluginLibTest(); - plugin_lib2 = new PluginLibTest(); - plugin_lib1->Unload(); - NPAPI::PluginLib::UnloadAllPlugins(); - - // Need to create it again, it should have been destroyed above. - ASSERT_EQ(static_cast<PluginLibTest*>(NULL), - PluginLibTest::CreatePluginLib(FilePath())); - - // Now try to manually Unload the only one and then UnloadAll. - plugin_lib1 = new PluginLibTest(); - plugin_lib1->Unload(); - NPAPI::PluginLib::UnloadAllPlugins(); -} - -#if defined(OS_LINUX) - -// Test parsing a simple description: Real Audio. -TEST(MIMEDescriptionParse, Simple) { - std::vector<WebPluginMimeType> types; - NPAPI::PluginLib::ParseMIMEDescription( - "audio/x-pn-realaudio-plugin:rpm:RealAudio document;", - &types); - ASSERT_EQ(1U, types.size()); - const WebPluginMimeType& type = types[0]; - EXPECT_EQ("audio/x-pn-realaudio-plugin", type.mime_type); - ASSERT_EQ(1U, type.file_extensions.size()); - EXPECT_EQ("rpm", type.file_extensions[0]); - EXPECT_EQ(ASCIIToUTF16("RealAudio document"), type.description); -} - -// Test parsing a multi-entry description: QuickTime as provided by Totem. -TEST(MIMEDescriptionParse, Multi) { - std::vector<WebPluginMimeType> types; - NPAPI::PluginLib::ParseMIMEDescription( - "video/quicktime:mov:QuickTime video;video/mp4:mp4:MPEG-4 " - "video;image/x-macpaint:pntg:MacPaint Bitmap image;image/x" - "-quicktime:pict, pict1, pict2:QuickTime image;video/x-m4v" - ":m4v:MPEG-4 video;", - &types); - - ASSERT_EQ(5U, types.size()); - - // Check the x-quicktime one, since it looks tricky with spaces in the - // extension list. - const WebPluginMimeType& type = types[3]; - EXPECT_EQ("image/x-quicktime", type.mime_type); - ASSERT_EQ(3U, type.file_extensions.size()); - EXPECT_EQ("pict2", type.file_extensions[2]); - EXPECT_EQ(ASCIIToUTF16("QuickTime image"), type.description); -} - -// Test parsing a Japanese description, since we got this wrong in the past. -// This comes from loading Totem with LANG=ja_JP.UTF-8. -TEST(MIMEDescriptionParse, JapaneseUTF8) { - std::vector<WebPluginMimeType> types; - NPAPI::PluginLib::ParseMIMEDescription( - "audio/x-ogg:ogg:Ogg \xe3\x82\xaa\xe3\x83\xbc\xe3\x83\x87" - "\xe3\x82\xa3\xe3\x83\xaa", - &types); - - ASSERT_EQ(1U, types.size()); - // Check we got the right number of Unicode characters out of the parse. - EXPECT_EQ(9U, types[0].description.size()); -} - -// Test that we handle corner cases gracefully. -TEST(MIMEDescriptionParse, CornerCases) { - std::vector<WebPluginMimeType> types; - NPAPI::PluginLib::ParseMIMEDescription("mime/type:", &types); - EXPECT_TRUE(types.empty()); - - types.clear(); - NPAPI::PluginLib::ParseMIMEDescription("mime/type:ext1:", &types); - ASSERT_EQ(1U, types.size()); - EXPECT_EQ("mime/type", types[0].mime_type); - EXPECT_EQ(1U, types[0].file_extensions.size()); - EXPECT_EQ("ext1", types[0].file_extensions[0]); - EXPECT_EQ(string16(), types[0].description); -} - -// This Java plugin has embedded semicolons in the mime type. -TEST(MIMEDescriptionParse, ComplicatedJava) { - std::vector<WebPluginMimeType> types; - NPAPI::PluginLib::ParseMIMEDescription( - "application/x-java-vm:class,jar:IcedTea;application/x-java" - "-applet:class,jar:IcedTea;application/x-java-applet;versio" - "n=1.1:class,jar:IcedTea;application/x-java-applet;version=" - "1.1.1:class,jar:IcedTea;application/x-java-applet;version=" - "1.1.2:class,jar:IcedTea;application/x-java-applet;version=" - "1.1.3:class,jar:IcedTea;application/x-java-applet;version=" - "1.2:class,jar:IcedTea;application/x-java-applet;version=1." - "2.1:class,jar:IcedTea;application/x-java-applet;version=1." - "2.2:class,jar:IcedTea;application/x-java-applet;version=1." - "3:class,jar:IcedTea;application/x-java-applet;version=1.3." - "1:class,jar:IcedTea;application/x-java-applet;version=1.4:" - "class,jar:IcedTea", - &types); - - ASSERT_EQ(12U, types.size()); - for (size_t i = 0; i < types.size(); ++i) - EXPECT_EQ(ASCIIToUTF16("IcedTea"), types[i].description); - - // Verify that the mime types with semis are coming through ok. - EXPECT_TRUE(types[4].mime_type.find(';') != std::string::npos); -} - -#endif // defined(OS_LINUX) diff --git a/webkit/glue/plugins/plugin_lib_win.cc b/webkit/glue/plugins/plugin_lib_win.cc deleted file mode 100644 index 382c2c8..0000000 --- a/webkit/glue/plugins/plugin_lib_win.cc +++ /dev/null @@ -1,46 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_lib.h" - -#include "base/file_version_info.h" -#include "base/file_version_info_win.h" -#include "base/logging.h" -#include "base/path_service.h" -#include "webkit/glue/plugins/plugin_constants_win.h" -#include "webkit/glue/plugins/plugin_list.h" - -namespace NPAPI { - -bool PluginLib::ReadWebPluginInfo(const FilePath &filename, - WebPluginInfo* info) { - // On windows, the way we get the mime types for the library is - // to check the version information in the DLL itself. This - // will be a string of the format: <type1>|<type2>|<type3>|... - // For example: - // video/quicktime|audio/aiff|image/jpeg - scoped_ptr<FileVersionInfo> version_info( - FileVersionInfo::CreateFileVersionInfo(filename.value())); - if (!version_info.get()) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Could not get version info for plugin " - << filename.value(); - return false; - } - - FileVersionInfoWin* version_info_win = - static_cast<FileVersionInfoWin*>(version_info.get()); - PluginVersionInfo pvi; - pvi.mime_types = version_info_win->GetStringValue(L"MIMEType"); - pvi.file_extensions = version_info_win->GetStringValue(L"FileExtents"); - pvi.type_descriptions = version_info_win->GetStringValue(L"FileOpenName"); - pvi.product_name = version_info->product_name(); - pvi.file_description = version_info->file_description(); - pvi.file_version = version_info->file_version(); - pvi.path = filename; - - return PluginList::CreateWebPluginInfo(pvi, info); -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_list.cc b/webkit/glue/plugins/plugin_list.cc deleted file mode 100644 index 84736cb..0000000 --- a/webkit/glue/plugins/plugin_list.cc +++ /dev/null @@ -1,613 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_list.h" - -#include <algorithm> - -#include "base/command_line.h" -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/string_split.h" -#include "base/string_util.h" -#include "base/sys_string_conversions.h" -#include "base/utf_string_conversions.h" -#include "googleurl/src/gurl.h" -#include "net/base/mime_util.h" -#include "webkit/glue/plugins/plugin_constants_win.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_switches.h" -#include "webkit/glue/webkit_glue.h" - -namespace NPAPI { - -base::LazyInstance<PluginList> g_singleton(base::LINKER_INITIALIZED); - -// static -PluginList* PluginList::Singleton() { - return g_singleton.Pointer(); -} - -// static -bool PluginList::DebugPluginLoading() { - return CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDebugPluginLoading); -} - -bool PluginList::PluginsLoaded() { - AutoLock lock(lock_); - return plugins_loaded_; -} - -void PluginList::RefreshPlugins() { - AutoLock lock(lock_); - plugins_need_refresh_ = true; -} - -void PluginList::AddExtraPluginPath(const FilePath& plugin_path) { - // Chrome OS only loads plugins from /opt/google/chrome/plugins. -#if !defined(OS_CHROMEOS) - AutoLock lock(lock_); - extra_plugin_paths_.push_back(plugin_path); -#endif -} - -void PluginList::RemoveExtraPluginPath(const FilePath& plugin_path) { - AutoLock lock(lock_); - std::vector<FilePath>::iterator it = - std::find(extra_plugin_paths_.begin(), extra_plugin_paths_.end(), - plugin_path); - if (it != extra_plugin_paths_.end()) - extra_plugin_paths_.erase(it); -} - -void PluginList::AddExtraPluginDir(const FilePath& plugin_dir) { - // Chrome OS only loads plugins from /opt/google/chrome/plugins. -#if !defined(OS_CHROMEOS) - AutoLock lock(lock_); - extra_plugin_dirs_.push_back(plugin_dir); -#endif -} - -void PluginList::RegisterInternalPlugin(const PluginVersionInfo& info) { - AutoLock lock(lock_); - internal_plugins_.push_back(info); -} - -void PluginList::UnregisterInternalPlugin(const FilePath& path) { - AutoLock lock(lock_); - for (size_t i = 0; i < internal_plugins_.size(); i++) { - if (internal_plugins_[i].path == path) { - internal_plugins_.erase(internal_plugins_.begin() + i); - return; - } - } - NOTREACHED(); -} - -bool PluginList::ReadPluginInfo(const FilePath& filename, - WebPluginInfo* info, - const PluginEntryPoints** entry_points) { - { - AutoLock lock(lock_); - for (size_t i = 0; i < internal_plugins_.size(); ++i) { - if (filename == internal_plugins_[i].path) { - *entry_points = &internal_plugins_[i].entry_points; - return CreateWebPluginInfo(internal_plugins_[i], info); - } - } - } - - // Not an internal plugin. - *entry_points = NULL; - - return PluginLib::ReadWebPluginInfo(filename, info); -} - -bool PluginList::CreateWebPluginInfo(const PluginVersionInfo& pvi, - WebPluginInfo* info) { - std::vector<std::string> mime_types, file_extensions; - std::vector<string16> descriptions; - base::SplitString(WideToUTF8(pvi.mime_types), '|', &mime_types); - base::SplitString(WideToUTF8(pvi.file_extensions), '|', &file_extensions); - base::SplitString(WideToUTF16(pvi.type_descriptions), '|', &descriptions); - - info->mime_types.clear(); - - if (mime_types.empty()) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Plugin " << pvi.product_name << " has no MIME types, skipping"; - return false; - } - - info->name = WideToUTF16(pvi.product_name); - info->desc = WideToUTF16(pvi.file_description); - info->version = WideToUTF16(pvi.file_version); - info->path = pvi.path; - info->enabled = true; - - for (size_t i = 0; i < mime_types.size(); ++i) { - WebPluginMimeType mime_type; - mime_type.mime_type = StringToLowerASCII(mime_types[i]); - if (file_extensions.size() > i) - base::SplitString(file_extensions[i], ',', &mime_type.file_extensions); - - if (descriptions.size() > i) { - mime_type.description = descriptions[i]; - - // On Windows, the description likely has a list of file extensions - // embedded in it (e.g. "SurfWriter file (*.swr)"). Remove an extension - // list from the description if it is present. - size_t ext = mime_type.description.find(ASCIIToUTF16("(*")); - if (ext != string16::npos) { - if (ext > 1 && mime_type.description[ext -1] == ' ') - ext--; - - mime_type.description.erase(ext); - } - } - - info->mime_types.push_back(mime_type); - } - - return true; -} - -PluginList::PluginList() - : plugins_loaded_(false), - plugins_need_refresh_(false), - disable_outdated_plugins_(false) { - PlatformInit(); -} - -bool PluginList::ShouldDisableGroup(const string16& group_name) { - AutoLock lock(lock_); - if (PluginGroup::IsPluginNameDisabledByPolicy(group_name)) { - disabled_groups_.insert(group_name); - return true; - } - return disabled_groups_.count(group_name) > 0; -} - -void PluginList::LoadPlugins(bool refresh) { - // Don't want to hold the lock while loading new plugins, so we don't block - // other methods if they're called on other threads. - std::vector<FilePath> extra_plugin_paths; - std::vector<FilePath> extra_plugin_dirs; - std::vector<PluginVersionInfo> internal_plugins; - { - AutoLock lock(lock_); - if (plugins_loaded_ && !refresh && !plugins_need_refresh_) - return; - - // Clear the refresh bit now, because it might get set again before we - // reach the end of the method. - plugins_need_refresh_ = false; - extra_plugin_paths = extra_plugin_paths_; - extra_plugin_dirs = extra_plugin_dirs_; - internal_plugins = internal_plugins_; - } - - std::vector<WebPluginInfo> new_plugins; - std::set<FilePath> visited_plugins; - - std::vector<FilePath> directories_to_scan; - GetPluginDirectories(&directories_to_scan); - - // Load internal plugins first so that, if both an internal plugin and a - // "discovered" plugin want to handle the same type, the internal plugin - // will have precedence. - for (size_t i = 0; i < internal_plugins.size(); ++i) { - if (internal_plugins[i].path.value() == kDefaultPluginLibraryName) - continue; - LoadPlugin(internal_plugins[i].path, &new_plugins); - } - - for (size_t i = 0; i < extra_plugin_paths.size(); ++i) { - const FilePath& path = extra_plugin_paths[i]; - if (visited_plugins.find(path) != visited_plugins.end()) - continue; - LoadPlugin(path, &new_plugins); - visited_plugins.insert(path); - } - - for (size_t i = 0; i < extra_plugin_dirs.size(); ++i) { - LoadPluginsFromDir(extra_plugin_dirs[i], &new_plugins, &visited_plugins); - } - - for (size_t i = 0; i < directories_to_scan.size(); ++i) { - LoadPluginsFromDir(directories_to_scan[i], &new_plugins, &visited_plugins); - } - -#if defined OS_WIN - LoadPluginsFromRegistry(&new_plugins, &visited_plugins); -#endif - - // Load the default plugin last. - if (webkit_glue::IsDefaultPluginEnabled()) - LoadPlugin(FilePath(kDefaultPluginLibraryName), &new_plugins); - - // Disable all of the plugins and plugin groups that are disabled by policy. - // There's currenly a bug that makes it impossible to correctly re-enable - // plugins or plugin-groups to their original, "pre-policy" state, so - // plugins and groups are only changed to a more "safe" state after a policy - // change, i.e. from enabled to disabled. See bug 54681. - PluginMap plugin_groups; - GetPluginGroups(&new_plugins, &plugin_groups); - for (PluginMap::const_iterator it = plugin_groups.begin(); - it != plugin_groups.end(); ++it) { - PluginGroup* group = it->second.get(); - string16 group_name = group->GetGroupName(); - if (ShouldDisableGroup(group_name)) { - it->second->Enable(false); - } - - if (disable_outdated_plugins_) { - group->DisableOutdatedPlugins(); - if (!group->Enabled()) { - AutoLock lock(lock_); - disabled_groups_.insert(group_name); - } - } - } - - // Only update the data now since loading plugins can take a while. - AutoLock lock(lock_); - - // Mark disabled plugins as such. - for (size_t i = 0; i < new_plugins.size(); ++i) { - if (disabled_plugins_.count(new_plugins[i].path)) - new_plugins[i].enabled = false; - } - - plugins_ = new_plugins; - plugins_loaded_ = true; -} - -void PluginList::LoadPlugin(const FilePath& path, - std::vector<WebPluginInfo>* plugins) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Loading plugin " << path.value(); - - WebPluginInfo plugin_info; - const PluginEntryPoints* entry_points; - - if (!ReadPluginInfo(path, &plugin_info, &entry_points)) - return; - - if (!ShouldLoadPlugin(plugin_info, plugins)) - return; - - if (path.value() != kDefaultPluginLibraryName -#if defined(OS_WIN) && !defined(NDEBUG) - && path.BaseName().value() != L"npspy.dll" // Make an exception for NPSPY -#endif - ) { - for (size_t i = 0; i < plugin_info.mime_types.size(); ++i) { - // TODO: don't load global handlers for now. - // WebKit hands to the Plugin before it tries - // to handle mimeTypes on its own. - const std::string &mime_type = plugin_info.mime_types[i].mime_type; - if (mime_type == "*" ) - return; - } - } - - plugins->push_back(plugin_info); -} - -bool PluginList::SupportsType(const WebPluginInfo& info, - const std::string &mime_type, - bool allow_wildcard) { - // Webkit will ask for a plugin to handle empty mime types. - if (mime_type.empty()) - return false; - - for (size_t i = 0; i < info.mime_types.size(); ++i) { - const WebPluginMimeType& mime_info = info.mime_types[i]; - if (net::MatchesMimeType(mime_info.mime_type, mime_type)) { - if (!allow_wildcard && mime_info.mime_type == "*") { - continue; - } - return true; - } - } - return false; -} - -bool PluginList::SupportsExtension(const WebPluginInfo& info, - const std::string &extension, - std::string* actual_mime_type) { - for (size_t i = 0; i < info.mime_types.size(); ++i) { - const WebPluginMimeType& mime_type = info.mime_types[i]; - for (size_t j = 0; j < mime_type.file_extensions.size(); ++j) { - if (mime_type.file_extensions[j] == extension) { - if (actual_mime_type) - *actual_mime_type = mime_type.mime_type; - return true; - } - } - } - - return false; -} - - -void PluginList::GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) { - LoadPlugins(refresh); - - AutoLock lock(lock_); - *plugins = plugins_; -} - -void PluginList::GetEnabledPlugins(bool refresh, - std::vector<WebPluginInfo>* plugins) { - LoadPlugins(refresh); - - plugins->clear(); - AutoLock lock(lock_); - for (std::vector<WebPluginInfo>::const_iterator it = plugins_.begin(); - it != plugins_.end(); - ++it) { - if (it->enabled) - plugins->push_back(*it); - } -} - -void PluginList::GetPluginInfoArray(const GURL& url, - const std::string& mime_type, - bool allow_wildcard, - std::vector<WebPluginInfo>* info, - std::vector<std::string>* actual_mime_types) -{ - DCHECK(mime_type == StringToLowerASCII(mime_type)); - DCHECK(info); - - LoadPlugins(false); - AutoLock lock(lock_); - info->clear(); - if (actual_mime_types) - actual_mime_types->clear(); - - std::set<FilePath> visited_plugins; - - // Add in enabled plugins by mime type. - WebPluginInfo default_plugin; - for (size_t i = 0; i < plugins_.size(); ++i) { - if (plugins_[i].enabled && - SupportsType(plugins_[i], mime_type, allow_wildcard)) { - FilePath path = plugins_[i].path; - if (path.value() != kDefaultPluginLibraryName && - visited_plugins.insert(path).second) { - info->push_back(plugins_[i]); - if (actual_mime_types) - actual_mime_types->push_back(mime_type); - } - } - } - - // Add in enabled plugins by url. - std::string path = url.path(); - std::string::size_type last_dot = path.rfind('.'); - if (last_dot != std::string::npos) { - std::string extension = StringToLowerASCII(std::string(path, last_dot+1)); - std::string actual_mime_type; - for (size_t i = 0; i < plugins_.size(); ++i) { - if (plugins_[i].enabled && - SupportsExtension(plugins_[i], extension, &actual_mime_type)) { - FilePath path = plugins_[i].path; - if (path.value() != kDefaultPluginLibraryName && - visited_plugins.insert(path).second) { - info->push_back(plugins_[i]); - if (actual_mime_types) - actual_mime_types->push_back(actual_mime_type); - } - } - } - } - - // Add in disabled plugins by mime type. - for (size_t i = 0; i < plugins_.size(); ++i) { - if (!plugins_[i].enabled && - SupportsType(plugins_[i], mime_type, allow_wildcard)) { - FilePath path = plugins_[i].path; - if (path.value() != kDefaultPluginLibraryName && - visited_plugins.insert(path).second) { - info->push_back(plugins_[i]); - if (actual_mime_types) - actual_mime_types->push_back(mime_type); - } - } - } - - // Add the default plugin at the end if it supports the mime type given, - // and the default plugin is enabled. - if (!plugins_.empty() && webkit_glue::IsDefaultPluginEnabled()) { - const WebPluginInfo& default_info = plugins_.back(); - if (SupportsType(default_info, mime_type, allow_wildcard)) { - info->push_back(default_info); - if (actual_mime_types) - actual_mime_types->push_back(mime_type); - } - } -} - -bool PluginList::GetPluginInfo(const GURL& url, - const std::string& mime_type, - bool allow_wildcard, - WebPluginInfo* info, - std::string* actual_mime_type) { - DCHECK(info); - std::vector<WebPluginInfo> info_list; - - // GetPluginInfoArray has slightly less work to do if we can pass - // NULL for the mime type list... - if (actual_mime_type) { - std::vector<std::string> mime_type_list; - GetPluginInfoArray( - url, mime_type, allow_wildcard, &info_list, &mime_type_list); - if (!info_list.empty()) { - *info = info_list[0]; - *actual_mime_type = mime_type_list[0]; - return true; - } - } else { - GetPluginInfoArray(url, mime_type, allow_wildcard, &info_list, NULL); - if (!info_list.empty()) { - *info = info_list[0]; - return true; - } - } - return false; -} - -bool PluginList::GetPluginInfoByPath(const FilePath& plugin_path, - WebPluginInfo* info) { - LoadPlugins(false); - AutoLock lock(lock_); - for (size_t i = 0; i < plugins_.size(); ++i) { - if (plugins_[i].path == plugin_path) { - *info = plugins_[i]; - return true; - } - } - - return false; -} - -void PluginList::GetPluginGroups(bool load_if_necessary, - PluginMap* plugin_groups) { - if (load_if_necessary) - LoadPlugins(false); - - AutoLock lock(lock_); - GetPluginGroups(&plugins_, plugin_groups); -} - -// static -void PluginList::GetPluginGroups(const std::vector<WebPluginInfo>* plugins, - PluginMap* plugin_groups) { - plugin_groups->clear(); - // We first search for an existing group that matches our name, - // and only create a new group if we can't find any. - for (size_t i = 0; i < plugins->size(); ++i) { - const WebPluginInfo& web_plugin = (*plugins)[i]; - PluginGroup* group = PluginGroup::FindGroupMatchingPlugin( - *plugin_groups, web_plugin); - if (!group) { - group = PluginGroup::CopyOrCreatePluginGroup(web_plugin); - std::string identifier = group->identifier(); - // If the identifier is not unique, use the full path. This means that we - // probably won't be able to search for this group by identifier, but at - // least it's going to be in the set of plugin groups, and if there - // is already a plug-in with the same filename, it's probably going to - // handle the same MIME types (and it has a higher priority), so this one - // is not going to run anyway. - if (plugin_groups->find(identifier) != plugin_groups->end()) -#if defined(OS_POSIX) - identifier = web_plugin.path.value(); -#elif defined(OS_WIN) - identifier = base::SysWideToUTF8(web_plugin.path.value()); -#endif - DCHECK(plugin_groups->find(identifier) == plugin_groups->end()); - (*plugin_groups)[identifier] = linked_ptr<PluginGroup>(group); - } - group->AddPlugin(web_plugin, i); - } -} - -bool PluginList::EnablePlugin(const FilePath& filename) { - AutoLock lock(lock_); - - bool did_enable = false; - - std::set<FilePath>::iterator entry = disabled_plugins_.find(filename); - if (entry == disabled_plugins_.end()) - return did_enable; // Early exit if plugin not in disabled list. - - disabled_plugins_.erase(entry); // Remove from disabled list. - - // Set enabled flags if necessary. - for (std::vector<WebPluginInfo>::iterator it = plugins_.begin(); - it != plugins_.end(); - ++it) { - if (it->path == filename) { - DCHECK(!it->enabled); // Should have been disabled. - it->enabled = true; - did_enable = true; - } - } - - return did_enable; -} - -bool PluginList::DisablePlugin(const FilePath& filename) { - AutoLock lock(lock_); - - bool did_disable = false; - - if (disabled_plugins_.find(filename) != disabled_plugins_.end()) - return did_disable; // Early exit if plugin already in disabled list. - - disabled_plugins_.insert(filename); // Add to disabled list. - - // Unset enabled flags if necessary. - for (std::vector<WebPluginInfo>::iterator it = plugins_.begin(); - it != plugins_.end(); - ++it) { - if (it->path == filename) { - DCHECK(it->enabled); // Should have been enabled. - it->enabled = false; - did_disable = true; - } - } - - return did_disable; -} - -bool PluginList::EnableGroup(bool enable, const string16& group_name) { - bool did_change = false; - { - AutoLock lock(lock_); - - std::set<string16>::iterator entry = disabled_groups_.find(group_name); - if (enable) { - if (entry == disabled_groups_.end()) - return did_change; // Early exit if group not in disabled list. - disabled_groups_.erase(entry); // Remove from disabled list. - } else { - if (entry != disabled_groups_.end()) - return did_change; // Early exit if group already in disabled list. - disabled_groups_.insert(group_name); - } - } - - PluginMap plugin_groups; - GetPluginGroups(false, &plugin_groups); - for (PluginMap::const_iterator it = plugin_groups.begin(); - it != plugin_groups.end(); ++it) { - if (it->second->GetGroupName() == group_name) { - if (it->second->Enabled() != enable) { - it->second->Enable(enable); - did_change = true; - break; - } - } - } - - return did_change; -} - -void PluginList::DisableOutdatedPluginGroups() { - disable_outdated_plugins_ = true; -} - -PluginList::~PluginList() { -} - -void PluginList::Shutdown() { - // TODO -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_list.h b/webkit/glue/plugins/plugin_list.h index 101e6b7..111e8fa 100644 --- a/webkit/glue/plugins/plugin_list.h +++ b/webkit/glue/plugins/plugin_list.h @@ -5,304 +5,26 @@ #ifndef WEBKIT_GLUE_PLUGINS_PLUGIN_LIST_H_ #define WEBKIT_GLUE_PLUGINS_PLUGIN_LIST_H_ -#include <map> -#include <set> -#include <string> -#include <vector> -#include <set> +// This file is here to keep NativeClient compiling. PluginList was moved to +// webkit/plugins/npapi and into the webkit::npapi namespace. Native Client +// depends on this old location & namespace, so we provide just enough +// definitions here to keep it compiling until it can be updated to use the +// new location & namespace. +// +// TODO(brettw) remove this flie when NaCl is updated. -#include "base/basictypes.h" -#include "base/file_path.h" -#include "base/linked_ptr.h" -#include "base/lock.h" -#include "third_party/npapi/bindings/nphostapi.h" -#include "webkit/glue/plugins/plugin_group.h" -#include "webkit/glue/plugins/webplugininfo.h" - -class GURL; - -namespace base { - -template <typename T> -struct DefaultLazyInstanceTraits; - -} // namespace base +#include "webkit/plugins/npapi/plugin_list.h" namespace NPAPI { -#define kDefaultPluginLibraryName FILE_PATH_LITERAL("default_plugin") -#define kGearsPluginLibraryName FILE_PATH_LITERAL("gears") +typedef webkit::npapi::PluginEntryPoints PluginEntryPoints; +typedef webkit::npapi::PluginVersionInfo PluginVersionInfo; -class PluginInstance; - -// This struct holds entry points into a plugin. The entry points are -// slightly different between Win/Mac and Unixes. -struct PluginEntryPoints { -#if !defined(OS_POSIX) || defined(OS_MACOSX) - NP_GetEntryPointsFunc np_getentrypoints; -#endif - NP_InitializeFunc np_initialize; - NP_ShutdownFunc np_shutdown; -}; - -// This struct fully describes a plugin. For external plugins, it's read in from -// the version info of the dll; For internal plugins, it's predefined and -// includes addresses of entry functions. (Yes, it's Win32 NPAPI-centric, but -// it'll do for holding descriptions of internal plugins cross-platform.) -struct PluginVersionInfo { - FilePath path; - // Info about the plugin itself. - std::wstring product_name; - std::wstring file_description; - std::wstring file_version; - // Info about the data types that the plugin supports. - std::wstring mime_types; - std::wstring file_extensions; - std::wstring type_descriptions; - // Entry points for internal plugins. Pointers are NULL for external plugins. - PluginEntryPoints entry_points; -}; - -// The PluginList is responsible for loading our NPAPI based plugins. It does -// so in whatever manner is appropriate for the platform. On Windows, it loads -// plugins from a known directory by looking for DLLs which start with "NP", -// and checking to see if they are valid NPAPI libraries. On the Mac, it walks -// the machine-wide and user plugin directories and loads anything that has -// the correct types. On Linux, it walks the plugin directories as well -// (e.g. /usr/lib/browser-plugins/). -// This object is thread safe. class PluginList { public: - // Gets the one instance of the PluginList. - static PluginList* Singleton(); - - // Returns true if we're in debug-plugin-loading mode. This is controlled - // by a command line switch. - static bool DebugPluginLoading(); - - // Returns true iff the plugin list has been loaded already. - bool PluginsLoaded(); - - // Cause the plugin list to refresh next time they are accessed, regardless - // of whether they are already loaded. - void RefreshPlugins(); - - // Add/Remove an extra plugin to load when we actually do the loading. Must - // be called before the plugins have been loaded. - void AddExtraPluginPath(const FilePath& plugin_path); - void RemoveExtraPluginPath(const FilePath& plugin_path); - - // Same as above, but specifies a directory in which to search for plugins. - void AddExtraPluginDir(const FilePath& plugin_dir); - - // Register an internal plugin with the specified plugin information and - // function pointers. An internal plugin must be registered before it can - // be loaded using PluginList::LoadPlugin(). - void RegisterInternalPlugin(const PluginVersionInfo& info); - - // Removes a specified internal plugin from the list. The search will match - // on the path from the version info previously registered. - // - // This is generally only necessary for tests. - void UnregisterInternalPlugin(const FilePath& path); - - // Creates a WebPluginInfo structure given a plugin's path. On success - // returns true, with the information being put into "info". If it's an - // internal plugin, "entry_points" is filled in as well with a - // internally-owned PluginEntryPoints pointer. - // Returns false if the library couldn't be found, or if it's not a plugin. - bool ReadPluginInfo(const FilePath& filename, - WebPluginInfo* info, - const PluginEntryPoints** entry_points); - - // Populate a WebPluginInfo from a PluginVersionInfo. - static bool CreateWebPluginInfo(const PluginVersionInfo& pvi, - WebPluginInfo* info); - - // Shutdown all plugins. Should be called at process teardown. - void Shutdown(); - - // Get all the plugins. - void GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins); - - // Get all the enabled plugins. - void GetEnabledPlugins(bool refresh, std::vector<WebPluginInfo>* plugins); - - // Returns a list in |info| containing plugins that are found for - // the given url and mime type (including disabled plugins, for - // which |info->enabled| is false). The mime type which corresponds - // to the URL is optionally returned back in |actual_mime_types| (if - // it is non-NULL), one for each of the plugin info objects found. - // The |allow_wildcard| parameter controls whether this function - // returns plugins which support wildcard mime types (* as the mime - // type). The |info| parameter is required to be non-NULL. The - // list is in order of "most desirable" to "least desirable", - // meaning that the default plugin is at the end of the list. - void GetPluginInfoArray(const GURL& url, - const std::string& mime_type, - bool allow_wildcard, - std::vector<WebPluginInfo>* info, - std::vector<std::string>* actual_mime_types); - - // Returns the first item from the list returned in GetPluginInfo in |info|. - // Returns true if it found a match. |actual_mime_type| may be NULL. - bool GetPluginInfo(const GURL& url, - const std::string& mime_type, - bool allow_wildcard, - WebPluginInfo* info, - std::string* actual_mime_type); - - // Get plugin info by plugin path (including disabled plugins). Returns true - // if the plugin is found and WebPluginInfo has been filled in |info|. - bool GetPluginInfoByPath(const FilePath& plugin_path, - WebPluginInfo* info); - - typedef std::map<std::string, linked_ptr<PluginGroup> > PluginMap; - - // Fill the map from identifier to plugin group for all plugin groups. If - // |load_if_necessary| is set, the plugins will be loaded if they haven't - // already been loaded, or if Refresh() has been called in the meantime; - // otherwise a possibly empty or stale list may be returned. - void GetPluginGroups(bool load_if_necessary, PluginMap* plugin_groups); - - // Load a specific plugin with full path. - void LoadPlugin(const FilePath& filename, - std::vector<WebPluginInfo>* plugins); - - // Enable a specific plugin, specified by path. Returns |true| iff a plugin - // currently in the plugin list was actually enabled as a result; regardless - // of return value, if a plugin is found in the future with the given name, it - // will be enabled. Note that plugins are enabled by default as far as - // |PluginList| is concerned. - bool EnablePlugin(const FilePath& filename); - - // Disable a specific plugin, specified by path. Returns |true| iff a plugin - // currently in the plugin list was actually disabled as a result; regardless - // of return value, if a plugin is found in the future with the given name, it - // will be disabled. - bool DisablePlugin(const FilePath& filename); - - // Enable/disable a plugin group, specified by group_name. Returns |true| iff - // a plugin currently in the plugin list was actually enabled/disabled as a - // result; regardless of return value, if a plugin is found in the future with - // the given name, it will be enabled/disabled. Note that plugins are enabled - // by default as far as |PluginList| is concerned. - bool EnableGroup(bool enable, const string16& name); - - // Disable all plugins groups that are known to be outdated, according to - // the information hardcoded in PluginGroup, to make sure that they can't - // be loaded on a web page and instead show a UI to update to the latest - // version. - void DisableOutdatedPluginGroups(); - - ~PluginList(); - - private: - // Constructors are private for singletons - PluginList(); - - // Load all plugins from the default plugins directory - void LoadPlugins(bool refresh); - - // Load all plugins from a specific directory. - // |plugins| is updated with loaded plugin information. - // |visited_plugins| is updated with paths to all plugins that were considered - // (including those we didn't load) - void LoadPluginsFromDir(const FilePath& path, - std::vector<WebPluginInfo>* plugins, - std::set<FilePath>* visited_plugins); - - // Returns true if we should load the given plugin, or false otherwise. - // plugins is the list of plugins we have crawled in the current plugin - // loading run. - bool ShouldLoadPlugin(const WebPluginInfo& info, - std::vector<WebPluginInfo>* plugins); - - // Return whether a plug-in group with the given name should be disabled, - // either because it already is on the list of disabled groups, or because it - // is blacklisted by a policy. In the latter case, add the plugin group to the - // list of disabled groups as well. - bool ShouldDisableGroup(const string16& group_name); - - // Like GetPluginGroups above, but works on a given vector of plugins. - static void GetPluginGroups(const std::vector<WebPluginInfo>* plugins, - PluginMap* plugin_groups); - - // Returns true if the given WebPluginInfo supports "mime-type". - // mime_type should be all lower case. - static bool SupportsType(const WebPluginInfo& info, - const std::string &mime_type, - bool allow_wildcard); - - // Returns true if the given WebPluginInfo supports a given file extension. - // extension should be all lower case. - // If mime_type is not NULL, it will be set to the mime type if found. - // The mime type which corresponds to the extension is optionally returned - // back. - static bool SupportsExtension(const WebPluginInfo& info, - const std::string &extension, - std::string* actual_mime_type); - - // - // Platform functions - // - - // Do any initialization. - void PlatformInit(); - - // Get the ordered list of directories from which to load plugins - void GetPluginDirectories(std::vector<FilePath>* plugin_dirs); - - // - // Command-line switches - // - -#if defined(OS_WIN) - // true if we shouldn't load the new WMP plugin. - bool dont_load_new_wmp_; - - // Loads plugins registered under HKCU\Software\MozillaPlugins and - // HKLM\Software\MozillaPlugins. - void LoadPluginsFromRegistry(std::vector<WebPluginInfo>* plugins, - std::set<FilePath>* visited_plugins); -#endif - - // - // Internals - // - - bool plugins_loaded_; - - // If true, we reload plugins even if they've been loaded already. - bool plugins_need_refresh_; - - // Contains information about the available plugins. - std::vector<WebPluginInfo> plugins_; - - // Extra plugin paths that we want to search when loading. - std::vector<FilePath> extra_plugin_paths_; - - // Extra plugin directories that we want to search when loading. - std::vector<FilePath> extra_plugin_dirs_; - - // Holds information about internal plugins. - std::vector<PluginVersionInfo> internal_plugins_; - - // Path names of plugins to disable (the default is to enable them all). - std::set<FilePath> disabled_plugins_; - - // Group names disable (the default is to enable them all). - std::set<string16> disabled_groups_; - - bool disable_outdated_plugins_; - - // Need synchronization for the above members since this object can be - // accessed on multiple threads. - Lock lock_; - - friend struct base::DefaultLazyInstanceTraits<PluginList>; - - DISALLOW_COPY_AND_ASSIGN(PluginList); + static inline webkit::npapi::PluginList* Singleton() { + return webkit::npapi::PluginList::Singleton(); + } }; } // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_list_mac.mm b/webkit/glue/plugins/plugin_list_mac.mm deleted file mode 100644 index 6e5019d..0000000 --- a/webkit/glue/plugins/plugin_list_mac.mm +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/plugin_list.h" - -#import <Foundation/Foundation.h> - -#include "base/file_util.h" -#include "base/mac_util.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "webkit/glue/plugins/plugin_lib.h" - -namespace { - -void GetPluginCommonDirectory(std::vector<FilePath>* plugin_dirs, - bool user) { - // Note that there are no NSSearchPathDirectory constants for these - // directories so we can't use Cocoa's NSSearchPathForDirectoriesInDomains(). - // Interestingly, Safari hard-codes the location (see - // WebKit/WebKit/mac/Plugins/WebPluginDatabase.mm's +_defaultPlugInPaths). - FSRef ref; - OSErr err = FSFindFolder(user ? kUserDomain : kLocalDomain, - kInternetPlugInFolderType, false, &ref); - - if (err) - return; - - plugin_dirs->push_back(FilePath(mac_util::PathFromFSRef(ref))); -} - -// Returns true if the plugin should be prevented from loading. -bool IsBlacklistedPlugin(const WebPluginInfo& info) { - // We blacklist Gears by included MIME type, since that is more stable than - // its name. Be careful about adding any more plugins to this list though, - // since it's easy to accidentally blacklist plugins that support lots of - // MIME types. - for (std::vector<WebPluginMimeType>::const_iterator i = - info.mime_types.begin(); i != info.mime_types.end(); ++i) { - // The Gears plugin is Safari-specific, so don't load it. - if (i->mime_type == "application/x-googlegears") - return true; - } - - return false; -} - -} // namespace - -namespace NPAPI -{ - -void PluginList::PlatformInit() { -} - -void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) { - // Load from the user's area - GetPluginCommonDirectory(plugin_dirs, true); - - // Load from the machine-wide area - GetPluginCommonDirectory(plugin_dirs, false); -} - -void PluginList::LoadPluginsFromDir(const FilePath &path, - std::vector<WebPluginInfo>* plugins, - std::set<FilePath>* visited_plugins) { - file_util::FileEnumerator enumerator(path, - false, // not recursive - file_util::FileEnumerator::DIRECTORIES); - for (FilePath path = enumerator.Next(); !path.value().empty(); - path = enumerator.Next()) { - LoadPlugin(path, plugins); - visited_plugins->insert(path); - } -} - -bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info, - std::vector<WebPluginInfo>* plugins) { - if (IsBlacklistedPlugin(info)) - return false; - - // Flip4Mac has a reproducible hang during a synchronous call from the render - // with certain content types (as well as a common crash). Disable by default - // to minimize those issues, but don't blacklist it so that users can choose - // to enable it. - if (StartsWith(info.name, ASCIIToUTF16("Flip4Mac Windows Media Plugin"), - false)) - DisablePlugin(info.path); - - // Hierarchy check - // (we're loading plugins hierarchically from Library folders, so plugins we - // encounter earlier must override plugins we encounter later) - for (size_t i = 0; i < plugins->size(); ++i) { - if ((*plugins)[i].path.BaseName() == info.path.BaseName()) { - return false; // We already have a loaded plugin higher in the hierarchy. - } - } - - return true; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_list_posix.cc b/webkit/glue/plugins/plugin_list_posix.cc deleted file mode 100644 index 654c0c5..0000000 --- a/webkit/glue/plugins/plugin_list_posix.cc +++ /dev/null @@ -1,270 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_list.h" - -#include "base/file_util.h" -#include "base/path_service.h" -#include "base/sha1.h" -#include "base/string_split.h" -#include "base/string_util.h" -#include "build/build_config.h" - -namespace { - -// We build up a list of files and mtimes so we can sort them. -typedef std::pair<FilePath, base::Time> FileAndTime; -typedef std::vector<FileAndTime> FileTimeList; - -// Comparator used to sort by descending mtime then ascending filename. -bool CompareTime(const FileAndTime& a, const FileAndTime& b) { - if (a.second == b.second) { - // Fall back on filename sorting, just to make the predicate valid. - return a.first < b.first; - } - - // Sort by mtime, descending. - return a.second > b.second; -} - -// Return true if |path| matches a known (file size, sha1sum) pair. -// The use of the file size is an optimization so we don't have to read in -// the entire file unless we have to. -bool IsBlacklistedBySha1sum(const FilePath& path) { - const struct BadEntry { - int64 size; - std::string sha1; - } bad_entries[] = { - // Flash 9 r31 - http://crbug.com/29237 - { 7040080, "fa5803061125ca47846713b34a26a42f1f1e98bb" }, - // Flash 9 r48 - http://crbug.com/29237 - { 7040036, "0c4b3768a6d4bfba003088e4b9090d381de1af2b" }, - }; - - int64 size; - if (!file_util::GetFileSize(path, &size)) - return false; - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(bad_entries); i++) { - if (bad_entries[i].size != size) - continue; - - std::string file_content; - if (!file_util::ReadFileToString(path, &file_content)) - continue; - std::string sha1 = base::SHA1HashString(file_content); - std::string sha1_readable; - for (size_t j = 0; j < sha1.size(); j++) - base::StringAppendF(&sha1_readable, "%02x", sha1[j] & 0xFF); - if (bad_entries[i].sha1 == sha1_readable) - return true; - } - return false; -} - -// Some plugins are shells around other plugins; we prefer to use the -// real plugin directly, if it's available. This function returns -// true if we should prefer other plugins over this one. We'll still -// use a "undesirable" plugin if no other option is available. -bool IsUndesirablePlugin(const WebPluginInfo& info) { - std::string filename = info.path.BaseName().value(); - const char* kUndesiredPlugins[] = { - "npcxoffice", // Crossover - "npwrapper", // nspluginwrapper - }; - for (size_t i = 0; i < arraysize(kUndesiredPlugins); i++) { - if (filename.find(kUndesiredPlugins[i]) != std::string::npos) { - return true; - } - } - return false; -} - -// Return true if we shouldn't load a plugin at all. -// This is an ugly hack to blacklist Adobe Acrobat due to not supporting -// its Xt-based mainloop. -// http://code.google.com/p/chromium/issues/detail?id=38229 -// The gecko-mediaplayer plugins also crashes the entire browser sometimes. -// http://code.google.com/p/chromium/issues/detail?id=24507 -bool IsBlacklistedPlugin(const FilePath& path) { - const char* kBlackListedPlugins[] = { - "nppdf.so", // Adobe PDF - "gecko-mediaplayer", // Gecko Media Player - }; - std::string filename = path.BaseName().value(); - for (size_t i = 0; i < arraysize(kBlackListedPlugins); i++) { - if (filename.find(kBlackListedPlugins[i]) != std::string::npos) { - return true; - } - } - return IsBlacklistedBySha1sum(path); -} - -} // anonymous namespace - -namespace NPAPI { - -void PluginList::PlatformInit() { -} - -void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) { - // See http://groups.google.com/group/chromium-dev/browse_thread/thread/7a70e5fcbac786a9 - // for discussion. - // We first consult Chrome-specific dirs, then fall back on the logic - // Mozilla uses. - - // Note: "extra" plugin dirs, including the Plugins subdirectory of - // your Chrome config, are examined before these. See the logic - // related to extra_plugin_dirs in plugin_list.cc. - - // The Chrome binary dir + "plugins/". - FilePath dir; - PathService::Get(base::DIR_EXE, &dir); - plugin_dirs->push_back(dir.Append("plugins")); - - // Chrome OS only loads plugins from /opt/google/chrome/plugins. -#if !defined(OS_CHROMEOS) - // Mozilla code to reference: - // http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST - // and tens of accompanying files (mxr is very helpful). - // This code carefully matches their behavior for compat reasons. - - // 1) MOZ_PLUGIN_PATH env variable. - const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH"); - if (moz_plugin_path) { - std::vector<std::string> paths; - base::SplitString(moz_plugin_path, ':', &paths); - for (size_t i = 0; i < paths.size(); ++i) - plugin_dirs->push_back(FilePath(paths[i])); - } - - // 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins. - // This is a de-facto standard, so even though we're not Mozilla, let's - // look in there too. - FilePath home = file_util::GetHomeDir(); - if (!home.empty()) - plugin_dirs->push_back(home.Append(".mozilla/plugins")); - - // 3) NS_SYSTEM_PLUGINS_DIR: - // This varies across different browsers and versions, so check 'em all. - plugin_dirs->push_back(FilePath("/usr/lib/browser-plugins")); - plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins")); - plugin_dirs->push_back(FilePath("/usr/lib/firefox/plugins")); - plugin_dirs->push_back(FilePath("/usr/lib/xulrunner-addons/plugins")); - -#if defined(ARCH_CPU_64_BITS) - // On my Ubuntu system, /usr/lib64 is a symlink to /usr/lib. - // But a user reported on their Fedora system they are separate. - plugin_dirs->push_back(FilePath("/usr/lib64/browser-plugins")); - plugin_dirs->push_back(FilePath("/usr/lib64/mozilla/plugins")); - plugin_dirs->push_back(FilePath("/usr/lib64/firefox/plugins")); - plugin_dirs->push_back(FilePath("/usr/lib64/xulrunner-addons/plugins")); -#endif // defined(ARCH_CPU_64_BITS) -#endif // !defined(OS_CHROMEOS) -} - -void PluginList::LoadPluginsFromDir(const FilePath& dir_path, - std::vector<WebPluginInfo>* plugins, - std::set<FilePath>* visited_plugins) { - // See ScanPluginsDirectory near - // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginHostImpl.cpp#5052 - - // Construct and stat a list of all filenames under consideration, for - // later sorting by mtime. - FileTimeList files; - file_util::FileEnumerator enumerator(dir_path, - false, // not recursive - file_util::FileEnumerator::FILES); - for (FilePath path = enumerator.Next(); !path.value().empty(); - path = enumerator.Next()) { - // Skip over Mozilla .xpt files. - if (path.MatchesExtension(FILE_PATH_LITERAL(".xpt"))) - continue; - - // Java doesn't like being loaded through a symlink, since it uses - // its path to find dependent data files. - // file_util::AbsolutePath calls through to realpath(), which resolves - // symlinks. - FilePath orig_path = path; - file_util::AbsolutePath(&path); - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Resolved " << orig_path.value() << " -> " << path.value(); - - if (visited_plugins->find(path) != visited_plugins->end()) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Skipping duplicate instance of " << path.value(); - continue; - } - visited_plugins->insert(path); - - if (IsBlacklistedPlugin(path)) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Skipping blacklisted plugin " << path.value(); - continue; - } - - // Flash stops working if the containing directory involves 'netscape'. - // No joke. So use the other path if it's better. - static const char kFlashPlayerFilename[] = "libflashplayer.so"; - static const char kNetscapeInPath[] = "/netscape/"; - if (path.BaseName().value() == kFlashPlayerFilename && - path.value().find(kNetscapeInPath) != std::string::npos) { - if (orig_path.value().find(kNetscapeInPath) == std::string::npos) { - // Go back to the old path. - path = orig_path; - } else { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Flash misbehaves when used from a directory containing " - << kNetscapeInPath << ", so skipping " << orig_path.value(); - continue; - } - } - - // Get mtime. - base::PlatformFileInfo info; - if (!file_util::GetFileInfo(path, &info)) - continue; - - files.push_back(std::make_pair(path, info.last_modified)); - } - - // Sort the file list by time (and filename). - std::sort(files.begin(), files.end(), CompareTime); - - // Load the files in order. - for (FileTimeList::const_iterator i = files.begin(); i != files.end(); ++i) { - LoadPlugin(i->first, plugins); - } -} - -bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info, - std::vector<WebPluginInfo>* plugins) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Considering " << info.path.value() << " (" << info.name << ")"; - - if (IsUndesirablePlugin(info)) { - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << info.path.value() << " is undesirable."; - - // See if we have a better version of this plugin. - for (size_t i = 0; i < plugins->size(); ++i) { - if (plugins->at(i).name == info.name && - !IsUndesirablePlugin(plugins->at(i))) { - // Skip the current undesirable one so we can use the better one - // we just found. - LOG_IF(ERROR, PluginList::DebugPluginLoading()) - << "Skipping " << info.path.value() << ", preferring " - << plugins->at(i).path.value(); - return false; - } - } - } - - // TODO(evanm): prefer the newest version of flash, etc. here? - - VLOG_IF(1, PluginList::DebugPluginLoading()) << "Using " << info.path.value(); - - return true; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_list_win.cc b/webkit/glue/plugins/plugin_list_win.cc deleted file mode 100644 index 4869262..0000000 --- a/webkit/glue/plugins/plugin_list_win.cc +++ /dev/null @@ -1,410 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_list.h" - -#include <tchar.h> - -#include <set> - -#include "base/basictypes.h" -#include "base/command_line.h" -#include "base/file_util.h" -#include "base/path_service.h" -#include "base/scoped_ptr.h" -#include "base/string_number_conversions.h" -#include "base/string_split.h" -#include "base/string_util.h" -#include "base/win/registry.h" -#include "webkit/glue/plugins/plugin_constants_win.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/webkit_glue.h" - -namespace { - -const TCHAR kRegistryApps[] = - _T("Software\\Microsoft\\Windows\\CurrentVersion\\App Paths"); -const TCHAR kRegistryFirefox[] = _T("firefox.exe"); -const TCHAR kRegistryAcrobat[] = _T("Acrobat.exe"); -const TCHAR kRegistryAcrobatReader[] = _T("AcroRd32.exe"); -const TCHAR kRegistryWindowsMedia[] = _T("wmplayer.exe"); -const TCHAR kRegistryQuickTime[] = _T("QuickTimePlayer.exe"); -const TCHAR kRegistryPath[] = _T("Path"); -const TCHAR kRegistryFirefoxInstalled[] = - _T("SOFTWARE\\Mozilla\\Mozilla Firefox"); -const TCHAR kRegistryJava[] = - _T("Software\\JavaSoft\\Java Runtime Environment"); -const TCHAR kRegistryBrowserJavaVersion[] = _T("BrowserJavaVersion"); -const TCHAR kRegistryCurrentJavaVersion[] = _T("CurrentVersion"); -const TCHAR kRegistryJavaHome[] = _T("JavaHome"); -const TCHAR kJavaDeploy1[] = _T("npdeploytk.dll"); -const TCHAR kJavaDeploy2[] = _T("npdeployjava1.dll"); - -// The application path where we expect to find plugins. -void GetAppDirectory(std::set<FilePath>* plugin_dirs) { - FilePath app_path; - if (!webkit_glue::GetApplicationDirectory(&app_path)) - return; - - app_path = app_path.AppendASCII("plugins"); - plugin_dirs->insert(app_path); -} - -// The executable path where we expect to find plugins. -void GetExeDirectory(std::set<FilePath>* plugin_dirs) { - FilePath exe_path; - if (!webkit_glue::GetExeDirectory(&exe_path)) - return; - - exe_path = exe_path.AppendASCII("plugins"); - plugin_dirs->insert(exe_path); -} - -// Gets the installed path for a registered app. -bool GetInstalledPath(const TCHAR* app, FilePath* out) { - std::wstring reg_path(kRegistryApps); - reg_path.append(L"\\"); - reg_path.append(app); - - base::win::RegKey key(HKEY_LOCAL_MACHINE, reg_path.c_str(), KEY_READ); - std::wstring path; - if (key.ReadValue(kRegistryPath, &path)) { - *out = FilePath(path); - return true; - } - - return false; -} - -// Search the registry at the given path and detect plugin directories. -void GetPluginsInRegistryDirectory( - HKEY root_key, - const std::wstring& registry_folder, - std::set<FilePath>* plugin_dirs) { - for (base::win::RegistryKeyIterator iter(root_key, registry_folder.c_str()); - iter.Valid(); ++iter) { - // Use the registry to gather plugin across the file system. - std::wstring reg_path = registry_folder; - reg_path.append(L"\\"); - reg_path.append(iter.Name()); - base::win::RegKey key(root_key, reg_path.c_str(), KEY_READ); - - std::wstring path; - if (key.ReadValue(kRegistryPath, &path)) - plugin_dirs->insert(FilePath(path)); - } -} - -// Enumerate through the registry key to find all installed FireFox paths. -// FireFox 3 beta and version 2 can coexist. See bug: 1025003 -void GetFirefoxInstalledPaths(std::vector<FilePath>* out) { - base::win::RegistryKeyIterator it(HKEY_LOCAL_MACHINE, - kRegistryFirefoxInstalled); - for (; it.Valid(); ++it) { - std::wstring full_path = std::wstring(kRegistryFirefoxInstalled) + L"\\" + - it.Name() + L"\\Main"; - base::win::RegKey key(HKEY_LOCAL_MACHINE, full_path.c_str(), KEY_READ); - std::wstring install_dir; - if (!key.ReadValue(L"Install Directory", &install_dir)) - continue; - out->push_back(FilePath(install_dir)); - } -} - -// Get plugin directory locations from the Firefox install path. This is kind -// of a kludge, but it helps us locate the flash player for users that -// already have it for firefox. Not having to download yet-another-plugin -// is a good thing. -void GetFirefoxDirectory(std::set<FilePath>* plugin_dirs) { - std::vector<FilePath> paths; - GetFirefoxInstalledPaths(&paths); - for (unsigned int i = 0; i < paths.size(); ++i) { - plugin_dirs->insert(paths[i].Append(L"plugins")); - } - - FilePath firefox_app_data_plugin_path; - if (PathService::Get(base::DIR_APP_DATA, &firefox_app_data_plugin_path)) { - firefox_app_data_plugin_path = - firefox_app_data_plugin_path.AppendASCII("Mozilla") - .AppendASCII("plugins"); - plugin_dirs->insert(firefox_app_data_plugin_path); - } -} - -// Hardcoded logic to detect Acrobat plugins locations. -void GetAcrobatDirectory(std::set<FilePath>* plugin_dirs) { - FilePath path; - if (!GetInstalledPath(kRegistryAcrobatReader, &path) && - !GetInstalledPath(kRegistryAcrobat, &path)) { - return; - } - - plugin_dirs->insert(path.Append(L"Browser")); -} - -// Hardcoded logic to detect QuickTime plugin location. -void GetQuicktimeDirectory(std::set<FilePath>* plugin_dirs) { - FilePath path; - if (GetInstalledPath(kRegistryQuickTime, &path)) - plugin_dirs->insert(path.Append(L"plugins")); -} - -// Hardcoded logic to detect Windows Media Player plugin location. -void GetWindowsMediaDirectory(std::set<FilePath>* plugin_dirs) { - FilePath path; - if (GetInstalledPath(kRegistryWindowsMedia, &path)) - plugin_dirs->insert(path); - - // If the Windows Media Player Firefox plugin is installed before Firefox, - // the plugin will get written under PFiles\Plugins on one the drives - // (usually, but not always, the last letter). - int size = GetLogicalDriveStrings(0, NULL); - if (size) { - scoped_array<wchar_t> strings(new wchar_t[size]); - if (GetLogicalDriveStrings(size, strings.get())) { - wchar_t* next_drive = strings.get(); - while (*next_drive) { - if (GetDriveType(next_drive) == DRIVE_FIXED) { - FilePath pfiles(next_drive); - pfiles = pfiles.Append(L"PFiles\\Plugins"); - if (file_util::PathExists(pfiles)) - plugin_dirs->insert(pfiles); - } - next_drive = &next_drive[wcslen(next_drive) + 1]; - } - } - } -} - -// Hardcoded logic to detect Java plugin location. -void GetJavaDirectory(std::set<FilePath>* plugin_dirs) { - // Load the new NPAPI Java plugin - // 1. Open the main JRE key under HKLM - base::win::RegKey java_key(HKEY_LOCAL_MACHINE, kRegistryJava, - KEY_QUERY_VALUE); - - // 2. Read the current Java version - std::wstring java_version; - if (!java_key.ReadValue(kRegistryBrowserJavaVersion, &java_version)) - java_key.ReadValue(kRegistryCurrentJavaVersion, &java_version); - - if (!java_version.empty()) { - java_key.OpenKey(java_version.c_str(), KEY_QUERY_VALUE); - - // 3. Install path of the JRE binaries is specified in "JavaHome" - // value under the Java version key. - std::wstring java_plugin_directory; - if (java_key.ReadValue(kRegistryJavaHome, &java_plugin_directory)) { - // 4. The new plugin resides under the 'bin/new_plugin' - // subdirectory. - DCHECK(!java_plugin_directory.empty()); - java_plugin_directory.append(L"\\bin\\new_plugin"); - - // 5. We don't know the exact name of the DLL but it's in the form - // NP*.dll so just invoke LoadPlugins on this path. - plugin_dirs->insert(FilePath(java_plugin_directory)); - } - } -} - -} // anonymous namespace - -namespace NPAPI { - -void PluginList::PlatformInit() { - const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - dont_load_new_wmp_ = command_line.HasSwitch(kUseOldWMPPluginSwitch); -} - -void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) { - // We use a set for uniqueness, which we require, over order, which we do not. - std::set<FilePath> dirs; - - // Load from the application-specific area - GetAppDirectory(&dirs); - - // Load from the executable area - GetExeDirectory(&dirs); - - // Load Java - GetJavaDirectory(&dirs); - - // Load firefox plugins too. This is mainly to try to locate - // a pre-installed Flash player. - GetFirefoxDirectory(&dirs); - - // Firefox hard-codes the paths of some popular plugins to ensure that - // the plugins are found. We are going to copy this as well. - GetAcrobatDirectory(&dirs); - GetQuicktimeDirectory(&dirs); - GetWindowsMediaDirectory(&dirs); - - for (std::set<FilePath>::iterator i = dirs.begin(); i != dirs.end(); ++i) - plugin_dirs->push_back(*i); -} - -void PluginList::LoadPluginsFromDir(const FilePath &path, - std::vector<WebPluginInfo>* plugins, - std::set<FilePath>* visited_plugins) { - WIN32_FIND_DATA find_file_data; - HANDLE find_handle; - - std::wstring dir = path.value(); - // FindFirstFile requires that you specify a wildcard for directories. - dir.append(L"\\NP*.DLL"); - - find_handle = FindFirstFile(dir.c_str(), &find_file_data); - if (find_handle == INVALID_HANDLE_VALUE) - return; - - do { - if (!(find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - FilePath filename = path.Append(find_file_data.cFileName); - LoadPlugin(filename, plugins); - visited_plugins->insert(filename); - } - } while (FindNextFile(find_handle, &find_file_data) != 0); - - DCHECK(GetLastError() == ERROR_NO_MORE_FILES); - FindClose(find_handle); -} - -void PluginList::LoadPluginsFromRegistry( - std::vector<WebPluginInfo>* plugins, - std::set<FilePath>* visited_plugins) { - std::set<FilePath> plugin_dirs; - - GetPluginsInRegistryDirectory( - HKEY_CURRENT_USER, kRegistryMozillaPlugins, &plugin_dirs); - GetPluginsInRegistryDirectory( - HKEY_LOCAL_MACHINE, kRegistryMozillaPlugins, &plugin_dirs); - - for (std::set<FilePath>::iterator i = plugin_dirs.begin(); - i != plugin_dirs.end(); ++i) { - LoadPlugin(*i, plugins); - visited_plugins->insert(*i); - } -} - -// Returns true if the given plugins share at least one mime type. This is used -// to differentiate newer versions of a plugin vs two plugins which happen to -// have the same filename. -bool HaveSharedMimeType(const WebPluginInfo& plugin1, - const WebPluginInfo& plugin2) { - for (size_t i = 0; i < plugin1.mime_types.size(); ++i) { - for (size_t j = 0; j < plugin2.mime_types.size(); ++j) { - if (plugin1.mime_types[i].mime_type == plugin2.mime_types[j].mime_type) - return true; - } - } - - return false; -} - -// Compares Windows style version strings (i.e. 1,2,3,4). Returns true if b's -// version is newer than a's, or false if it's equal or older. -bool IsNewerVersion(const std::wstring& a, const std::wstring& b) { - std::vector<std::wstring> a_ver, b_ver; - base::SplitString(a, ',', &a_ver); - base::SplitString(b, ',', &b_ver); - if (a_ver.size() == 1 && b_ver.size() == 1) { - a_ver.clear(); - b_ver.clear(); - base::SplitString(a, '.', &a_ver); - base::SplitString(b, '.', &b_ver); - } - if (a_ver.size() != b_ver.size()) - return false; - for (size_t i = 0; i < a_ver.size(); i++) { - int cur_a, cur_b; - base::StringToInt(a_ver[i], &cur_a); - base::StringToInt(b_ver[i], &cur_b); - - if (cur_a > cur_b) - return false; - if (cur_a < cur_b) - return true; - } - return false; -} - -bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info, - std::vector<WebPluginInfo>* plugins) { - // Version check - - for (size_t i = 0; i < plugins->size(); ++i) { - std::wstring plugin1 = - StringToLowerASCII((*plugins)[i].path.BaseName().ToWStringHack()); - std::wstring plugin2 = - StringToLowerASCII(info.path.BaseName().ToWStringHack()); - if ((plugin1 == plugin2 && HaveSharedMimeType((*plugins)[i], info)) || - (plugin1 == kJavaDeploy1 && plugin2 == kJavaDeploy2) || - (plugin1 == kJavaDeploy2 && plugin2 == kJavaDeploy1)) { - if (!IsNewerVersion((*plugins)[i].version, info.version)) - return false; // We have loaded a plugin whose version is newer. - - plugins->erase(plugins->begin() + i); - break; - } - } - - // Troublemakers - - std::wstring filename = StringToLowerASCII(info.path.BaseName().value()); - // Depends on XPCOM. - if (filename == kMozillaActiveXPlugin) - return false; - - // Disable the Yahoo Application State plugin as it crashes the plugin - // process on return from NPObjectStub::OnInvoke. Please refer to - // http://b/issue?id=1372124 for more information. - if (filename == kYahooApplicationStatePlugin) - return false; - - // Disable the WangWang protocol handler plugin (npww.dll) as it crashes - // chrome during shutdown. Firefox also disables this plugin. - // Please refer to http://code.google.com/p/chromium/issues/detail?id=3953 - // for more information. - if (filename == kWanWangProtocolHandlerPlugin) - return false; - - // We only work with newer versions of the Java plugin which use NPAPI only - // and don't depend on XPCOM. - if (filename == kJavaPlugin1 || filename == kJavaPlugin2) { - std::vector<std::wstring> ver; - base::SplitString(info.version, '.', &ver); - int major, minor, update; - if (ver.size() == 4 && - base::StringToInt(ver[0], &major) && - base::StringToInt(ver[1], &minor) && - base::StringToInt(ver[2], &update)) { - if (major == 6 && minor == 0 && update < 120) - return false; // Java SE6 Update 11 or older. - } - } - - // Special WMP handling - - // If both the new and old WMP plugins exist, only load the new one. - if (filename == kNewWMPPlugin) { - if (dont_load_new_wmp_) - return false; - - for (size_t i = 0; i < plugins->size(); ++i) { - if ((*plugins)[i].path.BaseName().value() == kOldWMPPlugin) { - plugins->erase(plugins->begin() + i); - break; - } - } - } else if (filename == kOldWMPPlugin) { - for (size_t i = 0; i < plugins->size(); ++i) { - if ((*plugins)[i].path.BaseName().value() == kNewWMPPlugin) - return false; - } - } - - return true; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_stream.cc b/webkit/glue/plugins/plugin_stream.cc deleted file mode 100644 index 728b180..0000000 --- a/webkit/glue/plugins/plugin_stream.cc +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO : Support NP_ASFILEONLY mode -// TODO : Support NP_SEEK mode -// TODO : Support SEEKABLE=true in NewStream - -#include "webkit/glue/plugins/plugin_stream.h" - -#include "base/message_loop.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "net/base/mime_util.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "googleurl/src/gurl.h" - -namespace NPAPI { - -PluginStream::~PluginStream() { - // always close our temporary files. - CloseTempFile(); - free(const_cast<char*>(stream_.url)); -} - -bool PluginStream::Open(const std::string &mime_type, - const std::string &headers, - uint32 length, - uint32 last_modified, - bool request_is_seekable) { - headers_ = headers; - NPP id = instance_->npp(); - stream_.end = length; - stream_.lastmodified = last_modified; - stream_.pdata = 0; - stream_.ndata = id->ndata; - stream_.notifyData = notify_data_; - if (!headers_.empty()) - stream_.headers = headers_.c_str(); - - bool seekable_stream = false; - if (request_is_seekable) { - std::string headers_lc = StringToLowerASCII(headers); - if (headers_lc.find("accept-ranges: bytes") != std::string::npos) { - seekable_stream = true; - } - } - - const char *char_mime_type = "application/x-unknown-content-type"; - std::string temp_mime_type; - if (!mime_type.empty()) { - char_mime_type = mime_type.c_str(); - } else { - GURL gurl(stream_.url); - -#if defined(OS_WIN) - FilePath path(UTF8ToWide(gurl.path())); -#elif defined(OS_POSIX) - FilePath path(gurl.path()); -#endif - if (net::GetMimeTypeFromFile(path, &temp_mime_type)) - char_mime_type = temp_mime_type.c_str(); - } - - // Silverlight expects a valid mime type - DCHECK(strlen(char_mime_type) != 0); - NPError err = instance_->NPP_NewStream((NPMIMEType)char_mime_type, - &stream_, seekable_stream, - &requested_plugin_mode_); - if (err != NPERR_NO_ERROR) { - Notify(err); - return false; - } - - opened_ = true; - - if (requested_plugin_mode_ == NP_SEEK) { - seekable_stream_ = true; - } - // If the plugin has requested certain modes, then we need a copy - // of this file on disk. Open it and save it as we go. - if (requested_plugin_mode_ == NP_ASFILEONLY || - requested_plugin_mode_ == NP_ASFILE) { - if (OpenTempFile() == false) - return false; - } - - mime_type_ = char_mime_type; - return true; -} - -int PluginStream::Write(const char *buffer, const int length, - int data_offset) { - // There may be two streams to write to - the plugin and the file. - // It is unclear what to do if we cannot write to both. The rules of - // this function are that the plugin must consume at least as many - // bytes as returned by the WriteReady call. So, we will attempt to - // write that many to both streams. If we can't write that many bytes - // to each stream, we'll return failure. - - DCHECK(opened_); - if (WriteToFile(buffer, length) && - WriteToPlugin(buffer, length, data_offset)) - return length; - - return -1; -} - -bool PluginStream::WriteToFile(const char *buf, size_t length) { - // For ASFILEONLY, ASFILE, and SEEK modes, we need to write - // to the disk - if (TempFileIsValid() && - (requested_plugin_mode_ == NP_ASFILE || - requested_plugin_mode_ == NP_ASFILEONLY) ) { - size_t totalBytesWritten = 0, bytes; - do { - bytes = WriteBytes(buf, length); - totalBytesWritten += bytes; - } while (bytes > 0U && totalBytesWritten < length); - - if (totalBytesWritten != length) - return false; - } - - return true; -} - -bool PluginStream::WriteToPlugin(const char *buf, const int length, - const int data_offset) { - // For NORMAL and ASFILE modes, we send the data to the plugin now - if (requested_plugin_mode_ != NP_NORMAL && - requested_plugin_mode_ != NP_ASFILE && - requested_plugin_mode_ != NP_SEEK) - return true; - - int written = TryWriteToPlugin(buf, length, data_offset); - if (written == -1) - return false; - - if (written < length) { - // Buffer the remaining data. - size_t remaining = length - written; - size_t previous_size = delivery_data_.size(); - delivery_data_.resize(previous_size + remaining); - data_offset_ = data_offset; - memcpy(&delivery_data_[previous_size], buf + written, remaining); - MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( - this, &PluginStream::OnDelayDelivery)); - } - - return true; -} - -void PluginStream::OnDelayDelivery() { - // It is possible that the plugin stream may have closed before the task - // was hit. - if (!opened_) { - return; - } - - int size = static_cast<int>(delivery_data_.size()); - int written = TryWriteToPlugin(&delivery_data_.front(), size, - data_offset_); - if (written > 0) { - // Remove the data that we already wrote. - delivery_data_.erase(delivery_data_.begin(), - delivery_data_.begin() + written); - } -} - -int PluginStream::TryWriteToPlugin(const char *buf, const int length, - const int data_offset) { - int byte_offset = 0; - - if (data_offset > 0) - data_offset_ = data_offset; - - while (byte_offset < length) { - int bytes_remaining = length - byte_offset; - int bytes_to_write = instance_->NPP_WriteReady(&stream_); - if (bytes_to_write > bytes_remaining) - bytes_to_write = bytes_remaining; - - if (bytes_to_write == 0) - return byte_offset; - - int bytes_consumed = instance_->NPP_Write( - &stream_, data_offset_, bytes_to_write, - const_cast<char*>(buf + byte_offset)); - if (bytes_consumed < 0) { - // The plugin failed, which means that we need to close the stream. - Close(NPRES_NETWORK_ERR); - return -1; - } - if (bytes_consumed == 0) { - // The plugin couldn't take all of the data now. - return byte_offset; - } - - // The plugin might report more that we gave it. - bytes_consumed = std::min(bytes_consumed, bytes_to_write); - - data_offset_ += bytes_consumed; - byte_offset += bytes_consumed; - } - - if (close_on_write_data_) - Close(NPRES_DONE); - - return length; -} - -bool PluginStream::Close(NPReason reason) { - if (opened_ == true) { - opened_ = false; - - if (delivery_data_.size()) { - if (reason == NPRES_DONE) { - // There is more data to be streamed, don't destroy the stream now. - close_on_write_data_ = true; - return true; - } else { - // Stop any pending data from being streamed - delivery_data_.resize(0); - } - } - - // If we have a temp file, be sure to close it. - // Also, allow the plugin to access it now. - if (TempFileIsValid()) { - CloseTempFile(); - if (reason == NPRES_DONE) - WriteAsFile(); - } - - if (stream_.ndata != NULL) { - // Stream hasn't been closed yet. - NPError err = instance_->NPP_DestroyStream(&stream_, reason); - DCHECK(err == NPERR_NO_ERROR); - } - } - - Notify(reason); - return true; -} - -void PluginStream::Notify(NPReason reason) { - if (notify_needed_) { - instance_->NPP_URLNotify(stream_.url, reason, notify_data_); - notify_needed_ = false; - } -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_stream.h b/webkit/glue/plugins/plugin_stream.h deleted file mode 100644 index b277465..0000000 --- a/webkit/glue/plugins/plugin_stream.h +++ /dev/null @@ -1,158 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PLUGIN_STREAM_H_ -#define WEBKIT_GLUE_PLUGINS_PLUGIN_STREAM_H_ - -#include "build/build_config.h" - -#include <string> -#include <vector> - -#if defined(OS_POSIX) -#include "base/file_path.h" -#endif -#include "base/ref_counted.h" -#include "third_party/npapi/bindings/npapi.h" - -namespace webkit_glue { -class WebPluginResourceClient; -} - -namespace NPAPI { - -class PluginInstance; - -// Base class for a NPAPI stream. Tracks basic elements -// of a stream for NPAPI notifications and stream position. -class PluginStream : public base::RefCounted<PluginStream> { - public: - // Create a new PluginStream object. If needNotify is true, then the - // plugin will be notified when the stream has been fully sent. - PluginStream(PluginInstance *instance, - const char *url, - bool need_notify, - void *notify_data); - - // In case of a redirect, this can be called to update the url. But it must - // be called before Open(). - void UpdateUrl(const char* url); - - // Opens the stream to the Plugin. - // If the mime-type is not specified, we'll try to find one based on the - // mime-types table and the extension (if any) in the URL. - // If the size of the stream is known, use length to set the size. If - // not known, set length to 0. - // The request_is_seekable parameter indicates whether byte range requests - // can be issued on the stream. - bool Open(const std::string &mime_type, - const std::string &headers, - uint32 length, - uint32 last_modified, - bool request_is_seekable); - - // Writes to the stream. - int Write(const char *buf, const int len, int data_offset); - - // Write the result as a file. - void WriteAsFile(); - - // Notify the plugin that a stream is complete. - void Notify(NPReason reason); - - // Close the stream. - virtual bool Close(NPReason reason); - - virtual webkit_glue::WebPluginResourceClient* AsResourceClient() { - return NULL; - } - - // Cancels any HTTP requests initiated by the stream. - virtual void CancelRequest() {} - - const NPStream* stream() const { return &stream_; } - - // setter/getter for the seekable attribute on the stream. - bool seekable() const { return seekable_stream_; } - - void set_seekable(bool seekable) { seekable_stream_ = seekable; } - - // getters for reading the notification related attributes on the stream. - bool notify_needed() const { return notify_needed_; } - - void* notify_data() const { return notify_data_; } - - std::string pending_redirect_url() const { return pending_redirect_url_; } - - protected: - friend class base::RefCounted<PluginStream>; - - virtual ~PluginStream(); - - PluginInstance* instance() { return instance_.get(); } - // Check if the stream is open. - bool open() { return opened_; } - - // If the plugin participates in HTTP URL redirect handling then this member - // holds the url being redirected to while we wait for the plugin to make a - // decision on whether to allow or deny the redirect. - std::string pending_redirect_url_; - - private: - - // Open a temporary file for this stream. - // If successful, will set temp_file_name_, temp_file_handle_, and - // return true. - bool OpenTempFile(); - - // Closes the temporary file if it is open. - void CloseTempFile(); - - // Sends the data to the file. Called From WriteToFile. - size_t WriteBytes(const char *buf, size_t length); - - // Sends the data to the file if it's open. - bool WriteToFile(const char *buf, size_t length); - - // Sends the data to the plugin. If it's not ready, handles buffering it - // and retrying later. - bool WriteToPlugin(const char *buf, const int length, const int data_offset); - - // Send the data to the plugin, returning how many bytes it accepted, or -1 - // if an error occurred. - int TryWriteToPlugin(const char *buf, const int length, - const int data_offset); - - // The callback which calls TryWriteToPlugin. - void OnDelayDelivery(); - - // Returns true if the temp file is valid and open for writing. - bool TempFileIsValid(); - - private: - NPStream stream_; - std::string headers_; - scoped_refptr<PluginInstance> instance_; - bool notify_needed_; - void * notify_data_; - bool close_on_write_data_; - uint16 requested_plugin_mode_; - bool opened_; -#if defined(OS_WIN) - char temp_file_name_[MAX_PATH]; - HANDLE temp_file_handle_; -#elif defined(OS_POSIX) - FILE* temp_file_; - FilePath temp_file_path_; -#endif - std::vector<char> delivery_data_; - int data_offset_; - bool seekable_stream_; - std::string mime_type_; - DISALLOW_COPY_AND_ASSIGN(PluginStream); -}; - -} // namespace NPAPI - -#endif // WEBKIT_GLUE_PLUGINS_PLUGIN_STREAM_H_ diff --git a/webkit/glue/plugins/plugin_stream_posix.cc b/webkit/glue/plugins/plugin_stream_posix.cc deleted file mode 100644 index d0e2291..0000000 --- a/webkit/glue/plugins/plugin_stream_posix.cc +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/plugin_stream.h" - -#include <string.h> - -#include "base/file_path.h" -#include "base/file_util.h" -#include "base/logging.h" -#include "webkit/glue/plugins/plugin_instance.h" - -namespace NPAPI { - -PluginStream::PluginStream( - PluginInstance *instance, - const char *url, - bool need_notify, - void *notify_data) - : instance_(instance), - notify_needed_(need_notify), - notify_data_(notify_data), - close_on_write_data_(false), - requested_plugin_mode_(NP_NORMAL), - opened_(false), - temp_file_(NULL), - temp_file_path_(), - data_offset_(0), - seekable_stream_(false) { - memset(&stream_, 0, sizeof(stream_)); - stream_.url = strdup(url); -} - -void PluginStream::UpdateUrl(const char* url) { - DCHECK(!opened_); - free(const_cast<char*>(stream_.url)); - stream_.url = strdup(url); -} - -void PluginStream::WriteAsFile() { - if (requested_plugin_mode_ == NP_ASFILE || - requested_plugin_mode_ == NP_ASFILEONLY) - instance_->NPP_StreamAsFile(&stream_, temp_file_path_.value().c_str()); -} - -size_t PluginStream::WriteBytes(const char *buf, size_t length) { - return fwrite(buf, sizeof(char), length, temp_file_); -} - -bool PluginStream::OpenTempFile() { - DCHECK(temp_file_ == NULL); - - if (file_util::CreateTemporaryFile(&temp_file_path_)) - temp_file_ = file_util::OpenFile(temp_file_path_, "a"); - - if (!temp_file_) { - temp_file_path_ = FilePath(""); - return false; - } - - return true; -} - -void PluginStream::CloseTempFile() { - file_util::CloseFile(temp_file_); - temp_file_ = NULL; -} - -bool PluginStream::TempFileIsValid() { - return temp_file_ != NULL; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_stream_url.cc b/webkit/glue/plugins/plugin_stream_url.cc deleted file mode 100644 index 1af4485..0000000 --- a/webkit/glue/plugins/plugin_stream_url.cc +++ /dev/null @@ -1,118 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_stream_url.h" - -#include "net/http/http_response_headers.h" -#include "webkit/glue/plugins/plugin_host.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/webplugin.h" - -namespace NPAPI { - -PluginStreamUrl::PluginStreamUrl( - unsigned long resource_id, - const GURL &url, - PluginInstance *instance, - bool notify_needed, - void *notify_data) - : PluginStream(instance, url.spec().c_str(), notify_needed, notify_data), - url_(url), - id_(resource_id) { -} - -PluginStreamUrl::~PluginStreamUrl() { - if (instance() && instance()->webplugin()) { - instance()->webplugin()->ResourceClientDeleted(AsResourceClient()); - } -} - -bool PluginStreamUrl::Close(NPReason reason) { - // Protect the stream against it being destroyed or the whole plugin instance - // being destroyed within the destroy stream handler. - scoped_refptr<PluginStream> protect(this); - CancelRequest(); - bool result = PluginStream::Close(reason); - instance()->RemoveStream(this); - return result; -} - -void PluginStreamUrl::WillSendRequest(const GURL& url, int http_status_code) { - if (notify_needed()) { - // If the plugin participates in HTTP url redirect handling then notify it. - if (net::HttpResponseHeaders::IsRedirectResponseCode(http_status_code) && - instance()->handles_url_redirects()) { - pending_redirect_url_ = url.spec(); - instance()->NPP_URLRedirectNotify(url.spec().c_str(), http_status_code, - notify_data()); - return; - } - } - url_ = url; - UpdateUrl(url.spec().c_str()); -} - -void PluginStreamUrl::DidReceiveResponse(const std::string& mime_type, - const std::string& headers, - uint32 expected_length, - uint32 last_modified, - bool request_is_seekable) { - // Protect the stream against it being destroyed or the whole plugin instance - // being destroyed within the new stream handler. - scoped_refptr<PluginStream> protect(this); - - bool opened = Open(mime_type, - headers, - expected_length, - last_modified, - request_is_seekable); - if (!opened) { - CancelRequest(); - instance()->RemoveStream(this); - } else { - if (id_ > 0) - instance()->webplugin()->SetDeferResourceLoading(id_, false); - } -} - -void PluginStreamUrl::DidReceiveData(const char* buffer, int length, - int data_offset) { - if (!open()) - return; - - // Protect the stream against it being destroyed or the whole plugin instance - // being destroyed within the write handlers - scoped_refptr<PluginStream> protect(this); - - if (length > 0) { - // The PluginStreamUrl instance could get deleted if the plugin fails to - // accept data in NPP_Write. - if (Write(const_cast<char*>(buffer), length, data_offset) > 0) { - if (id_ > 0) - instance()->webplugin()->SetDeferResourceLoading(id_, false); - } - } -} - -void PluginStreamUrl::DidFinishLoading() { - if (!seekable()) { - Close(NPRES_DONE); - } -} - -void PluginStreamUrl::DidFail() { - Close(NPRES_NETWORK_ERR); -} - -void PluginStreamUrl::CancelRequest() { - if (id_ > 0) { - if (instance()->webplugin()) { - instance()->webplugin()->CancelResource(id_); - } - id_ = 0; - } -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_stream_url.h b/webkit/glue/plugins/plugin_stream_url.h deleted file mode 100644 index 8c03edc..0000000 --- a/webkit/glue/plugins/plugin_stream_url.h +++ /dev/null @@ -1,71 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGIN_PLUGIN_STREAM_URL_H__ -#define WEBKIT_GLUE_PLUGIN_PLUGIN_STREAM_URL_H__ - - -#include "webkit/glue/plugins/plugin_stream.h" -#include "webkit/glue/plugins/webplugin.h" -#include "googleurl/src/gurl.h" - -namespace NPAPI { - -class PluginInstance; - -// A NPAPI Stream based on a URL. -class PluginStreamUrl : public PluginStream, - public webkit_glue::WebPluginResourceClient { - public: - // Create a new stream for sending to the plugin by fetching - // a URL. If notifyNeeded is set, then the plugin will be notified - // when the stream has been fully sent to the plugin. Initialize - // must be called before the object is used. - PluginStreamUrl(unsigned long resource_id, - const GURL &url, - PluginInstance *instance, - bool notify_needed, - void *notify_data); - virtual ~PluginStreamUrl(); - - // Stop sending the stream to the client. - // Overrides the base Close so we can cancel our fetching the URL if - // it is still loading. - virtual bool Close(NPReason reason); - - virtual webkit_glue::WebPluginResourceClient* AsResourceClient() { - return static_cast<webkit_glue::WebPluginResourceClient*>(this); - } - - virtual void CancelRequest(); - - // - // WebPluginResourceClient methods - // - void WillSendRequest(const GURL& url, int http_status_code); - void DidReceiveResponse(const std::string& mime_type, - const std::string& headers, - uint32 expected_length, - uint32 last_modified, - bool request_is_seekable); - void DidReceiveData(const char* buffer, int length, int data_offset); - void DidFinishLoading(); - void DidFail(); - bool IsMultiByteResponseExpected() { - return seekable(); - } - int ResourceId() { - return id_; - } - - private: - GURL url_; - unsigned long id_; - - DISALLOW_COPY_AND_ASSIGN(PluginStreamUrl); -}; - -} // namespace NPAPI - -#endif // WEBKIT_GLUE_PLUGIN_PLUGIN_STREAM_URL_H__ diff --git a/webkit/glue/plugins/plugin_stream_win.cc b/webkit/glue/plugins/plugin_stream_win.cc deleted file mode 100644 index 0b6fcbd..0000000 --- a/webkit/glue/plugins/plugin_stream_win.cc +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/plugin_stream.h" - -#include "base/logging.h" -#include "webkit/glue/plugins/plugin_instance.h" - -namespace NPAPI { - -PluginStream::PluginStream( - PluginInstance *instance, - const char *url, - bool need_notify, - void *notify_data) - : instance_(instance), - notify_needed_(need_notify), - notify_data_(notify_data), - close_on_write_data_(false), - opened_(false), - requested_plugin_mode_(NP_NORMAL), - temp_file_handle_(INVALID_HANDLE_VALUE), - seekable_stream_(false), - data_offset_(0) { - memset(&stream_, 0, sizeof(stream_)); - stream_.url = _strdup(url); - temp_file_name_[0] = '\0'; -} - -void PluginStream::UpdateUrl(const char* url) { - DCHECK(!opened_); - free(const_cast<char*>(stream_.url)); - stream_.url = _strdup(url); - pending_redirect_url_.clear(); -} - -void PluginStream::WriteAsFile() { - if (requested_plugin_mode_ == NP_ASFILE || - requested_plugin_mode_ == NP_ASFILEONLY) - instance_->NPP_StreamAsFile(&stream_, temp_file_name_); -} - -size_t PluginStream::WriteBytes(const char *buf, size_t length) { - DWORD bytes; - - if (!WriteFile(temp_file_handle_, buf, length, &bytes, 0)) - return 0U; - - return static_cast<size_t>(bytes); -} - -bool PluginStream::OpenTempFile() { - DCHECK(temp_file_handle_ == INVALID_HANDLE_VALUE); - - // The reason for using all the Ascii versions of these filesystem - // calls is that the filename which we pass back to the plugin - // via NPAPI is an ascii filename. Otherwise, we'd use wide-chars. - // - // TODO: - // This is a bug in NPAPI itself, and it needs to be fixed. - // The case which will fail is if a user has a multibyte name, - // but has the system locale set to english. GetTempPathA will - // return junk in this case, causing us to be unable to open the - // file. - - char temp_directory[MAX_PATH]; - if (GetTempPathA(MAX_PATH, temp_directory) == 0) - return false; - if (GetTempFileNameA(temp_directory, "npstream", 0, temp_file_name_) == 0) - return false; - temp_file_handle_ = CreateFileA(temp_file_name_, - FILE_ALL_ACCESS, - FILE_SHARE_READ, - 0, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - 0); - if (temp_file_handle_ == INVALID_HANDLE_VALUE) { - temp_file_name_[0] = '\0'; - return false; - } - return true; -} - -void PluginStream::CloseTempFile() { - if (temp_file_handle_ != INVALID_HANDLE_VALUE) { - CloseHandle(temp_file_handle_); - temp_file_handle_ = INVALID_HANDLE_VALUE; - } -} - -bool PluginStream::TempFileIsValid() { - return temp_file_handle_ != INVALID_HANDLE_VALUE; -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_string_stream.cc b/webkit/glue/plugins/plugin_string_stream.cc deleted file mode 100644 index f174267..0000000 --- a/webkit/glue/plugins/plugin_string_stream.cc +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/plugin_string_stream.h" - -#include "googleurl/src/gurl.h" - -namespace NPAPI { - -PluginStringStream::PluginStringStream( - PluginInstance* instance, - const GURL& url, - bool notify_needed, - void* notify_data) - : PluginStream(instance, url.spec().c_str(), notify_needed, notify_data) { -} - -PluginStringStream::~PluginStringStream() { -} - -void PluginStringStream::SendToPlugin(const std::string &data, - const std::string &mime_type) { - // Protect the stream against it being destroyed or the whole plugin instance - // being destroyed within the plugin stream callbacks. - scoped_refptr<PluginStringStream> protect(this); - - int length = static_cast<int>(data.length()); - if (Open(mime_type, std::string(), length, 0, false)) { - // TODO - check if it was not fully sent, and figure out a backup plan. - int written = Write(data.c_str(), length, 0); - NPReason reason = written == length ? NPRES_DONE : NPRES_NETWORK_ERR; - Close(reason); - } -} - -} diff --git a/webkit/glue/plugins/plugin_string_stream.h b/webkit/glue/plugins/plugin_string_stream.h deleted file mode 100644 index 68db2bf..0000000 --- a/webkit/glue/plugins/plugin_string_stream.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGIN_PLUGIN_STRING_STREAM_H_ -#define WEBKIT_GLUE_PLUGIN_PLUGIN_STRING_STREAM_H_ - -#include "webkit/glue/plugins/plugin_stream.h" - -class GURL; - -namespace NPAPI { - -class PluginInstance; - -// An NPAPI stream from a string. -class PluginStringStream : public PluginStream { - public: - // Create a new stream for sending to the plugin. - // If notify_needed, will notify the plugin after the data has - // all been sent. - PluginStringStream(PluginInstance* instance, - const GURL& url, - bool notify_needed, - void* notify_data); - - // Initiates the sending of data to the plugin. - void SendToPlugin(const std::string& data, - const std::string& mime_type); - - private: - virtual ~PluginStringStream(); - - DISALLOW_COPY_AND_ASSIGN(PluginStringStream); -}; - -} // namespace NPAPI - -#endif // WEBKIT_GLUE_PLUGIN_PLUGIN_STRING_STREAM_H_ diff --git a/webkit/glue/plugins/plugin_stubs.cc b/webkit/glue/plugins/plugin_stubs.cc deleted file mode 100644 index f8210c3..0000000 --- a/webkit/glue/plugins/plugin_stubs.cc +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file stubs out some functions needed to make the linker happy -// without linking in all the plugin code. It should be removed once -// we have plugins working on all platforms. - -// TODO(port): remove this file. - -#include "base/logging.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_stream.h" - -namespace NPAPI { - -PluginStream::~PluginStream() { - NOTIMPLEMENTED(); -} - -bool PluginStream::Close(NPReason reason) { - NOTIMPLEMENTED(); - return false; -} - -void PluginInstance::NPP_StreamAsFile(NPStream*, const char*) { - NOTIMPLEMENTED(); -} - -} // namespace NPAPI diff --git a/webkit/glue/plugins/plugin_switches.cc b/webkit/glue/plugins/plugin_switches.cc deleted file mode 100644 index eb5c958..0000000 --- a/webkit/glue/plugins/plugin_switches.cc +++ /dev/null @@ -1,15 +0,0 @@ -// 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 "webkit/glue/plugins/plugin_switches.h" - -namespace switches { - -// Enables the testing interface for PPAPI. -const char kEnablePepperTesting[] = "enable-pepper-testing"; - -// Dumps extra logging about plugin loading to the log file. -const char kDebugPluginLoading[] = "debug-plugin-loading"; - -} // namespace switches diff --git a/webkit/glue/plugins/plugin_switches.h b/webkit/glue/plugins/plugin_switches.h deleted file mode 100644 index 772c047..0000000 --- a/webkit/glue/plugins/plugin_switches.h +++ /dev/null @@ -1,15 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PLUGIN_SWITCHES_H_ -#define WEBKIT_GLUE_PLUGINS_PLUGIN_SWITCHES_H_ - -namespace switches { - -extern const char kDebugPluginLoading[]; -extern const char kEnablePepperTesting[]; - -} // namespace switches - -#endif // WEBKIT_GLUE_PLUGINS_PLUGIN_SWITCHES_H_ diff --git a/webkit/glue/plugins/plugin_web_event_converter_mac.h b/webkit/glue/plugins/plugin_web_event_converter_mac.h deleted file mode 100644 index ec5b86f..0000000 --- a/webkit/glue/plugins/plugin_web_event_converter_mac.h +++ /dev/null @@ -1,60 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGIN_PLUGIN_WEB_EVENT_CONVERTER_MAC_H_ -#define WEBKIT_GLUE_PLUGIN_PLUGIN_WEB_EVENT_CONVERTER_MAC_H_ - -#include "third_party/npapi/bindings/npapi.h" - -namespace WebKit { -class WebInputEvent; -class WebKeyboardEvent; -class WebMouseEvent; -class WebMouseWheelEvent; -} - -// Utility class to translating WebInputEvent structs to equivalent structures -// suitable for sending to Mac plugins (via NPP_HandleEvent). -class PluginWebEventConverter { - public: - PluginWebEventConverter() {} - virtual ~PluginWebEventConverter() {} - - // Initializes a converter for the given web event. Returns false if the event - // could not be converted. - virtual bool InitWithEvent(const WebKit::WebInputEvent& web_event); - - // Returns a pointer to a plugin event--suitable for passing to - // NPP_HandleEvent--corresponding to the the web event this converter was - // created with. The pointer is valid only as long as this object is. - // Returns NULL iff InitWithEvent returned false. - virtual void* plugin_event() = 0; - -protected: - // To be overridden by subclasses to store a converted plugin representation - // of the given web event, suitable for returning from plugin_event. - // Returns true if the event was successfully converted. - virtual bool ConvertKeyboardEvent( - const WebKit::WebKeyboardEvent& web_event) = 0; - virtual bool ConvertMouseEvent(const WebKit::WebMouseEvent& web_event) = 0; - virtual bool ConvertMouseWheelEvent( - const WebKit::WebMouseWheelEvent& web_event) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(PluginWebEventConverter); -}; - -// Factory for generating PluginWebEventConverter objects by event model. -class PluginWebEventConverterFactory { - public: - // Returns a new PluginWebEventConverter corresponding to the given plugin - // event model. - static PluginWebEventConverter* - CreateConverterForModel(NPEventModel event_model); - - private: - DISALLOW_COPY_AND_ASSIGN(PluginWebEventConverterFactory); -}; - -#endif // WEBKIT_GLUE_PLUGIN_PLUGIN_WEB_EVENT_CONVERTER_MAC_H_ diff --git a/webkit/glue/plugins/plugin_web_event_converter_mac.mm b/webkit/glue/plugins/plugin_web_event_converter_mac.mm deleted file mode 100644 index 12d5cc6..0000000 --- a/webkit/glue/plugins/plugin_web_event_converter_mac.mm +++ /dev/null @@ -1,359 +0,0 @@ -// 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. - -#import <Cocoa/Cocoa.h> - -#include "base/logging.h" -#include "webkit/glue/plugins/plugin_web_event_converter_mac.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" - -using WebKit::WebInputEvent; -using WebKit::WebKeyboardEvent; -using WebKit::WebMouseEvent; -using WebKit::WebMouseWheelEvent; - -namespace { - -// Returns true if the caps lock flag should be set for the given event. -bool CapsLockIsActive(const WebInputEvent& event) { - // Only key events have accurate information for the caps lock flag; see - // <https://bugs.webkit.org/show_bug.cgi?id=46518>. - // For other types, use the live state. - if (WebInputEvent::isKeyboardEventType(event.type)) - return (event.modifiers & WebInputEvent::CapsLockOn) != 0; - else - return ([[NSApp currentEvent] modifierFlags] & NSAlphaShiftKeyMask) != 0; -} - -} // namespace - -#pragma mark - - -#ifndef NP_NO_CARBON - -// Converter implementation for the Carbon event model. -class CarbonPluginWebEventConverter : public PluginWebEventConverter { - public: - CarbonPluginWebEventConverter() {} - virtual ~CarbonPluginWebEventConverter() {} - - virtual bool InitWithEvent(const WebInputEvent& web_event); - - virtual void* plugin_event() { return &carbon_event_; } - - protected: - virtual bool ConvertKeyboardEvent(const WebKeyboardEvent& key_event); - virtual bool ConvertMouseEvent(const WebMouseEvent& mouse_event); - virtual bool ConvertMouseWheelEvent(const WebMouseWheelEvent& wheel_event); - - private: - // Returns the Carbon translation of web_event's modifiers. - static EventModifiers CarbonModifiers(const WebInputEvent& web_event); - - NPEvent carbon_event_; - - DISALLOW_COPY_AND_ASSIGN(CarbonPluginWebEventConverter); -}; - -bool CarbonPluginWebEventConverter::InitWithEvent( - const WebInputEvent& web_event) { - memset(&carbon_event_, 0, sizeof(carbon_event_)); - // Set the fields common to all event types. - carbon_event_.when = TickCount(); - carbon_event_.modifiers |= CarbonModifiers(web_event); - - return PluginWebEventConverter::InitWithEvent(web_event); -} - -bool CarbonPluginWebEventConverter::ConvertKeyboardEvent( - const WebKeyboardEvent& key_event) { - // TODO: Figure out how to handle Unicode input to plugins, if that's - // even possible in the NPAPI Carbon event model. - carbon_event_.message = (key_event.nativeKeyCode << 8) & keyCodeMask; - carbon_event_.message |= key_event.text[0] & charCodeMask; - carbon_event_.modifiers |= btnState; - - switch (key_event.type) { - case WebInputEvent::KeyDown: - if (key_event.modifiers & WebInputEvent::IsAutoRepeat) - carbon_event_.what = autoKey; - else - carbon_event_.what = keyDown; - return true; - case WebInputEvent::KeyUp: - carbon_event_.what = keyUp; - return true; - case WebInputEvent::RawKeyDown: - case WebInputEvent::Char: - // May be used eventually for IME, but currently not needed. - return false; - default: - NOTREACHED(); - return false; - } -} - -bool CarbonPluginWebEventConverter::ConvertMouseEvent( - const WebMouseEvent& mouse_event) { - carbon_event_.where.h = mouse_event.globalX; - carbon_event_.where.v = mouse_event.globalY; - - // Default to "button up"; override this for mouse down events below. - carbon_event_.modifiers |= btnState; - - switch (mouse_event.button) { - case WebMouseEvent::ButtonLeft: - break; - case WebMouseEvent::ButtonMiddle: - carbon_event_.modifiers |= cmdKey; - break; - case WebMouseEvent::ButtonRight: - carbon_event_.modifiers |= controlKey; - break; - default: - NOTIMPLEMENTED(); - } - switch (mouse_event.type) { - case WebInputEvent::MouseMove: - carbon_event_.what = nullEvent; - return true; - case WebInputEvent::MouseLeave: - case WebInputEvent::MouseEnter: - carbon_event_.what = NPEventType_AdjustCursorEvent; - return true; - case WebInputEvent::MouseDown: - carbon_event_.modifiers &= ~btnState; - carbon_event_.what = mouseDown; - return true; - case WebInputEvent::MouseUp: - carbon_event_.what = mouseUp; - return true; - default: - NOTREACHED(); - return false; - } -} - -bool CarbonPluginWebEventConverter::ConvertMouseWheelEvent( - const WebMouseWheelEvent& wheel_event) { - return false; // The Carbon NPAPI event model has no "mouse wheel" concept. -} - -EventModifiers CarbonPluginWebEventConverter::CarbonModifiers( - const WebInputEvent& web_event) { - NSInteger modifiers = 0; - if (web_event.modifiers & WebInputEvent::ControlKey) - modifiers |= controlKey; - if (web_event.modifiers & WebInputEvent::ShiftKey) - modifiers |= shiftKey; - if (web_event.modifiers & WebInputEvent::AltKey) - modifiers |= optionKey; - if (web_event.modifiers & WebInputEvent::MetaKey) - modifiers |= cmdKey; - if (CapsLockIsActive(web_event)) - modifiers |= alphaLock; - return modifiers; -} - -#endif // !NP_NO_CARBON - -#pragma mark - - -// Converter implementation for the Cocoa event model. -class CocoaPluginWebEventConverter : public PluginWebEventConverter { -public: - CocoaPluginWebEventConverter() {} - virtual ~CocoaPluginWebEventConverter() {} - - virtual bool InitWithEvent(const WebInputEvent& web_event); - - virtual void* plugin_event() { return &cocoa_event_; } - -protected: - virtual bool ConvertKeyboardEvent(const WebKeyboardEvent& key_event); - virtual bool ConvertMouseEvent(const WebMouseEvent& mouse_event); - virtual bool ConvertMouseWheelEvent(const WebMouseWheelEvent& wheel_event); - -private: - // Returns the Cocoa translation of web_event's modifiers. - static NSUInteger CocoaModifiers(const WebInputEvent& web_event); - - // Returns true if the given key is a modifier key. - static bool KeyIsModifier(int native_key_code); - - NPCocoaEvent cocoa_event_; - - DISALLOW_COPY_AND_ASSIGN(CocoaPluginWebEventConverter); -}; - -bool CocoaPluginWebEventConverter::InitWithEvent( - const WebInputEvent& web_event) { - memset(&cocoa_event_, 0, sizeof(cocoa_event_)); - return PluginWebEventConverter::InitWithEvent(web_event); -} - -bool CocoaPluginWebEventConverter::ConvertKeyboardEvent( - const WebKeyboardEvent& key_event) { - cocoa_event_.data.key.keyCode = key_event.nativeKeyCode; - - cocoa_event_.data.key.modifierFlags |= CocoaModifiers(key_event); - - // Modifier keys have their own event type, and don't get character or - // repeat data. - if (KeyIsModifier(key_event.nativeKeyCode)) { - cocoa_event_.type = NPCocoaEventFlagsChanged; - return true; - } - - cocoa_event_.data.key.characters = reinterpret_cast<NPNSString*>( - [NSString stringWithFormat:@"%S", key_event.text]); - cocoa_event_.data.key.charactersIgnoringModifiers = - reinterpret_cast<NPNSString*>( - [NSString stringWithFormat:@"%S", key_event.unmodifiedText]); - - if (key_event.modifiers & WebInputEvent::IsAutoRepeat) - cocoa_event_.data.key.isARepeat = true; - - switch (key_event.type) { - case WebInputEvent::KeyDown: - cocoa_event_.type = NPCocoaEventKeyDown; - return true; - case WebInputEvent::KeyUp: - cocoa_event_.type = NPCocoaEventKeyUp; - return true; - case WebInputEvent::RawKeyDown: - case WebInputEvent::Char: - // May be used eventually for IME, but currently not needed. - return false; - default: - NOTREACHED(); - return false; - } -} - -bool CocoaPluginWebEventConverter::ConvertMouseEvent( - const WebMouseEvent& mouse_event) { - cocoa_event_.data.mouse.pluginX = mouse_event.x; - cocoa_event_.data.mouse.pluginY = mouse_event.y; - cocoa_event_.data.mouse.modifierFlags |= CocoaModifiers(mouse_event); - cocoa_event_.data.mouse.clickCount = mouse_event.clickCount; - switch (mouse_event.button) { - case WebMouseEvent::ButtonLeft: - cocoa_event_.data.mouse.buttonNumber = 0; - break; - case WebMouseEvent::ButtonMiddle: - cocoa_event_.data.mouse.buttonNumber = 2; - break; - case WebMouseEvent::ButtonRight: - cocoa_event_.data.mouse.buttonNumber = 1; - break; - default: - cocoa_event_.data.mouse.buttonNumber = mouse_event.button; - break; - } - switch (mouse_event.type) { - case WebInputEvent::MouseDown: - cocoa_event_.type = NPCocoaEventMouseDown; - return true; - case WebInputEvent::MouseUp: - cocoa_event_.type = NPCocoaEventMouseUp; - return true; - case WebInputEvent::MouseMove: { - bool mouse_is_down = - (mouse_event.modifiers & WebInputEvent::LeftButtonDown) || - (mouse_event.modifiers & WebInputEvent::RightButtonDown) || - (mouse_event.modifiers & WebInputEvent::MiddleButtonDown); - cocoa_event_.type = mouse_is_down ? NPCocoaEventMouseDragged - : NPCocoaEventMouseMoved; - return true; - } - case WebInputEvent::MouseEnter: - cocoa_event_.type = NPCocoaEventMouseEntered; - return true; - case WebInputEvent::MouseLeave: - cocoa_event_.type = NPCocoaEventMouseExited; - return true; - default: - NOTREACHED(); - return false; - } -} - -bool CocoaPluginWebEventConverter::ConvertMouseWheelEvent( - const WebMouseWheelEvent& wheel_event) { - cocoa_event_.type = NPCocoaEventScrollWheel; - cocoa_event_.data.mouse.pluginX = wheel_event.x; - cocoa_event_.data.mouse.pluginY = wheel_event.y; - cocoa_event_.data.mouse.modifierFlags |= CocoaModifiers(wheel_event); - cocoa_event_.data.mouse.deltaX = wheel_event.deltaX; - cocoa_event_.data.mouse.deltaY = wheel_event.deltaY; - return true; -} - -NSUInteger CocoaPluginWebEventConverter::CocoaModifiers( - const WebInputEvent& web_event) { - NSInteger modifiers = 0; - if (web_event.modifiers & WebInputEvent::ControlKey) - modifiers |= NSControlKeyMask; - if (web_event.modifiers & WebInputEvent::ShiftKey) - modifiers |= NSShiftKeyMask; - if (web_event.modifiers & WebInputEvent::AltKey) - modifiers |= NSAlternateKeyMask; - if (web_event.modifiers & WebInputEvent::MetaKey) - modifiers |= NSCommandKeyMask; - if (CapsLockIsActive(web_event)) - modifiers |= NSAlphaShiftKeyMask; - return modifiers; -} - -bool CocoaPluginWebEventConverter::KeyIsModifier(int native_key_code) { - switch (native_key_code) { - case 55: // Left command - case 54: // Right command - case 58: // Left option - case 61: // Right option - case 59: // Left control - case 62: // Right control - case 56: // Left shift - case 60: // Right shift - case 57: // Caps lock - return true; - default: - return false; - } -} - -#pragma mark - - -bool PluginWebEventConverter::InitWithEvent(const WebInputEvent& web_event) { - if (web_event.type == WebInputEvent::MouseWheel) { - return ConvertMouseWheelEvent( - *static_cast<const WebMouseWheelEvent*>(&web_event)); - } else if (WebInputEvent::isMouseEventType(web_event.type)) { - return ConvertMouseEvent(*static_cast<const WebMouseEvent*>(&web_event)); - } else if (WebInputEvent::isKeyboardEventType(web_event.type)) { - return ConvertKeyboardEvent( - *static_cast<const WebKeyboardEvent*>(&web_event)); - } - DLOG(WARNING) << "Unknown event type " << web_event.type; - return false; -} - -#pragma mark - - -PluginWebEventConverter* - PluginWebEventConverterFactory::CreateConverterForModel( - NPEventModel event_model) { - switch (event_model) { - case NPEventModelCocoa: - return new CocoaPluginWebEventConverter(); -#ifndef NP_NO_CARBON - case NPEventModelCarbon: - return new CarbonPluginWebEventConverter(); -#endif - default: - NOTIMPLEMENTED(); - return NULL; - } -} diff --git a/webkit/glue/plugins/ppb_private.h b/webkit/glue/plugins/ppb_private.h deleted file mode 100644 index b3d2b67..0000000 --- a/webkit/glue/plugins/ppb_private.h +++ /dev/null @@ -1,135 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PPB_PRIVATE_H_ -#define WEBKIT_GLUE_PLUGINS_PPB_PRIVATE_H_ - -#include "ppapi/c/dev/ppb_font_dev.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" - -#define PPB_PRIVATE_INTERFACE "PPB_Private;1" - -// From the public PPB_Font_Dev file. -struct PP_FontDescription_Dev; - -typedef enum { - PP_RESOURCESTRING_PDFGETPASSWORD = 0, - PP_RESOURCESTRING_PDFLOADING = 1, - PP_RESOURCESTRING_PDFLOAD_FAILED = 2, -} PP_ResourceString; - -typedef enum { - PP_RESOURCEIMAGE_PDF_BUTTON_FTH = 0, - PP_RESOURCEIMAGE_PDF_BUTTON_FTH_HOVER = 1, - PP_RESOURCEIMAGE_PDF_BUTTON_FTH_PRESSED = 2, - PP_RESOURCEIMAGE_PDF_BUTTON_FTW = 3, - PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER = 4, - PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED = 5, - PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN = 6, - PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER = 7, - PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED = 8, - PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT = 9, - PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER = 10, - PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED = 11, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0 = 12, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1 = 13, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2 = 14, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3 = 15, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4 = 16, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5 = 17, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6 = 18, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7 = 19, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8 = 20, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9 = 21, - PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND = 22, -} PP_ResourceImage; - -typedef enum { - PP_PRIVATEFONTCHARSET_ANSI = 0, - PP_PRIVATEFONTCHARSET_DEFAULT = 1, - PP_PRIVATEFONTCHARSET_SYMBOL = 2, - PP_PRIVATEFONTCHARSET_MAC = 77, - PP_PRIVATEFONTCHARSET_SHIFTJIS = 128, - PP_PRIVATEFONTCHARSET_HANGUL = 129, - PP_PRIVATEFONTCHARSET_JOHAB = 130, - PP_PRIVATEFONTCHARSET_GB2312 =134, - PP_PRIVATEFONTCHARSET_CHINESEBIG5 = 136, - PP_PRIVATEFONTCHARSET_GREEK = 161, - PP_PRIVATEFONTCHARSET_TURKISH = 162, - PP_PRIVATEFONTCHARSET_VIETNAMESE = 163, - PP_PRIVATEFONTCHARSET_HEBREW = 177, - PP_PRIVATEFONTCHARSET_ARABIC = 178, - PP_PRIVATEFONTCHARSET_BALTIC = 186, - PP_PRIVATEFONTCHARSET_RUSSIAN = 204, - PP_PRIVATEFONTCHARSET_THAI = 222, - PP_PRIVATEFONTCHARSET_EASTEUROPE = 238, - PP_PRIVATEFONTCHARSET_OEM = 255 -} PP_PrivateFontCharset; - -struct PP_PrivateFontFileDescription { - const char* face; - uint32_t weight; - bool italic; -}; - -struct PP_PrivateFindResult { - int start_index; - int length; -}; - -struct PPB_Private { - // Returns a localized string. - PP_Var (*GetLocalizedString)(PP_Module module, PP_ResourceString string_id); - - // Returns a resource image. - PP_Resource (*GetResourceImage)(PP_Module module, - PP_ResourceImage image_id); - - // Returns a resource identifying a font file corresponding to the given font - // request after applying the browser-specific fallback. - // - // Currently Linux-only. - PP_Resource (*GetFontFileWithFallback)( - PP_Module module, - const PP_FontDescription_Dev* description, - PP_PrivateFontCharset charset); - - // Given a resource previously returned by GetFontFileWithFallback, returns - // a pointer to the requested font table. Linux only. - bool (*GetFontTableForPrivateFontFile)(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length); - - // Search the given string using ICU. Use PPB_Core's MemFree on results when - // done. - void (*SearchString)( - PP_Module module, - const unsigned short* string, - const unsigned short* term, - bool case_sensitive, - PP_PrivateFindResult** results, - int* count); - - // Since WebFrame doesn't know about Pepper requests, it'll think the page has - // finished loading even if there are outstanding requests by the plugin. - // Take this out once WebFrame knows about requests by pepper plugins. - void (*DidStartLoading)(PP_Instance instance); - void (*DidStopLoading)(PP_Instance instance); - - // Sets content restriction for a full-page plugin (i.e. can't copy/print). - // The value is a bitfield of ContentRestriction enums. - void (*SetContentRestriction)(PP_Instance instance, int restrictions); - - // Use UMA so we know average pdf page count. - void (*HistogramPDFPageCount)(int count); - - // Notifies the browser that the given action has been performed. - void (*UserMetricsRecordAction)(PP_Var action); -}; - -#endif // WEBKIT_GLUE_PLUGINS_PPB_PRIVATE_H_ diff --git a/webkit/glue/plugins/ppb_private2.h b/webkit/glue/plugins/ppb_private2.h deleted file mode 100644 index acf7831..0000000 --- a/webkit/glue/plugins/ppb_private2.h +++ /dev/null @@ -1,117 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PPB_PRIVATE2_H_ -#define WEBKIT_GLUE_PLUGINS_PPB_PRIVATE2_H_ - -#ifdef _WIN32 -#include <windows.h> -#endif - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" - -#define PPB_PRIVATE2_INTERFACE "PPB_Private2;4" - -#ifdef _WIN32 -typedef HANDLE PP_FileHandle; -static const PP_FileHandle PP_kInvalidFileHandle = NULL; -#else -typedef int PP_FileHandle; -static const PP_FileHandle PP_kInvalidFileHandle = -1; -#endif - -struct PP_FontDescription_Dev; -struct PP_FileInfo_Dev; - -struct PP_DirEntry_Dev { - const char* name; - bool is_dir; -}; - -struct PP_DirContents_Dev { - int32_t count; - PP_DirEntry_Dev* entries; -}; - -struct PPB_Private2 { - // Sets or clears the rendering hint that the given plugin instance is always - // on top of page content. Somewhat more optimized painting can be used in - // this case. - void (*SetInstanceAlwaysOnTop)(PP_Instance instance, bool on_top); - - bool (*DrawGlyphs)(PP_Resource pp_image_data, - const PP_FontDescription_Dev* font_desc, - uint32_t color, - PP_Point position, - PP_Rect clip, - float transformation[3][3], - uint32_t glyph_count, - uint16_t glyph_indices[], - PP_Point glyph_advances[]); - - // Retrieves the proxy that will be used for the given URL. The result will - // be a string in PAC format, or an undefined var on error. - PP_Var (*GetProxyForURL)(PP_Module module, const char* url); - - // Opens a module-local file, returning a file descriptor (posix) or a HANDLE - // (win32) into file. Module-local file paths (here and below) are - // '/'-separated UTF-8 strings, relative to a module-specific root. The return - // value is the ppapi error, PP_OK if success, one of the PP_ERROR_* in case - // of failure. - int32_t (*OpenModuleLocalFile)(PP_Module module, - const char* path, - int32_t mode, - PP_FileHandle* file); - - // Renames a module-local file. The return value is the ppapi error, PP_OK if - // success, one of the PP_ERROR_* in case of failure. - int32_t (*RenameModuleLocalFile)(PP_Module module, - const char* path_from, - const char* path_to); - - // Deletes a module-local file or directory. If recursive is set and the path - // points to a directory, deletes all the contents of the directory. The - // return value is the ppapi error, PP_OK if success, one of the PP_ERROR_* in - // case of failure. - int32_t (*DeleteModuleLocalFileOrDir)(PP_Module module, - const char* path, - bool recursive); - - // Creates a module-local directory. The return value is the ppapi error, - // PP_OK if success, one of the PP_ERROR_* in case of failure. - int32_t (*CreateModuleLocalDir)(PP_Module module, const char* path); - - // Queries information about a module-local file. The return value is the - // ppapi error, PP_OK if success, one of the PP_ERROR_* in case of failure. - int32_t (*QueryModuleLocalFile)(PP_Module module, - const char* path, - PP_FileInfo_Dev* info); - - // Gets the list of files contained in a module-local directory. The return - // value is the ppapi error, PP_OK if success, one of the PP_ERROR_* in case - // of failure. If non-NULL, the returned contents should be freed with - // FreeModuleLocalDirContents. - int32_t (*GetModuleLocalDirContents)(PP_Module module, - const char* path, - PP_DirContents_Dev** contents); - - // Frees the data allocated by GetModuleLocalDirContents. - void (*FreeModuleLocalDirContents)(PP_Module module, - PP_DirContents_Dev* contents); - - // Navigate to URL. May open a new tab if target is not "_self". Return true - // if success. This differs from javascript:window.open() in that it bypasses - // the popup blocker, even when this is not called from an event handler. - bool (*NavigateToURL)(PP_Instance instance, - const char* url, - const char* target); -}; - -#endif // WEBKIT_GLUE_PLUGINS_PPB_PRIVATE2_H_ diff --git a/webkit/glue/plugins/ppp_private.h b/webkit/glue/plugins/ppp_private.h deleted file mode 100644 index 7f5921e..0000000 --- a/webkit/glue/plugins/ppp_private.h +++ /dev/null @@ -1,20 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_PPP_PRIVATE_H_ -#define WEBKIT_GLUE_PLUGINS_PPP_PRIVATE_H_ - -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_var.h" - -#define PPP_PRIVATE_INTERFACE "PPP_Private;1" - -struct PPP_Private { - // Returns an absolute URL if the position is over a link. - PP_Var (*GetLinkAtPosition)(PP_Instance instance, - PP_Point point); -}; - -#endif // WEBKIT_GLUE_PLUGINS_PPP_PRIVATE_H_ diff --git a/webkit/glue/plugins/quickdraw_drawing_manager_mac.cc b/webkit/glue/plugins/quickdraw_drawing_manager_mac.cc deleted file mode 100644 index 424cc1e..0000000 --- a/webkit/glue/plugins/quickdraw_drawing_manager_mac.cc +++ /dev/null @@ -1,154 +0,0 @@ -// 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 NP_NO_QUICKDRAW - -#include "webkit/glue/plugins/quickdraw_drawing_manager_mac.h" - -#include "webkit/glue/plugins/coregraphics_private_symbols_mac.h" - -// Turn off GCC warnings about deprecated functions (since QuickDraw is a -// deprecated API). According to the GCC documentation, this can only be done -// per file, not pushed and popped like some options can be. -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - -QuickDrawDrawingManager::QuickDrawDrawingManager() - : plugin_window_(NULL), target_context_(NULL), fast_path_enabled_(false), - current_port_(NULL), target_world_(NULL), plugin_world_(NULL) {} - -QuickDrawDrawingManager::~QuickDrawDrawingManager() { - DestroyGWorlds(); -} - -void QuickDrawDrawingManager::SetFastPathEnabled(bool enabled) { - if (fast_path_enabled_ == enabled) - return; - - fast_path_enabled_ = enabled; - if (enabled) { - if (!target_world_) - UpdateGWorlds(); - // Copy our last window snapshot into our new source, since the plugin - // may not repaint everything. - CopyGWorldBits(target_world_, plugin_world_, plugin_size_); - current_port_ = plugin_world_; - } else { - current_port_ = GetWindowPort(plugin_window_); - } -} - -void QuickDrawDrawingManager::SetTargetContext(CGContextRef context, - const gfx::Size& plugin_size) { - target_context_ = context; - if (plugin_size != plugin_size_) { - plugin_size_ = plugin_size; - // Pitch the old GWorlds, since they are the wrong size now. - DestroyGWorlds(); - if (fast_path_enabled_) - UpdateGWorlds(); - } -} - -void QuickDrawDrawingManager::SetPluginWindow(WindowRef window) { - plugin_window_ = window; - if (!fast_path_enabled_) - current_port_ = GetWindowPort(window); -} - -void QuickDrawDrawingManager::UpdateContext() { - if (fast_path_enabled_) - CopyGWorldBits(plugin_world_, target_world_, plugin_size_); - else - ScrapeWindow(plugin_window_, target_context_, plugin_size_); -} - -bool QuickDrawDrawingManager::IsFastPathEnabled() { - return fast_path_enabled_; -} - -void QuickDrawDrawingManager::MakePortCurrent() { - if (fast_path_enabled_) - SetGWorld(current_port_, NULL); - else - SetPort(current_port_); -} - -void QuickDrawDrawingManager::DestroyGWorlds() { - if (plugin_world_) { - DisposeGWorld(plugin_world_); - plugin_world_ = NULL; - } - if (target_world_) { - DisposeGWorld(target_world_); - target_world_ = NULL; - } -} - -void QuickDrawDrawingManager::UpdateGWorlds() { - DestroyGWorlds(); - if (!target_context_) - return; - - Rect window_bounds = { - 0, 0, plugin_size_.height(), plugin_size_.width() - }; - // Create a GWorld pointing at the same bits as our target context. - if (target_context_) { - NewGWorldFromPtr( - &target_world_, k32BGRAPixelFormat, &window_bounds, NULL, NULL, 0, - static_cast<Ptr>(CGBitmapContextGetData(target_context_)), - static_cast<SInt32>(CGBitmapContextGetBytesPerRow(target_context_))); - } - // Create a GWorld for the plugin to paint into whenever it wants; since - // QuickDraw plugins don't draw at known times, they can't be allowed to draw - // directly into the shared memory. - NewGWorld(&plugin_world_, k32ARGBPixelFormat, &window_bounds, - NULL, NULL, kNativeEndianPixMap); - if (fast_path_enabled_) - current_port_ = plugin_world_; -} - -void QuickDrawDrawingManager::ScrapeWindow(WindowRef window, - CGContextRef target_context, - const gfx::Size& plugin_size) { - if (!target_context) - return; - - CGRect window_bounds = CGRectMake(0, 0, - plugin_size.width(), - plugin_size.height()); - CGWindowID window_id = HIWindowGetCGWindowID(window); - CGContextSaveGState(target_context); - CGContextTranslateCTM(target_context, 0, plugin_size.height()); - CGContextScaleCTM(target_context, 1.0, -1.0); - CGContextCopyWindowCaptureContentsToRect(target_context, window_bounds, - _CGSDefaultConnection(), - window_id, 0); - CGContextRestoreGState(target_context); -} - -void QuickDrawDrawingManager::CopyGWorldBits(GWorldPtr source, GWorldPtr dest, - const gfx::Size& plugin_size) { - if (!(source && dest)) - return; - - Rect window_bounds = { 0, 0, plugin_size.height(), plugin_size.width() }; - PixMapHandle source_pixmap = GetGWorldPixMap(source); - if (LockPixels(source_pixmap)) { - PixMapHandle dest_pixmap = GetGWorldPixMap(dest); - if (LockPixels(dest_pixmap)) { - SetGWorld(dest, NULL); - // Set foreground and background colors to avoid "colorizing" the image. - ForeColor(blackColor); - BackColor(whiteColor); - CopyBits(reinterpret_cast<BitMap*>(*source_pixmap), - reinterpret_cast<BitMap*>(*dest_pixmap), - &window_bounds, &window_bounds, srcCopy, NULL); - UnlockPixels(dest_pixmap); - } - UnlockPixels(source_pixmap); - } -} - -#endif // !NP_NO_QUICKDRAW diff --git a/webkit/glue/plugins/quickdraw_drawing_manager_mac.h b/webkit/glue/plugins/quickdraw_drawing_manager_mac.h deleted file mode 100644 index 8163f92..0000000 --- a/webkit/glue/plugins/quickdraw_drawing_manager_mac.h +++ /dev/null @@ -1,83 +0,0 @@ -// 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 WEBKIT_GLUE_QUICKDRAW_DRAWING_MANAGER_MAC_H_ -#define WEBKIT_GLUE_QUICKDRAW_DRAWING_MANAGER_MAC_H_ - -#ifndef NP_NO_QUICKDRAW - -#import <Carbon/Carbon.h> - -#include "gfx/rect.h" - -// Plugin helper class encapsulating the details of capturing what a QuickDraw -// drawing model plugin draws, then drawing it into a CGContext. -class QuickDrawDrawingManager { - public: - QuickDrawDrawingManager(); - ~QuickDrawDrawingManager(); - - // Sets the mode used for plugin drawing. If enabled is true the plugin draws - // into a GWorld that's not connected to a window, otherwise the plugin draws - // into our the plugin's dummy window (which is slower, since the call we use - // to scrape the window contents is much more expensive than copying between - // GWorlds). - void SetFastPathEnabled(bool enabled); - - // Returns true if the fast path is currently enabled. - bool IsFastPathEnabled(); - - // Sets the context that the plugin bits should be copied into when - // UpdateContext is called. This object does not retain |context|, so the - // caller must call SetTargetContext again if the context changes. - // If the fast path is currently enabled, this call will cause the port to - // change. - void SetTargetContext(CGContextRef context, const gfx::Size& plugin_size); - - // Sets the window that is used by the plugin. This object does not own the - // window, so the caler must call SetPluginWindow again if the window changes. - void SetPluginWindow(WindowRef window); - - // Updates the target context with the current plugin bits. - void UpdateContext(); - - // Returns the port that the plugin should draw into. This returned port is - // only valid until the next call to SetFastPathEnabled (or SetTargetContext - // while the fast path is enabled). - CGrafPtr port() { return current_port_; } - - // Makes the QuickDraw port current; should be called before calls where the - // plugin might draw. - void MakePortCurrent(); - - private: - // Updates the GWorlds used by the faster path. - void UpdateGWorlds(); - - // Deletes the GWorlds used by the faster path. - void DestroyGWorlds(); - - // Scrapes the contents of the window into the given context. - // Used for the slower path. - static void ScrapeWindow(WindowRef window, CGContextRef target_context, - const gfx::Size& plugin_size); - - // Copies the source GWorld's bits into the target GWorld. - // Used for the faster path. - static void CopyGWorldBits(GWorldPtr source, GWorldPtr dest, - const gfx::Size& plugin_size); - - WindowRef plugin_window_; // Weak reference. - CGContextRef target_context_; // Weak reference. - gfx::Size plugin_size_; - bool fast_path_enabled_; - CGrafPtr current_port_; - // Variables used for the faster path: - GWorldPtr target_world_; // Created lazily; may be NULL. - GWorldPtr plugin_world_; // Created lazily; may be NULL. -}; - -#endif // !NP_NO_QUICKDRAW - -#endif // QUICKDRAW_DRAWING_MANAGER_MAC diff --git a/webkit/glue/plugins/test/Info.plist b/webkit/glue/plugins/test/Info.plist deleted file mode 100644 index 37145fd..0000000 --- a/webkit/glue/plugins/test/Info.plist +++ /dev/null @@ -1,46 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>CFBundleDevelopmentRegion</key> - <string>English</string> - <key>CFBundleExecutable</key> - <string>NPAPITestPlugIn</string> - <key>CFBundleIdentifier</key> - <string>org.chromium.npapi_test_plugin</string> - <key>CFBundleInfoDictionaryVersion</key> - <string>6.0</string> - <key>CFBundleExecutable</key> - <string>${EXECUTABLE_NAME}</string> - <key>CFBundleName</key> - <string>${PRODUCT_NAME}</string> - <key>CFBundlePackageType</key> - <string>BRPL</string> - <key>CFBundleShortVersionString</key> - <string>1.0</string> - <key>CFBundleSignature</key> - <string>????</string> - <key>CFBundleVersion</key> - <string>1.0</string> - <key>CFPlugInDynamicRegisterFunction</key> - <string></string> - <key>CFPlugInDynamicRegistration</key> - <string>NO</string> - <key>WebPluginDescription</key> - <string>Simple NPAPI plug-in for Chromium unit tests</string> - <key>WebPluginMIMETypes</key> - <dict> - <key>application/vnd.npapi-test</key> - <dict> - <key>WebPluginExtensions</key> - <array> - <string>npapitest</string> - </array> - <key>WebPluginTypeDescription</key> - <string>test npapi</string> - </dict> - </dict> - <key>WebPluginName</key> - <string>Chromium NPAPI Test Plugin</string> -</dict> -</plist> diff --git a/webkit/glue/plugins/test/npapi_constants.cc b/webkit/glue/plugins/test/npapi_constants.cc deleted file mode 100644 index 75cc68f..0000000 --- a/webkit/glue/plugins/test/npapi_constants.cc +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/npapi_constants.h" - -namespace NPAPIClient { -const char kTestCompleteCookie[] = "status"; -const char kTestCompleteSuccess[] = "OK"; -} diff --git a/webkit/glue/plugins/test/npapi_constants.h b/webkit/glue/plugins/test/npapi_constants.h deleted file mode 100644 index 6570c35..0000000 --- a/webkit/glue/plugins/test/npapi_constants.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Constants for the NPAPI test - -#ifndef WEBKIT_PORT_PLUGINS_TEST_NPAPI_CONSTANTS_H__ -#define WEBKIT_PORT_PLUGINS_TEST_NPAPI_CONSTANTS_H__ - -namespace NPAPIClient { -// The name of the cookie which will be used to communicate between -// the plugin and the test harness. -extern const char kTestCompleteCookie[]; - -// The cookie value which will be sent to the client upon successful -// test. -extern const char kTestCompleteSuccess[]; -} -#endif // WEBKIT_PORT_PLUGINS_TEST_NPAPI_CONSTANTS_H__ diff --git a/webkit/glue/plugins/test/npapi_test.cc b/webkit/glue/plugins/test/npapi_test.cc deleted file mode 100644 index 895a842..0000000 --- a/webkit/glue/plugins/test/npapi_test.cc +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// -// npapitest -// -// This is a NPAPI Plugin Program which is used to test the Browser's NPAPI -// host implementation. It is used in conjunction with the npapi_unittest. -// -// As a NPAPI Plugin, you can invoke it by creating a web page of the following -// type: -// -// <embed src="content-to-load" type="application/vnd.npapi-test" -// name="test-name"> -// -// arguments: -// src: This is the initial content which will be sent to the plugin. -// type: Must be "application/vnd.npapi-test" -// name: The testcase to run when invoked -// id: The id of the test being run (for testing concurrent plugins) -// -// The Plugin drives the actual test, calling host functions and validating the -// Host callbacks which it receives. It is the duty of the plugin to record -// all errors. -// -// To indicate test completion, the plugin expects the containing HTML page to -// implement two javascript functions: -// onSuccess(string testname); -// onFailure(string testname, string results); -// The HTML host pages used in this test will then set a document cookie -// which the automated test framework can poll for and discover that the -// test has completed. -// -// -// TESTS -// When the PluginClient receives a NPP_New callback from the browser, -// it looks at the "name" argument which is passed in. It verifies that -// the name matches a known test, and instantiates that test. The test is -// a subclass of PluginTest. -// -// - -#include "base/basictypes.h" - -#if defined(OS_WIN) -#include <windows.h> -#endif - -#if defined(__GNUC__) && __GNUC__ >= 4 -#define EXPORT __attribute__((visibility ("default"))) -#else -#define EXPORT -#endif - -#include "webkit/glue/plugins/test/plugin_client.h" - -#if defined(OS_WIN) -BOOL API_CALL DllMain(HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved) { - return TRUE; -} -#endif - -extern "C" { -EXPORT NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) { - return NPAPIClient::PluginClient::GetEntryPoints(pFuncs); -} - -EXPORT NPError API_CALL NP_Shutdown() { - return NPAPIClient::PluginClient::Shutdown(); -} - -#if defined(OS_WIN) || defined(OS_MACOSX) -EXPORT NPError API_CALL NP_Initialize(NPNetscapeFuncs* npnFuncs) { - return NPAPIClient::PluginClient::Initialize(npnFuncs); -} -#elif defined(OS_POSIX) -EXPORT NPError API_CALL NP_Initialize(NPNetscapeFuncs* npnFuncs, - NPPluginFuncs* nppFuncs) { - NPError error = NPAPIClient::PluginClient::Initialize(npnFuncs); - if (error == NPERR_NO_ERROR) { - error = NP_GetEntryPoints(nppFuncs); - } - return error; -} - -EXPORT NPError API_CALL NP_GetValue(NPP instance, NPPVariable variable, - void* value) { - NPError err = NPERR_NO_ERROR; - - switch (variable) { - case NPPVpluginNameString: - *(static_cast<const char**>(value)) = "NPAPI Test Plugin"; - break; - case NPPVpluginDescriptionString: - *(static_cast<const char**>(value)) = - "Simple NPAPI plug-in for Chromium unit tests"; - break; - case NPPVpluginNeedsXEmbed: - *(static_cast<NPBool*>(value)) = true; - break; - default: - err = NPERR_GENERIC_ERROR; - break; - } - - return err; -} - -EXPORT const char* API_CALL NP_GetMIMEDescription(void) { - // The layout test LayoutTests/fast/js/navigator-mimeTypes-length.html - // asserts that the number of mimetypes handled by plugins should be - // greater than the number of plugins. We specify a mimetype here so - // this plugin has at least one. - return "application/vnd.npapi-test:npapitest:test npapi"; -} -#endif // OS_POSIX -} // extern "C" - -namespace WebCore { - const char* currentTextBreakLocaleID() { return "en_us"; } -} diff --git a/webkit/glue/plugins/test/npapi_test.def b/webkit/glue/plugins/test/npapi_test.def deleted file mode 100644 index 4481c16..0000000 --- a/webkit/glue/plugins/test/npapi_test.def +++ /dev/null @@ -1,6 +0,0 @@ -LIBRARY npapi_test_plugin - -EXPORTS - NP_GetEntryPoints @1 - NP_Initialize @2 - NP_Shutdown @3 diff --git a/webkit/glue/plugins/test/npapi_test.rc b/webkit/glue/plugins/test/npapi_test.rc deleted file mode 100644 index 524dda4..0000000 --- a/webkit/glue/plugins/test/npapi_test.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "FileDescription", "NPAPI Test Plugin" - VALUE "FileVersion", "1, 0, 0, 1" - VALUE "InternalName", "npapi_test_plugin" - VALUE "LegalCopyright", "Copyright (C) 2007" - VALUE "MIMEType", "application/vnd.npapi-test" - VALUE "OriginalFilename", "npapi_test_plugin.dll" - VALUE "ProductName", "NPAPI Test Plugin" - VALUE "ProductVersion", "1, 0, 0, 1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/webkit/glue/plugins/test/plugin_arguments_test.cc b/webkit/glue/plugins/test/plugin_arguments_test.cc deleted file mode 100644 index 46ccf43..0000000 --- a/webkit/glue/plugins/test/plugin_arguments_test.cc +++ /dev/null @@ -1,69 +0,0 @@ -// 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 "base/basictypes.h" -#include "base/string_util.h" -#include "base/stringprintf.h" - -#include "webkit/glue/plugins/test/plugin_arguments_test.h" - -namespace NPAPIClient { - -PluginArgumentsTest::PluginArgumentsTest(NPP id, - NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPError PluginArgumentsTest::New(uint16 mode, int16 argc, - const char* argn[], const char* argv[], - NPSavedData* saved) { - // mode: should be the string either "NP_EMBED" or "NP_FULL", - // depending on the mode passed in. - // count: the count of "val" arguments. If the value is - // 2, then we'll find arguments "val1" and "val2". If - // the value is 0, then there will be no "val" arguments. - // size: each val string will be this size * the value's - // index. E.g if size is "10", val1 will be 10bytes, - // and val2 will be 20bytes. - const char *mode_string = GetArgValue("mode", argc, argn, argv); - ExpectAsciiStringNotEqual(mode_string, (const char *)NULL); - if (mode_string != NULL) { - std::string mode_dep_string = mode_string; - if (mode == NP_EMBED) - ExpectStringLowerCaseEqual(mode_dep_string, "np_embed"); - else if (mode == NP_FULL) - ExpectStringLowerCaseEqual(mode_dep_string, "np_full"); - } - - const char *count_string = GetArgValue("count", argc, argn, argv); - if (count_string != NULL) { - int max_args = atoi(count_string); - - const char *size_string = GetArgValue("size", argc, argn, argv); - ExpectAsciiStringNotEqual(size_string, (const char *)NULL); - if (size_string != NULL) { - int size = atoi(size_string); - - for (int index = 1; index <= max_args; index++) { - std::string arg_name = base::StringPrintf("%s%d", "val", index); - const char *val_string = GetArgValue(arg_name.c_str(), argc, argn, - argv); - ExpectAsciiStringNotEqual(val_string, (const char*)NULL); - if (val_string != NULL) - ExpectIntegerEqual((int)strlen(val_string), (index*size)); - } - } - } - - return PluginTest::New(mode, argc, argn, argv, saved); -} - -NPError PluginArgumentsTest::SetWindow(NPWindow* pNPWindow) { - // This test just tests the arguments. We're done now. - this->SignalTestCompleted(); - - return NPERR_NO_ERROR; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_arguments_test.h b/webkit/glue/plugins/test/plugin_arguments_test.h deleted file mode 100644 index aa05f19..0000000 --- a/webkit/glue/plugins/test/plugin_arguments_test.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_PORT_PLUGINS_TEST_PLUGIN_ARGUMENTS_TEST_H__ -#define WEBKIT_PORT_PLUGINS_TEST_PLUGIN_ARGUMENTS_TEST_H__ - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// The PluginArgumentsTest test that we properly receive arguments -// intended for the plugin. -// -// This is basically overkill for testing that the arguments passed -// to the plugin match what we expect. -// -// We expect to find the following arguments: -// mode: should be the string either "NP_EMBED" or "NP_FULL", -// depending on the mode passed in. -// count: the count of "val" arguments. If the value is -// 2, then we'll find arguments "val1" and "val2". If -// the value is 0, then there will be no "val" arguments. -// size: each val string will be this size * the value's -// index. E.g if size is "10", val1 will be 10bytes, -// and val2 will be 20bytes. -// -class PluginArgumentsTest : public PluginTest { - public: - // Constructor. - PluginArgumentsTest(NPP id, NPNetscapeFuncs *host_functions); - - // Initialize this PluginTest based on the arguments from NPP_New. - virtual NPError New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved); - - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* pNPWindow); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_PORT_PLUGINS_TEST_PLUGIN_ARGUMENTS_TEST_H__ diff --git a/webkit/glue/plugins/test/plugin_client.cc b/webkit/glue/plugins/test/plugin_client.cc deleted file mode 100644 index 8358340..0000000 --- a/webkit/glue/plugins/test/plugin_client.cc +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_client.h" - -#include "base/string_util.h" -#include "webkit/glue/plugins/test/plugin_test.h" -#include "webkit/glue/plugins/test/plugin_test_factory.h" - -namespace NPAPIClient { - -NPNetscapeFuncs* PluginClient::host_functions_; - -NPError PluginClient::GetEntryPoints(NPPluginFuncs* pFuncs) { - if (pFuncs == NULL) - return NPERR_INVALID_FUNCTABLE_ERROR; - - if (pFuncs->size < sizeof(NPPluginFuncs)) - return NPERR_INVALID_FUNCTABLE_ERROR; - - pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; - pFuncs->newp = NPP_New; - pFuncs->destroy = NPP_Destroy; - pFuncs->setwindow = NPP_SetWindow; - pFuncs->newstream = NPP_NewStream; - pFuncs->destroystream = NPP_DestroyStream; - pFuncs->asfile = NPP_StreamAsFile; - pFuncs->writeready = NPP_WriteReady; - pFuncs->write = NPP_Write; - pFuncs->print = NPP_Print; - pFuncs->event = NPP_HandleEvent; - pFuncs->urlnotify = NPP_URLNotify; - pFuncs->getvalue = NPP_GetValue; - pFuncs->setvalue = NPP_SetValue; - pFuncs->javaClass = NULL; - pFuncs->urlredirectnotify = NPP_URLRedirectNotify; - - return NPERR_NO_ERROR; -} - -NPError PluginClient::Initialize(NPNetscapeFuncs* pFuncs) { - if (pFuncs == NULL) { - return NPERR_INVALID_FUNCTABLE_ERROR; - } - - if (static_cast<unsigned char>((pFuncs->version >> 8) & 0xff) > - NP_VERSION_MAJOR) { - return NPERR_INCOMPATIBLE_VERSION_ERROR; - } - -#if defined(OS_WIN) - // Check if we should crash. - HANDLE crash_event = CreateEvent(NULL, TRUE, FALSE, L"TestPluginCrashOnInit"); - if (WaitForSingleObject(crash_event, 0) == WAIT_OBJECT_0) { - int *zero = NULL; - *zero = 0; - } - CloseHandle(crash_event); -#endif - - host_functions_ = pFuncs; - - return NPERR_NO_ERROR; -} - -NPError PluginClient::Shutdown() { - return NPERR_NO_ERROR; -} - -} // namespace NPAPIClient - -extern "C" { -NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, - int16 argc, char* argn[], char* argv[], NPSavedData* saved) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - // We look at the test name requested via the plugin arguments. We match - // that against a given test and try to instantiate it. - - // lookup the name parameter - std::string test_name; - for (int name_index = 0; name_index < argc; name_index++) { - if (base::strcasecmp(argn[name_index], "name") == 0) { - test_name = argv[name_index]; - break; - } - } - if (test_name.empty()) - return NPERR_GENERIC_ERROR; // no name found - - NPAPIClient::PluginTest* new_test = NPAPIClient::CreatePluginTest(test_name, - instance, NPAPIClient::PluginClient::HostFunctions()); - if (new_test == NULL) { - // If we don't have a test case for this, create a - // generic one which basically never fails. - LOG(WARNING) << "Unknown test name '" << test_name - << "'; using default test."; - new_test = new NPAPIClient::PluginTest(instance, - NPAPIClient::PluginClient::HostFunctions()); - } - - NPError ret = new_test->New(mode, argc, (const char**)argn, - (const char**)argv, saved); - if ((ret == NPERR_NO_ERROR) && new_test->IsWindowless()) { - NPAPIClient::PluginClient::HostFunctions()->setvalue( - instance, NPPVpluginWindowBool, NULL); - } - - return ret; -} - -NPError NPP_Destroy(NPP instance, NPSavedData** save) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - NPError rv = plugin->Destroy(); - delete plugin; - return rv; -} - -NPError NPP_SetWindow(NPP instance, NPWindow* pNPWindow) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->SetWindow(pNPWindow); -} - -NPError NPP_NewStream(NPP instance, NPMIMEType type, - NPStream* stream, NPBool seekable, uint16* stype) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->NewStream(type, stream, seekable, stype); -} - -int32 NPP_WriteReady(NPP instance, NPStream *stream) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->WriteReady(stream); -} - -int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, - int32 len, void *buffer) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->Write(stream, offset, len, buffer); -} - -NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPError reason) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->DestroyStream(stream, reason); -} - -void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) { - if (instance == NULL) - return; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->StreamAsFile(stream, fname); -} - -void NPP_Print(NPP instance, NPPrint* printInfo) { - if (instance == NULL) - return; - - // XXXMB - do work here. -} - -void NPP_URLNotify(NPP instance, const char* url, NPReason reason, - void* notifyData) { - if (instance == NULL) - return; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->URLNotify(url, reason, notifyData); -} - -NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - // XXXMB - do work here. - return NPERR_GENERIC_ERROR; -} - -NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { - if (instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - // XXXMB - do work here. - return NPERR_GENERIC_ERROR; -} - -int16 NPP_HandleEvent(NPP instance, void* event) { - if (instance == NULL) - return 0; - - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - - return plugin->HandleEvent(event); -} - -void NPP_URLRedirectNotify(NPP instance, const char* url, int32_t status, - void* notify_data) { - if (instance) { - NPAPIClient::PluginTest* plugin = - reinterpret_cast<NPAPIClient::PluginTest*>(instance->pdata); - plugin->URLRedirectNotify(url, status, notify_data); - } -} -} // extern "C" diff --git a/webkit/glue/plugins/test/plugin_client.h b/webkit/glue/plugins/test/plugin_client.h deleted file mode 100644 index a6291b0..0000000 --- a/webkit/glue/plugins/test/plugin_client.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_PORT_PLUGINS_TEST_PLUGIN_CLIENT_H__ -#define WEBKIT_PORT_PLUGINS_TEST_PLUGIN_CLIENT_H__ - -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/nphostapi.h" - -namespace NPAPIClient { - -// A PluginClient is a NPAPI Plugin. This class contains -// the bootstrapping functions used by the browser to load -// the plugin. -class PluginClient { - public: - // Although not documented in the NPAPI specification, this function - // gets the list of entry points in the NPAPI Plugin (client) for the - // NPAPI Host to call. - static NPError GetEntryPoints(NPPluginFuncs* pFuncs); - - // The browser calls this function only once: when a plug-in is loaded, - // before the first instance is created. This is the first function that - // the browser calls. NP_Initialize tells the plug-in that the browser has - // loaded it and provides global initialization. Allocate any memory or - // resources shared by all instances of your plug-in at this time. - static NPError Initialize(NPNetscapeFuncs* pFuncs); - - // The browser calls this function once after the last instance of your - // plug-in is destroyed, before unloading the plug-in library itself. Use - // NP_Shutdown to delete any data allocated in NP_Initialize to be shared - // by all instances of a plug-in. - static NPError Shutdown(); - - // The table of functions provided by the host. - static NPNetscapeFuncs *HostFunctions() { return host_functions_; } - - private: - static NPNetscapeFuncs* host_functions_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_PORT_PLUGINS_TEST_PLUGIN_CLIENT_H__ diff --git a/webkit/glue/plugins/test/plugin_create_instance_in_paint.cc b/webkit/glue/plugins/test/plugin_create_instance_in_paint.cc deleted file mode 100644 index f98f89b..0000000 --- a/webkit/glue/plugins/test/plugin_create_instance_in_paint.cc +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_create_instance_in_paint.h" - -#include "webkit/glue/plugins/test/plugin_client.h" - -namespace NPAPIClient { - -CreateInstanceInPaintTest::CreateInstanceInPaintTest( - NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - window_(NULL), created_(false) { -} - -NPError CreateInstanceInPaintTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - if (test_id() == "1") { - if (!window_) { - static ATOM window_class = 0; - if (!window_class) { - WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_DBLCLKS; - wcex.lpfnWndProc = - &NPAPIClient::CreateInstanceInPaintTest::WindowProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = GetModuleHandle(NULL); - wcex.hIcon = 0; - wcex.hCursor = 0; - wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW+1); - wcex.lpszMenuName = 0; - wcex.lpszClassName = L"CreateInstanceInPaintTestWindowClass"; - wcex.hIconSm = 0; - window_class = RegisterClassEx(&wcex); - } - - HWND parent = reinterpret_cast<HWND>(pNPWindow->window); - window_ = CreateWindowEx( - WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR, - MAKEINTATOM(window_class), 0, - WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE , - 0, 0, 100, 100, parent, 0, GetModuleHandle(NULL), 0); - DCHECK(window_); - // TODO: this property leaks. - ::SetProp(window_, L"Plugin_Instance", this); - } - } else if (test_id() == "2") { - SignalTestCompleted(); - } else { - NOTREACHED(); - } - return NPERR_NO_ERROR; -} - -LRESULT CALLBACK CreateInstanceInPaintTest::WindowProc( - HWND window, UINT message, WPARAM wparam, LPARAM lparam) { - if (message == WM_PAINT) { - CreateInstanceInPaintTest* this_instance = - reinterpret_cast<CreateInstanceInPaintTest*> - (::GetProp(window, L"Plugin_Instance")); - if (this_instance->test_id() == "1" && !this_instance->created_) { - ::RemoveProp(window, L"Plugin_Instance"); - this_instance->created_ = true; - this_instance->HostFunctions()->geturlnotify( - this_instance->id(), "javascript:CreateNewInstance()", NULL, - reinterpret_cast<void*>(1)); - } - } - - return DefWindowProc(window, message, wparam, lparam); -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_create_instance_in_paint.h b/webkit/glue/plugins/test/plugin_create_instance_in_paint.h deleted file mode 100644 index 84d7a94..0000000 --- a/webkit/glue/plugins/test/plugin_create_instance_in_paint.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_CREATE_INSTANCE_IN_PAINT_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_CREATE_INSTANCE_IN_PAINT_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class tests that creating a new plugin via script while handling a -// Windows message doesn't cause a deadlock. -class CreateInstanceInPaintTest : public PluginTest { - public: - // Constructor. - CreateInstanceInPaintTest(NPP id, NPNetscapeFuncs *host_functions); - // - // NPAPI functions - // - virtual NPError SetWindow(NPWindow* pNPWindow); - - private: - static LRESULT CALLBACK WindowProc( - HWND window, UINT message, WPARAM wparam, LPARAM lparam); - - HWND window_; - bool created_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_CREATE_INSTANCE_IN_PAINT_H diff --git a/webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.cc b/webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.cc deleted file mode 100644 index 15318b4..0000000 --- a/webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.cc +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h" - -#include "webkit/glue/plugins/test/plugin_client.h" - -namespace NPAPIClient { - -#define kUrl "javascript:window.location+\"\"" -#define kUrlStreamId 1 - -DeletePluginInStreamTest::DeletePluginInStreamTest(NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - test_started_(false) { -} - -NPError DeletePluginInStreamTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - if (!test_started_) { - std::string url = "self_delete_plugin_stream.html"; - HostFunctions()->geturlnotify(id(), url.c_str(), NULL, - reinterpret_cast<void*>(kUrlStreamId)); - test_started_ = true; - } - return NPERR_NO_ERROR; -} - -NPError DeletePluginInStreamTest::NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype) { - NPIdentifier delete_id = HostFunctions()->getstringidentifier("DeletePluginWithinScript"); - - NPObject *window_obj = NULL; - HostFunctions()->getvalue(id(), NPNVWindowNPObject, &window_obj); - - NPVariant rv; - HostFunctions()->invoke(id(), window_obj, delete_id, NULL, 0, &rv); - - return NPERR_NO_ERROR; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h b/webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h deleted file mode 100644 index 418e976..0000000 --- a/webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_DELETE_PLUGIN_IN_STREAM_TEST_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_DELETE_PLUGIN_IN_STREAM_TEST_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class tests -class DeletePluginInStreamTest : public PluginTest { - public: - // Constructor. - DeletePluginInStreamTest(NPP id, NPNetscapeFuncs *host_functions); - // - // NPAPI functions - // - virtual NPError SetWindow(NPWindow* pNPWindow); - virtual NPError NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype); - private: - bool test_started_; - std::string self_url_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_DELETE_PLUGIN_IN_STREAM_TEST_H diff --git a/webkit/glue/plugins/test/plugin_get_javascript_url2_test.cc b/webkit/glue/plugins/test/plugin_get_javascript_url2_test.cc deleted file mode 100644 index d17dced..0000000 --- a/webkit/glue/plugins/test/plugin_get_javascript_url2_test.cc +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_get_javascript_url2_test.h" - -#include "base/basictypes.h" - -// url for "self". -#define SELF_URL "javascript:window.location+\"\"" -// The identifier for the self url stream. -#define SELF_URL_STREAM_ID 1 - -// The identifier for the fetched url stream. -#define FETCHED_URL_STREAM_ID 2 - -// The maximum chunk size of stream data. -#define STREAM_CHUNK 197 - -const int kNPNEvaluateTimerID = 100; -const int kNPNEvaluateTimerElapse = 50; - -namespace NPAPIClient { - -ExecuteGetJavascriptUrl2Test::ExecuteGetJavascriptUrl2Test( - NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - test_started_(false) { -} - -NPError ExecuteGetJavascriptUrl2Test::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - if (!test_started_) { - std::string url = SELF_URL; - HostFunctions()->geturlnotify(id(), url.c_str(), "_self", - reinterpret_cast<void*>(SELF_URL_STREAM_ID)); - test_started_ = true; - } - return NPERR_NO_ERROR; -} - -NPError ExecuteGetJavascriptUrl2Test::NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype) { - if (stream == NULL) { - SetError("NewStream got null stream"); - return NPERR_INVALID_PARAM; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - break; - default: - SetError("Unexpected NewStream callback"); - break; - } - return NPERR_NO_ERROR; -} - -int32 ExecuteGetJavascriptUrl2Test::WriteReady(NPStream *stream) { - return STREAM_CHUNK; -} - -int32 ExecuteGetJavascriptUrl2Test::Write(NPStream *stream, int32 offset, int32 len, - void *buffer) { - if (stream == NULL) { - SetError("Write got null stream"); - return -1; - } - if (len < 0 || len > STREAM_CHUNK) { - SetError("Write got bogus stream chunk size"); - return -1; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - self_url_.append(static_cast<char*>(buffer), len); - break; - default: - SetError("Unexpected write callback"); - break; - } - // Pretend that we took all the data. - return len; -} - - -NPError ExecuteGetJavascriptUrl2Test::DestroyStream(NPStream *stream, NPError reason) { - if (stream == NULL) { - SetError("NewStream got null stream"); - return NPERR_INVALID_PARAM; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - // don't care - break; - default: - SetError("Unexpected NewStream callback"); - break; - } - return NPERR_NO_ERROR; -} - -void ExecuteGetJavascriptUrl2Test::URLNotify(const char* url, NPReason reason, void* data) { - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data), - cast_validity_check); - - unsigned long stream_id = reinterpret_cast<unsigned long>(data); - switch (stream_id) { - case SELF_URL_STREAM_ID: - if (strcmp(url, SELF_URL) != 0) - SetError("URLNotify reported incorrect url for SELF_URL"); - if (self_url_.empty()) - SetError("Failed to obtain window location."); - SignalTestCompleted(); - break; - default: - SetError("Unexpected NewStream callback"); - break; - } -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_get_javascript_url2_test.h b/webkit/glue/plugins/test/plugin_get_javascript_url2_test.h deleted file mode 100644 index 557da76..0000000 --- a/webkit/glue/plugins/test/plugin_get_javascript_url2_test.h +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_GET_JAVASCRIPT_URL2_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_GET_JAVASCRIPT_URL2_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class tests NPP_GetURLNotify for a javascript URL with _top -// as the target frame. -class ExecuteGetJavascriptUrl2Test : public PluginTest { - public: - // Constructor. - ExecuteGetJavascriptUrl2Test(NPP id, NPNetscapeFuncs *host_functions); - - // - // NPAPI functions - // - virtual NPError SetWindow(NPWindow* pNPWindow); - virtual NPError NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype); - virtual int32 WriteReady(NPStream *stream); - virtual int32 Write(NPStream *stream, int32 offset, int32 len, - void *buffer); - virtual NPError DestroyStream(NPStream *stream, NPError reason); - virtual void URLNotify(const char* url, NPReason reason, void* data); - - private: - bool test_started_; - std::string self_url_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_GET_JAVASCRIPT_URL2_H diff --git a/webkit/glue/plugins/test/plugin_get_javascript_url_test.cc b/webkit/glue/plugins/test/plugin_get_javascript_url_test.cc deleted file mode 100644 index 50f5e5a..0000000 --- a/webkit/glue/plugins/test/plugin_get_javascript_url_test.cc +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_get_javascript_url_test.h" - -#include "base/basictypes.h" - -// url for "self". -#define SELF_URL "javascript:window.location+\"\"" -// The identifier for the self url stream. -#define SELF_URL_STREAM_ID 1 - -// The identifier for the fetched url stream. -#define FETCHED_URL_STREAM_ID 2 - -// The maximum chunk size of stream data. -#define STREAM_CHUNK 197 - -const int kNPNEvaluateTimerID = 100; -const int kNPNEvaluateTimerElapse = 50; - - -namespace NPAPIClient { - -ExecuteGetJavascriptUrlTest::ExecuteGetJavascriptUrlTest( - NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - test_started_(false), -#ifdef OS_WIN - window_(NULL), -#endif - npn_evaluate_context_(false) { -} - -NPError ExecuteGetJavascriptUrlTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - if (!test_started_) { - std::string url = SELF_URL; - HostFunctions()->geturlnotify(id(), url.c_str(), "_top", - reinterpret_cast<void*>(SELF_URL_STREAM_ID)); - test_started_ = true; - -#ifdef OS_WIN - HWND window_handle = reinterpret_cast<HWND>(pNPWindow->window); - if (!::GetProp(window_handle, L"Plugin_Instance")) { - // TODO: this propery leaks. - ::SetProp(window_handle, L"Plugin_Instance", this); - // We attempt to retreive the NPObject for the plugin instance identified - // by the NPObjectLifetimeTestInstance2 class as it may not have been - // instantiated yet. - SetTimer(window_handle, kNPNEvaluateTimerID, kNPNEvaluateTimerElapse, - TimerProc); - } - window_ = window_handle; -#endif - } - - return NPERR_NO_ERROR; -} - -#ifdef OS_WIN -void CALLBACK ExecuteGetJavascriptUrlTest::TimerProc( - HWND window, UINT message, UINT timer_id, unsigned long elapsed_time) { - ExecuteGetJavascriptUrlTest* this_instance = - reinterpret_cast<ExecuteGetJavascriptUrlTest*> - (::GetProp(window, L"Plugin_Instance")); - - ::RemoveProp(window, L"Plugin_Instance"); - - NPObject *window_obj = NULL; - this_instance->HostFunctions()->getvalue(this_instance->id(), - NPNVWindowNPObject, - &window_obj); - if (!window_obj) { - this_instance->SetError("Failed to get NPObject for plugin instance2"); - this_instance->SignalTestCompleted(); - return; - } - - std::string script = "javascript:window.location"; - NPString script_string; - script_string.UTF8Characters = script.c_str(); - script_string.UTF8Length = static_cast<unsigned int>(script.length()); - NPVariant result_var; - - this_instance->npn_evaluate_context_ = true; - NPError result = this_instance->HostFunctions()->evaluate( - this_instance->id(), window_obj, &script_string, &result_var); - this_instance->npn_evaluate_context_ = false; -} -#endif - -NPError ExecuteGetJavascriptUrlTest::NewStream(NPMIMEType type, - NPStream* stream, - NPBool seekable, - uint16* stype) { - if (stream == NULL) { - SetError("NewStream got null stream"); - return NPERR_INVALID_PARAM; - } - - if (npn_evaluate_context_) { - SetError("NewStream received in context of NPN_Evaluate"); - return NPERR_NO_ERROR; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - break; - default: - SetError("Unexpected NewStream callback"); - break; - } - return NPERR_NO_ERROR; -} - -int32 ExecuteGetJavascriptUrlTest::WriteReady(NPStream *stream) { - if (npn_evaluate_context_) { - SetError("WriteReady received in context of NPN_Evaluate"); - return NPERR_NO_ERROR; - } - return STREAM_CHUNK; -} - -int32 ExecuteGetJavascriptUrlTest::Write(NPStream *stream, int32 offset, - int32 len, void *buffer) { - if (stream == NULL) { - SetError("Write got null stream"); - return -1; - } - if (len < 0 || len > STREAM_CHUNK) { - SetError("Write got bogus stream chunk size"); - return -1; - } - - if (npn_evaluate_context_) { - SetError("Write received in context of NPN_Evaluate"); - return len; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - self_url_.append(static_cast<char*>(buffer), len); - break; - default: - SetError("Unexpected write callback"); - break; - } - // Pretend that we took all the data. - return len; -} - - -NPError ExecuteGetJavascriptUrlTest::DestroyStream(NPStream *stream, - NPError reason) { - if (stream == NULL) { - SetError("NewStream got null stream"); - return NPERR_INVALID_PARAM; - } - -#ifdef OS_WIN - KillTimer(window_, kNPNEvaluateTimerID); -#endif - - if (npn_evaluate_context_) { - SetError("DestroyStream received in context of NPN_Evaluate"); - return NPERR_NO_ERROR; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - // don't care - break; - default: - SetError("Unexpected NewStream callback"); - break; - } - return NPERR_NO_ERROR; -} - -void ExecuteGetJavascriptUrlTest::URLNotify(const char* url, NPReason reason, - void* data) { - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data), - cast_validity_check); - - if (npn_evaluate_context_) { - SetError("URLNotify received in context of NPN_Evaluate"); - return; - } - - unsigned long stream_id = reinterpret_cast<unsigned long>(data); - switch (stream_id) { - case SELF_URL_STREAM_ID: - if (strcmp(url, SELF_URL) != 0) - SetError("URLNotify reported incorrect url for SELF_URL"); - if (self_url_.empty()) - SetError("Failed to obtain window location."); - SignalTestCompleted(); - break; - default: - SetError("Unexpected NewStream callback"); - break; - } -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_get_javascript_url_test.h b/webkit/glue/plugins/test/plugin_get_javascript_url_test.h deleted file mode 100644 index 5c2540d..0000000 --- a/webkit/glue/plugins/test/plugin_get_javascript_url_test.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_GET_JAVASCRIPT_URL_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_GET_JAVASCRIPT_URL_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class tests NPP_GetURLNotify for a javascript URL with _top -// as the target frame. -class ExecuteGetJavascriptUrlTest : public PluginTest { - public: - // Constructor. - ExecuteGetJavascriptUrlTest(NPP id, NPNetscapeFuncs *host_functions); - // - // NPAPI functions - // - virtual NPError SetWindow(NPWindow* pNPWindow); - virtual NPError NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype); - virtual int32 WriteReady(NPStream *stream); - virtual int32 Write(NPStream *stream, int32 offset, int32 len, - void *buffer); - virtual NPError DestroyStream(NPStream *stream, NPError reason); - virtual void URLNotify(const char* url, NPReason reason, void* data); - - private: -#if defined(OS_WIN) - static void CALLBACK TimerProc(HWND window, UINT message, UINT timer_id, - unsigned long elapsed_time); -#endif - bool test_started_; - // This flag is set to true in the context of the NPN_Evaluate call. - bool npn_evaluate_context_; - std::string self_url_; - -#if defined(OS_WIN) - HWND window_; -#endif -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_GET_JAVASCRIPT_URL_H diff --git a/webkit/glue/plugins/test/plugin_geturl_test.cc b/webkit/glue/plugins/test/plugin_geturl_test.cc deleted file mode 100644 index 5363a66..0000000 --- a/webkit/glue/plugins/test/plugin_geturl_test.cc +++ /dev/null @@ -1,414 +0,0 @@ -// 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 "webkit/glue/plugins/test/plugin_geturl_test.h" - -#include <stdio.h> - -#include "base/basictypes.h" -#include "base/file_util.h" -#include "base/string_number_conversions.h" -#include "base/utf_string_conversions.h" - -// url for "self". The %22%22 is to make a statement for javascript to -// evaluate and return. -#define SELF_URL "javascript:window.location+\"\"" - -// The identifier for the self url stream. -#define SELF_URL_STREAM_ID 1 - -// The identifier for the fetched url stream. -#define FETCHED_URL_STREAM_ID 2 - -// url for testing GetURL with a bogus URL. -#define BOGUS_URL "bogoproto:///x:/asdf.xysdhffieasdf.asdhj/" - -// url for testing redirect notifications sent to plugins. -#define REDIRECT_SRC_URL \ - "http://mock.http/npapi/plugin_read_page_redirect_src.html" - -// The notification id for the redirect notification url. -#define REDIRECT_SRC_URL_NOTIFICATION_ID 4 - -// The identifier for the bogus url stream. -#define BOGUS_URL_STREAM_ID 3 - -// The maximum chunk size of stream data. -#define STREAM_CHUNK 197 - -namespace NPAPIClient { - -PluginGetURLTest::PluginGetURLTest(NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - tests_started_(false), - tests_in_progress_(0), - test_file_(NULL), - expect_404_response_(false), - npn_evaluate_context_(false), - handle_url_redirects_(false), - received_url_redirect_notification_(false) { -} - -NPError PluginGetURLTest::New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved) { - const char* page_not_found_url = GetArgValue("page_not_found_url", argc, - argn, argv); - if (page_not_found_url) { - page_not_found_url_ = page_not_found_url; - expect_404_response_ = true; - } - - const char* fail_write_url = GetArgValue("fail_write_url", argc, - argn, argv); - if (fail_write_url) { - fail_write_url_ = fail_write_url; - } - - const char* referrer_target_url = GetArgValue("ref_target", argc, - argn, argv); - if (referrer_target_url) { - referrer_target_url_ = referrer_target_url; - } - - if (!base::strcasecmp(GetArgValue("name", argc, argn, argv), - "geturlredirectnotify")) { - handle_url_redirects_ = true; - } - return PluginTest::New(mode, argc, argn, argv, saved); -} - -NPError PluginGetURLTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - if (!tests_started_) { - tests_started_ = true; - - tests_in_progress_++; - - if (expect_404_response_) { - HostFunctions()->geturl(id(), page_not_found_url_.c_str(), NULL); - return NPERR_NO_ERROR; - } else if (!fail_write_url_.empty()) { - HostFunctions()->geturl(id(), fail_write_url_.c_str(), NULL); - return NPERR_NO_ERROR; - } else if (!referrer_target_url_.empty()) { - HostFunctions()->pushpopupsenabledstate(id(), true); - HostFunctions()->geturl(id(), referrer_target_url_.c_str(), "_blank"); - HostFunctions()->poppopupsenabledstate(id()); - return NPERR_NO_ERROR; - } else if (handle_url_redirects_) { - HostFunctions()->geturlnotify( - id(), REDIRECT_SRC_URL, NULL, - reinterpret_cast<void*>(REDIRECT_SRC_URL_NOTIFICATION_ID)); - return NPERR_NO_ERROR; - } - - std::string url = SELF_URL; - HostFunctions()->geturlnotify(id(), url.c_str(), NULL, - reinterpret_cast<void*>(SELF_URL_STREAM_ID)); - - tests_in_progress_++; - std::string bogus_url = BOGUS_URL; - HostFunctions()->geturlnotify(id(), bogus_url.c_str(), NULL, - reinterpret_cast<void*>(BOGUS_URL_STREAM_ID)); - } - return NPERR_NO_ERROR; -} - -NPError PluginGetURLTest::NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype) { - if (stream == NULL) { - SetError("NewStream got null stream"); - return NPERR_INVALID_PARAM; - } - - if (test_completed()) { - return PluginTest::NewStream(type, stream, seekable, stype); - } - - if (!referrer_target_url_.empty()) { - return NPERR_NO_ERROR; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - - if (expect_404_response_) { - NPObject *window_obj = NULL; - HostFunctions()->getvalue(id(), NPNVWindowNPObject, &window_obj); - if (!window_obj) { - SetError("Failed to get NPObject for plugin instance2"); - SignalTestCompleted(); - return NPERR_NO_ERROR; - } - - std::string script = "javascript:alert('Hi there from plugin');"; - NPString script_string; - script_string.UTF8Characters = script.c_str(); - script_string.UTF8Length = static_cast<unsigned int>(script.length()); - NPVariant result_var; - - npn_evaluate_context_ = true; - HostFunctions()->evaluate(id(), window_obj, &script_string, &result_var); - npn_evaluate_context_ = false; - return NPERR_NO_ERROR; - } - - if (!fail_write_url_.empty()) { - return NPERR_NO_ERROR; - } - - - unsigned long stream_id = reinterpret_cast<unsigned long>( - stream->notifyData); - - switch (stream_id) { - case SELF_URL_STREAM_ID: - break; - case FETCHED_URL_STREAM_ID: - { - std::string filename = self_url_; - if (filename.find("file:///", 0) != 0) { - SetError("Test expects a file-url."); - break; - } - - // TODO(evanm): use the net:: functions to convert file:// URLs to - // on-disk file paths. But it probably doesn't actually matter in - // this test. - -#if defined(OS_WIN) - filename = filename.substr(8); // remove "file:///" - // Assume an ASCII path on Windows. - FilePath path = FilePath(ASCIIToWide(filename)); -#else - filename = filename.substr(7); // remove "file://" - FilePath path = FilePath(filename); -#endif - - test_file_ = file_util::OpenFile(path, "r"); - if (!test_file_) { - SetError("Could not open source file"); - } - } - break; - case BOGUS_URL_STREAM_ID: - SetError("Unexpected NewStream for BOGUS_URL"); - break; - case REDIRECT_SRC_URL_NOTIFICATION_ID: - SetError("Should not redirect to URL when plugin denied it."); - break; - default: - SetError("Unexpected NewStream callback"); - break; - } - return NPERR_NO_ERROR; -} - -int32 PluginGetURLTest::WriteReady(NPStream *stream) { - if (test_completed()) { - return PluginTest::WriteReady(stream); - } - - if (!referrer_target_url_.empty()) { - return STREAM_CHUNK; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>( - stream->notifyData); - if (stream_id == BOGUS_URL_STREAM_ID) - SetError("Received WriteReady for BOGUS_URL"); - - return STREAM_CHUNK; -} - -int32 PluginGetURLTest::Write(NPStream *stream, int32 offset, int32 len, - void *buffer) { - if (test_completed()) { - return PluginTest::Write(stream, offset, len, buffer); - } - - if (!fail_write_url_.empty()) { - SignalTestCompleted(); - return -1; - } - - if (!referrer_target_url_.empty()) { - return len; - } - - if (stream == NULL) { - SetError("Write got null stream"); - return -1; - } - if (len < 0 || len > STREAM_CHUNK) { - SetError("Write got bogus stream chunk size"); - return -1; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>( - stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - self_url_.append(static_cast<char*>(buffer), len); - break; - case FETCHED_URL_STREAM_ID: - { - char read_buffer[STREAM_CHUNK]; - int32 bytes = fread(read_buffer, 1, len, test_file_); - // Technically, fread could return fewer than len - // bytes. But this is not likely. - if (bytes != len) - SetError("Did not read correct bytelength from source file"); - if (memcmp(read_buffer, buffer, len)) - SetError("Content mismatch between data and source!"); - } - break; - case BOGUS_URL_STREAM_ID: - SetError("Unexpected write callback for BOGUS_URL"); - break; - default: - SetError("Unexpected write callback"); - break; - } - // Pretend that we took all the data. - return len; -} - - -NPError PluginGetURLTest::DestroyStream(NPStream *stream, NPError reason) { - if (test_completed()) { - return PluginTest::DestroyStream(stream, reason); - } - - if (stream == NULL) { - SetError("NewStream got null stream"); - return NPERR_INVALID_PARAM; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - - if (expect_404_response_) { - if (npn_evaluate_context_) { - SetError("Received destroyStream in the context of NPN_Evaluate."); - } - - SignalTestCompleted(); - return NPERR_NO_ERROR; - } - - if (!referrer_target_url_.empty()) { - return NPERR_NO_ERROR; - } - - unsigned long stream_id = - reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - // don't care - break; - case FETCHED_URL_STREAM_ID: - { - char read_buffer[STREAM_CHUNK]; - size_t bytes = fread(read_buffer, 1, sizeof(read_buffer), test_file_); - if (bytes != 0) - SetError("Data and source mismatch on length"); - file_util::CloseFile(test_file_); - } - break; - default: - SetError("Unexpected NewStream callback"); - break; - } - return NPERR_NO_ERROR; -} - -void PluginGetURLTest::StreamAsFile(NPStream* stream, const char* fname) { - if (stream == NULL) { - SetError("NewStream got null stream"); - return; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), - cast_validity_check); - unsigned long stream_id = - reinterpret_cast<unsigned long>(stream->notifyData); - switch (stream_id) { - case SELF_URL_STREAM_ID: - // don't care - break; - default: - SetError("Unexpected NewStream callback"); - break; - } -} - -void PluginGetURLTest::URLNotify(const char* url, NPReason reason, void* data) { - if (!tests_in_progress_) { - SetError("URLNotify received after tests completed"); - return; - } - - if (!url) { - SetError("URLNotify received NULL url"); - return; - } - - COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data), cast_validity_check); - unsigned long stream_id = reinterpret_cast<unsigned long>(data); - switch (stream_id) { - case SELF_URL_STREAM_ID: - if (strcmp(url, SELF_URL) != 0) - SetError("URLNotify reported incorrect url for SELF_URL"); - - // We have our stream url. Go fetch it. - HostFunctions()->geturlnotify(id(), self_url_.c_str(), NULL, - reinterpret_cast<void*>(FETCHED_URL_STREAM_ID)); - break; - case FETCHED_URL_STREAM_ID: - if (!url || strcmp(url, self_url_.c_str()) != 0) - SetError("URLNotify reported incorrect url for FETCHED_URL"); - tests_in_progress_--; - break; - case BOGUS_URL_STREAM_ID: - if (reason != NPRES_NETWORK_ERR) { - std::string err = "BOGUS_URL received unexpected URLNotify status: "; - err.append(base::IntToString(reason)); - SetError(err); - } - tests_in_progress_--; - break; - case REDIRECT_SRC_URL_NOTIFICATION_ID: { - if (!received_url_redirect_notification_) { - SetError("Failed to receive URLRedirect notification"); - } - tests_in_progress_--; - break; - } - default: - SetError("Unexpected NewStream callback"); - break; - } - - if (tests_in_progress_ == 0) - SignalTestCompleted(); -} - -void PluginGetURLTest::URLRedirectNotify(const char* url, - int32_t status, - void* notify_data) { - if (!base::strcasecmp(url, "http://mock.http/npapi/plugin_read_page.html")) { - received_url_redirect_notification_ = true; - // Disallow redirect notification. - HostFunctions()->urlredirectresponse(id(), notify_data, false); - } -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_geturl_test.h b/webkit/glue/plugins/test/plugin_geturl_test.h deleted file mode 100644 index df8d741..0000000 --- a/webkit/glue/plugins/test/plugin_geturl_test.h +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_PORT_PLUGINS_TEST_PLUGIN_GETURL_TEST_H__ -#define WEBKIT_PORT_PLUGINS_TEST_PLUGIN_GETURL_TEST_H__ - -#include <stdio.h> - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// The PluginGetURLTest test functionality of the NPN_GetURL -// and NPN_GetURLNotify methods. -// -// This test first discovers it's URL by sending a GetURL request -// for 'javascript:top.location'. After receiving that, the -// test will request the url itself (again via GetURL). -class PluginGetURLTest : public PluginTest { - public: - // Constructor. - PluginGetURLTest(NPP id, NPNetscapeFuncs *host_functions); - - // - // NPAPI functions - // - virtual NPError New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved); - virtual NPError SetWindow(NPWindow* pNPWindow); - virtual NPError NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype); - virtual int32 WriteReady(NPStream *stream); - virtual int32 Write(NPStream *stream, int32 offset, int32 len, - void *buffer); - virtual NPError DestroyStream(NPStream *stream, NPError reason); - virtual void StreamAsFile(NPStream* stream, const char* fname); - virtual void URLNotify(const char* url, NPReason reason, void* data); - virtual void URLRedirectNotify(const char* url, int32_t status, - void* notify_data); - - private: - bool tests_started_; - int tests_in_progress_; - std::string self_url_; - FILE* test_file_; - bool expect_404_response_; - // This flag is set to true in the context of the NPN_Evaluate call. - bool npn_evaluate_context_; - // The following two flags handle URL redirect notifications received by - // plugins. - bool handle_url_redirects_; - bool received_url_redirect_notification_; - std::string page_not_found_url_; - std::string fail_write_url_; - std::string referrer_target_url_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_PORT_PLUGINS_TEST_PLUGIN_GETURL_TEST_H__ diff --git a/webkit/glue/plugins/test/plugin_javascript_open_popup.cc b/webkit/glue/plugins/test/plugin_javascript_open_popup.cc deleted file mode 100644 index 0f93bf4..0000000 --- a/webkit/glue/plugins/test/plugin_javascript_open_popup.cc +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "build/build_config.h" -#include "webkit/glue/plugins/test/plugin_javascript_open_popup.h" - -#if defined(USE_X11) -#include "third_party/npapi/bindings/npapi_x11.h" -#endif -#include "webkit/glue/plugins/test/plugin_client.h" - -namespace NPAPIClient { - -ExecuteJavascriptOpenPopupWithPluginTest:: - ExecuteJavascriptOpenPopupWithPluginTest(NPP id, - NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - popup_window_test_started_(false) { -} - -int16 ExecuteJavascriptOpenPopupWithPluginTest::SetWindow( - NPWindow* window) { - if (window->window == NULL) - return NPERR_NO_ERROR; - - if (!popup_window_test_started_) { - popup_window_test_started_ = true; - HostFunctions()->geturl( - id(), "popup_window_with_target_plugin.html", "_blank"); - } - return NPERR_NO_ERROR; -} - -// ExecuteJavascriptPopupWindowTargetPluginTest member defines. -ExecuteJavascriptPopupWindowTargetPluginTest:: - ExecuteJavascriptPopupWindowTargetPluginTest( - NPP id, NPNetscapeFuncs* host_functions) - : PluginTest(id, host_functions), - test_completed_(false) { -} - -int16 ExecuteJavascriptPopupWindowTargetPluginTest::SetWindow( - NPWindow* window) { - if (window->window == NULL) - return NPERR_NO_ERROR; - - if (!test_completed_) { - if (CheckWindow(window)) { - SignalTestCompleted(); - test_completed_ = true; - } - } - return PluginTest::SetWindow(window); -} - -#if defined(OS_WIN) -bool ExecuteJavascriptPopupWindowTargetPluginTest::CheckWindow( - NPWindow* window) { - HWND window_handle = reinterpret_cast<HWND>(window->window); - - if (IsWindow(window_handle)) { - HWND parent_window = GetParent(window_handle); - if (!IsWindow(parent_window) || parent_window == GetDesktopWindow()) - SetError("Windowed plugin instantiated with NULL parent"); - return true; - } - - return false; -} - -#elif defined(USE_X11) -// This code blindly follows the same sorts of verifications done on -// the Windows side. Does it make sense on X? Maybe not really, but -// it can't hurt to do extra validations. -bool ExecuteJavascriptPopupWindowTargetPluginTest::CheckWindow( - NPWindow* window) { - Window xwindow = reinterpret_cast<Window>(window->window); - // Grab a pointer to the extra SetWindow data so we can grab the display out. - NPSetWindowCallbackStruct* extra = - static_cast<NPSetWindowCallbackStruct*>(window->ws_info); - - if (xwindow) { - Window root, parent; - Status status = XQueryTree(extra->display, xwindow, &root, &parent, - NULL, NULL); // NULL children info. - DCHECK(status != 0); - if (!parent || parent == root) - SetError("Windowed plugin instantiated with NULL parent"); - return true; - } - - return false; -} -#elif defined(OS_MACOSX) -bool ExecuteJavascriptPopupWindowTargetPluginTest::CheckWindow( - NPWindow* window) { - // TODO(port) scaffolding--replace with a real test once NPWindow is done. - return false; -} -#endif - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_javascript_open_popup.h b/webkit/glue/plugins/test/plugin_javascript_open_popup.h deleted file mode 100644 index 552397a..0000000 --- a/webkit/glue/plugins/test/plugin_javascript_open_popup.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_JAVASCRIPT_OPEN_POPUP_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_JAVASCRIPT_OPEN_POPUP_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class tests the case where a windowed plugin instance is -// instantiated in a popup window. The plugin instance needs to -// have a valid parent window. -class ExecuteJavascriptOpenPopupWithPluginTest : public PluginTest { - public: - // Constructor. - ExecuteJavascriptOpenPopupWithPluginTest( - NPP id, NPNetscapeFuncs *host_functions); - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* window); - - private: - bool popup_window_test_started_; -}; - -// This class represents a windowed plugin instance instantiated within a -// popup window. It verifies that the plugin instance has a valid parent. -class ExecuteJavascriptPopupWindowTargetPluginTest : public PluginTest { - public: - ExecuteJavascriptPopupWindowTargetPluginTest( - NPP id, NPNetscapeFuncs *host_functions); - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* window); - - private: - // Do a platform-specific validation of the passed-in |window|. - // E.g. on Windows, verifies window->window is a reasonable HWND. - // Returns true if the test should be marked complete. - bool CheckWindow(NPWindow* window); - - bool test_completed_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_JAVASCRIPT_OPEN_POPUP_H diff --git a/webkit/glue/plugins/test/plugin_new_fails_test.cc b/webkit/glue/plugins/test/plugin_new_fails_test.cc deleted file mode 100644 index 2feeec6..0000000 --- a/webkit/glue/plugins/test/plugin_new_fails_test.cc +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_new_fails_test.h" - -namespace NPAPIClient { - -NewFailsTest::NewFailsTest(NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPError NewFailsTest::New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved) { - return NPERR_GENERIC_ERROR; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_new_fails_test.h b/webkit/glue/plugins/test/plugin_new_fails_test.h deleted file mode 100644 index 1acf9e5..0000000 --- a/webkit/glue/plugins/test/plugin_new_fails_test.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_PLUGIN_NEW_FAILS_TEST_H__ -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_PLUGIN_NEW_FAILS_TEST_H__ - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -class NewFailsTest : public PluginTest { - public: - NewFailsTest(NPP id, NPNetscapeFuncs *host_functions); - virtual NPError New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_PLUGIN_NPP_NEW_FAILS_TEST_H__ diff --git a/webkit/glue/plugins/test/plugin_npobject_lifetime_test.cc b/webkit/glue/plugins/test/plugin_npobject_lifetime_test.cc deleted file mode 100644 index 4564506..0000000 --- a/webkit/glue/plugins/test/plugin_npobject_lifetime_test.cc +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_npobject_lifetime_test.h" - -namespace NPAPIClient { - -const int kNPObjectLifetimeTimer = 100; -const int kNPObjectLifetimeTimerElapse = 2000; - -NPObject* NPObjectLifetimeTestInstance2::plugin_instance_object_ = NULL; - -NPObjectDeletePluginInNPN_Evaluate* - NPObjectDeletePluginInNPN_Evaluate::g_npn_evaluate_test_instance_ = NULL; - -NPObjectLifetimeTest::NPObjectLifetimeTest(NPP id, - NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - other_plugin_instance_object_(NULL), - timer_id_(0) { -} - -NPError NPObjectLifetimeTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - HWND window_handle = reinterpret_cast<HWND>(pNPWindow->window); - if (!::GetProp(window_handle, L"Plugin_Instance")) { - // TODO: this propery leaks. - ::SetProp(window_handle, L"Plugin_Instance", this); - // We attempt to retreive the NPObject for the plugin instance identified - // by the NPObjectLifetimeTestInstance2 class as it may not have been - // instantiated yet. - timer_id_ = SetTimer(window_handle, kNPObjectLifetimeTimer, - kNPObjectLifetimeTimerElapse, TimerProc); - } - return NPERR_NO_ERROR; -} - -void CALLBACK NPObjectLifetimeTest::TimerProc( - HWND window, UINT message, UINT timer_id, - unsigned long elapsed_milli_seconds) { - - NPObjectLifetimeTest* this_instance = - reinterpret_cast<NPObjectLifetimeTest*> - (::GetProp(window, L"Plugin_Instance")); - KillTimer(window, this_instance->timer_id_); - ::RemoveProp(window, L"Plugin_Instance"); - - this_instance->timer_id_ = 0; - - this_instance->other_plugin_instance_object_ = - NPObjectLifetimeTestInstance2::plugin_instance_object_; - this_instance->HostFunctions()->retainobject( - this_instance->other_plugin_instance_object_); - - NPString script; - script.UTF8Characters = "javascript:DeleteSecondPluginInstance()"; - script.UTF8Length = static_cast<uint32_t>(strlen(script.UTF8Characters)); - - this_instance->HostFunctions()->geturlnotify( - this_instance->id(), "javascript:DeleteSecondPluginInstance()", NULL, - reinterpret_cast<void*>(1)); -} - -void NPObjectLifetimeTest::URLNotify(const char* url, NPReason reason, - void* data) { - // Create a "location" identifier. - NPIdentifier identifier = HostFunctions()->getstringidentifier("location"); - // Declare a local variant value. - NPVariant variantValue; - // Get the location property from the window object (which is another object). - bool b1 = HostFunctions()->getproperty(id(), other_plugin_instance_object_, - identifier, &variantValue ); - HostFunctions()->releaseobject(other_plugin_instance_object_); - other_plugin_instance_object_ = NULL; - // If this test failed, then we'd have crashed by now. - SignalTestCompleted(); -} - -NPObjectLifetimeTestInstance2::NPObjectLifetimeTestInstance2( - NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPObjectLifetimeTestInstance2::~NPObjectLifetimeTestInstance2() { - if (plugin_instance_object_) { - HostFunctions()->releaseobject(plugin_instance_object_); - plugin_instance_object_ = NULL; - } -} - -NPError NPObjectLifetimeTestInstance2::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - if (!plugin_instance_object_) { - if (!HostFunctions()->getvalue(id(), NPNVWindowNPObject, - &plugin_instance_object_)) { - SetError("Failed to get NPObject for plugin instance2"); - SignalTestCompleted(); - return NPERR_GENERIC_ERROR; - } - } - - return NPERR_NO_ERROR; -} - - -NPObjectDeletePluginInNPN_Evaluate::NPObjectDeletePluginInNPN_Evaluate( - NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - plugin_instance_object_(NULL), - timer_id_(0) { - g_npn_evaluate_test_instance_ = this; -} - -NPObjectDeletePluginInNPN_Evaluate::~NPObjectDeletePluginInNPN_Evaluate() { - if (plugin_instance_object_) { - HostFunctions()->releaseobject(plugin_instance_object_); - plugin_instance_object_ = NULL; - } -} - -NPError NPObjectDeletePluginInNPN_Evaluate::SetWindow(NPWindow* np_window) { - if (np_window->window == NULL) - return NPERR_NO_ERROR; - - HWND window_handle = reinterpret_cast<HWND>(np_window->window); - // We setup a timerproc to invoke NPN_Evaluate to destroy this plugin - // instance. This is to ensure that we don't destroy the plugin instance - // while it is being used in webkit as this leads to crashes and is a - // more accurate representation of the renderer crash as described in - // http://b/issue?id=1134683. - if (!timer_id_) { - timer_id_ = SetTimer(window_handle, kNPObjectLifetimeTimer, - kNPObjectLifetimeTimerElapse, TimerProc); - } - return NPERR_NO_ERROR; -} - -void CALLBACK NPObjectDeletePluginInNPN_Evaluate::TimerProc( - HWND window, UINT message, UINT timer_id, - unsigned long elapsed_milli_seconds) { - - KillTimer(window, g_npn_evaluate_test_instance_->timer_id_); - g_npn_evaluate_test_instance_->timer_id_ = 0; - NPObject *window_obj = NULL; - g_npn_evaluate_test_instance_->HostFunctions()->getvalue( - g_npn_evaluate_test_instance_->id(), NPNVWindowNPObject, - &window_obj); - - if (!window_obj) { - g_npn_evaluate_test_instance_->SetError( - "Failed to get NPObject for plugin instance2"); - g_npn_evaluate_test_instance_->SignalTestCompleted(); - return; - } - - std::string script = "javascript:DeletePluginWithinScript()"; - NPString script_string; - script_string.UTF8Characters = script.c_str(); - script_string.UTF8Length = - static_cast<unsigned int>(script.length()); - - NPVariant result_var; - bool result = g_npn_evaluate_test_instance_->HostFunctions()->evaluate( - g_npn_evaluate_test_instance_->id(), window_obj, - &script_string, &result_var); - // If this test failed we would have crashed by now. -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_npobject_lifetime_test.h b/webkit/glue/plugins/test/plugin_npobject_lifetime_test.h deleted file mode 100644 index 60d0314..0000000 --- a/webkit/glue/plugins/test/plugin_npobject_lifetime_test.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_NPOBJECT_LIFETIME_TEST_H__ -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_NPOBJECT_LIFETIME_TEST_H__ - -#include "build/build_config.h" -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// The NPObjectLifeTime class tests the case where a plugin has an NPObject -// which points to a different plugin instance on a different frame in the -// page and whether refcounts on this npobject are valid when the source frame -// is destroyed. -class NPObjectLifetimeTest : public PluginTest { - public: - // Constructor. - NPObjectLifetimeTest(NPP id, NPNetscapeFuncs *host_functions); - - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* pNPWindow); - - virtual void URLNotify(const char* url, NPReason reason, void* data); - - protected: - NPObject* other_plugin_instance_object_; - -#if defined(OS_WIN) - static void CALLBACK TimerProc(HWND window, UINT message, UINT timer_id, - unsigned long elapsed_milli_seconds); - UINT_PTR timer_id_; -#endif - DISALLOW_IMPLICIT_CONSTRUCTORS(NPObjectLifetimeTest); -}; - -// The NPObjectLifetimeTestInstance2 class represents the plugin instance -// which is deleted by the NPObjectLifeTime class via a javascript function. -class NPObjectLifetimeTestInstance2 : public PluginTest { - public: - // Constructor. - NPObjectLifetimeTestInstance2(NPP id, NPNetscapeFuncs *host_functions); - ~NPObjectLifetimeTestInstance2(); - - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* pNPWindow); - protected: - static NPObject* plugin_instance_object_; - friend class NPObjectLifetimeTest; - - DISALLOW_IMPLICIT_CONSTRUCTORS(NPObjectLifetimeTestInstance2); -}; - -// The NPObjectLifeTime class tests the case where a plugin instance is -// destroyed in NPN_Evaluate -class NPObjectDeletePluginInNPN_Evaluate : public PluginTest { - public: - // Constructor. - NPObjectDeletePluginInNPN_Evaluate(NPP id, NPNetscapeFuncs *host_functions); - ~NPObjectDeletePluginInNPN_Evaluate(); - - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* pNPWindow); - - protected: - NPObject* plugin_instance_object_; -#if defined(OS_WIN) - static void CALLBACK TimerProc(HWND window, UINT message, UINT timer_id, - unsigned long elapsed_milli_seconds); - UINT_PTR timer_id_; -#endif - - private: - static NPObjectDeletePluginInNPN_Evaluate* g_npn_evaluate_test_instance_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(NPObjectDeletePluginInNPN_Evaluate); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_NPOBJECT_LIFETIME_TEST_H__ diff --git a/webkit/glue/plugins/test/plugin_npobject_proxy_test.cc b/webkit/glue/plugins/test/plugin_npobject_proxy_test.cc deleted file mode 100644 index 5b3a2ca..0000000 --- a/webkit/glue/plugins/test/plugin_npobject_proxy_test.cc +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/compiler_specific.h" - -#if defined(OS_WIN) -#define STRSAFE_NO_DEPRECATE -#include <strsafe.h> -#endif -#include "webkit/glue/plugins/test/plugin_npobject_proxy_test.h" - -namespace NPAPIClient { - -NPObjectProxyTest::NPObjectProxyTest(NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPError NPObjectProxyTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - NPIdentifier document_id = HostFunctions()->getstringidentifier("document"); - NPIdentifier create_text_node_id = HostFunctions()->getstringidentifier("createTextNode"); - NPIdentifier append_child_id = HostFunctions()->getstringidentifier("appendChild"); - - NPVariant docv; - NPObject *window_obj = NULL; - HostFunctions()->getvalue(id(), NPNVWindowNPObject, &window_obj); - - HostFunctions()->getproperty(id(), window_obj, document_id, &docv); - NPObject *doc = NPVARIANT_TO_OBJECT(docv); - - NPVariant strv; - MSVC_SUPPRESS_WARNING(4267); - STRINGZ_TO_NPVARIANT("div", strv); - - NPVariant textv; - HostFunctions()->invoke(id(), doc, create_text_node_id, &strv, 1, &textv); - - NPVariant v; - HostFunctions()->invoke(id(), doc, append_child_id, &textv, 1, &v); - - // If this test failed, then we'd have crashed by now. - SignalTestCompleted(); - - return NPERR_NO_ERROR; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_npobject_proxy_test.h b/webkit/glue/plugins/test/plugin_npobject_proxy_test.h deleted file mode 100644 index 3d14ddb..0000000 --- a/webkit/glue/plugins/test/plugin_npobject_proxy_test.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_NPOBJECT_PROXY_TEST_H__ -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_NPOBJECT_PROXY_TEST_H__ - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// The NPObjectProxyTest tests that when we proxy an NPObject that is itself -// a proxy, we don't create a new proxy but instead just use the original -// pointer. - -class NPObjectProxyTest : public PluginTest { - public: - // Constructor. - NPObjectProxyTest(NPP id, NPNetscapeFuncs *host_functions); - - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* pNPWindow); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_NPOBJECT_PROXY_TEST_H__ diff --git a/webkit/glue/plugins/test/plugin_private_test.cc b/webkit/glue/plugins/test/plugin_private_test.cc deleted file mode 100644 index cdab7ce..0000000 --- a/webkit/glue/plugins/test/plugin_private_test.cc +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_private_test.h" - -#include "base/basictypes.h" -#include "base/string_util.h" -#include "webkit/glue/plugins/test/plugin_client.h" - -namespace NPAPIClient { - -PrivateTest::PrivateTest(NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPError PrivateTest::New(uint16 mode, int16 argc, - const char* argn[], const char* argv[], - NPSavedData* saved) { - PluginTest::New(mode, argc, argn, argv, saved); - - NPBool private_mode = 0; - NPNetscapeFuncs* browser = NPAPIClient::PluginClient::HostFunctions(); - NPError result = browser->getvalue( - id(), NPNVprivateModeBool, &private_mode); - if (result != NPERR_NO_ERROR) { - SetError("Failed to read NPNVprivateModeBool value."); - } else { - NPIdentifier location = HostFunctions()->getstringidentifier("location"); - NPIdentifier href = HostFunctions()->getstringidentifier("href"); - - NPObject *window_obj = NULL; - HostFunctions()->getvalue(id(), NPNVWindowNPObject, &window_obj); - - NPVariant location_var; - HostFunctions()->getproperty(id(), window_obj, location, &location_var); - - NPVariant href_var; - HostFunctions()->getproperty(id(), NPVARIANT_TO_OBJECT(location_var), href, - &href_var); - std::string href_str(href_var.value.stringValue.UTF8Characters, - href_var.value.stringValue.UTF8Length); - bool private_expected = href_str.find("?private") != href_str.npos; - if (private_mode != static_cast<NPBool>(private_expected)) - SetError("NPNVprivateModeBool returned incorrect value."); - - HostFunctions()->releasevariantvalue(&href_var); - HostFunctions()->releasevariantvalue(&location_var); - HostFunctions()->releaseobject(window_obj); - } - - SignalTestCompleted(); - - return NPERR_NO_ERROR; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_private_test.h b/webkit/glue/plugins/test/plugin_private_test.h deleted file mode 100644 index db6b5d1..0000000 --- a/webkit/glue/plugins/test/plugin_private_test.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_PORT_PLUGINS_TEST_PLUGIN_PRIVATE_TEST_H_ -#define WEBKIT_PORT_PLUGINS_TEST_PLUGIN_PRIVATE_TEST_H_ - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// The PluginPrivateTest tests that a plugin can query if the browser is in -// private browsing mode. -class PrivateTest : public PluginTest { - public: - PrivateTest(NPP id, NPNetscapeFuncs *host_functions); - - // Initialize this PluginTest based on the arguments from NPP_New. - virtual NPError New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_PORT_PLUGINS_TEST_PLUGIN_PRIVATE_TEST_H_ diff --git a/webkit/glue/plugins/test/plugin_schedule_timer_test.cc b/webkit/glue/plugins/test/plugin_schedule_timer_test.cc deleted file mode 100644 index fbfce34..0000000 --- a/webkit/glue/plugins/test/plugin_schedule_timer_test.cc +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_schedule_timer_test.h" -#include "webkit/glue/plugins/test/plugin_client.h" - -using base::Time; - -namespace NPAPIClient { - -// The times below are accurate but they are not tested against because it -// might make the test flakey. -ScheduleTimerTest::Event - ScheduleTimerTest::schedule_[ScheduleTimerTest::kNumEvents] = { - { 0, -1, 0, 100, false, -1 }, // schedule 0 100ms no-repeat - { 100, 0, 0, 200, false, -1 }, // schedule 0 200ms no-repeat - { 300, 0, 0, 100, true, -1 }, // schedule 0 100ms repeat - { 400, 0, 1, 50, true, -1 }, // schedule 1 50ms repeat - { 450, 1, -1, 0, true, -1 }, // receive 1 repeating - { 500, 0, -1, 0, true, -1 }, // receive 0 repeating - { 500, 1, -1, 0, true, -1 }, // receive 1 repeating - { 550, 1, -1, 0, true, -1 }, // receive 1 repeating - { 600, 0, -1, 0, true, 0 }, // receive 0 repeating and unschedule - { 600, 1, 2, 400, true, 1 }, // receive 1 repeating and unschedule - { 1000, 2, -1, 0, true, 2 }, // receive final and unschedule -}; - -ScheduleTimerTest::ScheduleTimerTest( - NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - num_received_events_(0) { - for (int i = 0; i < kNumTimers; ++i) { - timer_ids_[i] = 0; - } - for (int i = 0; i < kNumEvents; ++i) { - received_events_[i] = false; - } -} - -NPError ScheduleTimerTest::New( - uint16 mode, int16 argc, const char* argn[], const char* argv[], - NPSavedData* saved) { - NPError error = PluginTest::New(mode, argc, argn, argv, saved); - if (error != NPERR_NO_ERROR) - return error; - - start_time_ = Time::Now(); - HandleEvent(0); - - return NPERR_NO_ERROR; -} - -void ScheduleTimerTest::OnTimer(uint32 timer_id) { - Time current_time = Time::Now(); - int relative_time = static_cast<int>( - (current_time - start_time_).InMilliseconds()); - - // See if there is a matching unreceived event. - int event_index = FindUnreceivedEvent(relative_time, timer_id); - if (event_index < 0) { - SetError("Received unexpected timer event"); - SignalTestCompleted(); - return; - } - - HandleEvent(event_index); - - // Finish test if all events have happened. - if (num_received_events_ == kNumEvents) - SignalTestCompleted(); -} - -int ScheduleTimerTest::FindUnreceivedEvent(int time, uint32 timer_id) { - for (int i = 0; i < kNumEvents; ++i) { - const Event& event = schedule_[i]; - if (!received_events_[i] && - timer_ids_[event.received_index] == timer_id) { - return i; - } - } - return -1; -} - -namespace { -void OnTimerHelper(NPP id, uint32 timer_id) { - ScheduleTimerTest* plugin_object = - static_cast<ScheduleTimerTest*>(id->pdata); - if (plugin_object) { - plugin_object->OnTimer(timer_id); - } -} -} - -void ScheduleTimerTest::HandleEvent(int event_index) { - const Event& event = schedule_[event_index]; - - // Mark event as received. - DCHECK(!received_events_[event_index]); - received_events_[event_index] = true; - ++num_received_events_; - - // Unschedule timer if present. - if (event.unscheduled_index >= 0) { - HostFunctions()->unscheduletimer( - id(), timer_ids_[event.unscheduled_index]); - } - - // Schedule timer if present. - if (event.scheduled_index >= 0) { - timer_ids_[event.scheduled_index] = HostFunctions()->scheduletimer( - id(), event.scheduled_interval, event.schedule_repeated, OnTimerHelper); - } -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_schedule_timer_test.h b/webkit/glue/plugins/test/plugin_schedule_timer_test.h deleted file mode 100644 index e3e6505..0000000 --- a/webkit/glue/plugins/test/plugin_schedule_timer_test.h +++ /dev/null @@ -1,68 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_SCHEDULE_TIMER_TEST_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_SCHEDULE_TIMER_TEST_H - -#include "base/at_exit.h" -#include "base/time.h" -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class tests scheduling and unscheduling of timers using -// NPN_ScheduleTimer and NPN_UnscheduleTimer. -class ScheduleTimerTest : public PluginTest { - public: - ScheduleTimerTest(NPP id, NPNetscapeFuncs *host_functions); - - virtual NPError New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved); - - void OnTimer(uint32 timer_id); - - private: - // base::Time needs one of these. - base::AtExitManager at_exit_manager_; - - // Table mapping timer index (as used in event schedule) to timer id. - static const int kNumTimers = 3; - uint32 timer_ids_[kNumTimers]; - - // Schedule of events for test. - static const int kNumEvents = 11; - struct Event { - int time; - - // The index of the timer that triggered the event or -1 for the first - // event. - int received_index; - - // The index of the timer to schedule on this event or -1. - int scheduled_index; - - // Info about the timer to be scheduled (if any). - uint32 scheduled_interval; - bool schedule_repeated; - - // The index of the timer to unschedule on this event or -1. - int unscheduled_index; - }; - static Event schedule_[kNumEvents]; - int num_received_events_; - - // Set of events that have been received (by index). - bool received_events_[kNumEvents]; - - // Time of initial event. - base::Time start_time_; - - // Returns index of matching unreceived event or -1 if not found. - int FindUnreceivedEvent(int time, uint32 timer_id); - void HandleEvent(int event_index); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_SCHEDULE_TIMER_TEST_H diff --git a/webkit/glue/plugins/test/plugin_setup_test.cc b/webkit/glue/plugins/test/plugin_setup_test.cc deleted file mode 100644 index e4c4903..0000000 --- a/webkit/glue/plugins/test/plugin_setup_test.cc +++ /dev/null @@ -1,22 +0,0 @@ -// 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 "base/basictypes.h" -#include "base/string_util.h" - -#include "webkit/glue/plugins/test/plugin_setup_test.h" - -namespace NPAPIClient { - -PluginSetupTest::PluginSetupTest(NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPError PluginSetupTest::SetWindow(NPWindow* pNPWindow) { - this->SignalTestCompleted(); - - return NPERR_NO_ERROR; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_setup_test.h b/webkit/glue/plugins/test/plugin_setup_test.h deleted file mode 100644 index b01bc42..0000000 --- a/webkit/glue/plugins/test/plugin_setup_test.h +++ /dev/null @@ -1,24 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_SETUP_TEST_H__ -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_SETUP_TEST_H__ - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// A very simple test that just sets up a new plug-in. -class PluginSetupTest : public PluginTest { - public: - // Constructor. - PluginSetupTest(NPP id, NPNetscapeFuncs *host_functions); - - // NPAPI SetWindow handler. - virtual NPError SetWindow(NPWindow* pNPWindow); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_SETUP_TEST_H__ diff --git a/webkit/glue/plugins/test/plugin_test.cc b/webkit/glue/plugins/test/plugin_test.cc deleted file mode 100644 index 6717e4b..0000000 --- a/webkit/glue/plugins/test/plugin_test.cc +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_test.h" - -#include "base/string_util.h" -#include "webkit/glue/plugins/test/npapi_constants.h" - -namespace NPAPIClient { - -PluginTest::PluginTest(NPP id, NPNetscapeFuncs *host_functions) { - id_ = id; - id_->pdata = this; - host_functions_ = host_functions; - test_completed_ = false; -} - -NPError PluginTest::New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved) { - test_name_ = this->GetArgValue("name", argc, argn, argv); - test_id_ = this->GetArgValue("id", argc, argn, argv); - return NPERR_NO_ERROR; -} - -NPError PluginTest::Destroy() { - return NPERR_NO_ERROR; -} - -NPError PluginTest::SetWindow(NPWindow* pNPWindow) { - return NPERR_NO_ERROR; -} - -// It's a shame I have to implement URLEncode. But, using webkit's -// or using chrome's means a ball of string of dlls and dependencies that -// is very very long. After spending far too much time on it, -// I'll just encode it myself. Too bad Microsoft doesn't implement -// this in a reusable way either. Both webkit and chrome will -// end up using libicu, which is a string of dependencies we don't -// want. - -inline unsigned char toHex(const unsigned char x) { - return x > 9 ? (x + 'A' - 10) : (x + '0'); -} - -std::string URLEncode(const std::string &sIn) { - std::string sOut; - - const size_t length = sIn.length(); - for (size_t idx = 0; idx < length;) { - const char ch = sIn.at(idx); - if (isalnum(ch)) { - sOut.append(1, ch); - } else if (isspace(ch) && ((ch != '\n') && (ch != '\r'))) { - sOut.append(1, '+'); - } else { - sOut.append(1, '%'); - sOut.append(1, toHex(ch>>4)); - sOut.append(1, toHex(ch%16)); - } - idx++; - } - return sOut; -} - -void PluginTest::SignalTestCompleted() { - NPObject *window_obj = NULL; - host_functions_->getvalue(id_, NPNVWindowNPObject, &window_obj); - if (!window_obj) - return; - - test_completed_ = true; - // To signal test completion, we expect a couple of - // javascript functions to be defined in the webpage - // which hosts this plugin: - // onSuccess(test_name, test_id) - // onFailure(test_name, test_id, error_message) - std::string script("javascript:"); - if (Succeeded()) { - script.append("onSuccess(\""); - script.append(test_name_); - script.append("\",\""); - script.append(test_id_); - script.append("\");"); - } else { - script.append("onFailure(\""); - script.append(test_name_); - script.append("\",\""); - script.append(test_id_); - script.append("\",\""); - script.append(test_status_); - script.append("\");"); - } - - NPString script_string; - script_string.UTF8Characters = script.c_str(); - script_string.UTF8Length = static_cast<unsigned int>(script.length()); - - NPVariant result_var; - host_functions_->evaluate(id_, window_obj, &script_string, &result_var); -} - -const char *PluginTest::GetArgValue(const char *name, const int16 argc, - const char *argn[], const char *argv[]) { - for (int idx = 0; idx < argc; idx++) - if (base::strcasecmp(argn[idx], name) == 0) - return argv[idx]; - return NULL; -} - -void PluginTest::SetError(const std::string &msg) { - test_status_.append(msg); -} - -NPError PluginTest::NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype) { - // There is no default action here. - return NPERR_NO_ERROR; -} - -int32 PluginTest::WriteReady(NPStream *stream) { - // Take data in small chunks - return 4096; -} - -int32 PluginTest::Write(NPStream *stream, int32 offset, int32 len, - void *buffer) { - // Pretend that we took all the data. - return len; -} - -NPError PluginTest::DestroyStream(NPStream *stream, NPError reason) { - // There is no default action. - return NPERR_NO_ERROR; -} - -void PluginTest::StreamAsFile(NPStream* stream, const char* fname) { - // There is no default action. -} - -void PluginTest::URLNotify(const char* url, NPReason reason, void* data) { - // There is no default action -} - -int16 PluginTest::HandleEvent(void* event) { - // There is no default action - return 0; -} - -void PluginTest::URLRedirectNotify(const char* url, int32_t status, - void* notify_data) { - // There is no default action -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_test.h b/webkit/glue/plugins/test/plugin_test.h deleted file mode 100644 index f3f8937..0000000 --- a/webkit/glue/plugins/test/plugin_test.h +++ /dev/null @@ -1,134 +0,0 @@ -// 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 WEBKIT_PORT_PLUGINS_TEST_PLUGIN_TEST_H_ -#define WEBKIT_PORT_PLUGINS_TEST_PLUGIN_TEST_H_ - -#include <string> - -#include "base/string_number_conversions.h" -#include "base/string_util.h" -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/nphostapi.h" - -namespace NPAPIClient { - -// A PluginTest represents an instance of the plugin, which in -// our case is a test case. -class PluginTest { - public: - // Constructor. - PluginTest(NPP id, NPNetscapeFuncs *host_functions); - - // Destructor - virtual ~PluginTest() {} - - // Returns true if the test runs in windowless plugin mode. - virtual bool IsWindowless() const { return false; } - - // - // NPAPI Functions - // - virtual NPError New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved); - virtual NPError Destroy(); - virtual NPError SetWindow(NPWindow* pNPWindow); - virtual NPError NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype); - virtual int32 WriteReady(NPStream *stream); - virtual int32 Write(NPStream *stream, int32 offset, int32 len, - void *buffer); - virtual NPError DestroyStream(NPStream *stream, NPError reason); - virtual void StreamAsFile(NPStream* stream, const char* fname); - virtual void URLNotify(const char* url, NPReason reason, void* data); - virtual int16 HandleEvent(void* event); - virtual void URLRedirectNotify(const char* url, int32_t status, - void* notify_data); - // Returns true if the test has not had any errors. - bool Succeeded() { return test_status_.length() == 0; } - - // Sets an error for the test case. Appends the msg to the - // error that will be returned from the test. - void SetError(const std::string &msg); - - // Expect two string values are equal, and if not, logs an - // appropriate error about it. - void ExpectStringLowerCaseEqual(const std::string &val1, const std::string &val2) { - if (!LowerCaseEqualsASCII(val1, val2.c_str())) { - std::string err; - err = "Expected Equal for '"; - err.append(val1); - err.append("' and '"); - err.append(val2); - err.append("'"); - SetError(err); - } - }; - - // Expect two values to not be equal, and if they are - // logs an appropriate error about it. - void ExpectAsciiStringNotEqual(const char *val1, const char *val2) { - if (val1 == val2) { - std::string err; - err = "Expected Not Equal for '"; - err.append(val1); - err.append("' and '"); - err.append(val2); - err.append("'"); - SetError(err); - } - } - // Expect two integer values are equal, and if not, logs an - // appropriate error about it. - void ExpectIntegerEqual(int val1, int val2) { - if (val1 != val2) { - std::string err; - err = "Expected Equal for '"; - err.append(base::IntToString(val1)); - err.append("' and '"); - err.append(base::IntToString(val2)); - err.append("'"); - SetError(err); - } - } - - - protected: - // Signals to the Test that invoked us that the test is - // completed. This is done by forcing the plugin to - // set a cookie in the browser window, which the test program - // is waiting for. Note - because this is done by - // using javascript, the browser must have the frame - // setup before the plugin calls this function. So plugin - // tests MUST NOT call this function prior to having - // received the SetWindow() callback from the browser. - void SignalTestCompleted(); - - // Helper function to lookup names in the input array. - // If the name is found, returns the value, otherwise - // returns NULL. - const char *GetArgValue(const char *name, const int16 argc, - const char *argn[], const char *argv[]); - - // Access to the list of functions provided - // by the NPAPI host. - NPNetscapeFuncs *HostFunctions() { return host_functions_; } - - // The NPP Identifier for this plugin instance. - NPP id() { return id_; } - std::string test_id() const { return test_id_; } - std::string test_name() const { return test_name_; } - bool test_completed() const { return test_completed_; } - private: - NPP id_; - NPNetscapeFuncs * host_functions_; - std::string test_name_; - std::string test_id_; - std::string test_status_; - bool test_completed_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_PORT_PLUGINS_TEST_PLUGIN_TEST_H_ diff --git a/webkit/glue/plugins/test/plugin_test_factory.cc b/webkit/glue/plugins/test/plugin_test_factory.cc deleted file mode 100644 index b4ae4f1..0000000 --- a/webkit/glue/plugins/test/plugin_test_factory.cc +++ /dev/null @@ -1,104 +0,0 @@ -// 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 "webkit/glue/plugins/test/plugin_test_factory.h" - -#include "webkit/glue/plugins/test/plugin_arguments_test.h" -#include "webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h" -#include "webkit/glue/plugins/test/plugin_get_javascript_url_test.h" -#include "webkit/glue/plugins/test/plugin_get_javascript_url2_test.h" -#include "webkit/glue/plugins/test/plugin_geturl_test.h" -#include "webkit/glue/plugins/test/plugin_javascript_open_popup.h" -#include "webkit/glue/plugins/test/plugin_new_fails_test.h" -#include "webkit/glue/plugins/test/plugin_npobject_lifetime_test.h" -#include "webkit/glue/plugins/test/plugin_npobject_proxy_test.h" -#include "webkit/glue/plugins/test/plugin_private_test.h" -#include "webkit/glue/plugins/test/plugin_schedule_timer_test.h" -#include "webkit/glue/plugins/test/plugin_setup_test.h" -#include "webkit/glue/plugins/test/plugin_thread_async_call_test.h" -#include "webkit/glue/plugins/test/plugin_window_size_test.h" -#if defined(OS_WIN) -#include "webkit/glue/plugins/test/plugin_windowed_test.h" -#endif -#include "webkit/glue/plugins/test/plugin_windowless_test.h" - -namespace NPAPIClient { - -PluginTest* CreatePluginTest(const std::string& test_name, - NPP instance, - NPNetscapeFuncs* host_functions) { - PluginTest* new_test = NULL; - - if (test_name == "arguments") { - new_test = new PluginArgumentsTest(instance, host_functions); - } else if (test_name == "geturl" || test_name == "geturl_404_response" || - test_name == "geturl_fail_write" || - test_name == "plugin_referrer_test" || - test_name == "geturlredirectnotify") { - new_test = new PluginGetURLTest(instance, host_functions); - } else if (test_name == "npobject_proxy") { - new_test = new NPObjectProxyTest(instance, host_functions); -#if defined(OS_WIN) || defined(OS_MACOSX) - // TODO(port): plugin_windowless_test.*. - } else if (test_name == "execute_script_delete_in_paint" || - test_name == "execute_script_delete_in_mouse_move" || - test_name == "delete_frame_test" || - test_name == "multiple_instances_sync_calls" || - test_name == "no_hang_if_init_crashes" || - test_name == "convert_point") { - new_test = new WindowlessPluginTest(instance, host_functions); -#endif - } else if (test_name == "getjavascripturl") { - new_test = new ExecuteGetJavascriptUrlTest(instance, host_functions); - } else if (test_name == "getjavascripturl2") { - new_test = new ExecuteGetJavascriptUrl2Test(instance, host_functions); -#if defined(OS_WIN) - // TODO(port): plugin_window_size_test.*. - } else if (test_name == "checkwindowrect") { - new_test = new PluginWindowSizeTest(instance, host_functions); -#endif - } else if (test_name == "self_delete_plugin_stream") { - new_test = new DeletePluginInStreamTest(instance, host_functions); -#if defined(OS_WIN) - // TODO(port): plugin_npobject_lifetime_test.*. - } else if (test_name == "npobject_lifetime_test") { - new_test = new NPObjectLifetimeTest(instance, host_functions); - } else if (test_name == "npobject_lifetime_test_second_instance") { - new_test = new NPObjectLifetimeTestInstance2(instance, host_functions); - } else if (test_name == "new_fails") { - new_test = new NewFailsTest(instance, host_functions); - } else if (test_name == "npobject_delete_plugin_in_evaluate" || - test_name == "npobject_delete_create_plugin_in_evaluate") { - new_test = new NPObjectDeletePluginInNPN_Evaluate(instance, host_functions); -#endif - } else if (test_name == "plugin_javascript_open_popup_with_plugin") { - new_test = new ExecuteJavascriptOpenPopupWithPluginTest( - instance, host_functions); - } else if (test_name == "plugin_popup_with_plugin_target") { - new_test = new ExecuteJavascriptPopupWindowTargetPluginTest( - instance, host_functions); - } else if (test_name == "plugin_thread_async_call") { - new_test = new PluginThreadAsyncCallTest(instance, host_functions); - } else if (test_name == "private") { - new_test = new PrivateTest(instance, host_functions); - } else if (test_name == "schedule_timer") { - new_test = new ScheduleTimerTest(instance, host_functions); -#if defined(OS_WIN) - // TODO(port): plugin_windowed_test.*. - } else if (test_name == "hidden_plugin" || - test_name == "create_instance_in_paint" || - test_name == "alert_in_window_message" || - test_name == "ensure_scripting_works_in_destroy" || - test_name == "invoke_js_function_on_create") { - new_test = new WindowedPluginTest(instance, host_functions); -#endif - } else if (test_name == "setup") { - // "plugin" is the name for plugin documents. - new_test = new PluginSetupTest(instance, host_functions); - } - - return new_test; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_test_factory.h b/webkit/glue/plugins/test/plugin_test_factory.h deleted file mode 100644 index 3fd38d5..0000000 --- a/webkit/glue/plugins/test/plugin_test_factory.h +++ /dev/null @@ -1,22 +0,0 @@ -// 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 WEBKIT_PORT_PLUGINS_TEST_PLUGIN_TEST_FACTROY_H__ -#define WEBKIT_PORT_PLUGINS_TEST_PLUGIN_TEST_FACTROY_H__ - -#include <string> - -#include "third_party/npapi/bindings/nphostapi.h" - -namespace NPAPIClient { - -class PluginTest; - -extern PluginTest* CreatePluginTest(const std::string& test_name, - NPP instance, - NPNetscapeFuncs* host_functions); - -} // namespace NPAPIClient - -#endif // WEBKIT_PORT_PLUGINS_TEST_PLUGIN_TEST_FACTROY_H__ diff --git a/webkit/glue/plugins/test/plugin_thread_async_call_test.cc b/webkit/glue/plugins/test/plugin_thread_async_call_test.cc deleted file mode 100644 index c01a49e..0000000 --- a/webkit/glue/plugins/test/plugin_thread_async_call_test.cc +++ /dev/null @@ -1,117 +0,0 @@ -// 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 "webkit/glue/plugins/test/plugin_thread_async_call_test.h" - -#include "base/at_exit.h" -#include "base/message_loop.h" -#include "base/thread.h" -#include "webkit/glue/plugins/test/plugin_client.h" - -namespace NPAPIClient { - -namespace { - -// There are two plugin instances in this test. The long lived instance is used -// for reporting errors and signalling test completion. The short lived one is -// used to verify that async callbacks are not invoked after NPP_Destroy. -PluginThreadAsyncCallTest* g_short_lived_instance; -PluginThreadAsyncCallTest* g_long_lived_instance; - -void OnCallSucceededHelper(void* data) { - static_cast<PluginThreadAsyncCallTest*>(data)->OnCallSucceeded(); -} - -class AsyncCallTask : public Task { - public: - AsyncCallTask(PluginThreadAsyncCallTest* test_class) - : test_class_(test_class) {} - - void Run() { - test_class_->AsyncCall(); - } - - private: - PluginThreadAsyncCallTest* test_class_; -}; - -void OnCallFailed(void* data) { - g_long_lived_instance->SetError("Async callback invoked after NPP_Destroy"); -} - -void OnCallCompletedHelper(void* data) { - static_cast<PluginThreadAsyncCallTest*>(data)->OnCallCompleted(); -} -} - -PluginThreadAsyncCallTest::PluginThreadAsyncCallTest( - NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPError PluginThreadAsyncCallTest::New( - uint16 mode, int16 argc, const char* argn[], const char* argv[], - NPSavedData* saved) { - NPError error = PluginTest::New(mode, argc, argn, argv, saved); - if (error != NPERR_NO_ERROR) - return error; - - // Determine whether this is the short lived instance. - for (int i = 0; i < argc; ++i) { - if (base::strcasecmp(argn[i], "short_lived") == 0) { - if (base::strcasecmp(argv[i], "true") == 0) { - g_short_lived_instance = this; - } else { - g_long_lived_instance = this; - } - } - } - - // Schedule an async call that will succeed. Make sure to call that API from - // a different thread to fully test it. - if (this == g_short_lived_instance) { - at_exit_manager_.reset(new base::AtExitManager()); - base::Thread random_thread("random_thread"); - random_thread.Start(); - random_thread.message_loop()->PostTask(FROM_HERE, new AsyncCallTask(this)); - } - - return NPERR_NO_ERROR; -} - -void PluginThreadAsyncCallTest::AsyncCall() { - HostFunctions()->pluginthreadasynccall(id(), OnCallSucceededHelper, this); -} - -void PluginThreadAsyncCallTest::OnCallSucceeded() { - // Delete the short lived instance. - NPIdentifier delete_id = HostFunctions()->getstringidentifier( - "deleteShortLivedInstance"); - - NPObject *window_obj = NULL; - HostFunctions()->getvalue(id(), NPNVWindowNPObject, &window_obj); - - NPVariant result; - HostFunctions()->invoke(id(), window_obj, delete_id, NULL, 0, &result); -} - -NPError PluginThreadAsyncCallTest::Destroy() { - if (this == g_short_lived_instance) { - // Schedule an async call that should not be called. - HostFunctions()->pluginthreadasynccall(id(), OnCallFailed, NULL); - - // Schedule an async call to end the test using the long lived instance. - HostFunctions()->pluginthreadasynccall(g_long_lived_instance->id(), - OnCallCompletedHelper, - g_long_lived_instance); - } - - return NPERR_NO_ERROR; -} - -void PluginThreadAsyncCallTest::OnCallCompleted() { - SignalTestCompleted(); -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_thread_async_call_test.h b/webkit/glue/plugins/test/plugin_thread_async_call_test.h deleted file mode 100644 index 78e4e8d..0000000 --- a/webkit/glue/plugins/test/plugin_thread_async_call_test.h +++ /dev/null @@ -1,39 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_THREAD_ASYNC_CALL_TEST_H_ -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_THREAD_ASYNC_CALL_TEST_H_ - -#include "base/scoped_ptr.h" -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace base { -class AtExitManager; -} - -namespace NPAPIClient { - -// This class tests scheduling and unscheduling of async callbacks using -// NPN_PluginThreadAsyncCall. -class PluginThreadAsyncCallTest : public PluginTest { - public: - PluginThreadAsyncCallTest(NPP id, NPNetscapeFuncs *host_functions); - - virtual NPError New(uint16 mode, int16 argc, const char* argn[], - const char* argv[], NPSavedData* saved); - - virtual NPError Destroy(); - - void AsyncCall(); - void OnCallSucceeded(); - void OnCallCompleted(); - - private: - // base::Thread needs one of these. - scoped_ptr<base::AtExitManager> at_exit_manager_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_THREAD_ASYNC_CALL_TEST_H_ diff --git a/webkit/glue/plugins/test/plugin_window_size_test.cc b/webkit/glue/plugins/test/plugin_window_size_test.cc deleted file mode 100644 index 9bfabca..0000000 --- a/webkit/glue/plugins/test/plugin_window_size_test.cc +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_window_size_test.h" -#include "webkit/glue/plugins/test/plugin_client.h" - -namespace NPAPIClient { - -PluginWindowSizeTest::PluginWindowSizeTest(NPP id, - NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { -} - -NPError PluginWindowSizeTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - HWND window = reinterpret_cast<HWND>(pNPWindow->window); - if (!pNPWindow || !::IsWindow(window)) { - SetError("Invalid arguments passed in"); - return NPERR_INVALID_PARAM; - } - - RECT window_rect = {0}; - window_rect.left = pNPWindow->x; - window_rect.top = pNPWindow->y; - window_rect.right = pNPWindow->width; - window_rect.bottom = pNPWindow->height; - - if (!::IsRectEmpty(&window_rect)) { - RECT client_rect = {0}; - ::GetClientRect(window, &client_rect); - if (::IsRectEmpty(&client_rect)) { - SetError("The client rect of the plugin window is empty. Test failed"); - } - - // Bug 6742: ensure that the coordinates passed in are relative to the - // parent HWND. - POINT origin_from_os; - RECT window_rect_from_os; - ::GetWindowRect(window, &window_rect_from_os); - origin_from_os.x = window_rect_from_os.left; - origin_from_os.y = window_rect_from_os.top; - ::ScreenToClient(GetParent(window), &origin_from_os); - if (origin_from_os.x != pNPWindow->x || origin_from_os.y != pNPWindow->y) - SetError("Wrong position passed in to SetWindow! Test failed"); - - SignalTestCompleted(); - } - - return NPERR_NO_ERROR; -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_window_size_test.h b/webkit/glue/plugins/test/plugin_window_size_test.h deleted file mode 100644 index 3650671..0000000 --- a/webkit/glue/plugins/test/plugin_window_size_test.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_WINDOW_SIZE_TEST_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_WINDOW_SIZE_TEST_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class tests whether the plugin window has a non zero rect -// on the second SetWindow call. -class PluginWindowSizeTest : public PluginTest { - public: - // Constructor. - PluginWindowSizeTest(NPP id, NPNetscapeFuncs *host_functions); - // NPAPI SetWindow handler - virtual NPError SetWindow(NPWindow* pNPWindow); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_WINDOW_SIZE_TEST_H diff --git a/webkit/glue/plugins/test/plugin_windowed_test.cc b/webkit/glue/plugins/test/plugin_windowed_test.cc deleted file mode 100644 index 2ed3ae6..0000000 --- a/webkit/glue/plugins/test/plugin_windowed_test.cc +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/test/plugin_windowed_test.h" -#include "webkit/glue/plugins/test/plugin_client.h" - -namespace NPAPIClient { - -WindowedPluginTest::WindowedPluginTest(NPP id, NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions), - window_(NULL), done_(false) { -} - -WindowedPluginTest::~WindowedPluginTest() { - if (window_) - DestroyWindow(window_); -} - -NPError WindowedPluginTest::SetWindow(NPWindow* pNPWindow) { - if (pNPWindow->window == NULL) - return NPERR_NO_ERROR; - - if (test_name() == "create_instance_in_paint" && test_id() == "2") { - SignalTestCompleted(); - return NPERR_NO_ERROR; - } - - if (window_) - return NPERR_NO_ERROR; - - HWND parent = reinterpret_cast<HWND>(pNPWindow->window); - if (!pNPWindow || !::IsWindow(parent)) { - SetError("Invalid arguments passed in"); - return NPERR_INVALID_PARAM; - } - - if ((test_name() == "create_instance_in_paint" && test_id() == "1") || - test_name() == "alert_in_window_message" || - test_name() == "invoke_js_function_on_create") { - static ATOM window_class = 0; - if (!window_class) { - WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_DBLCLKS; - wcex.lpfnWndProc = &NPAPIClient::WindowedPluginTest::WindowProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = GetModuleHandle(NULL); - wcex.hIcon = 0; - wcex.hCursor = 0; - wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW+1); - wcex.lpszMenuName = 0; - wcex.lpszClassName = L"CreateInstanceInPaintTestWindowClass"; - wcex.hIconSm = 0; - window_class = RegisterClassEx(&wcex); - } - - window_ = CreateWindowEx( - WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR, - MAKEINTATOM(window_class), 0, - WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE , - 0, 0, 100, 100, parent, 0, GetModuleHandle(NULL), 0); - DCHECK(window_); - // TODO: this propery leaks. - ::SetProp(window_, L"Plugin_Instance", this); - } - - return NPERR_NO_ERROR; -} - -NPError WindowedPluginTest::Destroy() { - if (test_name() != "ensure_scripting_works_in_destroy") - return NPERR_NO_ERROR; - - // Bug 23706: ensure that scripting works with no asserts. - NPObject *window_obj = NULL; - HostFunctions()->getvalue(id(), NPNVWindowNPObject,&window_obj); - - if (!window_obj) { - SetError("Failed to get NPObject for plugin instance"); - } else { - std::string script = "javascript:GetMagicNumber()"; - NPString script_string; - script_string.UTF8Characters = script.c_str(); - script_string.UTF8Length = - static_cast<unsigned int>(script.length()); - - NPVariant result_var; - bool result = HostFunctions()->evaluate( - id(), window_obj, &script_string, &result_var); - if (!result || - result_var.type != NPVariantType_Int32 || - result_var.value.intValue != 42) { - SetError("Failed to script during NPP_Destroy"); - } - } - - SignalTestCompleted(); - return NPERR_NO_ERROR; -} - -void WindowedPluginTest::CallJSFunction( - WindowedPluginTest* this_ptr, const char* function) { - NPIdentifier function_id = this_ptr->HostFunctions()->getstringidentifier( - function); - - NPObject *window_obj = NULL; - this_ptr->HostFunctions()->getvalue( - this_ptr->id(), NPNVWindowNPObject, &window_obj); - - NPVariant rv; - this_ptr->HostFunctions()->invoke( - this_ptr->id(), window_obj, function_id, NULL, 0, &rv); -} - -LRESULT CALLBACK WindowedPluginTest::WindowProc( - HWND window, UINT message, WPARAM wparam, LPARAM lparam) { - WindowedPluginTest* this_ptr = - reinterpret_cast<WindowedPluginTest*> - (::GetProp(window, L"Plugin_Instance")); - - if (this_ptr && !this_ptr->done_) { - if (this_ptr->test_name() == "create_instance_in_paint" && - message == WM_PAINT) { - this_ptr->done_ = true; - CallJSFunction(this_ptr, "CreateNewInstance"); - } else if (this_ptr->test_name() == "alert_in_window_message" && - message == WM_PAINT) { - this_ptr->done_ = true; - // We call this function twice as we want to display two alerts - // and verify that we don't hang the browser. - CallJSFunction(this_ptr, "CallAlert"); - CallJSFunction(this_ptr, "CallAlert"); - } else if (this_ptr->test_name() == - "invoke_js_function_on_create" && - message == WM_PAINT) { - this_ptr->done_ = true; - CallJSFunction(this_ptr, "PluginCreated"); - } - - if (this_ptr->done_) { - ::RemoveProp(window, L"Plugin_Instance"); - } - } - - return DefWindowProc(window, message, wparam, lparam); -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_windowed_test.h b/webkit/glue/plugins/test/plugin_windowed_test.h deleted file mode 100644 index 949ea86..0000000 --- a/webkit/glue/plugins/test/plugin_windowed_test.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_WINDOWED_TEST_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_WINDOWED_TEST_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class contains a list of windowed plugin tests. Please add additional -// tests to this class. -class WindowedPluginTest : public PluginTest { - public: - WindowedPluginTest(NPP id, NPNetscapeFuncs *host_functions); - ~WindowedPluginTest(); - - private: - static LRESULT CALLBACK WindowProc( - HWND window, UINT message, WPARAM wparam, LPARAM lparam); - static void CallJSFunction(WindowedPluginTest*, const char*); - - virtual NPError SetWindow(NPWindow* pNPWindow); - virtual NPError Destroy(); - - HWND window_; - bool done_; -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_WINDOWED_TEST_H diff --git a/webkit/glue/plugins/test/plugin_windowless_test.cc b/webkit/glue/plugins/test/plugin_windowless_test.cc deleted file mode 100644 index aa6a9d7..0000000 --- a/webkit/glue/plugins/test/plugin_windowless_test.cc +++ /dev/null @@ -1,261 +0,0 @@ -// 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. - -#define STRSAFE_NO_DEPRECATE -#include "base/string_number_conversions.h" -#include "base/string_util.h" -#include "webkit/glue/plugins/test/plugin_windowless_test.h" -#include "webkit/glue/plugins/test/plugin_client.h" - -#if defined(OS_MACOSX) -#include <ApplicationServices/ApplicationServices.h> -#include <Carbon/Carbon.h> -#endif - -namespace NPAPIClient { - -// Remember the first plugin instance for tests involving multiple instances -WindowlessPluginTest* g_other_instance = NULL; - -WindowlessPluginTest::WindowlessPluginTest(NPP id, - NPNetscapeFuncs *host_functions) - : PluginTest(id, host_functions) { - if (!g_other_instance) - g_other_instance = this; -} - -static bool IsPaintEvent(NPEvent* np_event) { -#if defined(OS_WIN) - return WM_PAINT == np_event->event; -#elif defined(OS_MACOSX) - return np_event->what == updateEvt; -#endif -} - -static bool IsMouseMoveEvent(NPEvent* np_event) { -#if defined(OS_WIN) - return WM_MOUSEMOVE == np_event->event; -#elif defined(OS_MACOSX) - return np_event->what == nullEvent; -#endif -} - -static bool IsMouseUpEvent(NPEvent* np_event) { -#if defined(OS_WIN) - return WM_LBUTTONUP == np_event->event; -#elif defined(OS_MACOSX) - return np_event->what == mouseUp; -#endif -} - -static bool IsWindowActivationEvent(NPEvent* np_event) { -#if defined(OS_WIN) - NOTIMPLEMENTED(); - return false; -#elif defined(OS_MACOSX) - return np_event->what == activateEvt; -#endif -} - -int16 WindowlessPluginTest::HandleEvent(void* event) { - - NPNetscapeFuncs* browser = NPAPIClient::PluginClient::HostFunctions(); - - NPBool supports_windowless = 0; - NPError result = browser->getvalue(id(), NPNVSupportsWindowless, - &supports_windowless); - if ((result != NPERR_NO_ERROR) || (supports_windowless != TRUE)) { - SetError("Failed to read NPNVSupportsWindowless value"); - SignalTestCompleted(); - return PluginTest::HandleEvent(event); - } - - NPEvent* np_event = reinterpret_cast<NPEvent*>(event); - if (IsPaintEvent(np_event)) { -#if defined(OS_WIN) - HDC paint_dc = reinterpret_cast<HDC>(np_event->wParam); - if (paint_dc == NULL) { - SetError("Invalid Window DC passed to HandleEvent for WM_PAINT"); - SignalTestCompleted(); - return NPERR_GENERIC_ERROR; - } - - HRGN clipping_region = CreateRectRgn(0, 0, 0, 0); - if (!GetClipRgn(paint_dc, clipping_region)) { - SetError("No clipping region set in window DC"); - DeleteObject(clipping_region); - SignalTestCompleted(); - return NPERR_GENERIC_ERROR; - } - - DeleteObject(clipping_region); -#endif - - if (test_name() == "execute_script_delete_in_paint") { - ExecuteScriptDeleteInPaint(browser); - } else if (test_name() == "multiple_instances_sync_calls") { - MultipleInstanceSyncCalls(browser); - } -#if OS_MACOSX - } else if (IsWindowActivationEvent(np_event) && - test_name() == "convert_point") { - ConvertPoint(browser); -#endif - } else if (IsMouseMoveEvent(np_event) && - test_name() == "execute_script_delete_in_mouse_move") { - ExecuteScript(browser, id(), "DeletePluginWithinScript();", NULL); - SignalTestCompleted(); - } else if (IsMouseUpEvent(np_event) && - test_name() == "delete_frame_test") { - ExecuteScript( - browser, id(), - "parent.document.getElementById('frame').outerHTML = ''", NULL); - } - // If this test failed, then we'd have crashed by now. - return PluginTest::HandleEvent(event); -} - -NPError WindowlessPluginTest::ExecuteScript(NPNetscapeFuncs* browser, NPP id, - const std::string& script, NPVariant* result) { - std::string script_url = "javascript:"; - script_url += script; - - NPString script_string = { script_url.c_str(), script_url.length() }; - NPObject *window_obj = NULL; - browser->getvalue(id, NPNVWindowNPObject, &window_obj); - - NPVariant unused_result; - if (!result) - result = &unused_result; - - return browser->evaluate(id, window_obj, &script_string, result); -} - -void WindowlessPluginTest::ExecuteScriptDeleteInPaint( - NPNetscapeFuncs* browser) { - const NPUTF8* urlString = "javascript:DeletePluginWithinScript()"; - const NPUTF8* targetString = NULL; - browser->geturl(id(), urlString, targetString); - SignalTestCompleted(); -} - -void WindowlessPluginTest::MultipleInstanceSyncCalls(NPNetscapeFuncs* browser) { - if (this == g_other_instance) - return; - - DCHECK(g_other_instance); - ExecuteScript(browser, g_other_instance->id(), "TestCallback();", NULL); - SignalTestCompleted(); -} - -#if defined(OS_MACOSX) -std::string StringForPoint(int x, int y) { - std::string point_string("("); - point_string.append(base::IntToString(x)); - point_string.append(", "); - point_string.append(base::IntToString(y)); - point_string.append(")"); - return point_string; -} -#endif - -void WindowlessPluginTest::ConvertPoint(NPNetscapeFuncs* browser) { -#if defined(OS_MACOSX) - // First, just sanity-test that round trips work. - NPCoordinateSpace spaces[] = { NPCoordinateSpacePlugin, - NPCoordinateSpaceWindow, - NPCoordinateSpaceFlippedWindow, - NPCoordinateSpaceScreen, - NPCoordinateSpaceFlippedScreen }; - for (unsigned int i = 0; i < arraysize(spaces); ++i) { - for (unsigned int j = 0; j < arraysize(spaces); ++j) { - double x, y, round_trip_x, round_trip_y; - if (!(browser->convertpoint(id(), 0, 0, spaces[i], &x, &y, spaces[j])) || - !(browser->convertpoint(id(), x, y, spaces[j], &round_trip_x, - &round_trip_y, spaces[i]))) { - SetError("Conversion failed"); - SignalTestCompleted(); - return; - } - if (i != j && x == 0 && y == 0) { - SetError("Converting a coordinate should change it"); - SignalTestCompleted(); - return; - } - if (round_trip_x != 0 || round_trip_y != 0) { - SetError("Round-trip conversion should return the original point"); - SignalTestCompleted(); - return; - } - } - } - - // Now, more extensive testing on a single point. - double screen_x, screen_y; - browser->convertpoint(id(), 0, 0, NPCoordinateSpacePlugin, - &screen_x, &screen_y, NPCoordinateSpaceScreen); - double flipped_screen_x, flipped_screen_y; - browser->convertpoint(id(), 0, 0, NPCoordinateSpacePlugin, - &flipped_screen_x, &flipped_screen_y, - NPCoordinateSpaceFlippedScreen); - double window_x, window_y; - browser->convertpoint(id(), 0, 0, NPCoordinateSpacePlugin, - &window_x, &window_y, NPCoordinateSpaceWindow); - double flipped_window_x, flipped_window_y; - browser->convertpoint(id(), 0, 0, NPCoordinateSpacePlugin, - &flipped_window_x, &flipped_window_y, - NPCoordinateSpaceFlippedWindow); - - CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID()); - - // Check that all the coordinates are right. The constants below are based on - // the window frame set in the UI test and the content offset in the test - // html. Y-coordinates are not checked exactly so that the test is robust - // against toolbar changes, info and bookmark bar visibility, etc. - const int kWindowHeight = 400; - const int kWindowXOrigin = 50; - const int kWindowYOrigin = 50; - const int kPluginXContentOffset = 50; - const int kPluginYContentOffset = 50; - const int kChromeYTolerance = 200; - - std::string error_string; - if (screen_x != flipped_screen_x) - error_string = "Flipping screen coordinates shouldn't change x"; - else if (flipped_screen_y != main_display_bounds.size.height - screen_y) - error_string = "Flipped screen coordinates should be flipped vertically"; - else if (screen_x != kWindowXOrigin + kPluginXContentOffset) - error_string = "Screen x location is wrong"; - else if (flipped_screen_y < kWindowYOrigin + kPluginYContentOffset || - flipped_screen_y > kWindowYOrigin + kPluginYContentOffset + - kChromeYTolerance) - error_string = "Screen y location is wrong"; - else if (window_x != flipped_window_x) - error_string = "Flipping window coordinates shouldn't change x"; - else if (flipped_window_y != kWindowHeight - window_y) - error_string = "Flipped window coordinates should be flipped vertically"; - else if (window_x != kPluginXContentOffset) - error_string = "Window x location is wrong"; - else if (flipped_window_y < kPluginYContentOffset || - flipped_window_y > kPluginYContentOffset + kChromeYTolerance) - error_string = "Window y location is wrong"; - - if (!error_string.empty()) { - error_string.append(" - "); - error_string.append(StringForPoint(screen_x, screen_y)); - error_string.append(" - "); - error_string.append(StringForPoint(flipped_screen_x, flipped_screen_y)); - error_string.append(" - "); - error_string.append(StringForPoint(window_x, window_y)); - error_string.append(" - "); - error_string.append(StringForPoint(flipped_window_x, flipped_window_y)); - SetError(error_string); - } -#else - SetError("Unimplemented"); -#endif - SignalTestCompleted(); -} - -} // namespace NPAPIClient diff --git a/webkit/glue/plugins/test/plugin_windowless_test.h b/webkit/glue/plugins/test/plugin_windowless_test.h deleted file mode 100644 index f336653..0000000 --- a/webkit/glue/plugins/test/plugin_windowless_test.h +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_EXECUTE_SCRIPT_DELETE_TEST_H -#define WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_EXECUTE_SCRIPT_DELETE_TEST_H - -#include "webkit/glue/plugins/test/plugin_test.h" - -namespace NPAPIClient { - -// This class contains a list of windowless plugin tests. Please add additional -// tests to this class. -class WindowlessPluginTest : public PluginTest { - public: - // Constructor. - WindowlessPluginTest(NPP id, NPNetscapeFuncs *host_functions); - - // These tests run in windowless plugin mode. - virtual bool IsWindowless() const { return true; } - - // NPAPI HandleEvent handler - virtual int16 HandleEvent(void* event); - - protected: - NPError ExecuteScript(NPNetscapeFuncs* browser, NPP id, - const std::string& script, NPVariant* result); - void ExecuteScriptDeleteInPaint(NPNetscapeFuncs* browser); - void MultipleInstanceSyncCalls(NPNetscapeFuncs* browser); - void ConvertPoint(NPNetscapeFuncs* browser); -}; - -} // namespace NPAPIClient - -#endif // WEBKIT_GLUE_PLUGINS_TEST_PLUGIN_EXECUTE_SCRIPT_DELETE_TEST_H diff --git a/webkit/glue/plugins/test/resource.h b/webkit/glue/plugins/test/resource.h deleted file mode 100644 index c52fa82..0000000 --- a/webkit/glue/plugins/test/resource.h +++ /dev/null @@ -1,15 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by npapi_test.rc -// - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/webkit/glue/plugins/webplugin.cc b/webkit/glue/plugins/webplugin.cc deleted file mode 100644 index 18f722b..0000000 --- a/webkit/glue/plugins/webplugin.cc +++ /dev/null @@ -1,26 +0,0 @@ -// 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 "webkit/glue/plugins/webplugin.h" - -namespace webkit_glue { - -WebPluginGeometry::WebPluginGeometry() - : window(gfx::kNullPluginWindow), - rects_valid(false), - visible(false) { -} - -WebPluginGeometry::~WebPluginGeometry() { -} - -bool WebPluginGeometry::Equals(const WebPluginGeometry& rhs) const { - return window == rhs.window && - window_rect == rhs.window_rect && - clip_rect == rhs.clip_rect && - cutout_rects == rhs.cutout_rects && - rects_valid == rhs.rects_valid && - visible == rhs.visible; -} -} // namespace webkit_glue diff --git a/webkit/glue/plugins/webplugin.h b/webkit/glue/plugins/webplugin.h deleted file mode 100644 index 5fbef1f..0000000 --- a/webkit/glue/plugins/webplugin.h +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_WEBPLUGIN_H_ -#define WEBKIT_GLUE_WEBPLUGIN_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "gfx/native_widget_types.h" -#include "gfx/rect.h" - -// TODO(port): this typedef is obviously incorrect on non-Windows -// platforms, but now a lot of code now accidentally depends on them -// existing. #ifdef out these declarations and fix all the users. -typedef void* HANDLE; - -class GURL; -struct NPObject; - -namespace WebKit { -class WebFrame; -} - -namespace webkit_glue { - -class WebPluginDelegate; -class WebPluginParentView; -class WebPluginResourceClient; -#if defined(OS_MACOSX) -class WebPluginAcceleratedSurface; -#endif - -// Describes the new location for a plugin window. -struct WebPluginGeometry { - WebPluginGeometry(); - ~WebPluginGeometry(); - - bool Equals(const WebPluginGeometry& rhs) const; - - // On Windows, this is the plugin window in the plugin process. - // On X11, this is the XID of the plugin-side GtkPlug containing the - // GtkSocket hosting the actual plugin window. - // - // On Mac OS X, all of the plugin types are currently "windowless" - // (window == 0) except for the special case of the GPU plugin, - // which currently performs rendering on behalf of the Pepper 3D API - // and WebGL. The GPU plugin uses a simple integer for the - // PluginWindowHandle which is used to map to a side data structure - // containing information about the plugin. Soon this plugin will be - // generalized, at which point this mechanism will be rethought or - // removed. - gfx::PluginWindowHandle window; - gfx::Rect window_rect; - // Clip rect (include) and cutouts (excludes), relative to - // window_rect origin. - gfx::Rect clip_rect; - std::vector<gfx::Rect> cutout_rects; - bool rects_valid; - bool visible; -}; - -// The WebKit side of a plugin implementation. It provides wrappers around -// operations that need to interact with the frame and other WebCore objects. -class WebPlugin { - public: - virtual ~WebPlugin() {} - - // Called by the plugin delegate to let the WebPlugin know if the plugin is - // windowed (i.e. handle is not NULL) or windowless (handle is NULL). This - // tells the WebPlugin to send mouse/keyboard events to the plugin delegate, - // as well as the information about the HDC for paint operations. - virtual void SetWindow(gfx::PluginWindowHandle window) = 0; - - // Whether input events should be sent to the delegate. - virtual void SetAcceptsInputEvents(bool accepts) = 0; - - // Called by the plugin delegate to let it know that the window is being - // destroyed. - virtual void WillDestroyWindow(gfx::PluginWindowHandle window) = 0; -#if defined(OS_WIN) - // The pump_messages_event is a event handle which is valid only for - // windowless plugins and is used in NPP_HandleEvent calls to pump messages - // if the plugin enters a modal loop. - // Cancels a pending request. - virtual void SetWindowlessPumpEvent(HANDLE pump_messages_event) = 0; -#endif - virtual void CancelResource(unsigned long id) = 0; - virtual void Invalidate() = 0; - virtual void InvalidateRect(const gfx::Rect& rect) = 0; - - // Returns the NPObject for the browser's window object. - virtual NPObject* GetWindowScriptNPObject() = 0; - - // Returns the DOM element that loaded the plugin. - virtual NPObject* GetPluginElement() = 0; - - // Cookies - virtual void SetCookie(const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie) = 0; - virtual std::string GetCookies(const GURL& url, - const GURL& first_party_for_cookies) = 0; - - // Shows a modal HTML dialog containing the given URL. json_arguments are - // passed to the dialog via the DOM 'window.chrome.dialogArguments', and the - // retval is the string returned by 'window.chrome.send("DialogClose", - // retval)'. - virtual void ShowModalHTMLDialog(const GURL& url, int width, int height, - const std::string& json_arguments, - std::string* json_retval) = 0; - - // When a default plugin has downloaded the plugin list and finds it is - // available, it calls this method to notify the renderer. Also it will update - // the status when user clicks on the plugin to install. - virtual void OnMissingPluginStatus(int status) = 0; - - // Handles GetURL/GetURLNotify/PostURL/PostURLNotify requests initiated - // by plugins. If the plugin wants notification of the result, notify_id will - // be non-zero. - virtual void HandleURLRequest(const char* url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - int notify_id, - bool popups_allowed, - bool notify_redirects) = 0; - - // Cancels document load. - virtual void CancelDocumentLoad() = 0; - - // Initiates a HTTP range request for an existing stream. - virtual void InitiateHTTPRangeRequest(const char* url, - const char* range_info, - int range_request_id) = 0; - - // Returns true iff in off the record (Incognito) mode. - virtual bool IsOffTheRecord() = 0; - - // Called when the WebPluginResourceClient instance is deleted. - virtual void ResourceClientDeleted( - WebPluginResourceClient* resource_client) {} - - // Defers the loading of the resource identified by resource_id. This is - // controlled by the defer parameter. - virtual void SetDeferResourceLoading(unsigned long resource_id, - bool defer) = 0; - -#if defined(OS_MACOSX) - // Enables/disables plugin IME. - virtual void SetImeEnabled(bool enabled) {}; - - // Synthesize a fake window handle for the plug-in to identify the instance - // to the browser, allowing mapping to a surface for hardware accelleration - // of plug-in content. The browser generates the handle which is then set on - // the plug-in. |opaque| indicates whether the content should be treated as - // opaque or translucent. - // TODO(stuartmorgan): Move this into WebPluginProxy. - virtual void BindFakePluginWindowHandle(bool opaque) {} - - // Returns the accelerated surface abstraction for accelerated plugins. - virtual WebPluginAcceleratedSurface* GetAcceleratedSurface() { return NULL; } -#endif - - // Gets the WebPluginDelegate that implements the interface. - // This API is only for use with Pepper, and is only overridden - // by in-renderer implementations. - virtual WebPluginDelegate* delegate() { return NULL; } - - // Handles NPN_URLRedirectResponse calls issued by plugins in response to - // HTTP URL redirect notifications. - virtual void URLRedirectResponse(bool allow, int resource_id) = 0; -}; - -// Simpler version of ResourceHandleClient that lends itself to proxying. -class WebPluginResourceClient { - public: - virtual ~WebPluginResourceClient() {} - virtual void WillSendRequest(const GURL& url, int http_status_code) = 0; - // The request_is_seekable parameter indicates whether byte range requests - // can be issued for the underlying stream. - virtual void DidReceiveResponse(const std::string& mime_type, - const std::string& headers, - uint32 expected_length, - uint32 last_modified, - bool request_is_seekable) = 0; - virtual void DidReceiveData(const char* buffer, int length, - int data_offset) = 0; - virtual void DidFinishLoading() = 0; - virtual void DidFail() = 0; - virtual bool IsMultiByteResponseExpected() = 0; - virtual int ResourceId() = 0; -}; - -} // namespace webkit_glue - -#endif // #ifndef WEBKIT_GLUE_WEBPLUGIN_H_ diff --git a/webkit/glue/plugins/webplugin_2d_device_delegate.h b/webkit/glue/plugins/webplugin_2d_device_delegate.h deleted file mode 100644 index 69bd53a..0000000 --- a/webkit/glue/plugins/webplugin_2d_device_delegate.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_WEBPLUGIN_2D_DEVICE_DELEGATE_H_ -#define WEBKIT_GLUE_PLUGINS_WEBPLUGIN_2D_DEVICE_DELEGATE_H_ - -#include "base/basictypes.h" -#include "third_party/npapi/bindings/npapi_extensions.h" - -namespace webkit_glue { - -// Interface for the NPAPI 2D device extension. This class implements "NOP" -// versions of all these functions so it can be used seamlessly by the -// "regular" plugin delegate while being overridden by the "pepper" one. -class WebPlugin2DDeviceDelegate { - public: - virtual NPError Device2DQueryCapability(int32 capability, int32* value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device2DQueryConfig(const NPDeviceContext2DConfig* request, - NPDeviceContext2DConfig* obtain) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device2DInitializeContext( - const NPDeviceContext2DConfig* config, - NPDeviceContext2D* context) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device2DSetStateContext(NPDeviceContext2D* context, - int32 state, - intptr_t value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device2DGetStateContext(NPDeviceContext2D* context, - int32 state, - intptr_t* value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device2DFlushContext(NPP id, - NPDeviceContext2D* context, - NPDeviceFlushContextCallbackPtr callback, - void* user_data) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device2DDestroyContext(NPDeviceContext2D* context) { - return NPERR_GENERIC_ERROR; - } - - protected: - WebPlugin2DDeviceDelegate() {} - virtual ~WebPlugin2DDeviceDelegate() {} -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_PLUGINS_WEBPLUGIN_2D_DEVICE_DELEGATE_H_ diff --git a/webkit/glue/plugins/webplugin_3d_device_delegate.h b/webkit/glue/plugins/webplugin_3d_device_delegate.h deleted file mode 100644 index fbb46eb..0000000 --- a/webkit/glue/plugins/webplugin_3d_device_delegate.h +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_WEBPLUGIN_3D_DEVICE_DELEGATE_H_ -#define WEBKIT_GLUE_PLUGINS_WEBPLUGIN_3D_DEVICE_DELEGATE_H_ - -#include "base/basictypes.h" -#include "third_party/npapi/bindings/npapi_extensions.h" - -namespace webkit_glue { - -// Interface for the NPAPI 3D device extension. This class implements "NOP" -// versions of all these functions so it can be used seamlessly by the -// "regular" plugin delegate while being overridden by the "pepper" one. -class WebPlugin3DDeviceDelegate { - public: - virtual NPError Device3DQueryCapability(int32 capability, int32* value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DQueryConfig(const NPDeviceContext3DConfig* request, - NPDeviceContext3DConfig* obtain) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DInitializeContext( - const NPDeviceContext3DConfig* config, - NPDeviceContext3D* context) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DSetStateContext(NPDeviceContext3D* context, - int32 state, - intptr_t value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DGetStateContext(NPDeviceContext3D* context, - int32 state, - intptr_t* value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DFlushContext(NPP id, - NPDeviceContext3D* context, - NPDeviceFlushContextCallbackPtr callback, - void* user_data) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DDestroyContext(NPDeviceContext3D* context) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DCreateBuffer(NPDeviceContext3D* context, - size_t size, - int32* id) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DDestroyBuffer(NPDeviceContext3D* context, - int32 id) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DMapBuffer(NPDeviceContext3D* context, - int32 id, - NPDeviceBuffer* buffer) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DGetNumConfigs(int32* num_configs) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DGetConfigAttribs(int32 config, - int32* attrib_list) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DCreateContext(int32 config, - const int32* attrib_list, - NPDeviceContext3D** context) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DRegisterCallback( - NPP id, - NPDeviceContext* context, - int32 callback_type, - NPDeviceGenericCallbackPtr callback, - void* callback_data) { - return NPERR_GENERIC_ERROR; - } - virtual NPError Device3DSynchronizeContext( - NPP id, - NPDeviceContext3D* context, - NPDeviceSynchronizationMode mode, - const int32* input_attrib_list, - int32* output_attrib_list, - NPDeviceSynchronizeContextCallbackPtr callback, - void* callback_data) { - return NPERR_GENERIC_ERROR; - } - - protected: - WebPlugin3DDeviceDelegate() {} - virtual ~WebPlugin3DDeviceDelegate() {} -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_PLUGINS_WEBPLUGIN_3D_DEVICE_DELEGATE_H_ diff --git a/webkit/glue/plugins/webplugin_accelerated_surface_mac.h b/webkit/glue/plugins/webplugin_accelerated_surface_mac.h deleted file mode 100644 index 13980ca..0000000 --- a/webkit/glue/plugins/webplugin_accelerated_surface_mac.h +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_WEBPLUGIN_ACCELERATED_SURFACE_MAC_H_ -#define WEBKIT_GLUE_WEBPLUGIN_ACCELERATED_SURFACE_MAC_H_ -#pragma once - -#include "gfx/native_widget_types.h" -#include "gfx/size.h" - -// Avoid having to include OpenGL headers here. -typedef struct _CGLContextObject* CGLContextObj; - -namespace webkit_glue { - -// Interface class for interacting with an accelerated plugin surface, used -// for the Core Animation flavors of plugin drawing on the Mac. -class WebPluginAcceleratedSurface { - public: - virtual ~WebPluginAcceleratedSurface() {} - - // Sets the window handle used throughout the browser to identify this - // surface. - virtual void SetWindowHandle(gfx::PluginWindowHandle window) = 0; - - // Sets the size of the surface. - virtual void SetSize(const gfx::Size& size) = 0; - - // Returns the context used to draw into this surface. - // If initializing the surface failed, this will be NULL. - virtual CGLContextObj context() = 0; - - // Readies the surface for drawing. Must be called before any drawing session. - virtual void StartDrawing() = 0; - - // Ends a drawing session. Changes to the surface may not be reflected until - // this is called. - virtual void EndDrawing() = 0; -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_WEBPLUGIN_ACCELERATED_SURFACE_MAC_H_ diff --git a/webkit/glue/plugins/webplugin_audio_device_delegate.h b/webkit/glue/plugins/webplugin_audio_device_delegate.h deleted file mode 100644 index 3f37246..0000000 --- a/webkit/glue/plugins/webplugin_audio_device_delegate.h +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_PLUGINS_WEBPLUGIN_AUDIO_DEVICE_DELEGATE_H_ -#define WEBKIT_GLUE_PLUGINS_WEBPLUGIN_AUDIO_DEVICE_DELEGATE_H_ - -#include "base/basictypes.h" -#include "third_party/npapi/bindings/npapi_extensions.h" - -namespace webkit_glue { - -// Interface for the NPAPI audio device extension. This class implements "NOP" -// versions of all these functions so it can be used seamlessly by the -// "regular" plugin delegate while being overridden by the "pepper" one. -class WebPluginAudioDeviceDelegate { - public: - virtual NPError DeviceAudioQueryCapability(int32 capability, int32* value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError DeviceAudioQueryConfig( - const NPDeviceContextAudioConfig* request, - NPDeviceContextAudioConfig* obtain) { - return NPERR_GENERIC_ERROR; - } - virtual NPError DeviceAudioInitializeContext( - const NPDeviceContextAudioConfig* config, - NPDeviceContextAudio* context) { - return NPERR_GENERIC_ERROR; - } - virtual NPError DeviceAudioSetStateContext(NPDeviceContextAudio* context, - int32 state, intptr_t value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError DeviceAudioGetStateContext(NPDeviceContextAudio* context, - int32 state, intptr_t* value) { - return NPERR_GENERIC_ERROR; - } - virtual NPError DeviceAudioFlushContext( - NPP id, NPDeviceContextAudio* context, - NPDeviceFlushContextCallbackPtr callback, void* user_data) { - return NPERR_GENERIC_ERROR; - } - virtual NPError DeviceAudioDestroyContext(NPDeviceContextAudio* context) { - return NPERR_GENERIC_ERROR; - } - - protected: - WebPluginAudioDeviceDelegate() {} - virtual ~WebPluginAudioDeviceDelegate() {} -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_PLUGINS_WEBPLUGIN_AUDIO_DEVICE_DELEGATE_H_ - diff --git a/webkit/glue/plugins/webplugin_delegate.h b/webkit/glue/plugins/webplugin_delegate.h deleted file mode 100644 index 901cdea..0000000 --- a/webkit/glue/plugins/webplugin_delegate.h +++ /dev/null @@ -1,166 +0,0 @@ -// 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 WEBKIT_GLUE_WEBPLUGIN_DELEGATE_H_ -#define WEBKIT_GLUE_WEBPLUGIN_DELEGATE_H_ - -#include <string> -#include <vector> - -#include "base/string16.h" -#include "build/build_config.h" -#include "gfx/native_widget_types.h" -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/npapi_extensions.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCanvas.h" -#include "webkit/glue/plugins/webplugin_2d_device_delegate.h" -#include "webkit/glue/plugins/webplugin_3d_device_delegate.h" -#include "webkit/glue/plugins/webplugin_audio_device_delegate.h" -#include "webkit/glue/plugins/webplugin_file_delegate.h" -#include "webkit/glue/plugins/webplugin_print_delegate.h" - -class FilePath; -class GURL; -struct NPObject; - -namespace WebKit { -class WebInputEvent; -struct WebCursorInfo; -} - -namespace gfx { -class Rect; -} - -namespace webkit_glue { - -class WebPlugin; -class WebPluginResourceClient; - -// This is the interface that a plugin implementation needs to provide. -class WebPluginDelegate : public WebPlugin2DDeviceDelegate, - public WebPlugin3DDeviceDelegate, - public WebPluginAudioDeviceDelegate, - public WebPluginPrintDelegate, - public WebPluginFileDelegate { - public: - virtual ~WebPluginDelegate() {} - - // Initializes the plugin implementation with the given (UTF8) arguments. - // Note that the lifetime of WebPlugin must be longer than this delegate. - // If this function returns false the plugin isn't started and shouldn't be - // called again. If this method succeeds, then the WebPlugin is valid until - // PluginDestroyed is called. - // The load_manually parameter if true indicates that the plugin data would - // be passed from webkit. if false indicates that the plugin should download - // the data. This also controls whether the plugin is instantiated as a full - // page plugin (NP_FULL) or embedded (NP_EMBED). - virtual bool Initialize(const GURL& url, - const std::vector<std::string>& arg_names, - const std::vector<std::string>& arg_values, - WebPlugin* plugin, - bool load_manually) = 0; - - // Called when the WebPlugin is being destroyed. This is a signal to the - // delegate that it should tear-down the plugin implementation and not call - // methods on the WebPlugin again. - virtual void PluginDestroyed() = 0; - - // Update the geometry of the plugin. This is a request to move the - // plugin, relative to its containing window, to the coords given by - // window_rect. Its contents should be clipped to the coords given - // by clip_rect, which are relative to the origin of the plugin - // window. The clip_rect is in plugin-relative coordinates. - virtual void UpdateGeometry(const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) = 0; - - // Tells the plugin to paint the damaged rect. |canvas| is only used for - // windowless plugins. - virtual void Paint(WebKit::WebCanvas* canvas, const gfx::Rect& rect) = 0; - - // Tells the plugin to print itself. - virtual void Print(gfx::NativeDrawingContext hdc) = 0; - - // Informs the plugin that it has gained or lost focus. This is only called in - // windowless mode. - virtual void SetFocus(bool focused) = 0; - - // For windowless plugins, gives them a user event like mouse/keyboard. - // Returns whether the event was handled. This is only called in windowsless - // mode. See NPAPI NPP_HandleEvent for more information. - virtual bool HandleInputEvent(const WebKit::WebInputEvent& event, - WebKit::WebCursorInfo* cursor) = 0; - - // Gets the NPObject associated with the plugin for scripting. - virtual NPObject* GetPluginScriptableObject() = 0; - - // Receives notification about a resource load that the plugin initiated - // for a frame. - virtual void DidFinishLoadWithReason(const GURL& url, NPReason reason, - int notify_id) = 0; - - // Returns the process id of the process that is running the plugin. - virtual int GetProcessId() = 0; - - // The result, UTF-8 encoded, of the script execution is returned via this - // function. - virtual void SendJavaScriptStream(const GURL& url, - const std::string& result, - bool success, - int notify_id) = 0; - - // Receives notification about data being available. - virtual void DidReceiveManualResponse(const GURL& url, - const std::string& mime_type, - const std::string& headers, - uint32 expected_length, - uint32 last_modified) = 0; - - // Receives the data. - virtual void DidReceiveManualData(const char* buffer, int length) = 0; - - // Indicates end of data load. - virtual void DidFinishManualLoading() = 0; - - // Indicates a failure in data receipt. - virtual void DidManualLoadFail() = 0; - - // Only supported when the plugin is the default plugin. - virtual void InstallMissingPlugin() = 0; - - // Creates a WebPluginResourceClient instance and returns the same. - virtual WebPluginResourceClient* CreateResourceClient( - unsigned long resource_id, - const GURL& url, - int notify_id) = 0; - - // Creates a WebPluginResourceClient instance for an existing stream that is - // has become seekable. - virtual WebPluginResourceClient* CreateSeekableResourceClient( - unsigned long resource_id, int range_request_id) = 0; - - // See WebPluginContainerImpl's description of the interface. - virtual bool StartFind(const string16& search_text, - bool case_sensitive, - int identifier) { return false; } - virtual void SelectFindResult(bool forward) {} - virtual void StopFind() {} - virtual void NumberOfFindResultsChanged(int total, bool final_result) {} - virtual void SelectedFindResultChanged(int index) {} - virtual NPWidgetExtensions* GetWidgetExtensions() { return NULL; } - virtual bool SetCursor(NPCursorType type) { return false; } - virtual NPFontExtensions* GetFontExtensions() { return NULL; } - - // Used for zooming of full page plugins. 0 means reset, while -1 means zoom - // out and +1 means zoom in. - virtual void SetZoomFactor(float scale, bool text_only) {} - // Gets the selected text, if any. - virtual bool HasSelection() const { return false; } - virtual string16 GetSelectionAsText() const { return string16(); } - virtual string16 GetSelectionAsMarkup() const { return string16(); } -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_WEBPLUGIN_DELEGATE_H_ diff --git a/webkit/glue/plugins/webplugin_delegate_impl.cc b/webkit/glue/plugins/webplugin_delegate_impl.cc deleted file mode 100644 index e3e4f9d..0000000 --- a/webkit/glue/plugins/webplugin_delegate_impl.cc +++ /dev/null @@ -1,304 +0,0 @@ -// 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 "webkit/glue/plugins/webplugin_delegate_impl.h" - -#include <string> -#include <vector> - -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/process_util.h" -#include "base/scoped_ptr.h" -#include "base/string_util.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "webkit/glue/plugins/plugin_constants_win.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/plugin_stream_url.h" -#include "webkit/glue/webkit_glue.h" - -using webkit_glue::WebPlugin; -using webkit_glue::WebPluginDelegate; -using webkit_glue::WebPluginResourceClient; -using WebKit::WebCursorInfo; -using WebKit::WebKeyboardEvent; -using WebKit::WebInputEvent; -using WebKit::WebMouseEvent; - -WebPluginDelegateImpl* WebPluginDelegateImpl::Create( - const FilePath& filename, - const std::string& mime_type, - gfx::PluginWindowHandle containing_view) { - scoped_refptr<NPAPI::PluginLib> plugin_lib( - NPAPI::PluginLib::CreatePluginLib(filename)); - if (plugin_lib.get() == NULL) - return NULL; - - NPError err = plugin_lib->NP_Initialize(); - if (err != NPERR_NO_ERROR) - return NULL; - - scoped_refptr<NPAPI::PluginInstance> instance( - plugin_lib->CreateInstance(mime_type)); - return new WebPluginDelegateImpl(containing_view, instance.get()); -} - -void WebPluginDelegateImpl::PluginDestroyed() { - if (handle_event_depth_) { - MessageLoop::current()->DeleteSoon(FROM_HERE, this); - } else { - delete this; - } -} - -bool WebPluginDelegateImpl::Initialize( - const GURL& url, - const std::vector<std::string>& arg_names, - const std::vector<std::string>& arg_values, - WebPlugin* plugin, - bool load_manually) { - plugin_ = plugin; - - instance_->set_web_plugin(plugin_); - if (quirks_ & PLUGIN_QUIRK_DONT_ALLOW_MULTIPLE_INSTANCES) { - NPAPI::PluginLib* plugin_lib = instance()->plugin_lib(); - if (plugin_lib->instance_count() > 1) { - return false; - } - } - - if (quirks_ & PLUGIN_QUIRK_DIE_AFTER_UNLOAD) - webkit_glue::SetForcefullyTerminatePluginProcess(true); - - int argc = 0; - scoped_array<char*> argn(new char*[arg_names.size()]); - scoped_array<char*> argv(new char*[arg_names.size()]); - for (size_t i = 0; i < arg_names.size(); ++i) { - if (quirks_ & PLUGIN_QUIRK_NO_WINDOWLESS && - LowerCaseEqualsASCII(arg_names[i], "windowlessvideo")) { - continue; - } - argn[argc] = const_cast<char*>(arg_names[i].c_str()); - argv[argc] = const_cast<char*>(arg_values[i].c_str()); - argc++; - } - - creation_succeeded_ = instance_->Start( - url, argn.get(), argv.get(), argc, load_manually); - if (!creation_succeeded_) - return false; - - windowless_ = instance_->windowless(); - if (!windowless_) { - if (!WindowedCreatePlugin()) - return false; - } else { - // For windowless plugins we should set the containing window handle - // as the instance window handle. This is what Safari does. Not having - // a valid window handle causes subtle bugs with plugins which retrieve - // the window handle and validate the same. The window handle can be - // retrieved via NPN_GetValue of NPNVnetscapeWindow. - instance_->set_window_handle(parent_); - } - - bool should_load = PlatformInitialize(); - - plugin_url_ = url.spec(); - - return should_load; -} - -void WebPluginDelegateImpl::DestroyInstance() { - if (instance_ && (instance_->npp()->ndata != NULL)) { - // Shutdown all streams before destroying so that - // no streams are left "in progress". Need to do - // this before calling set_web_plugin(NULL) because the - // instance uses the helper to do the download. - instance_->CloseStreams(); - - window_.window = NULL; - if (creation_succeeded_ && - !(quirks_ & PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY)) { - instance_->NPP_SetWindow(&window_); - } - - instance_->NPP_Destroy(); - - instance_->set_web_plugin(NULL); - - PlatformDestroyInstance(); - - instance_ = 0; - } -} - -void WebPluginDelegateImpl::UpdateGeometry( - const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - - if (first_set_window_call_) { - first_set_window_call_ = false; - // Plugins like media player on Windows have a bug where in they handle the - // first geometry update and ignore the rest resulting in painting issues. - // This quirk basically ignores the first set window call sequence for - // these plugins and has been tested for Windows plugins only. - if (quirks_ & PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL) - return; - } - - if (windowless_) { - WindowlessUpdateGeometry(window_rect, clip_rect); - } else { - WindowedUpdateGeometry(window_rect, clip_rect); - } -} - -void WebPluginDelegateImpl::SetFocus(bool focused) { - DCHECK(windowless_); - // This is called when internal WebKit focus (the focused element on the page) - // changes, but plugins need to know about OS-level focus, so we have an extra - // layer of focus tracking. - // - // On Windows, historically browsers did not set focus events to windowless - // plugins when the toplevel window focus changes. Sending such focus events - // breaks full screen mode in Flash because it will come out of full screen - // mode when it loses focus, and its full screen window causes the browser to - // lose focus. - has_webkit_focus_ = focused; -#ifndef OS_WIN - if (containing_view_has_focus_) - SetPluginHasFocus(focused); -#else - SetPluginHasFocus(focused); -#endif -} - -void WebPluginDelegateImpl::SetPluginHasFocus(bool focused) { - if (focused == plugin_has_focus_) - return; - if (PlatformSetPluginHasFocus(focused)) - plugin_has_focus_ = focused; -} - -void WebPluginDelegateImpl::SetContentAreaHasFocus(bool has_focus) { - containing_view_has_focus_ = has_focus; - if (!windowless_) - return; -#ifndef OS_WIN // See SetFocus above. - SetPluginHasFocus(containing_view_has_focus_ && has_webkit_focus_); -#endif -} - -NPObject* WebPluginDelegateImpl::GetPluginScriptableObject() { - return instance_->GetPluginScriptableObject(); -} - -void WebPluginDelegateImpl::DidFinishLoadWithReason(const GURL& url, - NPReason reason, - int notify_id) { - if (quirks_ & PLUGIN_QUIRK_ALWAYS_NOTIFY_SUCCESS && - reason == NPRES_NETWORK_ERR) { - // Flash needs this or otherwise it unloads the launching swf object. - reason = NPRES_DONE; - } - - instance()->DidFinishLoadWithReason(url, reason, notify_id); -} - -int WebPluginDelegateImpl::GetProcessId() { - // We are in process, so the plugin pid is this current process pid. - return base::GetCurrentProcId(); -} - -void WebPluginDelegateImpl::SendJavaScriptStream(const GURL& url, - const std::string& result, - bool success, - int notify_id) { - instance()->SendJavaScriptStream(url, result, success, notify_id); -} - -void WebPluginDelegateImpl::DidReceiveManualResponse( - const GURL& url, const std::string& mime_type, - const std::string& headers, uint32 expected_length, uint32 last_modified) { - if (!windowless_) { - // Calling NPP_WriteReady before NPP_SetWindow causes movies to not load in - // Flash. See http://b/issue?id=892174. - DCHECK(windowed_did_set_window_); - } - - instance()->DidReceiveManualResponse(url, mime_type, headers, - expected_length, last_modified); -} - -void WebPluginDelegateImpl::DidReceiveManualData(const char* buffer, - int length) { - instance()->DidReceiveManualData(buffer, length); -} - -void WebPluginDelegateImpl::DidFinishManualLoading() { - instance()->DidFinishManualLoading(); -} - -void WebPluginDelegateImpl::DidManualLoadFail() { - instance()->DidManualLoadFail(); -} - -FilePath WebPluginDelegateImpl::GetPluginPath() { - return instance()->plugin_lib()->plugin_info().path; -} - -void WebPluginDelegateImpl::WindowedUpdateGeometry( - const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - if (WindowedReposition(window_rect, clip_rect) || - !windowed_did_set_window_) { - // Let the plugin know that it has been moved - WindowedSetWindow(); - } -} - -bool WebPluginDelegateImpl::HandleInputEvent(const WebInputEvent& event, - WebCursorInfo* cursor_info) { - DCHECK(windowless_) << "events should only be received in windowless mode"; - - bool pop_user_gesture = false; - if (IsUserGesture(event)) { - pop_user_gesture = true; - instance()->PushPopupsEnabledState(true); - } - - bool handled = PlatformHandleInputEvent(event, cursor_info); - - if (pop_user_gesture) { - instance()->PopPopupsEnabledState(); - } - - return handled; -} - -bool WebPluginDelegateImpl::IsUserGesture(const WebInputEvent& event) { - switch (event.type) { - case WebInputEvent::MouseDown: - case WebInputEvent::MouseUp: - case WebInputEvent::KeyDown: - case WebInputEvent::KeyUp: - return true; - default: - return false; - } - return false; -} - -WebPluginResourceClient* WebPluginDelegateImpl::CreateResourceClient( - unsigned long resource_id, const GURL& url, int notify_id) { - return instance()->CreateStream( - resource_id, url, std::string(), notify_id); -} - -WebPluginResourceClient* WebPluginDelegateImpl::CreateSeekableResourceClient( - unsigned long resource_id, int range_request_id) { - return instance()->GetRangeRequest(range_request_id); -} diff --git a/webkit/glue/plugins/webplugin_delegate_impl.h b/webkit/glue/plugins/webplugin_delegate_impl.h deleted file mode 100644 index 4046c95..0000000 --- a/webkit/glue/plugins/webplugin_delegate_impl.h +++ /dev/null @@ -1,511 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_WEBPLUGIN_DELEGATE_IMPL_H_ -#define WEBKIT_GLUE_PLUGINS_WEBPLUGIN_DELEGATE_IMPL_H_ - -#include "build/build_config.h" - -#include <string> -#include <list> - -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "base/task.h" -#include "base/time.h" -#include "base/timer.h" -#include "gfx/native_widget_types.h" -#include "gfx/rect.h" -#include "third_party/npapi/bindings/npapi.h" -#include "webkit/glue/plugins/webplugin_delegate.h" -#include "webkit/glue/webcursor.h" - -#if defined(USE_X11) -#include "app/x11_util.h" - -typedef struct _GdkDrawable GdkPixmap; -#endif - -class FilePath; - -namespace NPAPI { -class PluginInstance; -} - -namespace WebKit { -class WebMouseEvent; -} - -#if defined(OS_MACOSX) -class ExternalDragTracker; -#ifndef NP_NO_QUICKDRAW -class QuickDrawDrawingManager; -#endif -#ifdef __OBJC__ -@class CALayer; -@class CARenderer; -#else -class CALayer; -class CARenderer; -#endif -namespace webkit_glue { -class WebPluginAcceleratedSurface; -} -#endif - -// An implementation of WebPluginDelegate that runs in the plugin process, -// proxied from the renderer by WebPluginDelegateProxy. -class WebPluginDelegateImpl : public webkit_glue::WebPluginDelegate { - public: - enum PluginQuirks { - PLUGIN_QUIRK_SETWINDOW_TWICE = 1, // Win32 - PLUGIN_QUIRK_THROTTLE_WM_USER_PLUS_ONE = 2, // Win32 - PLUGIN_QUIRK_DONT_CALL_WND_PROC_RECURSIVELY = 4, // Win32 - PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY = 8, // Win32 - PLUGIN_QUIRK_DONT_ALLOW_MULTIPLE_INSTANCES = 16, // Win32 - PLUGIN_QUIRK_DIE_AFTER_UNLOAD = 32, // Win32 - PLUGIN_QUIRK_PATCH_SETCURSOR = 64, // Win32 - PLUGIN_QUIRK_BLOCK_NONSTANDARD_GETURL_REQUESTS = 128, // Win32 - PLUGIN_QUIRK_WINDOWLESS_OFFSET_WINDOW_TO_DRAW = 256, // Linux - PLUGIN_QUIRK_WINDOWLESS_INVALIDATE_AFTER_SET_WINDOW = 512, // Linux - PLUGIN_QUIRK_NO_WINDOWLESS = 1024, // Windows - PLUGIN_QUIRK_PATCH_REGENUMKEYEXW = 2048, // Windows - PLUGIN_QUIRK_ALWAYS_NOTIFY_SUCCESS = 4096, // Windows - PLUGIN_QUIRK_ALLOW_FASTER_QUICKDRAW_PATH = 8192, // Mac - PLUGIN_QUIRK_HANDLE_MOUSE_CAPTURE = 16384, // Windows - PLUGIN_QUIRK_WINDOWLESS_NO_RIGHT_CLICK = 32768, // Linux - PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL = 65536, // Windows. - }; - - static WebPluginDelegateImpl* Create(const FilePath& filename, - const std::string& mime_type, - gfx::PluginWindowHandle containing_view); - - static bool IsPluginDelegateWindow(gfx::NativeWindow window); - static bool GetPluginNameFromWindow(gfx::NativeWindow window, - std::wstring *plugin_name); - - // Returns true if the window handle passed in is that of the dummy - // activation window for windowless plugins. - static bool IsDummyActivationWindow(gfx::NativeWindow window); - - // WebPluginDelegate implementation - virtual bool Initialize(const GURL& url, - const std::vector<std::string>& arg_names, - const std::vector<std::string>& arg_values, - webkit_glue::WebPlugin* plugin, - bool load_manually); - virtual void PluginDestroyed(); - virtual void UpdateGeometry(const gfx::Rect& window_rect, - const gfx::Rect& clip_rect); - virtual void Paint(WebKit::WebCanvas* canvas, const gfx::Rect& rect); - virtual void Print(gfx::NativeDrawingContext context); - virtual void SetFocus(bool focused); - virtual bool HandleInputEvent(const WebKit::WebInputEvent& event, - WebKit::WebCursorInfo* cursor_info); - virtual NPObject* GetPluginScriptableObject(); - virtual void DidFinishLoadWithReason( - const GURL& url, NPReason reason, int notify_id); - virtual int GetProcessId(); - virtual void SendJavaScriptStream(const GURL& url, - const std::string& result, - bool success, - int notify_id); - virtual void DidReceiveManualResponse(const GURL& url, - const std::string& mime_type, - const std::string& headers, - uint32 expected_length, - uint32 last_modified); - virtual void DidReceiveManualData(const char* buffer, int length); - virtual void DidFinishManualLoading(); - virtual void DidManualLoadFail(); - virtual void InstallMissingPlugin(); - virtual webkit_glue::WebPluginResourceClient* CreateResourceClient( - unsigned long resource_id, const GURL& url, int notify_id); - virtual webkit_glue::WebPluginResourceClient* CreateSeekableResourceClient( - unsigned long resource_id, int range_request_id); - // End of WebPluginDelegate implementation. - - bool IsWindowless() const { return windowless_ ; } - gfx::Rect GetRect() const { return window_rect_; } - gfx::Rect GetClipRect() const { return clip_rect_; } - - // Returns the path for the library implementing this plugin. - FilePath GetPluginPath(); - - // Returns a combination of PluginQuirks. - int GetQuirks() const { return quirks_; } - - // Informs the plugin that the view it is in has gained or lost focus. - void SetContentAreaHasFocus(bool has_focus); - -#if defined(OS_MACOSX) - // Informs the plugin that the geometry has changed, as with UpdateGeometry, - // but also includes the new buffer context for that new geometry. - void UpdateGeometryAndContext(const gfx::Rect& window_rect, - const gfx::Rect& clip_rect, - gfx::NativeDrawingContext context); - // Informs the delegate that the plugin called NPN_Invalidate*. Used as a - // trigger for Core Animation drawing. - void PluginDidInvalidate(); - // Returns the delegate currently processing events. - static WebPluginDelegateImpl* GetActiveDelegate(); - // Informs the plugin that the window it is in has gained or lost focus. - void SetWindowHasFocus(bool has_focus); - // Returns whether or not the window the plugin is in has focus. - bool GetWindowHasFocus() const { return containing_window_has_focus_; } - // Informs the plugin that its tab or window has been hidden or shown. - void SetContainerVisibility(bool is_visible); - // Informs the plugin that its containing window's frame has changed. - // Frames are in screen coordinates. - void WindowFrameChanged(const gfx::Rect& window_frame, - const gfx::Rect& view_frame); - // Informs the plugin that IME composition has been confirmed. - void ImeCompositionConfirmed(const string16& text); - // Informs the delegate that the plugin set a Carbon ThemeCursor. - void SetThemeCursor(ThemeCursor cursor); - // Informs the delegate that the plugin set a Carbon Cursor. - void SetCursor(const Cursor* cursor); - // Informs the delegate that the plugin set a Cocoa NSCursor. - void SetNSCursor(NSCursor* cursor); - -#ifndef NP_NO_CARBON - // Indicates that it's time to send the plugin a null event. - void FireIdleEvent(); -#endif -#endif // OS_MACOSX - - gfx::PluginWindowHandle windowed_handle() const { - return windowed_handle_; - } - -#if defined(OS_MACOSX) - // Allow setting a "fake" window handle to associate this plug-in with - // an IOSurface in the browser. Used for accelerated drawing surfaces. - void set_windowed_handle(gfx::PluginWindowHandle handle); -#endif - -#if defined(USE_X11) - void SetWindowlessShmPixmap(XID shm_pixmap) { - windowless_shm_pixmap_ = shm_pixmap; - } -#endif - - private: - friend class DeleteTask<WebPluginDelegateImpl>; - friend class webkit_glue::WebPluginDelegate; - - WebPluginDelegateImpl(gfx::PluginWindowHandle containing_view, - NPAPI::PluginInstance *instance); - ~WebPluginDelegateImpl(); - - // Called by Initialize() for platform-specific initialization. - // If this returns false, the plugin shouldn't be started--see Initialize(). - bool PlatformInitialize(); - - // Called by DestroyInstance(), used for platform-specific destruction. - void PlatformDestroyInstance(); - - //-------------------------- - // used for windowed plugins - void WindowedUpdateGeometry(const gfx::Rect& window_rect, - const gfx::Rect& clip_rect); - // Create the native window. - // Returns true if the window is created (or already exists). - // Returns false if unable to create the window. - bool WindowedCreatePlugin(); - - // Destroy the native window. - void WindowedDestroyWindow(); - - // Reposition the native window to be in sync with the given geometry. - // Returns true if the native window has moved or been clipped differently. - bool WindowedReposition(const gfx::Rect& window_rect, - const gfx::Rect& clip_rect); - - // Tells the plugin about the current state of the window. - // See NPAPI NPP_SetWindow for more information. - void WindowedSetWindow(); - -#if defined(OS_WIN) - // Registers the window class for our window - ATOM RegisterNativeWindowClass(); - - // Our WndProc functions. - static LRESULT CALLBACK DummyWindowProc( - HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - static LRESULT CALLBACK NativeWndProc( - HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); - static LRESULT CALLBACK FlashWindowlessWndProc( - HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); - - // Used for throttling Flash messages. - static void ClearThrottleQueueForWindow(HWND window); - static void OnThrottleMessage(); - static void ThrottleMessage(WNDPROC proc, HWND hwnd, UINT message, - WPARAM wParam, LPARAM lParam); -#endif - - //---------------------------- - // used for windowless plugins - void WindowlessUpdateGeometry(const gfx::Rect& window_rect, - const gfx::Rect& clip_rect); - void WindowlessPaint(gfx::NativeDrawingContext hdc, const gfx::Rect& rect); - - // Tells the plugin about the current state of the window. - // See NPAPI NPP_SetWindow for more information. - void WindowlessSetWindow(); - - // Informs the plugin that it has gained or lost keyboard focus (on the Mac, - // this just means window first responder status). - void SetPluginHasFocus(bool focused); - - // Handles the platform specific details of setting plugin focus. Returns - // false if the platform cancelled the focus tranfer. - bool PlatformSetPluginHasFocus(bool focused); - - //----------------------------------------- - // used for windowed and windowless plugins - - // Does platform-specific event handling. Arguments and return are identical - // to HandleInputEvent. - bool PlatformHandleInputEvent(const WebKit::WebInputEvent& event, - WebKit::WebCursorInfo* cursor_info); - - NPAPI::PluginInstance* instance() { return instance_.get(); } - - // Closes down and destroys our plugin instance. - void DestroyInstance(); - - - // used for windowed plugins - // Note: on Mac OS X, the only time the windowed handle is non-zero - // is the case of accelerated rendering, which uses a fake window handle to - // identify itself back to the browser. It still performs all of its - // work offscreen. - gfx::PluginWindowHandle windowed_handle_; - gfx::Rect windowed_last_pos_; - - bool windowed_did_set_window_; - - // used by windowed and windowless plugins - bool windowless_; - - webkit_glue::WebPlugin* plugin_; - scoped_refptr<NPAPI::PluginInstance> instance_; - -#if defined(OS_WIN) - // Original wndproc before we subclassed. - WNDPROC plugin_wnd_proc_; - - // Used to throttle WM_USER+1 messages in Flash. - uint32 last_message_; - bool is_calling_wndproc; - - // The current keyboard layout of this process and the main thread ID of the - // browser process. These variables are used for synchronizing the keyboard - // layout of this process with the one of the browser process. - HKL keyboard_layout_; - int parent_thread_id_; -#endif // defined(OS_WIN) - -#if defined(USE_X11) - // The SHM pixmap for a windowless plugin. - XID windowless_shm_pixmap_; - - // The pixmap we're drawing into, for a windowless plugin. - GdkPixmap* pixmap_; - double first_event_time_; - - // On Linux some plugins assume that the GtkSocket container is in the same - // process. So we create a GtkPlug to plug into the browser's container, and - // a GtkSocket to hold the plugin. We then send the GtkPlug to the browser - // process. - GtkWidget* plug_; - GtkWidget* socket_; - - // Ensure pixmap_ exists and is at least width by height pixels. - void EnsurePixmapAtLeastSize(int width, int height); -#endif - - gfx::PluginWindowHandle parent_; - NPWindow window_; - gfx::Rect window_rect_; - gfx::Rect clip_rect_; - int quirks_; - -#if defined(OS_WIN) - // Windowless plugins don't have keyboard focus causing issues with the - // plugin not receiving keyboard events if the plugin enters a modal - // loop like TrackPopupMenuEx or MessageBox, etc. - // This is a basic issue with windows activation and focus arising due to - // the fact that these windows are created by different threads. Activation - // and focus are thread specific states, and if the browser has focus, - // the plugin may not have focus. - // To fix a majority of these activation issues we create a dummy visible - // child window to which we set focus whenever the windowless plugin - // receives a WM_LBUTTONDOWN/WM_RBUTTONDOWN message via NPP_HandleEvent. - - HWND dummy_window_for_activation_; - bool CreateDummyWindowForActivation(); - - // Returns true if the event passed in needs to be tracked for a potential - // modal loop. - static bool ShouldTrackEventForModalLoops(NPEvent* event); - - // The message filter hook procedure, which tracks modal loops entered by - // a plugin in the course of a NPP_HandleEvent call. - static LRESULT CALLBACK HandleEventMessageFilterHook(int code, WPARAM wParam, - LPARAM lParam); - - // TrackPopupMenu interceptor. Parameters are the same as the Win32 function - // TrackPopupMenu. - static BOOL WINAPI TrackPopupMenuPatch(HMENU menu, unsigned int flags, int x, - int y, int reserved, HWND window, - const RECT* rect); - - // SetCursor interceptor for windowless plugins. - static HCURSOR WINAPI SetCursorPatch(HCURSOR cursor); - - // RegEnumKeyExW interceptor. - static LONG WINAPI RegEnumKeyExWPatch( - HKEY key, DWORD index, LPWSTR name, LPDWORD name_size, LPDWORD reserved, - LPWSTR class_name, LPDWORD class_size, PFILETIME last_write_time); - - // The mouse hook proc which handles mouse capture in windowed plugins. - static LRESULT CALLBACK MouseHookProc(int code, WPARAM wParam, - LPARAM lParam); - - // Calls SetCapture/ReleaseCapture based on the message type. - static void HandleCaptureForMessage(HWND window, UINT message); - -#elif defined(OS_MACOSX) - // Sets window_rect_ to |rect| - void SetPluginRect(const gfx::Rect& rect); - // Sets content_area_origin to |origin| - void SetContentAreaOrigin(const gfx::Point& origin); - // Updates everything that depends on the plugin's absolute screen location. - void PluginScreenLocationChanged(); - // Updates anything that depends on plugin visibility. - void PluginVisibilityChanged(); - - // Enables/disables IME. - void SetImeEnabled(bool enabled); - - // Informs the browser about the updated accelerated drawing surface. - void UpdateAcceleratedSurface(); - - // Uses a CARenderer to draw the plug-in's layer in our OpenGL surface. - void DrawLayerInSurface(); - -#ifndef NP_NO_CARBON - // Moves our dummy window to match the current screen location of the plugin. - void UpdateDummyWindowBounds(const gfx::Point& plugin_origin); - -#ifndef NP_NO_QUICKDRAW - // Sets the mode used for QuickDraw plugin drawing. If enabled is true the - // plugin draws into a GWorld that's not connected to a window (the faster - // path), otherwise the plugin draws into our invisible dummy window (which is - // slower, since the call we use to scrape the window contents is much more - // expensive than copying between GWorlds). - void SetQuickDrawFastPathEnabled(bool enabled); -#endif - - // Adjusts the idle event rate for a Carbon plugin based on its current - // visibility. - void UpdateIdleEventRate(); -#endif // !NP_NO_CARBON - - CGContextRef buffer_context_; // Weak ref. - -#ifndef NP_NO_CARBON - NP_CGContext np_cg_context_; -#endif -#ifndef NP_NO_QUICKDRAW - NP_Port qd_port_; - scoped_ptr<QuickDrawDrawingManager> qd_manager_; - base::TimeTicks fast_path_enable_tick_; -#endif - - CALayer* layer_; // Used for CA drawing mode. Weak, retained by plug-in. - webkit_glue::WebPluginAcceleratedSurface* surface_; // Weak ref. - CARenderer* renderer_; // Renders layer_ to surface_. - scoped_ptr<base::RepeatingTimer<WebPluginDelegateImpl> > redraw_timer_; - - // The upper-left corner of the web content area in screen coordinates, - // relative to an upper-left (0,0). - gfx::Point content_area_origin_; - - bool containing_window_has_focus_; - bool initial_window_focus_; - bool container_is_visible_; - bool have_called_set_window_; - - gfx::Rect cached_clip_rect_; - - bool ime_enabled_; - - scoped_ptr<ExternalDragTracker> external_drag_tracker_; -#endif // OS_MACOSX - - // Called by the message filter hook when the plugin enters a modal loop. - void OnModalLoopEntered(); - - // Returns true if the message passed in corresponds to a user gesture. - static bool IsUserGesture(const WebKit::WebInputEvent& event); - - // The url with which the plugin was instantiated. - std::string plugin_url_; - -#if defined(OS_WIN) - // Indicates the end of a user gesture period. - void OnUserGestureEnd(); - - // Handle to the message filter hook - HHOOK handle_event_message_filter_hook_; - - // Event which is set when the plugin enters a modal loop in the course - // of a NPP_HandleEvent call. - HANDLE handle_event_pump_messages_event_; - - // This flag indicates whether we started tracking a user gesture message. - bool user_gesture_message_posted_; - - // Runnable Method Factory used to invoke the OnUserGestureEnd method - // asynchronously. - ScopedRunnableMethodFactory<WebPluginDelegateImpl> user_gesture_msg_factory_; - - // Handle to the mouse hook installed for certain windowed plugins like - // flash. - HHOOK mouse_hook_; -#endif - - // Holds the depth of the HandleEvent callstack. - int handle_event_depth_; - - // Holds the current cursor set by the windowless plugin. - WebCursor current_windowless_cursor_; - - // Set to true initially and indicates if this is the first npp_setwindow - // call received by the plugin. - bool first_set_window_call_; - - // True if the plugin thinks it has keyboard focus - bool plugin_has_focus_; - // True if the plugin element has focus within the web content, regardless of - // whether its containing view currently has focus. - bool has_webkit_focus_; - // True if the containing view currently has focus. - // Initially set to true so that plugin focus still works in environments - // where SetContentAreaHasFocus is never called. See - // https://bugs.webkit.org/show_bug.cgi?id=46013 for details. - bool containing_view_has_focus_; - - // True if NPP_New did not return an error. - bool creation_succeeded_; - - DISALLOW_COPY_AND_ASSIGN(WebPluginDelegateImpl); -}; - -#endif // WEBKIT_GLUE_PLUGINS_WEBPLUGIN_DELEGATE_IMPL_H_ diff --git a/webkit/glue/plugins/webplugin_delegate_impl_gtk.cc b/webkit/glue/plugins/webplugin_delegate_impl_gtk.cc deleted file mode 100644 index 609b41e..0000000 --- a/webkit/glue/plugins/webplugin_delegate_impl_gtk.cc +++ /dev/null @@ -1,767 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "webkit/glue/plugins/webplugin_delegate_impl.h" - -#include <string> -#include <vector> - -#include <gtk/gtk.h> -#include <gdk/gdkx.h> - -#include "base/basictypes.h" -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/process_util.h" -#include "base/metrics/stats_counters.h" -#include "base/string_util.h" -#include "gfx/blit.h" -#include "skia/ext/platform_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "webkit/glue/plugins/gtk_plugin_container.h" -#include "webkit/glue/plugins/plugin_constants_win.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/plugin_stream_url.h" -#include "webkit/glue/plugins/webplugin.h" -#include "webkit/glue/webkit_glue.h" - -#include "third_party/npapi/bindings/npapi_x11.h" - -using WebKit::WebCursorInfo; -using WebKit::WebKeyboardEvent; -using WebKit::WebInputEvent; -using WebKit::WebMouseEvent; - -WebPluginDelegateImpl::WebPluginDelegateImpl( - gfx::PluginWindowHandle containing_view, - NPAPI::PluginInstance *instance) - : windowed_handle_(0), - windowed_did_set_window_(false), - windowless_(false), - plugin_(NULL), - instance_(instance), - windowless_shm_pixmap_(None), - pixmap_(NULL), - first_event_time_(-1.0), - plug_(NULL), - socket_(NULL), - parent_(containing_view), - quirks_(0), - handle_event_depth_(0), - first_set_window_call_(true), - plugin_has_focus_(false), - has_webkit_focus_(false), - containing_view_has_focus_(true), - creation_succeeded_(false) { - memset(&window_, 0, sizeof(window_)); - if (instance_->mime_type() == "application/x-shockwave-flash") { - // Flash is tied to Firefox's whacky behavior with windowless plugins. See - // comments in WindowlessPaint. - // TODO(viettrungluu): PLUGIN_QUIRK_WINDOWLESS_NO_RIGHT_CLICK: Don't allow - // right-clicks in windowless content since Flash 10.1 (initial release, at - // least) hangs in that case. Remove this once Flash is fixed. - quirks_ |= PLUGIN_QUIRK_WINDOWLESS_OFFSET_WINDOW_TO_DRAW - | PLUGIN_QUIRK_WINDOWLESS_INVALIDATE_AFTER_SET_WINDOW - | PLUGIN_QUIRK_WINDOWLESS_NO_RIGHT_CLICK; - } - - // TODO(evanm): I played with this for quite a while but couldn't - // figure out a way to make Flash not crash unless I didn't call - // NPP_SetWindow. - // However, after piman's grand refactor of windowed plugins, maybe - // this is no longer necessary. - quirks_ |= PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY; -} - -WebPluginDelegateImpl::~WebPluginDelegateImpl() { - DestroyInstance(); - - if (!windowless_) - WindowedDestroyWindow(); - - if (window_.ws_info) { - // We only ever use ws_info as an NPSetWindowCallbackStruct. - delete static_cast<NPSetWindowCallbackStruct*>(window_.ws_info); - } - - if (pixmap_) { - g_object_unref(pixmap_); - pixmap_ = NULL; - } -} - -bool WebPluginDelegateImpl::PlatformInitialize() { - gfx::PluginWindowHandle handle = - windowless_ ? 0 : gtk_plug_get_id(GTK_PLUG(plug_)); - plugin_->SetWindow(handle); - return true; -} - -void WebPluginDelegateImpl::PlatformDestroyInstance() { - // Nothing to do here. -} - -void WebPluginDelegateImpl::Paint(WebKit::WebCanvas* canvas, - const gfx::Rect& rect) { - if (!windowless_) - return; - cairo_t* context = canvas->beginPlatformPaint(); - WindowlessPaint(context, rect); - canvas->endPlatformPaint(); -} - -void WebPluginDelegateImpl::Print(cairo_t* context) { - NOTIMPLEMENTED(); -} - -void WebPluginDelegateImpl::InstallMissingPlugin() { - NOTIMPLEMENTED(); -} - -bool WebPluginDelegateImpl::WindowedCreatePlugin() { - DCHECK(!windowed_handle_); - DCHECK(!plug_); - - // NPP_GetValue() might write 4 bytes of data to this variable. Don't use a - // single byte bool, use an int instead and make sure it is initialized. - int xembed = 0; - NPError err = instance_->NPP_GetValue(NPPVpluginNeedsXEmbed, &xembed); - if (err != NPERR_NO_ERROR || !xembed) { - NOTIMPLEMENTED() << " windowed plugin but without xembed. " - "See http://code.google.com/p/chromium/issues/detail?id=38229"; - return false; - } - - // Passing 0 as the socket XID creates a plug without plugging it in a socket - // yet, so that it can be latter added with gtk_socket_add_id(). - plug_ = gtk_plug_new(0); - gtk_widget_show(plug_); - socket_ = gtk_socket_new(); - gtk_widget_show(socket_); - gtk_container_add(GTK_CONTAINER(plug_), socket_); - gtk_widget_show_all(plug_); - - // Prevent the plug from being destroyed if the browser kills the container - // window. - g_signal_connect(plug_, "delete-event", G_CALLBACK(gtk_true), NULL); - // Prevent the socket from being destroyed when the plugin removes itself. - g_signal_connect(socket_, "plug_removed", G_CALLBACK(gtk_true), NULL); - - windowed_handle_ = gtk_socket_get_id(GTK_SOCKET(socket_)); - - window_.window = reinterpret_cast<void*>(windowed_handle_); - - if (!window_.ws_info) - window_.ws_info = new NPSetWindowCallbackStruct; - NPSetWindowCallbackStruct* extra = - static_cast<NPSetWindowCallbackStruct*>(window_.ws_info); - extra->display = GDK_DISPLAY(); - extra->visual = DefaultVisual(GDK_DISPLAY(), 0); - extra->depth = DefaultDepth(GDK_DISPLAY(), 0); - extra->colormap = DefaultColormap(GDK_DISPLAY(), 0); - - return true; -} - -void WebPluginDelegateImpl::WindowedDestroyWindow() { - if (plug_) { - plugin_->WillDestroyWindow(gtk_plug_get_id(GTK_PLUG(plug_))); - - gtk_widget_destroy(plug_); - plug_ = NULL; - socket_ = NULL; - windowed_handle_ = 0; - } -} - -bool WebPluginDelegateImpl::WindowedReposition( - const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - if (window_rect == window_rect_ && clip_rect == clip_rect_) - return false; - - window_rect_ = window_rect; - clip_rect_ = clip_rect; - - return true; -} - -void WebPluginDelegateImpl::WindowedSetWindow() { - if (!instance_) - return; - - if (!windowed_handle_) { - NOTREACHED(); - return; - } - - // See https://bugzilla.mozilla.org/show_bug.cgi?id=108347 - // If we call NPP_SetWindow with a <= 0 width or height, problems arise in - // Flash (and possibly other plugins). - // TODO(piman): the Mozilla code suggests that for the Java plugin, we should - // still call NPP_SetWindow in that case. We need to verify that. - if (window_rect_.width() <= 0 || window_rect_.height() <= 0) { - return; - } - - instance()->set_window_handle(windowed_handle_); - - DCHECK(!instance()->windowless()); - - window_.clipRect.top = clip_rect_.y(); - window_.clipRect.left = clip_rect_.x(); - window_.clipRect.bottom = clip_rect_.y() + clip_rect_.height(); - window_.clipRect.right = clip_rect_.x() + clip_rect_.width(); - window_.height = window_rect_.height(); - window_.width = window_rect_.width(); - window_.x = window_rect_.x(); - window_.y = window_rect_.y(); - - //window_.window = windowed_handle_; - window_.type = NPWindowTypeWindow; - - // Reset this flag before entering the instance in case of side-effects. - windowed_did_set_window_ = true; - - NPError err = instance()->NPP_SetWindow(&window_); - DCHECK(err == NPERR_NO_ERROR); -} - -void WebPluginDelegateImpl::WindowlessUpdateGeometry( - const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - // Only resend to the instance if the geometry has changed. - if (window_rect == window_rect_ && clip_rect == clip_rect_) - return; - - clip_rect_ = clip_rect; - window_rect_ = window_rect; - WindowlessSetWindow(); -} - -void WebPluginDelegateImpl::EnsurePixmapAtLeastSize(int width, int height) { - if (pixmap_) { - gint cur_width, cur_height; - gdk_drawable_get_size(pixmap_, &cur_width, &cur_height); - if (cur_width >= width && cur_height >= height) - return; // We are already the appropriate size. - - // Otherwise, we need to recreate ourselves. - g_object_unref(pixmap_); - pixmap_ = NULL; - } - - // |sys_visual| is owned by gdk; we shouldn't free it. - GdkVisual* sys_visual = gdk_visual_get_system(); - pixmap_ = gdk_pixmap_new(NULL, // use width/height/depth params - std::max(1, width), std::max(1, height), - sys_visual->depth); - GdkColormap* colormap = gdk_colormap_new(gdk_visual_get_system(), - FALSE); - gdk_drawable_set_colormap(GDK_DRAWABLE(pixmap_), colormap); - // The GdkDrawable now owns the GdkColormap. - g_object_unref(colormap); -} - -#ifdef DEBUG_RECTANGLES -namespace { - -// Draw a rectangle on a Cairo context. -// Useful for debugging various rectangles involved in drawing plugins. -void DrawDebugRectangle(cairo_t* cairo, - const gfx::Rect& rect, - float r, float g, float b) { - cairo_set_source_rgba(cairo, r, g, b, 0.5); - cairo_rectangle(cairo, rect.x(), rect.y(), - rect.width(), rect.height()); - cairo_stroke(cairo); -} - -} // namespace -#endif - -void WebPluginDelegateImpl::WindowlessPaint(cairo_t* context, - const gfx::Rect& damage_rect) { - // Compare to: - // http://mxr.mozilla.org/firefox/source/layout/generic/nsObjectFrame.cpp: - // nsPluginInstanceOwner::Renderer::NativeDraw(). - - DCHECK(context); - - // TODO(darin): we should avoid calling NPP_SetWindow here since it may - // cause page layout to be invalidated. - - // The actual dirty region is just the intersection of the plugin window and - // the clip window with the damage region. However, the plugin wants to draw - // relative to the containing window's origin, so our pixmap must be from the - // window's origin down to the bottom-right edge of the dirty region. - // - // Typical case: - // X-----------------------------------+-----------------------------+ - // | | | - // | pixmap +-------------------+ | - // | | damage | window | - // | | | | - // | +---+-------------------+-------------+ | - // | | | | clip | | - // | +---+---+-------------------+----------+ | | - // | | | | | | | | - // | | | | draw | | | | - // | | | | | | | | - // +-------+---+---+-------------------+----------+--+ | - // | | | | | | - // | | +-------------------+ | | - // | | | | - // | | plugin | | - // | +--------------------------------------+ | - // | | - // | | - // +-----------------------------------------------------------------+ - // X = origin - // - // NPAPI doesn't properly define which coordinates each of - // - window.clipRect, window.x and window.y in the SetWindow call - // - x and y in GraphicsExpose HandleEvent call - // are relative to, nor does it define what the pixmap is relative to. - // - // Any sane values for them just don't work with the flash plugin. Firefox - // has some interesting behavior. Experiments showed that: - // - window.clipRect is always in the same space as window.x and window.y - // - in the first SetWindow call, or when scrolling, window.x and window.y are - // the coordinates of the plugin relative to the window. - // - whenever only a part of the plugin is drawn, Firefox issues a SetWindow - // call before each GraphicsExpose event, that sets the drawing origin to - // (0, 0) as if the plugin was scrolled to be partially out of the view. The - // GraphicsExpose event has coordinates relative to the "window" (assuming - // that virtual scroll). The pixmap is also relative to the window. It always - // sets the clip rect to the draw rect. - // - // Attempts to deviate from that makes Flash render at the wrong place in the - // pixmap, or render the wrong pixels. - // - // Flash plugin: - // X-----------------------------------------------------------------+ - // | | - // | +-------------------+ "real" window | - // | | damage | | - // | | | | - // | +---+-------------------+-------------+ | - // | | | | "real" clip | | - // | +---+---O===================#==========#==#===============# - // | | | H draw | | | H - // | | | H = pixmap | | | H - // | | | H = "apparent" clip | | | H - // | + +---#-------------------+----------+--+ H - // | | H | | H - // | | H-------------------+ | H - // | | H | H - // | | H plugin | H - // | +-------#------------------------------+ H - // | H H - // | H "apparent" window H - // +---------------#=================================================# - // X = "real" origin - // O = "apparent" origin - // "real" means as seen by Chrome - // "apparent" means as seen by the plugin. - - gfx::Rect draw_rect = window_rect_.Intersect(damage_rect); - - // clip_rect_ is relative to the plugin - gfx::Rect clip_rect_window = clip_rect_; - clip_rect_window.Offset(window_rect_.x(), window_rect_.y()); - draw_rect = draw_rect.Intersect(clip_rect_window); - - // These offsets represent by how much the view is shifted to accomodate - // Flash (the coordinates of X relative to O in the diagram above). - int offset_x = 0; - int offset_y = 0; - if (quirks_ & PLUGIN_QUIRK_WINDOWLESS_OFFSET_WINDOW_TO_DRAW) { - offset_x = -draw_rect.x(); - offset_y = -draw_rect.y(); - window_.clipRect.top = 0; - window_.clipRect.left = 0; - window_.clipRect.bottom = draw_rect.height(); - window_.clipRect.right = draw_rect.width(); - window_.height = window_rect_.height(); - window_.width = window_rect_.width(); - window_.x = window_rect_.x() - draw_rect.x(); - window_.y = window_rect_.y() - draw_rect.y(); - window_.type = NPWindowTypeDrawable; - DCHECK(window_.ws_info); - NPError err = instance()->NPP_SetWindow(&window_); - DCHECK_EQ(err, NPERR_NO_ERROR); - } - - gfx::Rect pixmap_draw_rect = draw_rect; - pixmap_draw_rect.Offset(offset_x, offset_y); - - gfx::Rect pixmap_rect(0, 0, - pixmap_draw_rect.right(), - pixmap_draw_rect.bottom()); - - // Construct the paint message, targeting the pixmap. - NPEvent np_event = {0}; - XGraphicsExposeEvent &event = np_event.xgraphicsexpose; - event.type = GraphicsExpose; - event.x = pixmap_draw_rect.x(); - event.y = pixmap_draw_rect.y(); - event.width = pixmap_draw_rect.width(); - event.height = pixmap_draw_rect.height(); - event.display = GDK_DISPLAY(); - - if (windowless_shm_pixmap_ != None) { - Pixmap pixmap = None; - GC xgc = NULL; - Display* display = event.display; - gfx::Rect plugin_draw_rect = draw_rect; - - // Make plugin_draw_rect relative to the plugin window. - plugin_draw_rect.Offset(-window_rect_.x(), -window_rect_.y()); - - // In case the drawing area does not start with the plugin window origin, - // we can not let the plugin directly draw over the shared memory pixmap. - if (plugin_draw_rect.x() != pixmap_draw_rect.x() || - plugin_draw_rect.y() != pixmap_draw_rect.y()) { - pixmap = XCreatePixmap(display, windowless_shm_pixmap_, - std::max(1, pixmap_rect.width()), - std::max(1, pixmap_rect.height()), - DefaultDepth(display, 0)); - xgc = XCreateGC(display, windowless_shm_pixmap_, 0, NULL); - // Copy the current image into the pixmap, so the plugin can draw over it. - XCopyArea(display, windowless_shm_pixmap_, pixmap, xgc, - plugin_draw_rect.x(), plugin_draw_rect.y(), - pixmap_draw_rect.width(), pixmap_draw_rect.height(), - pixmap_draw_rect.x(), pixmap_draw_rect.y()); - - event.drawable = pixmap; - } else { - event.drawable = windowless_shm_pixmap_; - } - - // Tell the plugin to paint into the pixmap. - static base::StatsRate plugin_paint("Plugin.Paint"); - base::StatsScope<base::StatsRate> scope(plugin_paint); - NPError err = instance()->NPP_HandleEvent(&np_event); - DCHECK_EQ(err, NPERR_NO_ERROR); - - if (pixmap != None) { - // Copy the rendered image pixmap back into the shm pixmap - // and thus the drawing buffer. - XCopyArea(display, pixmap, windowless_shm_pixmap_, xgc, - pixmap_draw_rect.x(), pixmap_draw_rect.y(), - pixmap_draw_rect.width(), pixmap_draw_rect.height(), - plugin_draw_rect.x(), plugin_draw_rect.y()); - XSync(display, FALSE); - if (xgc) - XFreeGC(display, xgc); - XFreePixmap(display, pixmap); - } else { - XSync(display, FALSE); - } - } else { - EnsurePixmapAtLeastSize(pixmap_rect.width(), pixmap_rect.height()); - - // Copy the current image into the pixmap, so the plugin can draw over - // this background. - cairo_t* cairo = gdk_cairo_create(pixmap_); - BlitContextToContext(cairo, pixmap_draw_rect, context, draw_rect.origin()); - cairo_destroy(cairo); - - event.drawable = GDK_PIXMAP_XID(pixmap_); - - // Tell the plugin to paint into the pixmap. - static base::StatsRate plugin_paint("Plugin.Paint"); - base::StatsScope<base::StatsRate> scope(plugin_paint); - NPError err = instance()->NPP_HandleEvent(&np_event); - DCHECK_EQ(err, NPERR_NO_ERROR); - - cairo_save(context); - // Now copy the rendered image pixmap back into the drawing buffer. - gdk_cairo_set_source_pixmap(context, pixmap_, -offset_x, -offset_y); - cairo_rectangle(context, draw_rect.x(), draw_rect.y(), - draw_rect.width(), draw_rect.height()); - cairo_clip(context); - cairo_paint(context); - -#ifdef DEBUG_RECTANGLES - // Draw some debugging rectangles. - // Pixmap rect = blue. - DrawDebugRectangle(context, pixmap_rect, 0, 0, 1); - // Drawing rect = red. - DrawDebugRectangle(context, draw_rect, 1, 0, 0); -#endif - cairo_restore(context); - } -} - -void WebPluginDelegateImpl::WindowlessSetWindow() { - if (!instance()) - return; - - if (window_rect_.IsEmpty()) // wait for geometry to be set. - return; - - DCHECK(instance()->windowless()); - // Mozilla docs say that this window param is not used for windowless - // plugins; rather, the window is passed during the GraphicsExpose event. - DCHECK(window_.window == 0); - - window_.clipRect.top = clip_rect_.y() + window_rect_.y(); - window_.clipRect.left = clip_rect_.x() + window_rect_.x(); - window_.clipRect.bottom = - clip_rect_.y() + clip_rect_.height() + window_rect_.y(); - window_.clipRect.right = - clip_rect_.x() + clip_rect_.width() + window_rect_.x(); - window_.height = window_rect_.height(); - window_.width = window_rect_.width(); - window_.x = window_rect_.x(); - window_.y = window_rect_.y(); - window_.type = NPWindowTypeDrawable; - - if (!window_.ws_info) - window_.ws_info = new NPSetWindowCallbackStruct; - NPSetWindowCallbackStruct* extra = - static_cast<NPSetWindowCallbackStruct*>(window_.ws_info); - extra->display = GDK_DISPLAY(); - extra->visual = DefaultVisual(GDK_DISPLAY(), 0); - extra->depth = DefaultDepth(GDK_DISPLAY(), 0); - extra->colormap = DefaultColormap(GDK_DISPLAY(), 0); - - NPError err = instance()->NPP_SetWindow(&window_); - DCHECK(err == NPERR_NO_ERROR); - if (quirks_ & PLUGIN_QUIRK_WINDOWLESS_INVALIDATE_AFTER_SET_WINDOW) { - // After a NPP_SetWindow, Flash cancels its timer that generates the - // invalidates until it gets a paint event, but doesn't explicitly call - // NPP_InvalidateRect. - plugin_->InvalidateRect(clip_rect_); - } -} - -bool WebPluginDelegateImpl::PlatformSetPluginHasFocus(bool focused) { - DCHECK(instance()->windowless()); - - NPEvent np_event = {0}; - XFocusChangeEvent &event = np_event.xfocus; - event.type = focused ? FocusIn : FocusOut; - event.display = GDK_DISPLAY(); - // Same values as Firefox. .serial and .window stay 0. - event.mode = -1; - event.detail = NotifyDetailNone; - instance()->NPP_HandleEvent(&np_event); - return true; -} - -// Converts a WebInputEvent::Modifiers bitfield into a -// corresponding X modifier state. -static int GetXModifierState(int modifiers) { - int x_state = 0; - if (modifiers & WebInputEvent::ControlKey) - x_state |= ControlMask; - if (modifiers & WebInputEvent::ShiftKey) - x_state |= ShiftMask; - if (modifiers & WebInputEvent::AltKey) - x_state |= Mod1Mask; - if (modifiers & WebInputEvent::MetaKey) - x_state |= Mod2Mask; - if (modifiers & WebInputEvent::LeftButtonDown) - x_state |= Button1Mask; - if (modifiers & WebInputEvent::MiddleButtonDown) - x_state |= Button2Mask; - if (modifiers & WebInputEvent::RightButtonDown) - x_state |= Button3Mask; - // TODO(piman@google.com): There are other modifiers, e.g. Num Lock, that - // should be set (and Firefox does), but we didn't keep the information in - // the WebKit event. - return x_state; -} - -static bool NPEventFromWebMouseEvent(const WebMouseEvent& event, - Time timestamp, - NPEvent *np_event) { - np_event->xany.display = GDK_DISPLAY(); - // NOTE: Firefox keeps xany.serial and xany.window as 0. - - int modifier_state = GetXModifierState(event.modifiers); - - Window root = GDK_ROOT_WINDOW(); - switch (event.type) { - case WebInputEvent::MouseMove: { - np_event->type = MotionNotify; - XMotionEvent &motion_event = np_event->xmotion; - motion_event.root = root; - motion_event.time = timestamp; - motion_event.x = event.x; - motion_event.y = event.y; - motion_event.x_root = event.globalX; - motion_event.y_root = event.globalY; - motion_event.state = modifier_state; - motion_event.is_hint = NotifyNormal; - motion_event.same_screen = True; - break; - } - case WebInputEvent::MouseLeave: - case WebInputEvent::MouseEnter: { - if (event.type == WebInputEvent::MouseEnter) { - np_event->type = EnterNotify; - } else { - np_event->type = LeaveNotify; - } - XCrossingEvent &crossing_event = np_event->xcrossing; - crossing_event.root = root; - crossing_event.time = timestamp; - crossing_event.x = event.x; - crossing_event.y = event.y; - crossing_event.x_root = event.globalX; - crossing_event.y_root = event.globalY; - crossing_event.mode = -1; // This is what Firefox sets it to. - crossing_event.detail = NotifyDetailNone; - crossing_event.same_screen = True; - // TODO(piman@google.com): set this to the correct value. Firefox does. I - // don't know where to get the information though, we get focus - // notifications, but no unfocus. - crossing_event.focus = 0; - crossing_event.state = modifier_state; - break; - } - case WebInputEvent::MouseUp: - case WebInputEvent::MouseDown: { - if (event.type == WebInputEvent::MouseDown) { - np_event->type = ButtonPress; - } else { - np_event->type = ButtonRelease; - } - XButtonEvent &button_event = np_event->xbutton; - button_event.root = root; - button_event.time = timestamp; - button_event.x = event.x; - button_event.y = event.y; - button_event.x_root = event.globalX; - button_event.y_root = event.globalY; - button_event.state = modifier_state; - switch (event.button) { - case WebMouseEvent::ButtonLeft: - button_event.button = Button1; - break; - case WebMouseEvent::ButtonMiddle: - button_event.button = Button2; - break; - case WebMouseEvent::ButtonRight: - button_event.button = Button3; - break; - default: - NOTREACHED(); - } - button_event.same_screen = True; - break; - } - default: - NOTREACHED(); - return false; - } - return true; -} - -static bool NPEventFromWebKeyboardEvent(const WebKeyboardEvent& event, - Time timestamp, - NPEvent *np_event) { - np_event->xany.display = GDK_DISPLAY(); - // NOTE: Firefox keeps xany.serial and xany.window as 0. - - switch (event.type) { - case WebKeyboardEvent::KeyDown: - np_event->type = KeyPress; - break; - case WebKeyboardEvent::KeyUp: - np_event->type = KeyRelease; - break; - default: - NOTREACHED(); - return false; - } - XKeyEvent &key_event = np_event->xkey; - key_event.send_event = False; - key_event.display = GDK_DISPLAY(); - // NOTE: Firefox keeps xany.serial and xany.window as 0. - // TODO(piman@google.com): is this right for multiple screens ? - key_event.root = DefaultRootWindow(key_event.display); - key_event.time = timestamp; - // NOTE: We don't have the correct information for x/y/x_root/y_root. Firefox - // doesn't have it either, so we pass the same values. - key_event.x = 0; - key_event.y = 0; - key_event.x_root = -1; - key_event.y_root = -1; - key_event.state = GetXModifierState(event.modifiers); - key_event.keycode = event.nativeKeyCode; - key_event.same_screen = True; - return true; -} - -static bool NPEventFromWebInputEvent(const WebInputEvent& event, - Time timestamp, - NPEvent* np_event) { - switch (event.type) { - case WebInputEvent::MouseMove: - case WebInputEvent::MouseLeave: - case WebInputEvent::MouseEnter: - case WebInputEvent::MouseDown: - case WebInputEvent::MouseUp: - if (event.size < sizeof(WebMouseEvent)) { - NOTREACHED(); - return false; - } - return NPEventFromWebMouseEvent( - *static_cast<const WebMouseEvent*>(&event), timestamp, np_event); - case WebInputEvent::KeyDown: - case WebInputEvent::KeyUp: - if (event.size < sizeof(WebKeyboardEvent)) { - NOTREACHED(); - return false; - } - return NPEventFromWebKeyboardEvent( - *static_cast<const WebKeyboardEvent*>(&event), timestamp, np_event); - default: - return false; - } -} - -bool WebPluginDelegateImpl::PlatformHandleInputEvent( - const WebInputEvent& event, WebCursorInfo* cursor_info) { - - if (first_event_time_ < 0.0) - first_event_time_ = event.timeStampSeconds; - Time timestamp = static_cast<Time>( - (event.timeStampSeconds - first_event_time_) * 1.0e3); - NPEvent np_event = {0}; - if (!NPEventFromWebInputEvent(event, timestamp, &np_event)) { - return false; - } - // See comment about PLUGIN_QUIRK_WINDOWLESS_NO_RIGHT_CLICK in constructor. - if (windowless_ && - (quirks_ & PLUGIN_QUIRK_WINDOWLESS_NO_RIGHT_CLICK) && - (np_event.type == ButtonPress || np_event.type == ButtonRelease) && - (np_event.xbutton.button == Button3)) { - return false; - } - - bool ret = instance()->NPP_HandleEvent(&np_event) != 0; - - // Flash always returns false, even when the event is handled. - ret = true; - -#if 0 - if (event->event == WM_MOUSEMOVE) { - // Snag a reference to the current cursor ASAP in case the plugin modified - // it. There is a nasty race condition here with the multiprocess browser - // as someone might be setting the cursor in the main process as well. - *cursor = current_windowless_cursor_; - } -#endif - - return ret; -} diff --git a/webkit/glue/plugins/webplugin_delegate_impl_mac.mm b/webkit/glue/plugins/webplugin_delegate_impl_mac.mm deleted file mode 100644 index 552484a..0000000 --- a/webkit/glue/plugins/webplugin_delegate_impl_mac.mm +++ /dev/null @@ -1,1145 +0,0 @@ -// 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. - -#import <Cocoa/Cocoa.h> -#import <QuartzCore/QuartzCore.h> - -#include "webkit/glue/plugins/webplugin_delegate_impl.h" - -#include <string> -#include <unistd.h> -#include <set> - -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/metrics/stats_counters.h" -#include "base/scoped_ptr.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "base/sys_string_conversions.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/plugin_stream_url.h" -#include "webkit/glue/plugins/plugin_web_event_converter_mac.h" -#include "webkit/glue/plugins/webplugin.h" -#include "webkit/glue/plugins/webplugin_accelerated_surface_mac.h" -#include "webkit/glue/webkit_glue.h" - -#ifndef NP_NO_CARBON -#include "webkit/glue/plugins/carbon_plugin_window_tracker_mac.h" -#endif - -#ifndef NP_NO_QUICKDRAW -#include "webkit/glue/plugins/quickdraw_drawing_manager_mac.h" -#endif - -using webkit_glue::WebPlugin; -using webkit_glue::WebPluginDelegate; -using webkit_glue::WebPluginResourceClient; -using WebKit::WebCursorInfo; -using WebKit::WebKeyboardEvent; -using WebKit::WebInputEvent; -using WebKit::WebMouseEvent; -using WebKit::WebMouseWheelEvent; - -const int kCoreAnimationRedrawPeriodMs = 10; // 100 Hz - -// Important implementation notes: The Mac definition of NPAPI, particularly -// the distinction between windowed and windowless modes, differs from the -// Windows and Linux definitions. Most of those differences are -// accomodated by the WebPluginDelegate class. - -namespace { - -WebPluginDelegateImpl* g_active_delegate; - -// Helper to simplify correct usage of g_active_delegate. Instantiating will -// set the active delegate to |delegate| for the lifetime of the object, then -// NULL when it goes out of scope. -class ScopedActiveDelegate { -public: - explicit ScopedActiveDelegate(WebPluginDelegateImpl* delegate) { - g_active_delegate = delegate; - } - ~ScopedActiveDelegate() { - g_active_delegate = NULL; - } -private: - DISALLOW_COPY_AND_ASSIGN(ScopedActiveDelegate); -}; - -#ifndef NP_NO_CARBON -// Timer periods for sending idle events to Carbon plugins. The visible value -// (50Hz) matches both Safari and Firefox. The hidden value (8Hz) matches -// Firefox; according to https://bugzilla.mozilla.org/show_bug.cgi?id=525533 -// going lower than that causes issues. -const int kVisibleIdlePeriodMs = 20; // (50Hz) -const int kHiddenIdlePeriodMs = 125; // (8Hz) - -class CarbonIdleEventSource { - public: - // Returns the shared Carbon idle event source. - static CarbonIdleEventSource* SharedInstance() { - DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI); - static CarbonIdleEventSource* event_source = new CarbonIdleEventSource(); - return event_source; - } - - // Registers the plugin delegate as interested in receiving idle events at - // a rate appropriate for the given visibility. A delegate can safely be - // re-registered any number of times, with the latest registration winning. - void RegisterDelegate(WebPluginDelegateImpl* delegate, bool visible) { - if (visible) { - visible_delegates_->RegisterDelegate(delegate); - hidden_delegates_->UnregisterDelegate(delegate); - } else { - hidden_delegates_->RegisterDelegate(delegate); - visible_delegates_->UnregisterDelegate(delegate); - } - } - - // Removes the plugin delegate from the list of plugins receiving idle events. - void UnregisterDelegate(WebPluginDelegateImpl* delegate) { - visible_delegates_->UnregisterDelegate(delegate); - hidden_delegates_->UnregisterDelegate(delegate); - } - - private: - class VisibilityGroup { - public: - explicit VisibilityGroup(int timer_period) - : timer_period_(timer_period), iterator_(delegates_.end()) {} - - // Adds |delegate| to this visibility group. - void RegisterDelegate(WebPluginDelegateImpl* delegate) { - if (delegates_.empty()) { - timer_.Start(base::TimeDelta::FromMilliseconds(timer_period_), - this, &VisibilityGroup::SendIdleEvents); - } - delegates_.insert(delegate); - } - - // Removes |delegate| from this visibility group. - void UnregisterDelegate(WebPluginDelegateImpl* delegate) { - // If a plugin changes visibility during idle event handling, it - // may be removed from this set while SendIdleEvents is still iterating; - // if that happens and it's next on the list, increment the iterator - // before erasing so that the iteration won't be corrupted. - if ((iterator_ != delegates_.end()) && (*iterator_ == delegate)) - ++iterator_; - size_t removed = delegates_.erase(delegate); - if (removed > 0 && delegates_.empty()) - timer_.Stop(); - } - - private: - // Fires off idle events for each delegate in the group. - void SendIdleEvents() { - for (iterator_ = delegates_.begin(); iterator_ != delegates_.end();) { - // Pre-increment so that the skip logic in UnregisterDelegates works. - WebPluginDelegateImpl* delegate = *(iterator_++); - delegate->FireIdleEvent(); - } - } - - int timer_period_; - base::RepeatingTimer<VisibilityGroup> timer_; - std::set<WebPluginDelegateImpl*> delegates_; - std::set<WebPluginDelegateImpl*>::iterator iterator_; - }; - - CarbonIdleEventSource() - : visible_delegates_(new VisibilityGroup(kVisibleIdlePeriodMs)), - hidden_delegates_(new VisibilityGroup(kHiddenIdlePeriodMs)) {} - - scoped_ptr<VisibilityGroup> visible_delegates_; - scoped_ptr<VisibilityGroup> hidden_delegates_; - - DISALLOW_COPY_AND_ASSIGN(CarbonIdleEventSource); -}; -#endif // !NP_NO_CARBON - -} // namespace - -// Helper to build and maintain a model of a drag entering the plugin but not -// starting there. See explanation in PlatformHandleInputEvent. -class ExternalDragTracker { - public: - ExternalDragTracker() : pressed_buttons_(0) {} - - // Returns true if an external drag is in progress. - bool IsDragInProgress() { return pressed_buttons_ != 0; }; - - // Returns true if the given event appears to be related to an external drag. - bool EventIsRelatedToDrag(const WebInputEvent& event); - - // Updates the tracking of whether an external drag is in progress--and if - // so what buttons it involves--based on the given event. - void UpdateDragStateFromEvent(const WebInputEvent& event); - - private: - // Returns the mask for just the button state in a WebInputEvent's modifiers. - static int WebEventButtonModifierMask(); - - // The WebInputEvent modifier flags for any buttons that were down when an - // external drag entered the plugin, and which and are still down now. - int pressed_buttons_; - - DISALLOW_COPY_AND_ASSIGN(ExternalDragTracker); -}; - -void ExternalDragTracker::UpdateDragStateFromEvent(const WebInputEvent& event) { - switch (event.type) { - case WebInputEvent::MouseEnter: - pressed_buttons_ = event.modifiers & WebEventButtonModifierMask(); - break; - case WebInputEvent::MouseUp: { - const WebMouseEvent* mouse_event = - static_cast<const WebMouseEvent*>(&event); - if (mouse_event->button == WebMouseEvent::ButtonLeft) - pressed_buttons_ &= ~WebInputEvent::LeftButtonDown; - if (mouse_event->button == WebMouseEvent::ButtonMiddle) - pressed_buttons_ &= ~WebInputEvent::MiddleButtonDown; - if (mouse_event->button == WebMouseEvent::ButtonRight) - pressed_buttons_ &= ~WebInputEvent::RightButtonDown; - break; - } - default: - break; - } -} - -bool ExternalDragTracker::EventIsRelatedToDrag(const WebInputEvent& event) { - const WebMouseEvent* mouse_event = static_cast<const WebMouseEvent*>(&event); - switch (event.type) { - case WebInputEvent::MouseUp: - // We only care about release of buttons that were part of the drag. - return ((mouse_event->button == WebMouseEvent::ButtonLeft && - (pressed_buttons_ & WebInputEvent::LeftButtonDown)) || - (mouse_event->button == WebMouseEvent::ButtonMiddle && - (pressed_buttons_ & WebInputEvent::MiddleButtonDown)) || - (mouse_event->button == WebMouseEvent::ButtonRight && - (pressed_buttons_ & WebInputEvent::RightButtonDown))); - case WebInputEvent::MouseEnter: - return (event.modifiers & WebEventButtonModifierMask()) != 0; - case WebInputEvent::MouseLeave: - case WebInputEvent::MouseMove: { - int event_buttons = (event.modifiers & WebEventButtonModifierMask()); - return (pressed_buttons_ && - pressed_buttons_ == event_buttons); - } - default: - return false; - } - return false; -} - -int ExternalDragTracker::WebEventButtonModifierMask() { - return WebInputEvent::LeftButtonDown | - WebInputEvent::RightButtonDown | - WebInputEvent::MiddleButtonDown; -} - -#pragma mark - -#pragma mark Core WebPluginDelegate implementation - -WebPluginDelegateImpl::WebPluginDelegateImpl( - gfx::PluginWindowHandle containing_view, - NPAPI::PluginInstance *instance) - : windowed_handle_(NULL), - // all Mac plugins are "windowless" in the Windows/X11 sense - windowless_(true), - plugin_(NULL), - instance_(instance), - parent_(containing_view), - quirks_(0), - buffer_context_(NULL), - layer_(nil), - surface_(NULL), - renderer_(nil), - containing_window_has_focus_(false), - initial_window_focus_(false), - container_is_visible_(false), - have_called_set_window_(false), - ime_enabled_(false), - external_drag_tracker_(new ExternalDragTracker()), - handle_event_depth_(0), - first_set_window_call_(true), - plugin_has_focus_(false), - has_webkit_focus_(false), - containing_view_has_focus_(true), - creation_succeeded_(false) { - memset(&window_, 0, sizeof(window_)); -#ifndef NP_NO_CARBON - memset(&np_cg_context_, 0, sizeof(np_cg_context_)); -#endif -#ifndef NP_NO_QUICKDRAW - memset(&qd_port_, 0, sizeof(qd_port_)); -#endif - instance->set_windowless(true); -} - -WebPluginDelegateImpl::~WebPluginDelegateImpl() { - DestroyInstance(); - -#ifndef NP_NO_CARBON - if (np_cg_context_.window) { - CarbonPluginWindowTracker::SharedInstance()->DestroyDummyWindowForDelegate( - this, reinterpret_cast<WindowRef>(np_cg_context_.window)); - } -#endif -} - -bool WebPluginDelegateImpl::PlatformInitialize() { - // Don't set a NULL window handle on destroy for Mac plugins. This matches - // Safari and other Mac browsers (see PluginView::stop() in PluginView.cpp, - // where code to do so is surrounded by an #ifdef that excludes Mac OS X, or - // destroyPlugin in WebNetscapePluginView.mm, for examples). - quirks_ |= PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY; - - // Mac plugins don't expect to be unloaded, and they don't always do so - // cleanly, so don't unload them at shutdown. - instance()->plugin_lib()->PreventLibraryUnload(); - -#ifndef NP_NO_QUICKDRAW - if (instance()->drawing_model() == NPDrawingModelQuickDraw) { - // For some QuickDraw plugins, we can sometimes get away with giving them - // a port pointing to a pixel buffer instead of a our actual dummy window. - // This gives us much better frame rates, because the window scraping we - // normally use is very slow. - // This breaks down if the plugin does anything complicated with the port - // (as QuickTime seems to during event handling, and sometimes when painting - // its controls), so we switch on the fly as necessary. (It might be - // possible to interpose sufficiently that we wouldn't have to switch back - // and forth, but the current approach gets us most of the benefit.) - // We can't do this at all with plugins that bypass the port entirely and - // attaches their own surface to the window. - // TODO(stuartmorgan): Test other QuickDraw plugins that we support and - // see if any others can use the fast path. - const WebPluginInfo& plugin_info = instance_->plugin_lib()->plugin_info(); - if (plugin_info.name.find(ASCIIToUTF16("QuickTime")) != string16::npos) - quirks_ |= PLUGIN_QUIRK_ALLOW_FASTER_QUICKDRAW_PATH; - } -#endif - -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon) { - // Create a stand-in for the browser window so that the plugin will have - // a non-NULL WindowRef to which it can refer. - CarbonPluginWindowTracker* window_tracker = - CarbonPluginWindowTracker::SharedInstance(); - np_cg_context_.window = window_tracker->CreateDummyWindowForDelegate(this); - np_cg_context_.context = NULL; - UpdateDummyWindowBounds(gfx::Point(0, 0)); - } -#endif - - NPDrawingModel drawing_model = instance()->drawing_model(); - switch (drawing_model) { -#ifndef NP_NO_QUICKDRAW - case NPDrawingModelQuickDraw: - if (instance()->event_model() != NPEventModelCarbon) - return false; - qd_manager_.reset(new QuickDrawDrawingManager()); - qd_manager_->SetPluginWindow( - reinterpret_cast<WindowRef>(np_cg_context_.window)); - qd_port_.port = qd_manager_->port(); - window_.window = &qd_port_; - window_.type = NPWindowTypeDrawable; - break; -#endif - case NPDrawingModelCoreGraphics: -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon) - window_.window = &np_cg_context_; -#endif - window_.type = NPWindowTypeDrawable; - break; - case NPDrawingModelCoreAnimation: - case NPDrawingModelInvalidatingCoreAnimation: { - if (instance()->event_model() != NPEventModelCocoa) - return false; - window_.type = NPWindowTypeDrawable; - // Ask the plug-in for the CALayer it created for rendering content. - // Create a surface to host it, and request a "window" handle to identify - // the surface. - CALayer* layer = nil; - NPError err = instance()->NPP_GetValue(NPPVpluginCoreAnimationLayer, - reinterpret_cast<void*>(&layer)); - if (!err) { - if (drawing_model == NPDrawingModelCoreAnimation) { - // Create the timer; it will be started when we get a window handle. - redraw_timer_.reset(new base::RepeatingTimer<WebPluginDelegateImpl>); - } - layer_ = layer; - surface_ = plugin_->GetAcceleratedSurface(); - - // If surface initialization fails for some reason, just continue - // without any drawing; returning false would be a more confusing user - // experience (since it triggers a missing plugin placeholder). - if (surface_->context()) { - renderer_ = [[CARenderer rendererWithCGLContext:surface_->context() - options:NULL] retain]; - [renderer_ setLayer:layer_]; - } - plugin_->BindFakePluginWindowHandle(false); - } - break; - } - default: - NOTREACHED(); - break; - } - - // Let the WebPlugin know that we are windowless (unless this is a - // Core Animation plugin, in which case BindFakePluginWindowHandle will take - // care of setting up the appropriate window handle). - if (!layer_) - plugin_->SetWindow(NULL); - -#ifndef NP_NO_CARBON - // If the plugin wants Carbon events, hook up to the source of idle events. - if (instance()->event_model() == NPEventModelCarbon) - UpdateIdleEventRate(); -#endif - - // QuickTime (in QD mode only) can crash if it gets other calls (e.g., - // NPP_Write) before it gets a SetWindow call, so call SetWindow (with a 0x0 - // rect) immediately. -#ifndef NP_NO_QUICKDRAW - if (instance()->drawing_model() == NPDrawingModelQuickDraw) { - const WebPluginInfo& plugin_info = instance_->plugin_lib()->plugin_info(); - if (plugin_info.name.find(ASCIIToUTF16("QuickTime")) != string16::npos) - WindowlessSetWindow(); - } -#endif - - return true; -} - -void WebPluginDelegateImpl::PlatformDestroyInstance() { -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon) - CarbonIdleEventSource::SharedInstance()->UnregisterDelegate(this); -#endif - if (redraw_timer_.get()) - redraw_timer_->Stop(); - [renderer_ release]; - renderer_ = nil; - layer_ = nil; -} - -void WebPluginDelegateImpl::UpdateGeometryAndContext( - const gfx::Rect& window_rect, const gfx::Rect& clip_rect, - CGContextRef context) { - buffer_context_ = context; -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon) { - // Update the structure that is passed to Carbon+CoreGraphics plugins in - // NPP_SetWindow before calling UpdateGeometry, since that will trigger an - // NPP_SetWindow call if the geometry changes (which is the only time the - // context would be different), and some plugins (e.g., Flash) have an - // internal cache of the context that they only update when NPP_SetWindow - // is called. - np_cg_context_.context = context; - } -#endif -#ifndef NP_NO_QUICKDRAW - if (instance()->drawing_model() == NPDrawingModelQuickDraw) - qd_manager_->SetTargetContext(context, window_rect.size()); -#endif - UpdateGeometry(window_rect, clip_rect); -} - -void WebPluginDelegateImpl::Paint(CGContextRef context, const gfx::Rect& rect) { - WindowlessPaint(context, rect); - -#ifndef NP_NO_QUICKDRAW - // Paint events are our cue to dump the current plugin bits into the buffer - // context if we are dealing with a QuickDraw plugin. - if (instance()->drawing_model() == NPDrawingModelQuickDraw) { - qd_manager_->UpdateContext(); - } -#endif -} - -void WebPluginDelegateImpl::Print(CGContextRef context) { - NOTIMPLEMENTED(); -} - -bool WebPluginDelegateImpl::PlatformHandleInputEvent( - const WebInputEvent& event, WebCursorInfo* cursor_info) { - DCHECK(cursor_info != NULL); - - // If we get an event before we've set up the plugin, bail. - if (!have_called_set_window_) - return false; -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon && - !np_cg_context_.context) { - return false; - } -#endif - - if (WebInputEvent::isMouseEventType(event.type) || - event.type == WebInputEvent::MouseWheel) { - // Check our plugin location before we send the event to the plugin, just - // in case we somehow missed a plugin frame change. - const WebMouseEvent* mouse_event = - static_cast<const WebMouseEvent*>(&event); - gfx::Point content_origin( - mouse_event->globalX - mouse_event->x - window_rect_.x(), - mouse_event->globalY - mouse_event->y - window_rect_.y()); - if (content_origin.x() != content_area_origin_.x() || - content_origin.y() != content_area_origin_.y()) { - DLOG(WARNING) << "Stale plugin content area location: " - << content_area_origin_ << " instead of " - << content_origin; - SetContentAreaOrigin(content_origin); - } - - current_windowless_cursor_.GetCursorInfo(cursor_info); - } - -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon) { -#ifndef NP_NO_QUICKDRAW - if (instance()->drawing_model() == NPDrawingModelQuickDraw) { - if (quirks_ & PLUGIN_QUIRK_ALLOW_FASTER_QUICKDRAW_PATH) { - // Mouse event handling doesn't work correctly in the fast path mode, - // so any time we get a mouse event turn the fast path off, but set a - // time to switch it on again (we don't rely just on MouseLeave because - // we don't want poor performance in the case of clicking the play - // button and then leaving the mouse there). - // This isn't perfect (specifically, click-and-hold doesn't seem to work - // if the fast path is on), but the slight regression is worthwhile - // for the improved framerates. - if (WebInputEvent::isMouseEventType(event.type)) { - if (event.type == WebInputEvent::MouseLeave) { - SetQuickDrawFastPathEnabled(true); - } else { - SetQuickDrawFastPathEnabled(false); - } - // Make sure the plugin wasn't destroyed during the switch. - if (!instance()) - return false; - } - } - - qd_manager_->MakePortCurrent(); - } -#endif - - if (event.type == WebInputEvent::MouseMove) { - return true; // The recurring FireIdleEvent will send null events. - } - } -#endif - - ScopedActiveDelegate active_delegate(this); - - // Create the plugin event structure. - NPEventModel event_model = instance()->event_model(); - scoped_ptr<PluginWebEventConverter> event_converter( - PluginWebEventConverterFactory::CreateConverterForModel(event_model)); - if (!(event_converter.get() && event_converter->InitWithEvent(event))) { - // Silently consume any keyboard event types that we don't handle, so that - // they don't fall through to the page. - if (WebInputEvent::isKeyboardEventType(event.type)) - return true; - return false; - } - void* plugin_event = event_converter->plugin_event(); - - if (instance()->event_model() == NPEventModelCocoa) { - // We recieve events related to drags starting outside the plugin, but the - // NPAPI Cocoa event model spec says plugins shouldn't receive them, so - // filter them out. - // If we add a page capture mode at the WebKit layer (like the plugin - // capture mode that handles drags starting inside) this can be removed. - bool drag_related = external_drag_tracker_->EventIsRelatedToDrag(event); - external_drag_tracker_->UpdateDragStateFromEvent(event); - if (drag_related) { - if (event.type == WebInputEvent::MouseUp && - !external_drag_tracker_->IsDragInProgress()) { - // When an external drag ends, we need to synthesize a MouseEntered. - NPCocoaEvent enter_event = *(static_cast<NPCocoaEvent*>(plugin_event)); - enter_event.type = NPCocoaEventMouseEntered; - NPAPI::ScopedCurrentPluginEvent event_scope(instance(), &enter_event); - instance()->NPP_HandleEvent(&enter_event); - } - return false; - } - } - - // Send the plugin the event. - scoped_ptr<NPAPI::ScopedCurrentPluginEvent> event_scope(NULL); - if (instance()->event_model() == NPEventModelCocoa) { - event_scope.reset(new NPAPI::ScopedCurrentPluginEvent( - instance(), static_cast<NPCocoaEvent*>(plugin_event))); - } - int16_t handle_response = instance()->NPP_HandleEvent(plugin_event); - bool handled = handle_response != kNPEventNotHandled; - - if (handled && event.type == WebInputEvent::KeyDown) { - // Update IME state as requested by the plugin. - SetImeEnabled(handle_response == kNPEventStartIME); - } - - // Plugins don't give accurate information about whether or not they handled - // events, so browsers on the Mac ignore the return value. - // Scroll events are the exception, since the Cocoa spec defines a meaning - // for the return value. - if (WebInputEvent::isMouseEventType(event.type)) { - handled = true; - } else if (WebInputEvent::isKeyboardEventType(event.type)) { - // For Command-key events, trust the return value since eating all menu - // shortcuts is not ideal. - // TODO(stuartmorgan): Implement the advanced key handling spec, and trust - // trust the key event return value from plugins that implement it. - if (!(event.modifiers & WebInputEvent::MetaKey)) - handled = true; - } - - return handled; -} - -void WebPluginDelegateImpl::InstallMissingPlugin() { - NOTIMPLEMENTED(); -} - -#pragma mark - - -void WebPluginDelegateImpl::WindowlessUpdateGeometry( - const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - gfx::Rect old_clip_rect = clip_rect_; - cached_clip_rect_ = clip_rect; - if (container_is_visible_) // Remove check when cached_clip_rect_ is removed. - clip_rect_ = clip_rect; - bool clip_rect_changed = (clip_rect_ != old_clip_rect); - bool window_size_changed = (window_rect.size() != window_rect_.size()); - - bool force_set_window = false; -#ifndef NP_NO_QUICKDRAW - // In a QuickDraw plugin, a geometry update might have caused a port change; - // if so, we need to call SetWindow even if nothing else changed. - if (qd_manager_.get() && (qd_port_.port != qd_manager_->port())) { - qd_port_.port = qd_manager_->port(); - force_set_window = true; - } -#endif - - if (window_rect == window_rect_ && !clip_rect_changed && !force_set_window) - return; - - if (old_clip_rect.IsEmpty() != clip_rect_.IsEmpty()) { - PluginVisibilityChanged(); - } - - SetPluginRect(window_rect); - -#ifndef NP_NO_QUICKDRAW - if (window_size_changed && qd_manager_.get() && - qd_manager_->IsFastPathEnabled()) { - // If the window size has changed, we need to turn off the fast path so that - // the full redraw goes to the window and we get a correct baseline paint. - SetQuickDrawFastPathEnabled(false); - return; // SetQuickDrawFastPathEnabled will call SetWindow for us. - } -#endif - - if (window_size_changed || clip_rect_changed || force_set_window) - WindowlessSetWindow(); -} - -void WebPluginDelegateImpl::WindowlessPaint(gfx::NativeDrawingContext context, - const gfx::Rect& damage_rect) { - // If we get a paint event before we are completely set up (e.g., a nested - // call while the plugin is still in NPP_SetWindow), bail. - if (!have_called_set_window_ || !buffer_context_) - return; - DCHECK(buffer_context_ == context); - - static base::StatsRate plugin_paint("Plugin.Paint"); - base::StatsScope<base::StatsRate> scope(plugin_paint); - - // Plugin invalidates trigger asynchronous paints with the original - // invalidation rect; the plugin may be resized before the paint is handled, - // so we need to ensure that the damage rect is still sane. - const gfx::Rect paint_rect(damage_rect.Intersect( - gfx::Rect(0, 0, window_rect_.width(), window_rect_.height()))); - - ScopedActiveDelegate active_delegate(this); - -#ifndef NP_NO_QUICKDRAW - if (instance()->drawing_model() == NPDrawingModelQuickDraw) - qd_manager_->MakePortCurrent(); -#endif - - CGContextSaveGState(context); - - switch (instance()->event_model()) { -#ifndef NP_NO_CARBON - case NPEventModelCarbon: { - NPEvent paint_event = { 0 }; - paint_event.what = updateEvt; - paint_event.message = reinterpret_cast<uint32>(np_cg_context_.window); - paint_event.when = TickCount(); - instance()->NPP_HandleEvent(&paint_event); - break; - } -#endif - case NPEventModelCocoa: { - NPCocoaEvent paint_event; - memset(&paint_event, 0, sizeof(NPCocoaEvent)); - paint_event.type = NPCocoaEventDrawRect; - paint_event.data.draw.context = context; - paint_event.data.draw.x = paint_rect.x(); - paint_event.data.draw.y = paint_rect.y(); - paint_event.data.draw.width = paint_rect.width(); - paint_event.data.draw.height = paint_rect.height(); - instance()->NPP_HandleEvent(&paint_event); - break; - } - } - - // The backing buffer can change during the call to NPP_HandleEvent, in which - // case the old context is (or is about to be) invalid. - if (context == buffer_context_) - CGContextRestoreGState(context); -} - -void WebPluginDelegateImpl::WindowlessSetWindow() { - if (!instance()) - return; - - window_.x = 0; - window_.y = 0; - window_.height = window_rect_.height(); - window_.width = window_rect_.width(); - window_.clipRect.left = clip_rect_.x(); - window_.clipRect.top = clip_rect_.y(); - window_.clipRect.right = clip_rect_.x() + clip_rect_.width(); - window_.clipRect.bottom = clip_rect_.y() + clip_rect_.height(); - - NPError err = instance()->NPP_SetWindow(&window_); - - // Send an appropriate window focus event after the first SetWindow. - if (!have_called_set_window_) { - have_called_set_window_ = true; - SetWindowHasFocus(initial_window_focus_); - } - -#ifndef NP_NO_QUICKDRAW - if ((quirks_ & PLUGIN_QUIRK_ALLOW_FASTER_QUICKDRAW_PATH) && - !qd_manager_->IsFastPathEnabled() && !clip_rect_.IsEmpty()) { - // Give the plugin a few seconds to stabilize so we get a good initial paint - // to use as a baseline, then switch to the fast path. - fast_path_enable_tick_ = base::TimeTicks::Now() + - base::TimeDelta::FromSeconds(3); - } -#endif - - DCHECK(err == NPERR_NO_ERROR); -} - -#pragma mark - - -bool WebPluginDelegateImpl::WindowedCreatePlugin() { - NOTREACHED(); - return false; -} - -void WebPluginDelegateImpl::WindowedDestroyWindow() { - NOTREACHED(); -} - -bool WebPluginDelegateImpl::WindowedReposition(const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - NOTREACHED(); - return false; -} - -void WebPluginDelegateImpl::WindowedSetWindow() { - NOTREACHED(); -} - -#pragma mark - -#pragma mark Mac Extensions - -void WebPluginDelegateImpl::PluginDidInvalidate() { - if (instance()->drawing_model() == NPDrawingModelInvalidatingCoreAnimation) - DrawLayerInSurface(); -} - -WebPluginDelegateImpl* WebPluginDelegateImpl::GetActiveDelegate() { - return g_active_delegate; -} - -void WebPluginDelegateImpl::SetWindowHasFocus(bool has_focus) { - // If we get a window focus event before calling SetWindow, just remember the - // states (WindowlessSetWindow will then send it on the first call). - if (!have_called_set_window_) { - initial_window_focus_ = has_focus; - return; - } - - if (has_focus == containing_window_has_focus_) - return; - containing_window_has_focus_ = has_focus; - - if (!has_focus) - SetImeEnabled(false); - -#ifndef NP_NO_QUICKDRAW - // Make sure controls repaint with the correct look. - if (quirks_ & PLUGIN_QUIRK_ALLOW_FASTER_QUICKDRAW_PATH) - SetQuickDrawFastPathEnabled(false); -#endif - - ScopedActiveDelegate active_delegate(this); - switch (instance()->event_model()) { -#ifndef NP_NO_CARBON - case NPEventModelCarbon: { - NPEvent focus_event = { 0 }; - focus_event.what = activateEvt; - if (has_focus) - focus_event.modifiers |= activeFlag; - focus_event.message = - reinterpret_cast<unsigned long>(np_cg_context_.window); - focus_event.when = TickCount(); - instance()->NPP_HandleEvent(&focus_event); - break; - } -#endif - case NPEventModelCocoa: { - NPCocoaEvent focus_event; - memset(&focus_event, 0, sizeof(focus_event)); - focus_event.type = NPCocoaEventWindowFocusChanged; - focus_event.data.focus.hasFocus = has_focus; - instance()->NPP_HandleEvent(&focus_event); - break; - } - } -} - -bool WebPluginDelegateImpl::PlatformSetPluginHasFocus(bool focused) { - if (!have_called_set_window_) - return false; - - if (!focused) - SetImeEnabled(false); - - ScopedActiveDelegate active_delegate(this); - - switch (instance()->event_model()) { -#ifndef NP_NO_CARBON - case NPEventModelCarbon: { - NPEvent focus_event = { 0 }; - if (focused) - focus_event.what = NPEventType_GetFocusEvent; - else - focus_event.what = NPEventType_LoseFocusEvent; - focus_event.when = TickCount(); - instance()->NPP_HandleEvent(&focus_event); - break; - } -#endif - case NPEventModelCocoa: { - NPCocoaEvent focus_event; - memset(&focus_event, 0, sizeof(focus_event)); - focus_event.type = NPCocoaEventFocusChanged; - focus_event.data.focus.hasFocus = focused; - instance()->NPP_HandleEvent(&focus_event); - break; - } - } - return true; -} - -void WebPluginDelegateImpl::SetContainerVisibility(bool is_visible) { - if (is_visible == container_is_visible_) - return; - container_is_visible_ = is_visible; - - // TODO(stuartmorgan): This is a temporary workarond for - // <http://crbug.com/34266>. When that is fixed, the cached_clip_rect_ code - // should all be removed. - if (is_visible) { - clip_rect_ = cached_clip_rect_; - } else { - clip_rect_.set_width(0); - clip_rect_.set_height(0); - } - - // If the plugin is changing visibility, let the plugin know. If it's scrolled - // off screen (i.e., cached_clip_rect_ is empty), then container visibility - // doesn't change anything. - if (!cached_clip_rect_.IsEmpty()) { - PluginVisibilityChanged(); - WindowlessSetWindow(); - } - - // When the plugin become visible, send an empty invalidate. If there were any - // pending invalidations this will trigger a paint event for the damaged - // region, and if not it's a no-op. This is necessary since higher levels - // that would normally do this weren't responsible for the clip_rect_ change). - if (!clip_rect_.IsEmpty()) - instance()->webplugin()->InvalidateRect(gfx::Rect()); -} - -void WebPluginDelegateImpl::WindowFrameChanged(const gfx::Rect& window_frame, - const gfx::Rect& view_frame) { - instance()->set_window_frame(window_frame); - SetContentAreaOrigin(gfx::Point(view_frame.x(), view_frame.y())); -} - -void WebPluginDelegateImpl::ImeCompositionConfirmed(const string16& text) { - if (instance()->event_model() != NPEventModelCocoa) { - DLOG(ERROR) << "IME text receieved in Carbon event model"; - return; - } - - NPCocoaEvent text_event; - memset(&text_event, 0, sizeof(NPCocoaEvent)); - text_event.type = NPCocoaEventTextInput; - text_event.data.text.text = - reinterpret_cast<NPNSString*>(base::SysUTF16ToNSString(text)); - instance()->NPP_HandleEvent(&text_event); -} - -void WebPluginDelegateImpl::SetThemeCursor(ThemeCursor cursor) { - current_windowless_cursor_.InitFromThemeCursor(cursor); -} - -void WebPluginDelegateImpl::SetCursor(const Cursor* cursor) { - current_windowless_cursor_.InitFromCursor(cursor); -} - -void WebPluginDelegateImpl::SetNSCursor(NSCursor* cursor) { - current_windowless_cursor_.InitFromNSCursor(cursor); -} - -#pragma mark - -#pragma mark Internal Tracking - -void WebPluginDelegateImpl::SetPluginRect(const gfx::Rect& rect) { - bool plugin_size_changed = rect.width() != window_rect_.width() || - rect.height() != window_rect_.height(); - window_rect_ = rect; - PluginScreenLocationChanged(); - if (plugin_size_changed) - UpdateAcceleratedSurface(); -} - -void WebPluginDelegateImpl::SetContentAreaOrigin(const gfx::Point& origin) { - content_area_origin_ = origin; - PluginScreenLocationChanged(); -} - -void WebPluginDelegateImpl::PluginScreenLocationChanged() { - gfx::Point plugin_origin(content_area_origin_.x() + window_rect_.x(), - content_area_origin_.y() + window_rect_.y()); - instance()->set_plugin_origin(plugin_origin); - -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon) { - UpdateDummyWindowBounds(plugin_origin); - } -#endif -} - -void WebPluginDelegateImpl::PluginVisibilityChanged() { -#ifndef NP_NO_CARBON - if (instance()->event_model() == NPEventModelCarbon) - UpdateIdleEventRate(); -#endif - if (instance()->drawing_model() == NPDrawingModelCoreAnimation) { - bool plugin_visible = container_is_visible_ && !clip_rect_.IsEmpty(); - if (plugin_visible && !redraw_timer_->IsRunning() && windowed_handle()) { - redraw_timer_->Start( - base::TimeDelta::FromMilliseconds(kCoreAnimationRedrawPeriodMs), - this, &WebPluginDelegateImpl::DrawLayerInSurface); - } else if (!plugin_visible) { - redraw_timer_->Stop(); - } - } -} - -void WebPluginDelegateImpl::SetImeEnabled(bool enabled) { - if (instance()->event_model() != NPEventModelCocoa) - return; - if (enabled == ime_enabled_) - return; - ime_enabled_ = enabled; - plugin_->SetImeEnabled(enabled); -} - -#pragma mark - -#pragma mark Core Animation Support - -void WebPluginDelegateImpl::DrawLayerInSurface() { - // If we haven't plumbed up the surface yet, don't try to draw. - if (!windowed_handle() || !renderer_) - return; - - [renderer_ beginFrameAtTime:CACurrentMediaTime() timeStamp:NULL]; - if (CGRectIsEmpty([renderer_ updateBounds])) { - // If nothing has changed, we are done. - [renderer_ endFrame]; - return; - } - - surface_->StartDrawing(); - - CGRect layerRect = [layer_ bounds]; - [renderer_ addUpdateRect:layerRect]; - [renderer_ render]; - [renderer_ endFrame]; - - surface_->EndDrawing(); -} - -// Update the size of the surface to match the current size of the plug-in. -void WebPluginDelegateImpl::UpdateAcceleratedSurface() { - // Will only have a window handle when using a Core Animation drawing model. - if (!windowed_handle() || !layer_) - return; - - [CATransaction begin]; - [CATransaction setValue:[NSNumber numberWithInt:0] - forKey:kCATransactionAnimationDuration]; - [layer_ setFrame:CGRectMake(0, 0, - window_rect_.width(), window_rect_.height())]; - [CATransaction commit]; - - [renderer_ setBounds:[layer_ bounds]]; - surface_->SetSize(window_rect_.size()); -} - -void WebPluginDelegateImpl::set_windowed_handle( - gfx::PluginWindowHandle handle) { - windowed_handle_ = handle; - surface_->SetWindowHandle(handle); - UpdateAcceleratedSurface(); - // Kick off the drawing timer, if necessary. - PluginVisibilityChanged(); -} - -#pragma mark - -#pragma mark Carbon Event support - -#ifndef NP_NO_CARBON -void WebPluginDelegateImpl::UpdateDummyWindowBounds( - const gfx::Point& plugin_origin) { - WindowRef window = reinterpret_cast<WindowRef>(np_cg_context_.window); - Rect current_bounds; - GetWindowBounds(window, kWindowContentRgn, ¤t_bounds); - - Rect new_bounds; - // We never want to resize the window to 0x0, so if the plugin is 0x0 just - // move the window without resizing it. - if (window_rect_.width() > 0 && window_rect_.height() > 0) { - SetRect(&new_bounds, 0, 0, window_rect_.width(), window_rect_.height()); - OffsetRect(&new_bounds, plugin_origin.x(), plugin_origin.y()); - } else { - new_bounds = current_bounds; - OffsetRect(&new_bounds, plugin_origin.x() - current_bounds.left, - plugin_origin.y() - current_bounds.top); - } - - if (new_bounds.left != current_bounds.left || - new_bounds.top != current_bounds.top || - new_bounds.right != current_bounds.right || - new_bounds.bottom != current_bounds.bottom) - SetWindowBounds(window, kWindowContentRgn, &new_bounds); -} - -void WebPluginDelegateImpl::UpdateIdleEventRate() { - bool plugin_visible = container_is_visible_ && !clip_rect_.IsEmpty(); - CarbonIdleEventSource::SharedInstance()->RegisterDelegate(this, - plugin_visible); -} - -void WebPluginDelegateImpl::FireIdleEvent() { - // Avoid a race condition between IO and UI threads during plugin shutdown - if (!instance()) - return; - // Don't send idle events until we've called SetWindow. - if (!have_called_set_window_) - return; - -#ifndef NP_NO_QUICKDRAW - // Check whether it's time to turn the QuickDraw fast path back on. - if (!fast_path_enable_tick_.is_null() && - (base::TimeTicks::Now() > fast_path_enable_tick_)) { - SetQuickDrawFastPathEnabled(true); - fast_path_enable_tick_ = base::TimeTicks(); - } -#endif - - ScopedActiveDelegate active_delegate(this); - -#ifndef NP_NO_QUICKDRAW - if (instance()->drawing_model() == NPDrawingModelQuickDraw) - qd_manager_->MakePortCurrent(); -#endif - - // Send an idle event so that the plugin can do background work - NPEvent np_event = {0}; - np_event.what = nullEvent; - np_event.when = TickCount(); - np_event.modifiers = GetCurrentKeyModifiers(); - if (!Button()) - np_event.modifiers |= btnState; - HIPoint mouse_location; - HIGetMousePosition(kHICoordSpaceScreenPixel, NULL, &mouse_location); - np_event.where.h = mouse_location.x; - np_event.where.v = mouse_location.y; - instance()->NPP_HandleEvent(&np_event); - -#ifndef NP_NO_QUICKDRAW - // Quickdraw-based plugins can draw at any time, so tell the renderer to - // repaint. - if (instance() && instance()->drawing_model() == NPDrawingModelQuickDraw) - instance()->webplugin()->Invalidate(); -#endif -} -#endif // !NP_NO_CARBON - -#pragma mark - -#pragma mark QuickDraw Support - -#ifndef NP_NO_QUICKDRAW -void WebPluginDelegateImpl::SetQuickDrawFastPathEnabled(bool enabled) { - if (!enabled) { - // Wait a couple of seconds, then turn the fast path back on. If we're - // turning it off for event handling, that ensures that the common case of - // move-mouse-then-click works (as well as making it likely that a second - // click attempt will work if the first one fails). If we're turning it - // off to force a new baseline image, this leaves plenty of time for the - // plugin to draw. - fast_path_enable_tick_ = base::TimeTicks::Now() + - base::TimeDelta::FromSeconds(2); - } - - if (enabled == qd_manager_->IsFastPathEnabled()) - return; - if (enabled && clip_rect_.IsEmpty()) { - // Don't switch to the fast path while the plugin is completely clipped; - // we can only switch when the window has an up-to-date image for us to - // scrape. We'll automatically switch after we become visible again. - return; - } - - qd_manager_->SetFastPathEnabled(enabled); - qd_port_.port = qd_manager_->port(); - WindowlessSetWindow(); - // Send a paint event so that the new buffer gets updated immediately. - WindowlessPaint(buffer_context_, clip_rect_); -} -#endif // !NP_NO_QUICKDRAW diff --git a/webkit/glue/plugins/webplugin_delegate_impl_win.cc b/webkit/glue/plugins/webplugin_delegate_impl_win.cc deleted file mode 100644 index e1acba1..0000000 --- a/webkit/glue/plugins/webplugin_delegate_impl_win.cc +++ /dev/null @@ -1,1410 +0,0 @@ -// 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 "webkit/glue/plugins/webplugin_delegate_impl.h" - -#include <map> -#include <string> -#include <vector> - -#include "app/win/iat_patch_function.h" -#include "base/file_util.h" -#include "base/lazy_instance.h" -#include "base/message_loop.h" -#include "base/metrics/stats_counters.h" -#include "base/scoped_ptr.h" -#include "base/string_number_conversions.h" -#include "base/string_split.h" -#include "base/string_util.h" -#include "base/stringprintf.h" -#include "base/win/registry.h" -#include "base/win/windows_version.h" -#include "skia/ext/platform_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "webkit/glue/plugins/default_plugin_shared.h" -#include "webkit/glue/plugins/plugin_constants_win.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/plugin_stream_url.h" -#include "webkit/glue/plugins/webplugin.h" -#include "webkit/glue/webkit_glue.h" - -using WebKit::WebCursorInfo; -using WebKit::WebKeyboardEvent; -using WebKit::WebInputEvent; -using WebKit::WebMouseEvent; - -namespace { - -const wchar_t kWebPluginDelegateProperty[] = L"WebPluginDelegateProperty"; -const wchar_t kPluginNameAtomProperty[] = L"PluginNameAtom"; -const wchar_t kDummyActivationWindowName[] = L"DummyWindowForActivation"; -const wchar_t kPluginFlashThrottle[] = L"FlashThrottle"; - -// The fastest we are willing to process WM_USER+1 events for Flash. -// Flash can easily exceed the limits of our CPU if we don't throttle it. -// The throttle has been chosen by testing various delays and compromising -// on acceptable Flash performance and reasonable CPU consumption. -// -// I'd like to make the throttle delay variable, based on the amount of -// time currently required to paint Flash plugins. There isn't a good -// way to count the time spent in aggregate plugin painting, however, so -// this seems to work well enough. -const int kFlashWMUSERMessageThrottleDelayMs = 5; - -// Flash displays popups in response to user clicks by posting a WM_USER -// message to the plugin window. The handler for this message displays -// the popup. To ensure that the popups allowed state is sent correctly -// to the renderer we reset the popups allowed state in a timer. -const int kWindowedPluginPopupTimerMs = 50; - -// The current instance of the plugin which entered the modal loop. -WebPluginDelegateImpl* g_current_plugin_instance = NULL; - -typedef std::deque<MSG> ThrottleQueue; -base::LazyInstance<ThrottleQueue> g_throttle_queue(base::LINKER_INITIALIZED); -base::LazyInstance<std::map<HWND, WNDPROC> > g_window_handle_proc_map( - base::LINKER_INITIALIZED); - - -// Helper object for patching the TrackPopupMenu API. -base::LazyInstance<app::win::IATPatchFunction> g_iat_patch_track_popup_menu( - base::LINKER_INITIALIZED); - -// Helper object for patching the SetCursor API. -base::LazyInstance<app::win::IATPatchFunction> g_iat_patch_set_cursor( - base::LINKER_INITIALIZED); - -// Helper object for patching the RegEnumKeyExW API. -base::LazyInstance<app::win::IATPatchFunction> g_iat_patch_reg_enum_key_ex_w( - base::LINKER_INITIALIZED); - -// http://crbug.com/16114 -// Enforces providing a valid device context in NPWindow, so that NPP_SetWindow -// is never called with NPNWindoTypeDrawable and NPWindow set to NULL. -// Doing so allows removing NPP_SetWindow call during painting a windowless -// plugin, which otherwise could trigger layout change while painting by -// invoking NPN_Evaluate. Which would cause bad, bad crashes. Bad crashes. -// TODO(dglazkov): If this approach doesn't produce regressions, move class to -// webplugin_delegate_impl.h and implement for other platforms. -class DrawableContextEnforcer { - public: - explicit DrawableContextEnforcer(NPWindow* window) - : window_(window), - disposable_dc_(window && !window->window) { - // If NPWindow is NULL, create a device context with monochrome 1x1 surface - // and stuff it to NPWindow. - if (disposable_dc_) - window_->window = CreateCompatibleDC(NULL); - } - - ~DrawableContextEnforcer() { - if (!disposable_dc_) - return; - - DeleteDC(static_cast<HDC>(window_->window)); - window_->window = NULL; - } - - private: - NPWindow* window_; - bool disposable_dc_; -}; - -// These are from ntddk.h -typedef LONG NTSTATUS; - -#ifndef STATUS_SUCCESS -#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) -#endif - -#ifndef STATUS_BUFFER_TOO_SMALL -#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L) -#endif - -typedef enum _KEY_INFORMATION_CLASS { - KeyBasicInformation, - KeyNodeInformation, - KeyFullInformation, - KeyNameInformation, - KeyCachedInformation, - KeyVirtualizationInformation -} KEY_INFORMATION_CLASS; - -typedef struct _KEY_NAME_INFORMATION { - ULONG NameLength; - WCHAR Name[1]; -} KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION; - -typedef DWORD (__stdcall *ZwQueryKeyType)( - HANDLE key_handle, - int key_information_class, - PVOID key_information, - ULONG length, - PULONG result_length); - -// Returns a key's full path. -std::wstring GetKeyPath(HKEY key) { - if (key == NULL) - return L""; - - HMODULE dll = GetModuleHandle(L"ntdll.dll"); - if (dll == NULL) - return L""; - - ZwQueryKeyType func = reinterpret_cast<ZwQueryKeyType>( - ::GetProcAddress(dll, "ZwQueryKey")); - if (func == NULL) - return L""; - - DWORD size = 0; - DWORD result = 0; - result = func(key, KeyNameInformation, 0, 0, &size); - if (result != STATUS_BUFFER_TOO_SMALL) - return L""; - - scoped_array<char> buffer(new char[size]); - if (buffer.get() == NULL) - return L""; - - result = func(key, KeyNameInformation, buffer.get(), size, &size); - if (result != STATUS_SUCCESS) - return L""; - - KEY_NAME_INFORMATION* info = - reinterpret_cast<KEY_NAME_INFORMATION*>(buffer.get()); - return std::wstring(info->Name, info->NameLength / sizeof(wchar_t)); -} - -} // namespace - -bool WebPluginDelegateImpl::IsPluginDelegateWindow(HWND window) { - // We use a buffer that is one char longer than we need to detect cases where - // kNativeWindowClassName is a prefix of the given window's class name. It - // happens that GetClassNameW will just silently truncate the class name to - // fit into the given buffer. - wchar_t class_name[arraysize(kNativeWindowClassName) + 1]; - if (!GetClassNameW(window, class_name, arraysize(class_name))) - return false; - return wcscmp(class_name, kNativeWindowClassName) == 0; -} - -bool WebPluginDelegateImpl::GetPluginNameFromWindow( - HWND window, std::wstring *plugin_name) { - if (NULL == plugin_name) { - return false; - } - if (!IsPluginDelegateWindow(window)) { - return false; - } - ATOM plugin_name_atom = reinterpret_cast<ATOM>( - GetPropW(window, kPluginNameAtomProperty)); - if (plugin_name_atom != 0) { - WCHAR plugin_name_local[MAX_PATH] = {0}; - GlobalGetAtomNameW(plugin_name_atom, - plugin_name_local, - ARRAYSIZE(plugin_name_local)); - *plugin_name = plugin_name_local; - return true; - } - return false; -} - -bool WebPluginDelegateImpl::IsDummyActivationWindow(HWND window) { - if (!IsWindow(window)) - return false; - - wchar_t window_title[MAX_PATH + 1] = {0}; - if (GetWindowText(window, window_title, arraysize(window_title))) { - return (0 == lstrcmpiW(window_title, kDummyActivationWindowName)); - } - return false; -} - -LRESULT CALLBACK WebPluginDelegateImpl::HandleEventMessageFilterHook( - int code, WPARAM wParam, LPARAM lParam) { - if (g_current_plugin_instance) { - g_current_plugin_instance->OnModalLoopEntered(); - } else { - NOTREACHED(); - } - return CallNextHookEx(NULL, code, wParam, lParam); -} - -LRESULT CALLBACK WebPluginDelegateImpl::MouseHookProc( - int code, WPARAM wParam, LPARAM lParam) { - if (code == HC_ACTION) { - MOUSEHOOKSTRUCT* hook_struct = reinterpret_cast<MOUSEHOOKSTRUCT*>(lParam); - if (hook_struct) - HandleCaptureForMessage(hook_struct->hwnd, wParam); - } - - return CallNextHookEx(NULL, code, wParam, lParam); -} - -WebPluginDelegateImpl::WebPluginDelegateImpl( - gfx::PluginWindowHandle containing_view, - NPAPI::PluginInstance *instance) - : parent_(containing_view), - instance_(instance), - quirks_(0), - plugin_(NULL), - windowless_(false), - windowed_handle_(NULL), - windowed_did_set_window_(false), - plugin_wnd_proc_(NULL), - last_message_(0), - is_calling_wndproc(false), - keyboard_layout_(NULL), - parent_thread_id_(0), - dummy_window_for_activation_(NULL), - handle_event_message_filter_hook_(NULL), - handle_event_pump_messages_event_(NULL), - user_gesture_message_posted_(false), -#pragma warning(suppress: 4355) // can use this - user_gesture_msg_factory_(this), - handle_event_depth_(0), - mouse_hook_(NULL), - first_set_window_call_(true), - plugin_has_focus_(false), - has_webkit_focus_(false), - containing_view_has_focus_(true), - creation_succeeded_(false) { - memset(&window_, 0, sizeof(window_)); - - const WebPluginInfo& plugin_info = instance_->plugin_lib()->plugin_info(); - std::wstring filename = - StringToLowerASCII(plugin_info.path.BaseName().value()); - - if (instance_->mime_type() == "application/x-shockwave-flash" || - filename == kFlashPlugin) { - // Flash only requests windowless plugins if we return a Mozilla user - // agent. - instance_->set_use_mozilla_user_agent(); - quirks_ |= PLUGIN_QUIRK_THROTTLE_WM_USER_PLUS_ONE; - quirks_ |= PLUGIN_QUIRK_PATCH_SETCURSOR; - quirks_ |= PLUGIN_QUIRK_ALWAYS_NOTIFY_SUCCESS; - quirks_ |= PLUGIN_QUIRK_HANDLE_MOUSE_CAPTURE; - } else if (filename == kAcrobatReaderPlugin) { - // Check for the version number above or equal 9. - std::vector<std::wstring> version; - base::SplitString(plugin_info.version, L'.', &version); - if (version.size() > 0) { - int major; - base::StringToInt(version[0], &major); - if (major >= 9) { - quirks_ |= PLUGIN_QUIRK_DIE_AFTER_UNLOAD; - - // 9.2 needs this. - quirks_ |= PLUGIN_QUIRK_SETWINDOW_TWICE; - } - } - quirks_ |= PLUGIN_QUIRK_BLOCK_NONSTANDARD_GETURL_REQUESTS; - } else if (plugin_info.name.find(L"Windows Media Player") != - std::wstring::npos) { - // Windows Media Player needs two NPP_SetWindow calls. - quirks_ |= PLUGIN_QUIRK_SETWINDOW_TWICE; - - // Windowless mode doesn't work in the WMP NPAPI plugin. - quirks_ |= PLUGIN_QUIRK_NO_WINDOWLESS; - - // The media player plugin sets its size on the first NPP_SetWindow call - // and never updates its size. We should call the underlying NPP_SetWindow - // only when we have the correct size. - quirks_ |= PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL; - - if (filename == kOldWMPPlugin) { - // Non-admin users on XP couldn't modify the key to force the new UI. - quirks_ |= PLUGIN_QUIRK_PATCH_REGENUMKEYEXW; - } - } else if (instance_->mime_type() == "audio/x-pn-realaudio-plugin" || - filename == kRealPlayerPlugin) { - quirks_ |= PLUGIN_QUIRK_DONT_CALL_WND_PROC_RECURSIVELY; - } else if (plugin_info.name.find(L"VLC Multimedia Plugin") != - std::wstring::npos || - plugin_info.name.find(L"VLC Multimedia Plug-in") != - std::wstring::npos) { - // VLC hangs on NPP_Destroy if we call NPP_SetWindow with a null window - // handle - quirks_ |= PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY; - // VLC 0.8.6d and 0.8.6e crash if multiple instances are created. - quirks_ |= PLUGIN_QUIRK_DONT_ALLOW_MULTIPLE_INSTANCES; - } else if (filename == kSilverlightPlugin) { - // Explanation for this quirk can be found in - // WebPluginDelegateImpl::Initialize. - quirks_ |= PLUGIN_QUIRK_PATCH_SETCURSOR; - } else if (plugin_info.name.find(L"DivX Web Player") != - std::wstring::npos) { - // The divx plugin sets its size on the first NPP_SetWindow call and never - // updates its size. We should call the underlying NPP_SetWindow only when - // we have the correct size. - quirks_ |= PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL; - } -} - -WebPluginDelegateImpl::~WebPluginDelegateImpl() { - if (::IsWindow(dummy_window_for_activation_)) { - ::DestroyWindow(dummy_window_for_activation_); - } - - DestroyInstance(); - - if (!windowless_) - WindowedDestroyWindow(); - - if (handle_event_pump_messages_event_) { - CloseHandle(handle_event_pump_messages_event_); - } -} - -bool WebPluginDelegateImpl::PlatformInitialize() { - plugin_->SetWindow(windowed_handle_); - - if (windowless_ && !instance_->plugin_lib()->internal()) { - CreateDummyWindowForActivation(); - handle_event_pump_messages_event_ = CreateEvent(NULL, TRUE, FALSE, NULL); - plugin_->SetWindowlessPumpEvent(handle_event_pump_messages_event_); - } - - // We cannot patch internal plugins as they are not shared libraries. - if (!instance_->plugin_lib()->internal()) { - // Windowless plugins call the WindowFromPoint API and passes the result of - // that to the TrackPopupMenu API call as the owner window. This causes the - // API to fail as the API expects the window handle to live on the same - // thread as the caller. It works in the other browsers as the plugin lives - // on the browser thread. Our workaround is to intercept the TrackPopupMenu - // API and replace the window handle with the dummy activation window. - if (windowless_ && !g_iat_patch_track_popup_menu.Pointer()->is_patched()) { - g_iat_patch_track_popup_menu.Pointer()->Patch( - GetPluginPath().value().c_str(), "user32.dll", "TrackPopupMenu", - WebPluginDelegateImpl::TrackPopupMenuPatch); - } - - // Windowless plugins can set cursors by calling the SetCursor API. This - // works because the thread inputs of the browser UI thread and the plugin - // thread are attached. We intercept the SetCursor API for windowless - // plugins and remember the cursor being set. This is shipped over to the - // browser in the HandleEvent call, which ensures that the cursor does not - // change when a windowless plugin instance changes the cursor - // in a background tab. - if (windowless_ && !g_iat_patch_set_cursor.Pointer()->is_patched() && - (quirks_ & PLUGIN_QUIRK_PATCH_SETCURSOR)) { - g_iat_patch_set_cursor.Pointer()->Patch( - GetPluginPath().value().c_str(), "user32.dll", "SetCursor", - WebPluginDelegateImpl::SetCursorPatch); - } - - // The windowed flash plugin has a bug which occurs when the plugin enters - // fullscreen mode. It basically captures the mouse on WM_LBUTTONDOWN and - // does not release capture correctly causing it to stop receiving - // subsequent mouse events. This problem is also seen in Safari where there - // is code to handle this in the wndproc. However the plugin subclasses the - // window again in WM_LBUTTONDOWN before entering full screen. As a result - // Safari does not receive the WM_LBUTTONUP message. To workaround this - // issue we use a per thread mouse hook. This bug does not occur in Firefox - // and opera. Firefox has code similar to Safari. It could well be a bug in - // the flash plugin, which only occurs in webkit based browsers. - if (quirks_ & PLUGIN_QUIRK_HANDLE_MOUSE_CAPTURE) { - mouse_hook_ = SetWindowsHookEx(WH_MOUSE, MouseHookProc, NULL, - GetCurrentThreadId()); - } - } - - // On XP, WMP will use its old UI unless a registry key under HKLM has the - // name of the current process. We do it in the installer for admin users, - // for the rest patch this function. - if ((quirks_ & PLUGIN_QUIRK_PATCH_REGENUMKEYEXW) && - base::win::GetVersion() == base::win::VERSION_XP && - !base::win::RegKey().Open(HKEY_LOCAL_MACHINE, - L"SOFTWARE\\Microsoft\\MediaPlayer\\ShimInclusionList\\chrome.exe", - KEY_READ) && - !g_iat_patch_reg_enum_key_ex_w.Pointer()->is_patched()) { - g_iat_patch_reg_enum_key_ex_w.Pointer()->Patch( - L"wmpdxm.dll", "advapi32.dll", "RegEnumKeyExW", - WebPluginDelegateImpl::RegEnumKeyExWPatch); - } - - return true; -} - -void WebPluginDelegateImpl::PlatformDestroyInstance() { - if (!instance_->plugin_lib()) - return; - - // Unpatch if this is the last plugin instance. - if (instance_->plugin_lib()->instance_count() != 1) - return; - - if (g_iat_patch_set_cursor.Pointer()->is_patched()) - g_iat_patch_set_cursor.Pointer()->Unpatch(); - - if (g_iat_patch_track_popup_menu.Pointer()->is_patched()) - g_iat_patch_track_popup_menu.Pointer()->Unpatch(); - - if (g_iat_patch_reg_enum_key_ex_w.Pointer()->is_patched()) - g_iat_patch_reg_enum_key_ex_w.Pointer()->Unpatch(); - - if (mouse_hook_) { - UnhookWindowsHookEx(mouse_hook_); - mouse_hook_ = NULL; - } -} - -void WebPluginDelegateImpl::Paint(skia::PlatformCanvas* canvas, - const gfx::Rect& rect) { - if (windowless_) { - HDC hdc = canvas->beginPlatformPaint(); - WindowlessPaint(hdc, rect); - canvas->endPlatformPaint(); - } -} - -void WebPluginDelegateImpl::Print(HDC hdc) { - // Disabling the call to NPP_Print as it causes a crash in - // flash in some cases. In any case this does not work as expected - // as the EMF meta file dc passed in needs to be created with the - // the plugin window dc as its sibling dc and the window rect - // in .01 mm units. -#if 0 - NPPrint npprint; - npprint.mode = NP_EMBED; - npprint.print.embedPrint.platformPrint = reinterpret_cast<void*>(hdc); - npprint.print.embedPrint.window = window_; - instance()->NPP_Print(&npprint); -#endif -} - -void WebPluginDelegateImpl::InstallMissingPlugin() { - NPEvent evt; - evt.event = default_plugin::kInstallMissingPluginMessage; - evt.lParam = 0; - evt.wParam = 0; - instance()->NPP_HandleEvent(&evt); -} - -bool WebPluginDelegateImpl::WindowedCreatePlugin() { - DCHECK(!windowed_handle_); - - RegisterNativeWindowClass(); - - // The window will be sized and shown later. - windowed_handle_ = CreateWindowEx( - WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR, - kNativeWindowClassName, - 0, - WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, - 0, - 0, - 0, - 0, - parent_, - 0, - GetModuleHandle(NULL), - 0); - if (windowed_handle_ == 0) - return false; - - if (IsWindow(parent_)) { - // This is a tricky workaround for Issue 2673 in chromium "Flash: IME not - // available". To use IMEs in this window, we have to make Windows attach - // IMEs to this window (i.e. load IME DLLs, attach them to this process, - // and add their message hooks to this window). Windows attaches IMEs while - // this process creates a top-level window. On the other hand, to layout - // this window correctly in the given parent window (RenderWidgetHostHWND), - // this window should be a child window of the parent window. - // To satisfy both of the above conditions, this code once creates a - // top-level window and change it to a child window of the parent window. - SetWindowLongPtr(windowed_handle_, GWL_STYLE, - WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS); - SetParent(windowed_handle_, parent_); - } - - BOOL result = SetProp(windowed_handle_, kWebPluginDelegateProperty, this); - DCHECK(result == TRUE) << "SetProp failed, last error = " << GetLastError(); - // Get the name of the plugin, create an atom and set that in a window - // property. Use an atom so that other processes can access the name of - // the plugin that this window is hosting - if (instance_ != NULL) { - NPAPI::PluginLib* plugin_lib = instance()->plugin_lib(); - if (plugin_lib != NULL) { - std::wstring plugin_name = plugin_lib->plugin_info().name; - if (!plugin_name.empty()) { - ATOM plugin_name_atom = GlobalAddAtomW(plugin_name.c_str()); - DCHECK(0 != plugin_name_atom); - result = SetProp(windowed_handle_, - kPluginNameAtomProperty, - reinterpret_cast<HANDLE>(plugin_name_atom)); - DCHECK(result == TRUE) << "SetProp failed, last error = " << - GetLastError(); - } - } - } - - // Calling SetWindowLongPtrA here makes the window proc ASCII, which is - // required by at least the Shockwave Director plug-in. - SetWindowLongPtrA( - windowed_handle_, GWL_WNDPROC, reinterpret_cast<LONG>(DefWindowProcA)); - - return true; -} - -void WebPluginDelegateImpl::WindowedDestroyWindow() { - if (windowed_handle_ != NULL) { - // Unsubclass the window. - WNDPROC current_wnd_proc = reinterpret_cast<WNDPROC>( - GetWindowLongPtr(windowed_handle_, GWLP_WNDPROC)); - if (current_wnd_proc == NativeWndProc) { - SetWindowLongPtr(windowed_handle_, - GWLP_WNDPROC, - reinterpret_cast<LONG>(plugin_wnd_proc_)); - } - - plugin_->WillDestroyWindow(windowed_handle_); - - DestroyWindow(windowed_handle_); - windowed_handle_ = 0; - } -} - -// Erase all messages in the queue destined for a particular window. -// When windows are closing, callers should use this function to clear -// the queue. -// static -void WebPluginDelegateImpl::ClearThrottleQueueForWindow(HWND window) { - ThrottleQueue* throttle_queue = g_throttle_queue.Pointer(); - - ThrottleQueue::iterator it; - for (it = throttle_queue->begin(); it != throttle_queue->end(); ) { - if (it->hwnd == window) { - it = throttle_queue->erase(it); - } else { - it++; - } - } -} - -// Delayed callback for processing throttled messages. -// Throttled messages are aggregated globally across all plugins. -// static -void WebPluginDelegateImpl::OnThrottleMessage() { - // The current algorithm walks the list and processes the first - // message it finds for each plugin. It is important to service - // all active plugins with each pass through the throttle, otherwise - // we see video jankiness. Copy the set to notify before notifying - // since we may re-enter OnThrottleMessage from CallWindowProc! - ThrottleQueue* throttle_queue = g_throttle_queue.Pointer(); - ThrottleQueue notify_queue; - std::set<HWND> processed; - - ThrottleQueue::iterator it = throttle_queue->begin(); - while (it != throttle_queue->end()) { - const MSG& msg = *it; - if (processed.find(msg.hwnd) == processed.end()) { - processed.insert(msg.hwnd); - notify_queue.push_back(msg); - it = throttle_queue->erase(it); - } else { - it++; - } - } - - for (it = notify_queue.begin(); it != notify_queue.end(); ++it) { - const MSG& msg = *it; - WNDPROC proc = reinterpret_cast<WNDPROC>(msg.time); - // It is possible that the window was closed after we queued - // this message. This is a rare event; just verify the window - // is alive. (see also bug 1259488) - if (IsWindow(msg.hwnd)) - CallWindowProc(proc, msg.hwnd, msg.message, msg.wParam, msg.lParam); - } - - if (!throttle_queue->empty()) { - MessageLoop::current()->PostDelayedTask(FROM_HERE, - NewRunnableFunction(&WebPluginDelegateImpl::OnThrottleMessage), - kFlashWMUSERMessageThrottleDelayMs); - } -} - -// Schedule a windows message for delivery later. -// static -void WebPluginDelegateImpl::ThrottleMessage(WNDPROC proc, HWND hwnd, - UINT message, WPARAM wParam, - LPARAM lParam) { - MSG msg; - msg.time = reinterpret_cast<DWORD>(proc); - msg.hwnd = hwnd; - msg.message = message; - msg.wParam = wParam; - msg.lParam = lParam; - - ThrottleQueue* throttle_queue = g_throttle_queue.Pointer(); - - throttle_queue->push_back(msg); - - if (throttle_queue->size() == 1) { - MessageLoop::current()->PostDelayedTask(FROM_HERE, - NewRunnableFunction(&WebPluginDelegateImpl::OnThrottleMessage), - kFlashWMUSERMessageThrottleDelayMs); - } -} - -// We go out of our way to find the hidden windows created by Flash for -// windowless plugins. We throttle the rate at which they deliver messages -// so that they will not consume outrageous amounts of CPU. -// static -LRESULT CALLBACK WebPluginDelegateImpl::FlashWindowlessWndProc(HWND hwnd, - UINT message, WPARAM wparam, LPARAM lparam) { - std::map<HWND, WNDPROC>::iterator index = - g_window_handle_proc_map.Get().find(hwnd); - - WNDPROC old_proc = (*index).second; - DCHECK(old_proc); - - switch (message) { - case WM_NCDESTROY: { - WebPluginDelegateImpl::ClearThrottleQueueForWindow(hwnd); - g_window_handle_proc_map.Get().erase(index); - break; - } - // Flash may flood the message queue with WM_USER+1 message causing 100% CPU - // usage. See https://bugzilla.mozilla.org/show_bug.cgi?id=132759. We - // prevent this by throttling the messages. - case WM_USER + 1: { - WebPluginDelegateImpl::ThrottleMessage(old_proc, hwnd, message, wparam, - lparam); - return TRUE; - } - default: { - break; - } - } - return CallWindowProc(old_proc, hwnd, message, wparam, lparam); -} - -// Callback for enumerating the Flash windows. -BOOL CALLBACK EnumFlashWindows(HWND window, LPARAM arg) { - WNDPROC wnd_proc = reinterpret_cast<WNDPROC>(arg); - TCHAR class_name[1024]; - if (!RealGetWindowClass(window, class_name, - sizeof(class_name)/sizeof(TCHAR))) { - LOG(ERROR) << "RealGetWindowClass failure: " << GetLastError(); - return FALSE; - } - - if (wcscmp(class_name, L"SWFlash_PlaceholderX")) - return TRUE; - - WNDPROC current_wnd_proc = reinterpret_cast<WNDPROC>( - GetWindowLongPtr(window, GWLP_WNDPROC)); - if (current_wnd_proc != wnd_proc) { - WNDPROC old_flash_proc = reinterpret_cast<WNDPROC>(SetWindowLongPtr( - window, GWLP_WNDPROC, - reinterpret_cast<LONG>(wnd_proc))); - DCHECK(old_flash_proc); - g_window_handle_proc_map.Get()[window] = old_flash_proc; - } - - return TRUE; -} - -bool WebPluginDelegateImpl::CreateDummyWindowForActivation() { - DCHECK(!dummy_window_for_activation_); - dummy_window_for_activation_ = CreateWindowEx( - 0, - L"Static", - kDummyActivationWindowName, - WS_CHILD, - 0, - 0, - 0, - 0, - parent_, - 0, - GetModuleHandle(NULL), - 0); - - if (dummy_window_for_activation_ == 0) - return false; - - // Flash creates background windows which use excessive CPU in our - // environment; we wrap these windows and throttle them so that they don't - // get out of hand. - if (!EnumThreadWindows(::GetCurrentThreadId(), EnumFlashWindows, - reinterpret_cast<LPARAM>( - &WebPluginDelegateImpl::FlashWindowlessWndProc))) { - // Log that this happened. Flash will still work; it just means the - // throttle isn't installed (and Flash will use more CPU). - NOTREACHED(); - LOG(ERROR) << "Failed to wrap all windowless Flash windows"; - } - return true; -} - -bool WebPluginDelegateImpl::WindowedReposition( - const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - if (!windowed_handle_) { - NOTREACHED(); - return false; - } - - if (window_rect_ == window_rect && clip_rect_ == clip_rect) - return false; - - // We only set the plugin's size here. Its position is moved elsewhere, which - // allows the window moves/scrolling/clipping to be synchronized with the page - // and other windows. - // If the plugin window has no parent, then don't focus it because it isn't - // being displayed anywhere. See: - // http://code.google.com/p/chromium/issues/detail?id=32658 - if (window_rect.size() != window_rect_.size()) { - UINT flags = SWP_NOMOVE | SWP_NOZORDER; - if (!GetParent(windowed_handle_)) - flags |= SWP_NOACTIVATE; - ::SetWindowPos(windowed_handle_, - NULL, - 0, - 0, - window_rect.width(), - window_rect.height(), - flags); - } - - window_rect_ = window_rect; - clip_rect_ = clip_rect; - - // Ensure that the entire window gets repainted. - ::InvalidateRect(windowed_handle_, NULL, FALSE); - - return true; -} - -void WebPluginDelegateImpl::WindowedSetWindow() { - if (!instance_) - return; - - if (!windowed_handle_) { - NOTREACHED(); - return; - } - - instance()->set_window_handle(windowed_handle_); - - DCHECK(!instance()->windowless()); - - window_.clipRect.top = std::max(0, clip_rect_.y()); - window_.clipRect.left = std::max(0, clip_rect_.x()); - window_.clipRect.bottom = std::max(0, clip_rect_.y() + clip_rect_.height()); - window_.clipRect.right = std::max(0, clip_rect_.x() + clip_rect_.width()); - window_.height = window_rect_.height(); - window_.width = window_rect_.width(); - window_.x = 0; - window_.y = 0; - - window_.window = windowed_handle_; - window_.type = NPWindowTypeWindow; - - // Reset this flag before entering the instance in case of side-effects. - windowed_did_set_window_ = true; - - NPError err = instance()->NPP_SetWindow(&window_); - if (quirks_ & PLUGIN_QUIRK_SETWINDOW_TWICE) - instance()->NPP_SetWindow(&window_); - - WNDPROC current_wnd_proc = reinterpret_cast<WNDPROC>( - GetWindowLongPtr(windowed_handle_, GWLP_WNDPROC)); - if (current_wnd_proc != NativeWndProc) { - plugin_wnd_proc_ = reinterpret_cast<WNDPROC>(SetWindowLongPtr( - windowed_handle_, GWLP_WNDPROC, reinterpret_cast<LONG>(NativeWndProc))); - } -} - -ATOM WebPluginDelegateImpl::RegisterNativeWindowClass() { - static bool have_registered_window_class = false; - if (have_registered_window_class == true) - return true; - - have_registered_window_class = true; - - WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_DBLCLKS; - wcex.lpfnWndProc = DummyWindowProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = GetModuleHandle(NULL); - wcex.hIcon = 0; - wcex.hCursor = 0; - // Some plugins like windows media player 11 create child windows parented - // by our plugin window, where the media content is rendered. These plugins - // dont implement WM_ERASEBKGND, which causes painting issues, when the - // window where the media is rendered is moved around. DefWindowProc does - // implement WM_ERASEBKGND correctly if we have a valid background brush. - wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW+1); - wcex.lpszMenuName = 0; - wcex.lpszClassName = kNativeWindowClassName; - wcex.hIconSm = 0; - - return RegisterClassEx(&wcex); -} - -LRESULT CALLBACK WebPluginDelegateImpl::DummyWindowProc( - HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - // This is another workaround for Issue 2673 in chromium "Flash: IME not - // available". Somehow, the CallWindowProc() function does not dispatch - // window messages when its first parameter is a handle representing the - // DefWindowProc() function. To avoid this problem, this code creates a - // wrapper function which just encapsulates the DefWindowProc() function - // and set it as the window procedure of a windowed plug-in. - return DefWindowProc(hWnd, message, wParam, lParam); -} - -// Returns true if the message passed in corresponds to a user gesture. -static bool IsUserGestureMessage(unsigned int message) { - switch (message) { - case WM_LBUTTONUP: - case WM_RBUTTONUP: - case WM_MBUTTONUP: - case WM_KEYUP: - return true; - - default: - break; - } - - return false; -} - -LRESULT CALLBACK WebPluginDelegateImpl::NativeWndProc( - HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { - WebPluginDelegateImpl* delegate = reinterpret_cast<WebPluginDelegateImpl*>( - GetProp(hwnd, kWebPluginDelegateProperty)); - if (!delegate) { - NOTREACHED(); - return 0; - } - - if (message == delegate->last_message_ && - delegate->GetQuirks() & PLUGIN_QUIRK_DONT_CALL_WND_PROC_RECURSIVELY && - delegate->is_calling_wndproc) { - // Real may go into a state where it recursively dispatches the same event - // when subclassed. See https://bugzilla.mozilla.org/show_bug.cgi?id=192914 - // We only do the recursive check for Real because it's possible and valid - // for a plugin to synchronously dispatch a message to itself such that it - // looks like it's in recursion. - return TRUE; - } - - // Flash may flood the message queue with WM_USER+1 message causing 100% CPU - // usage. See https://bugzilla.mozilla.org/show_bug.cgi?id=132759. We - // prevent this by throttling the messages. - if (message == WM_USER + 1 && - delegate->GetQuirks() & PLUGIN_QUIRK_THROTTLE_WM_USER_PLUS_ONE) { - WebPluginDelegateImpl::ThrottleMessage(delegate->plugin_wnd_proc_, hwnd, - message, wparam, lparam); - return FALSE; - } - - LRESULT result; - uint32 old_message = delegate->last_message_; - delegate->last_message_ = message; - - static UINT custom_msg = RegisterWindowMessage(kPaintMessageName); - if (message == custom_msg) { - // Get the invalid rect which is in screen coordinates and convert to - // window coordinates. - gfx::Rect invalid_rect; - invalid_rect.set_x(wparam >> 16); - invalid_rect.set_y(wparam & 0xFFFF); - invalid_rect.set_width(lparam >> 16); - invalid_rect.set_height(lparam & 0xFFFF); - - RECT window_rect; - GetWindowRect(hwnd, &window_rect); - invalid_rect.Offset(-window_rect.left, -window_rect.top); - - // The plugin window might have non-client area. If we don't pass in - // RDW_FRAME then the children don't receive WM_NCPAINT messages while - // scrolling, which causes painting problems (http://b/issue?id=923945). - uint32 flags = RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_FRAME; - - // If a plugin (like Google Earth or Java) has child windows that are hosted - // in a different process, then RedrawWindow with UPDATENOW will - // synchronously wait for this call to complete. Some messages are pumped - // but not others, which could lead to a deadlock. So avoid reentrancy by - // only synchronously calling RedrawWindow once at a time. - if (old_message != custom_msg) - flags |= RDW_UPDATENOW; - - RedrawWindow(hwnd, &invalid_rect.ToRECT(), NULL, flags); - result = FALSE; - } else { - delegate->is_calling_wndproc = true; - - if (!delegate->user_gesture_message_posted_ && - IsUserGestureMessage(message)) { - delegate->user_gesture_message_posted_ = true; - - delegate->instance()->PushPopupsEnabledState(true); - - MessageLoop::current()->PostDelayedTask(FROM_HERE, - delegate->user_gesture_msg_factory_.NewRunnableMethod( - &WebPluginDelegateImpl::OnUserGestureEnd), - kWindowedPluginPopupTimerMs); - } - - HandleCaptureForMessage(hwnd, message); - - // Maintain a local/global stack for the g_current_plugin_instance variable - // as this may be a nested invocation. - WebPluginDelegateImpl* last_plugin_instance = g_current_plugin_instance; - - g_current_plugin_instance = delegate; - - result = CallWindowProc( - delegate->plugin_wnd_proc_, hwnd, message, wparam, lparam); - - delegate->is_calling_wndproc = false; - g_current_plugin_instance = last_plugin_instance; - - if (message == WM_NCDESTROY) { - RemoveProp(hwnd, kWebPluginDelegateProperty); - ATOM plugin_name_atom = reinterpret_cast<ATOM>( - RemoveProp(hwnd, kPluginNameAtomProperty)); - if (plugin_name_atom != 0) - GlobalDeleteAtom(plugin_name_atom); - ClearThrottleQueueForWindow(hwnd); - } - } - delegate->last_message_ = old_message; - return result; -} - -void WebPluginDelegateImpl::WindowlessUpdateGeometry( - const gfx::Rect& window_rect, - const gfx::Rect& clip_rect) { - bool window_rect_changed = (window_rect_ != window_rect); - // Only resend to the instance if the geometry has changed. - if (!window_rect_changed && clip_rect == clip_rect_) - return; - - clip_rect_ = clip_rect; - window_rect_ = window_rect; - - WindowlessSetWindow(); - - if (window_rect_changed) { - WINDOWPOS win_pos = {0}; - win_pos.x = window_rect_.x(); - win_pos.y = window_rect_.y(); - win_pos.cx = window_rect_.width(); - win_pos.cy = window_rect_.height(); - - NPEvent pos_changed_event; - pos_changed_event.event = WM_WINDOWPOSCHANGED; - pos_changed_event.wParam = 0; - pos_changed_event.lParam = PtrToUlong(&win_pos); - - instance()->NPP_HandleEvent(&pos_changed_event); - } -} - -void WebPluginDelegateImpl::WindowlessPaint(HDC hdc, - const gfx::Rect& damage_rect) { - DCHECK(hdc); - - RECT damage_rect_win; - damage_rect_win.left = damage_rect.x(); // + window_rect_.x(); - damage_rect_win.top = damage_rect.y(); // + window_rect_.y(); - damage_rect_win.right = damage_rect_win.left + damage_rect.width(); - damage_rect_win.bottom = damage_rect_win.top + damage_rect.height(); - - // Save away the old HDC as this could be a nested invocation. - void* old_dc = window_.window; - window_.window = hdc; - - NPEvent paint_event; - paint_event.event = WM_PAINT; - // NOTE: NPAPI is not 64bit safe. It puts pointers into 32bit values. - paint_event.wParam = PtrToUlong(hdc); - paint_event.lParam = PtrToUlong(&damage_rect_win); - static base::StatsRate plugin_paint("Plugin.Paint"); - base::StatsScope<base::StatsRate> scope(plugin_paint); - instance()->NPP_HandleEvent(&paint_event); - window_.window = old_dc; -} - -void WebPluginDelegateImpl::WindowlessSetWindow() { - if (!instance()) - return; - - if (window_rect_.IsEmpty()) // wait for geometry to be set. - return; - - DCHECK(instance()->windowless()); - - window_.clipRect.top = clip_rect_.y(); - window_.clipRect.left = clip_rect_.x(); - window_.clipRect.bottom = clip_rect_.y() + clip_rect_.height(); - window_.clipRect.right = clip_rect_.x() + clip_rect_.width(); - window_.height = window_rect_.height(); - window_.width = window_rect_.width(); - window_.x = window_rect_.x(); - window_.y = window_rect_.y(); - window_.type = NPWindowTypeDrawable; - DrawableContextEnforcer enforcer(&window_); - - NPError err = instance()->NPP_SetWindow(&window_); - DCHECK(err == NPERR_NO_ERROR); -} - -bool WebPluginDelegateImpl::PlatformSetPluginHasFocus(bool focused) { - DCHECK(instance()->windowless()); - - NPEvent focus_event; - focus_event.event = focused ? WM_SETFOCUS : WM_KILLFOCUS; - focus_event.wParam = 0; - focus_event.lParam = 0; - - instance()->NPP_HandleEvent(&focus_event); - return true; -} - -static bool NPEventFromWebMouseEvent(const WebMouseEvent& event, - NPEvent *np_event) { - np_event->lParam = static_cast<uint32>(MAKELPARAM(event.windowX, - event.windowY)); - np_event->wParam = 0; - - if (event.modifiers & WebInputEvent::ControlKey) - np_event->wParam |= MK_CONTROL; - if (event.modifiers & WebInputEvent::ShiftKey) - np_event->wParam |= MK_SHIFT; - if (event.modifiers & WebInputEvent::LeftButtonDown) - np_event->wParam |= MK_LBUTTON; - if (event.modifiers & WebInputEvent::MiddleButtonDown) - np_event->wParam |= MK_MBUTTON; - if (event.modifiers & WebInputEvent::RightButtonDown) - np_event->wParam |= MK_RBUTTON; - - switch (event.type) { - case WebInputEvent::MouseMove: - case WebInputEvent::MouseLeave: - case WebInputEvent::MouseEnter: - np_event->event = WM_MOUSEMOVE; - return true; - case WebInputEvent::MouseDown: - switch (event.button) { - case WebMouseEvent::ButtonLeft: - np_event->event = WM_LBUTTONDOWN; - break; - case WebMouseEvent::ButtonMiddle: - np_event->event = WM_MBUTTONDOWN; - break; - case WebMouseEvent::ButtonRight: - np_event->event = WM_RBUTTONDOWN; - break; - } - return true; - case WebInputEvent::MouseUp: - switch (event.button) { - case WebMouseEvent::ButtonLeft: - np_event->event = WM_LBUTTONUP; - break; - case WebMouseEvent::ButtonMiddle: - np_event->event = WM_MBUTTONUP; - break; - case WebMouseEvent::ButtonRight: - np_event->event = WM_RBUTTONUP; - break; - } - return true; - default: - NOTREACHED(); - return false; - } -} - -static bool NPEventFromWebKeyboardEvent(const WebKeyboardEvent& event, - NPEvent *np_event) { - np_event->wParam = event.windowsKeyCode; - - switch (event.type) { - case WebInputEvent::KeyDown: - np_event->event = WM_KEYDOWN; - np_event->lParam = 0; - return true; - case WebInputEvent::Char: - np_event->event = WM_CHAR; - np_event->lParam = 0; - return true; - case WebInputEvent::KeyUp: - np_event->event = WM_KEYUP; - np_event->lParam = 0x8000; - return true; - default: - NOTREACHED(); - return false; - } -} - -static bool NPEventFromWebInputEvent(const WebInputEvent& event, - NPEvent* np_event) { - switch (event.type) { - case WebInputEvent::MouseMove: - case WebInputEvent::MouseLeave: - case WebInputEvent::MouseEnter: - case WebInputEvent::MouseDown: - case WebInputEvent::MouseUp: - if (event.size < sizeof(WebMouseEvent)) { - NOTREACHED(); - return false; - } - return NPEventFromWebMouseEvent( - *static_cast<const WebMouseEvent*>(&event), np_event); - case WebInputEvent::KeyDown: - case WebInputEvent::Char: - case WebInputEvent::KeyUp: - if (event.size < sizeof(WebKeyboardEvent)) { - NOTREACHED(); - return false; - } - return NPEventFromWebKeyboardEvent( - *static_cast<const WebKeyboardEvent*>(&event), np_event); - default: - return false; - } -} - -bool WebPluginDelegateImpl::PlatformHandleInputEvent( - const WebInputEvent& event, WebCursorInfo* cursor_info) { - DCHECK(cursor_info != NULL); - - NPEvent np_event; - if (!NPEventFromWebInputEvent(event, &np_event)) { - return false; - } - - // Synchronize the keyboard layout with the one of the browser process. Flash - // uses the keyboard layout of this window to verify a WM_CHAR message is - // valid. That is, Flash discards a WM_CHAR message unless its character is - // the one translated with ToUnicode(). (Since a plug-in is running on a - // separate process from the browser process, we need to syncronize it - // manually.) - if (np_event.event == WM_CHAR) { - if (!keyboard_layout_) - keyboard_layout_ = GetKeyboardLayout(GetCurrentThreadId()); - if (!parent_thread_id_) - parent_thread_id_ = GetWindowThreadProcessId(parent_, NULL); - HKL parent_layout = GetKeyboardLayout(parent_thread_id_); - if (keyboard_layout_ != parent_layout) { - std::wstring layout_name(base::StringPrintf(L"%08x", parent_layout)); - LoadKeyboardLayout(layout_name.c_str(), KLF_ACTIVATE); - keyboard_layout_ = parent_layout; - } - } - - if (ShouldTrackEventForModalLoops(&np_event)) { - // A windowless plugin can enter a modal loop in a NPP_HandleEvent call. - // For e.g. Flash puts up a context menu when we right click on the - // windowless plugin area. We detect this by setting up a message filter - // hook pror to calling NPP_HandleEvent on the plugin and unhook on - // return from NPP_HandleEvent. If the plugin does enter a modal loop - // in that context we unhook on receiving the first notification in - // the message filter hook. - handle_event_message_filter_hook_ = - SetWindowsHookEx(WH_MSGFILTER, HandleEventMessageFilterHook, NULL, - GetCurrentThreadId()); - } - - bool old_task_reentrancy_state = - MessageLoop::current()->NestableTasksAllowed(); - - - // Maintain a local/global stack for the g_current_plugin_instance variable - // as this may be a nested invocation. - WebPluginDelegateImpl* last_plugin_instance = g_current_plugin_instance; - - g_current_plugin_instance = this; - - handle_event_depth_++; - - bool ret = instance()->NPP_HandleEvent(&np_event) != 0; - - // Flash and SilverLight always return false, even when they swallow the - // event. Flash does this because it passes the event to its window proc, - // which is supposed to return 0 if an event was handled. There are few - // exceptions, such as IME, where it sometimes returns true. - ret = true; - - if (np_event.event == WM_MOUSEMOVE) { - // Snag a reference to the current cursor ASAP in case the plugin modified - // it. There is a nasty race condition here with the multiprocess browser - // as someone might be setting the cursor in the main process as well. - current_windowless_cursor_.GetCursorInfo(cursor_info); - } - - handle_event_depth_--; - - g_current_plugin_instance = last_plugin_instance; - - MessageLoop::current()->SetNestableTasksAllowed(old_task_reentrancy_state); - - // We could have multiple NPP_HandleEvent calls nested together in case - // the plugin enters a modal loop. Reset the pump messages event when - // the outermost NPP_HandleEvent call unwinds. - if (handle_event_depth_ == 0) { - ResetEvent(handle_event_pump_messages_event_); - } - - return ret; -} - - -void WebPluginDelegateImpl::OnModalLoopEntered() { - DCHECK(handle_event_pump_messages_event_ != NULL); - SetEvent(handle_event_pump_messages_event_); - - MessageLoop::current()->SetNestableTasksAllowed(true); - - UnhookWindowsHookEx(handle_event_message_filter_hook_); - handle_event_message_filter_hook_ = NULL; -} - -bool WebPluginDelegateImpl::ShouldTrackEventForModalLoops(NPEvent* event) { - if (event->event == WM_RBUTTONDOWN) - return true; - return false; -} - -void WebPluginDelegateImpl::OnUserGestureEnd() { - user_gesture_message_posted_ = false; - instance()->PopPopupsEnabledState(); -} - -BOOL WINAPI WebPluginDelegateImpl::TrackPopupMenuPatch( - HMENU menu, unsigned int flags, int x, int y, int reserved, - HWND window, const RECT* rect) { - - HWND last_focus_window = NULL; - - if (g_current_plugin_instance) { - unsigned long window_process_id = 0; - unsigned long window_thread_id = - GetWindowThreadProcessId(window, &window_process_id); - // TrackPopupMenu fails if the window passed in belongs to a different - // thread. - if (::GetCurrentThreadId() != window_thread_id) { - window = g_current_plugin_instance->dummy_window_for_activation_; - } - - // To ensure that the plugin receives keyboard events we set focus to the - // dummy window. - // TODO(iyengar) We need a framework in the renderer to identify which - // windowless plugin is under the mouse and to handle this. This would - // also require some changes in RenderWidgetHost to detect this in the - // WM_MOUSEACTIVATE handler and inform the renderer accordingly. - if (g_current_plugin_instance->dummy_window_for_activation_) { - last_focus_window = - ::SetFocus(g_current_plugin_instance->dummy_window_for_activation_); - } - } - - BOOL result = TrackPopupMenu(menu, flags, x, y, reserved, window, rect); - - if (IsWindow(last_focus_window)) { - // The Flash plugin at times sets focus to its hidden top level window - // with class name SWFlash_PlaceholderX. This causes the chrome browser - // window to receive a WM_ACTIVATEAPP message as a top level window from - // another thread is now active. We end up in a state where the chrome - // browser window is not active even though the user clicked on it. - // Our workaround for this is to send over a raw - // WM_LBUTTONDOWN/WM_LBUTTONUP combination to the last focus window, which - // does the trick. - if (g_current_plugin_instance->dummy_window_for_activation_ != - ::GetFocus()) { - INPUT input_info = {0}; - input_info.type = INPUT_MOUSE; - input_info.mi.dwFlags = MOUSEEVENTF_LEFTDOWN; - ::SendInput(1, &input_info, sizeof(INPUT)); - - input_info.type = INPUT_MOUSE; - input_info.mi.dwFlags = MOUSEEVENTF_LEFTUP; - ::SendInput(1, &input_info, sizeof(INPUT)); - } else { - ::SetFocus(last_focus_window); - } - } - - return result; -} - -HCURSOR WINAPI WebPluginDelegateImpl::SetCursorPatch(HCURSOR cursor) { - // The windowless flash plugin periodically calls SetCursor in a wndproc - // instantiated on the plugin thread. This causes annoying cursor flicker - // when the mouse is moved on a foreground tab, with a windowless plugin - // instance in a background tab. We just ignore the call here. - if (!g_current_plugin_instance) { - HCURSOR current_cursor = GetCursor(); - if (current_cursor != cursor) { - ::SetCursor(cursor); - } - return current_cursor; - } - - if (!g_current_plugin_instance->IsWindowless()) { - return ::SetCursor(cursor); - } - - // It is ok to pass NULL here to GetCursor as we are not looking for cursor - // types defined by Webkit. - HCURSOR previous_cursor = - g_current_plugin_instance->current_windowless_cursor_.GetCursor(NULL); - - g_current_plugin_instance->current_windowless_cursor_.InitFromExternalCursor( - cursor); - return previous_cursor; -} - -LONG WINAPI WebPluginDelegateImpl::RegEnumKeyExWPatch( - HKEY key, DWORD index, LPWSTR name, LPDWORD name_size, LPDWORD reserved, - LPWSTR class_name, LPDWORD class_size, PFILETIME last_write_time) { - DWORD orig_size = *name_size; - LONG rv = RegEnumKeyExW(key, index, name, name_size, reserved, class_name, - class_size, last_write_time); - if (rv == ERROR_SUCCESS && - GetKeyPath(key).find(L"Microsoft\\MediaPlayer\\ShimInclusionList") != - std::wstring::npos) { - static const wchar_t kChromeExeName[] = L"chrome.exe"; - wcsncpy_s(name, orig_size, kChromeExeName, arraysize(kChromeExeName)); - *name_size = - std::min(orig_size, static_cast<DWORD>(arraysize(kChromeExeName))); - } - - return rv; -} - -void WebPluginDelegateImpl::HandleCaptureForMessage(HWND window, - UINT message) { - if (!WebPluginDelegateImpl::IsPluginDelegateWindow(window)) - return; - - switch (message) { - case WM_LBUTTONDOWN: - case WM_MBUTTONDOWN: - case WM_RBUTTONDOWN: - ::SetCapture(window); - break; - - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - ::ReleaseCapture(); - break; - - default: - break; - } -} diff --git a/webkit/glue/plugins/webplugin_file_delegate.h b/webkit/glue/plugins/webplugin_file_delegate.h deleted file mode 100644 index 162516c..0000000 --- a/webkit/glue/plugins/webplugin_file_delegate.h +++ /dev/null @@ -1,35 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_WEBPLUGIN_FILE_DELEGATE_H_ -#define WEBKIT_GLUE_PLUGINS_WEBPLUGIN_FILE_DELEGATE_H_ - -#include "base/basictypes.h" -#include "third_party/npapi/bindings/npapi_extensions.h" - -namespace webkit_glue { - -// Interface for the NPAPI file extensions. This class implements "NOP" -// versions of all these functions so it can be used seamlessly by the -// "regular" plugin delegate while being overridden by the "pepper" one. -class WebPluginFileDelegate { - public: - // See NPChooseFilePtr in npapi_extensions.h. Returns true on success, on - // cancel, returns true but *filename will be filled with an empty FilePath - // and *handle will be 0. - virtual bool ChooseFile(const char* mime_types, - int mode, - NPChooseFileCallback callback, - void* user_data) { - return false; - } - - protected: - WebPluginFileDelegate() {} - virtual ~WebPluginFileDelegate() {} -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_PLUGINS_WEBPLUGIN_FILE_DELEGATE_H_ diff --git a/webkit/glue/plugins/webplugin_impl.cc b/webkit/glue/plugins/webplugin_impl.cc deleted file mode 100644 index cd91744..0000000 --- a/webkit/glue/plugins/webplugin_impl.cc +++ /dev/null @@ -1,1379 +0,0 @@ -// 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 "webkit/glue/plugins/webplugin_impl.h" - -#include "base/linked_ptr.h" -#include "base/logging.h" -#include "base/message_loop.h" -#include "base/string_util.h" -#include "base/stringprintf.h" -#include "base/utf_string_conversions.h" -#include "gfx/rect.h" -#include "googleurl/src/gurl.h" -#include "net/base/escape.h" -#include "net/base/net_errors.h" -#include "net/http/http_response_headers.h" -#include "skia/ext/platform_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebConsoleMessage.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCookieJar.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h" -#include "third_party/WebKit/WebKit/chromium/public/WebData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPHeaderVisitor.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKitClient.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginContainer.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLLoader.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/appcache/web_application_cache_host_impl.h" -#include "webkit/glue/multipart_response_delegate.h" -#include "webkit/glue/plugins/plugin_host.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/webplugin_delegate.h" -#include "webkit/glue/plugins/webplugin_page_delegate.h" - -using appcache::WebApplicationCacheHostImpl; -using WebKit::WebCanvas; -using WebKit::WebConsoleMessage; -using WebKit::WebCookieJar; -using WebKit::WebCString; -using WebKit::WebCursorInfo; -using WebKit::WebData; -using WebKit::WebDataSource; -using WebKit::WebDevToolsAgent; -using WebKit::WebFrame; -using WebKit::WebHTTPBody; -using WebKit::WebHTTPHeaderVisitor; -using WebKit::WebInputEvent; -using WebKit::WebKeyboardEvent; -using WebKit::WebMouseEvent; -using WebKit::WebPluginContainer; -using WebKit::WebPluginParams; -using WebKit::WebRect; -using WebKit::WebString; -using WebKit::WebURL; -using WebKit::WebURLError; -using WebKit::WebURLLoader; -using WebKit::WebURLLoaderClient; -using WebKit::WebURLRequest; -using WebKit::WebURLResponse; -using WebKit::WebVector; -using WebKit::WebView; -using webkit_glue::MultipartResponseDelegate; - -namespace webkit_glue { -namespace { - -// This class handles individual multipart responses. It is instantiated when -// we receive HTTP status code 206 in the HTTP response. This indicates -// that the response could have multiple parts each separated by a boundary -// specified in the response header. -class MultiPartResponseClient : public WebURLLoaderClient { - public: - explicit MultiPartResponseClient(WebPluginResourceClient* resource_client) - : resource_client_(resource_client) { - Clear(); - } - - virtual void willSendRequest( - WebURLLoader*, WebURLRequest&, const WebURLResponse&) {} - virtual void didSendData( - WebURLLoader*, unsigned long long, unsigned long long) {} - - // Called when the multipart parser encounters an embedded multipart - // response. - virtual void didReceiveResponse( - WebURLLoader*, const WebURLResponse& response) { - if (!MultipartResponseDelegate::ReadContentRanges( - response, - &byte_range_lower_bound_, - &byte_range_upper_bound_)) { - NOTREACHED(); - return; - } - - resource_response_ = response; - } - - // Receives individual part data from a multipart response. - virtual void didReceiveData( - WebURLLoader*, const char* data, int data_size) { - // TODO(ananta) - // We should defer further loads on multipart resources on the same lines - // as regular resources requested by plugins to prevent reentrancy. - resource_client_->DidReceiveData( - data, data_size, byte_range_lower_bound_); - byte_range_lower_bound_ += data_size; - } - - virtual void didFinishLoading(WebURLLoader*, double finishTime) {} - virtual void didFail(WebURLLoader*, const WebURLError&) {} - - void Clear() { - resource_response_.reset(); - byte_range_lower_bound_ = 0; - byte_range_upper_bound_ = 0; - } - - private: - WebURLResponse resource_response_; - // The lower bound of the byte range. - int byte_range_lower_bound_; - // The upper bound of the byte range. - int byte_range_upper_bound_; - // The handler for the data. - WebPluginResourceClient* resource_client_; -}; - -class HeaderFlattener : public WebHTTPHeaderVisitor { - public: - HeaderFlattener(std::string* buf) : buf_(buf) { - } - - virtual void visitHeader(const WebString& name, const WebString& value) { - // TODO(darin): Should we really exclude headers with an empty value? - if (!name.isEmpty() && !value.isEmpty()) { - buf_->append(name.utf8()); - buf_->append(": "); - buf_->append(value.utf8()); - buf_->append("\n"); - } - } - - private: - std::string* buf_; -}; - -std::string GetAllHeaders(const WebURLResponse& response) { - // TODO(darin): It is possible for httpStatusText to be empty and still have - // an interesting response, so this check seems wrong. - std::string result; - const WebString& status = response.httpStatusText(); - if (status.isEmpty()) - return result; - - // TODO(darin): Shouldn't we also report HTTP version numbers? - result = base::StringPrintf("HTTP %d ", response.httpStatusCode()); - result.append(status.utf8()); - result.append("\n"); - - HeaderFlattener flattener(&result); - response.visitHTTPHeaderFields(&flattener); - - return result; -} - -struct ResponseInfo { - GURL url; - std::string mime_type; - uint32 last_modified; - uint32 expected_length; -}; - -void GetResponseInfo(const WebURLResponse& response, - ResponseInfo* response_info) { - response_info->url = response.url(); - response_info->mime_type = response.mimeType().utf8(); - - // Measured in seconds since 12:00 midnight GMT, January 1, 1970. - response_info->last_modified = - static_cast<uint32>(response.lastModifiedDate()); - - // If the length comes in as -1, then it indicates that it was not - // read off the HTTP headers. We replicate Safari webkit behavior here, - // which is to set it to 0. - response_info->expected_length = - static_cast<uint32>(std::max(response.expectedContentLength(), 0LL)); - - WebString content_encoding = - response.httpHeaderField(WebString::fromUTF8("Content-Encoding")); - if (!content_encoding.isNull() && - !EqualsASCII(content_encoding, "identity")) { - // Don't send the compressed content length to the plugin, which only - // cares about the decoded length. - response_info->expected_length = 0; - } -} - -} // namespace - -// WebKit::WebPlugin ---------------------------------------------------------- - -struct WebPluginImpl::ClientInfo { - unsigned long id; - WebPluginResourceClient* client; - WebKit::WebURLRequest request; - bool pending_failure_notification; - linked_ptr<WebKit::WebURLLoader> loader; - bool notify_redirects; -}; - -bool WebPluginImpl::initialize(WebPluginContainer* container) { - if (!page_delegate_) - return false; - - WebPluginDelegate* plugin_delegate = page_delegate_->CreatePluginDelegate( - file_path_, mime_type_); - if (!plugin_delegate) - return false; - - // Set the container before Initialize because the plugin may - // synchronously call NPN_GetValue to get its container during its - // initialization. - SetContainer(container); - bool ok = plugin_delegate->Initialize( - plugin_url_, arg_names_, arg_values_, this, load_manually_); - if (!ok) { - plugin_delegate->PluginDestroyed(); - return false; - } - - delegate_ = plugin_delegate; - - return true; -} - -void WebPluginImpl::destroy() { - SetContainer(NULL); - MessageLoop::current()->DeleteSoon(FROM_HERE, this); -} - -NPObject* WebPluginImpl::scriptableObject() { - return delegate_->GetPluginScriptableObject(); -} - -void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& paint_rect) { - if (!delegate_ || !container_) - return; - -#if defined(OS_WIN) - // Force a geometry update if needed to allow plugins like media player - // which defer the initial geometry update to work. - container_->reportGeometry(); -#endif // OS_WIN - - // Note that |canvas| is only used when in windowless mode. - delegate_->Paint(canvas, paint_rect); -} - -void WebPluginImpl::updateGeometry( - const WebRect& window_rect, const WebRect& clip_rect, - const WebVector<WebRect>& cutout_rects, bool is_visible) { - WebPluginGeometry new_geometry; - new_geometry.window = window_; - new_geometry.window_rect = window_rect; - new_geometry.clip_rect = clip_rect; - new_geometry.visible = is_visible; - new_geometry.rects_valid = true; - for (size_t i = 0; i < cutout_rects.size(); ++i) - new_geometry.cutout_rects.push_back(cutout_rects[i]); - - // Only send DidMovePlugin if the geometry changed in some way. - if (window_ && - page_delegate_ && - (first_geometry_update_ || !new_geometry.Equals(geometry_))) { - page_delegate_->DidMovePlugin(new_geometry); - } - - // Only UpdateGeometry if either the window or clip rects have changed. - if (first_geometry_update_ || - new_geometry.window_rect != geometry_.window_rect || - new_geometry.clip_rect != geometry_.clip_rect) { - // Notify the plugin that its parameters have changed. - delegate_->UpdateGeometry(new_geometry.window_rect, new_geometry.clip_rect); - } - - // Initiate a download on the plugin url. This should be done for the - // first update geometry sequence. We need to ensure that the plugin - // receives the geometry update before it starts receiving data. - if (first_geometry_update_) { - // An empty url corresponds to an EMBED tag with no src attribute. - if (!load_manually_ && plugin_url_.is_valid()) { - // The Flash plugin hangs for a while if it receives data before - // receiving valid plugin geometry. By valid geometry we mean the - // geometry received by a call to setFrameRect in the Webkit - // layout code path. To workaround this issue we download the - // plugin source url on a timer. - MessageLoop::current()->PostDelayedTask( - FROM_HERE, method_factory_.NewRunnableMethod( - &WebPluginImpl::OnDownloadPluginSrcUrl), 0); - } - } - -#if defined(OS_WIN) - // Don't cache the geometry during the first geometry update. The first - // geometry update sequence is received when Widget::setParent is called. - // For plugins like media player which have a bug where they only honor - // the first geometry update, we have a quirk which ignores the first - // geometry update. To ensure that these plugins work correctly in cases - // where we receive only one geometry update from webkit, we also force - // a geometry update during paint which should go out correctly as the - // initial geometry update was not cached. - if (!first_geometry_update_) - geometry_ = new_geometry; -#else // OS_WIN - geometry_ = new_geometry; -#endif // OS_WIN - first_geometry_update_ = false; -} - -unsigned WebPluginImpl::getBackingTextureId() { - // Regular plugins do not have a backing texture. - return 0; -} - -void WebPluginImpl::updateFocus(bool focused) { - if (accepts_input_events_) - delegate_->SetFocus(focused); -} - -void WebPluginImpl::updateVisibility(bool visible) { - if (!window_ || !page_delegate_) - return; - - WebPluginGeometry move; - move.window = window_; - move.window_rect = gfx::Rect(); - move.clip_rect = gfx::Rect(); - move.rects_valid = false; - move.visible = visible; - - page_delegate_->DidMovePlugin(move); -} - -bool WebPluginImpl::acceptsInputEvents() { - return accepts_input_events_; -} - -bool WebPluginImpl::handleInputEvent( - const WebInputEvent& event, WebCursorInfo& cursor_info) { - // Swallow context menu events in order to suppress the default context menu. - if (event.type == WebInputEvent::ContextMenu) - return true; - - return delegate_->HandleInputEvent(event, &cursor_info); -} - -void WebPluginImpl::didReceiveResponse(const WebURLResponse& response) { - ignore_response_error_ = false; - - ResponseInfo response_info; - GetResponseInfo(response, &response_info); - - delegate_->DidReceiveManualResponse( - response_info.url, - response_info.mime_type, - GetAllHeaders(response), - response_info.expected_length, - response_info.last_modified); -} - -void WebPluginImpl::didReceiveData(const char* data, int data_length) { - delegate_->DidReceiveManualData(data, data_length); -} - -void WebPluginImpl::didFinishLoading() { - delegate_->DidFinishManualLoading(); -} - -void WebPluginImpl::didFailLoading(const WebURLError& error) { - if (!ignore_response_error_) - delegate_->DidManualLoadFail(); -} - -void WebPluginImpl::didFinishLoadingFrameRequest( - const WebURL& url, void* notify_data) { - if (delegate_) { - // We're converting a void* into an arbitrary int id. Though - // these types are the same size on all the platforms we support, - // the compiler may complain as though they are different, so to - // make the casting gods happy go through an intptr_t (the union - // of void* and int) rather than converting straight across. - delegate_->DidFinishLoadWithReason( - url, NPRES_DONE, reinterpret_cast<intptr_t>(notify_data)); - } -} - -void WebPluginImpl::didFailLoadingFrameRequest( - const WebURL& url, void* notify_data, const WebURLError& error) { - if (!delegate_) - return; - - NPReason reason = - error.reason == net::ERR_ABORTED ? NPRES_USER_BREAK : NPRES_NETWORK_ERR; - // See comment in didFinishLoadingFrameRequest about the cast here. - delegate_->DidFinishLoadWithReason( - url, reason, reinterpret_cast<intptr_t>(notify_data)); -} - -bool WebPluginImpl::supportsPaginatedPrint() { - if (!delegate_) - return false; - return delegate_->PrintSupportsPrintExtension(); -} - -int WebPluginImpl::printBegin(const WebRect& printable_area, int printer_dpi) { - if (!delegate_) - return 0; - - if (!supportsPaginatedPrint()) - return 0; - - return delegate_->PrintBegin(printable_area, printer_dpi); -} - -bool WebPluginImpl::printPage(int page_number, WebCanvas* canvas) { - if (!delegate_) - return false; - - return delegate_->PrintPage(page_number, canvas); -} - -void WebPluginImpl::printEnd() { - if (delegate_) - delegate_->PrintEnd(); -} - -bool WebPluginImpl::hasSelection() const { - if (!delegate_) - return false; - - return delegate_->HasSelection(); -} - -WebKit::WebString WebPluginImpl::selectionAsText() const { - if (!delegate_) - return WebString(); - - return delegate_->GetSelectionAsText(); -} - -WebKit::WebString WebPluginImpl::selectionAsMarkup() const { - if (!delegate_) - return WebString(); - - return delegate_->GetSelectionAsMarkup(); -} - -void WebPluginImpl::setZoomFactor(float scale, bool text_only) { - if (delegate_) - delegate_->SetZoomFactor(scale, text_only); -} - -bool WebPluginImpl::startFind(const WebKit::WebString& search_text, - bool case_sensitive, - int identifier) { - if (!delegate_) - return false; - return delegate_->StartFind(search_text, case_sensitive, identifier); -} - -void WebPluginImpl::selectFindResult(bool forward) { - if (delegate_) - delegate_->SelectFindResult(forward); -} - -void WebPluginImpl::stopFind() { - if (delegate_) - delegate_->StopFind(); -} - - -// ----------------------------------------------------------------------------- - -WebPluginImpl::WebPluginImpl( - WebFrame* webframe, - const WebPluginParams& params, - const FilePath& file_path, - const std::string& mime_type, - const base::WeakPtr<WebPluginPageDelegate>& page_delegate) - : windowless_(false), - window_(gfx::kNullPluginWindow), - accepts_input_events_(false), - page_delegate_(page_delegate), - webframe_(webframe), - delegate_(NULL), - container_(NULL), - plugin_url_(params.url), - load_manually_(params.loadManually), - first_geometry_update_(true), - ignore_response_error_(false), - file_path_(file_path), - mime_type_(mime_type), - ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) { - DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size()); - StringToLowerASCII(&mime_type_); - - for (size_t i = 0; i < params.attributeNames.size(); ++i) { - arg_names_.push_back(params.attributeNames[i].utf8()); - arg_values_.push_back(params.attributeValues[i].utf8()); - } -} - -WebPluginImpl::~WebPluginImpl() { -} - -void WebPluginImpl::SetWindow(gfx::PluginWindowHandle window) { -#if defined(OS_MACOSX) - // The only time this is called twice, and the second time with a - // non-zero PluginWindowHandle, is the case when this WebPluginImpl - // is created on behalf of the GPU plugin. This entire code path - // will go away soon, as soon as the GPU plugin becomes the GPU - // process, so it is being separated out for easy deletion. - - // The logic we want here is: if (window) DCHECK(!window_); - DCHECK(!(window_ && window)); - window_ = window; - // Lie to ourselves about being windowless even if we got a fake - // plugin window handle, so we continue to get input events. - windowless_ = true; - accepts_input_events_ = true; - // We do not really need to notify the page delegate that a plugin - // window was created -- so don't. -#else - if (window) { - DCHECK(!windowless_); - window_ = window; - accepts_input_events_ = false; - if (page_delegate_) { - // Tell the view delegate that the plugin window was created, so that it - // can create necessary container widgets. - page_delegate_->CreatedPluginWindow(window); - } - } else { - DCHECK(!window_); // Make sure not called twice. - windowless_ = true; - accepts_input_events_ = true; - } -#endif -} - -void WebPluginImpl::WillDestroyWindow(gfx::PluginWindowHandle window) { - DCHECK_EQ(window, window_); - window_ = gfx::kNullPluginWindow; - if (page_delegate_) - page_delegate_->WillDestroyPluginWindow(window); -} - -GURL WebPluginImpl::CompleteURL(const char* url) { - if (!webframe_) { - NOTREACHED(); - return GURL(); - } - // TODO(darin): Is conversion from UTF8 correct here? - return webframe_->document().completeURL(WebString::fromUTF8(url)); -} - -void WebPluginImpl::CancelResource(unsigned long id) { - for (size_t i = 0; i < clients_.size(); ++i) { - if (clients_[i].id == id) { - if (clients_[i].loader.get()) { - clients_[i].loader->setDefersLoading(false); - clients_[i].loader->cancel(); - RemoveClient(i); - } - return; - } - } -} - -bool WebPluginImpl::SetPostData(WebURLRequest* request, - const char *buf, - uint32 length) { - std::vector<std::string> names; - std::vector<std::string> values; - std::vector<char> body; - bool rv = NPAPI::PluginHost::SetPostData(buf, length, &names, &values, &body); - - for (size_t i = 0; i < names.size(); ++i) { - request->addHTTPHeaderField(WebString::fromUTF8(names[i]), - WebString::fromUTF8(values[i])); - } - - WebString content_type_header = WebString::fromUTF8("Content-Type"); - const WebString& content_type = - request->httpHeaderField(content_type_header); - if (content_type.isEmpty()) { - request->setHTTPHeaderField( - content_type_header, - WebString::fromUTF8("application/x-www-form-urlencoded")); - } - - WebHTTPBody http_body; - if (body.size()) { - http_body.initialize(); - http_body.appendData(WebData(&body[0], body.size())); - } - request->setHTTPBody(http_body); - - return rv; -} - -bool WebPluginImpl::IsValidUrl(const GURL& url, Referrer referrer_flag) { - if (referrer_flag == PLUGIN_SRC && - mime_type_ == "application/x-shockwave-flash" && - url.GetOrigin() != plugin_url_.GetOrigin()) { - // Do url check to make sure that there are no @, ;, \ chars in between url - // scheme and url path. - const char* url_to_check(url.spec().data()); - url_parse::Parsed parsed; - url_parse::ParseStandardURL(url_to_check, strlen(url_to_check), &parsed); - if (parsed.path.begin <= parsed.scheme.end()) - return true; - std::string string_to_search; - string_to_search.assign(url_to_check + parsed.scheme.end(), - parsed.path.begin - parsed.scheme.end()); - if (string_to_search.find("@") != std::string::npos || - string_to_search.find(";") != std::string::npos || - string_to_search.find("\\") != std::string::npos) - return false; - } - - return true; -} - -WebPluginImpl::RoutingStatus WebPluginImpl::RouteToFrame( - const char* url, - bool is_javascript_url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - int notify_id, - Referrer referrer_flag) { - // If there is no target, there is nothing to do - if (!target) - return NOT_ROUTED; - - // This could happen if the WebPluginContainer was already deleted. - if (!webframe_) - return NOT_ROUTED; - - WebString target_str = WebString::fromUTF8(target); - - // Take special action for JavaScript URLs - if (is_javascript_url) { - WebFrame* target_frame = - webframe_->view()->findFrameByName(target_str, webframe_); - // For security reasons, do not allow JavaScript on frames - // other than this frame. - if (target_frame != webframe_) { - // TODO(darin): Localize this message. - const char kMessage[] = - "Ignoring cross-frame javascript URL load requested by plugin."; - webframe_->addMessageToConsole( - WebConsoleMessage(WebConsoleMessage::LevelError, - WebString::fromUTF8(kMessage))); - return ROUTED; - } - - // Route javascript calls back to the plugin. - return NOT_ROUTED; - } - - // If we got this far, we're routing content to a target frame. - // Go fetch the URL. - - GURL complete_url = CompleteURL(url); - // Remove when flash bug is fixed. http://crbug.com/40016. - if (!WebPluginImpl::IsValidUrl(complete_url, referrer_flag)) - return INVALID_URL; - - if (strcmp(method, "GET") != 0) { - // We're only going to route HTTP/HTTPS requests - if (!(complete_url.SchemeIs("http") || complete_url.SchemeIs("https"))) - return INVALID_URL; - } - - WebURLRequest request(complete_url); - SetReferrer(&request, referrer_flag); - - request.setHTTPMethod(WebString::fromUTF8(method)); - request.setFirstPartyForCookies( - webframe_->document().firstPartyForCookies()); - if (len > 0) { - if (!SetPostData(&request, buf, len)) { - // Uhoh - we're in trouble. There isn't a good way - // to recover at this point. Break out. - NOTREACHED(); - return ROUTED; - } - } - - container_->loadFrameRequest( - request, target_str, notify_id != 0, reinterpret_cast<void*>(notify_id)); - return ROUTED; -} - -NPObject* WebPluginImpl::GetWindowScriptNPObject() { - if (!webframe_) { - NOTREACHED(); - return NULL; - } - return webframe_->windowObject(); -} - -NPObject* WebPluginImpl::GetPluginElement() { - return container_->scriptableObjectForElement(); -} - -void WebPluginImpl::SetCookie(const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie) { - if (!page_delegate_) - return; - - WebCookieJar* cookie_jar = page_delegate_->GetCookieJar(); - if (!cookie_jar) { - DLOG(WARNING) << "No cookie jar!"; - return; - } - - cookie_jar->setCookie( - url, first_party_for_cookies, WebString::fromUTF8(cookie)); -} - -std::string WebPluginImpl::GetCookies(const GURL& url, - const GURL& first_party_for_cookies) { - if (!page_delegate_) - return std::string(); - - WebCookieJar* cookie_jar = page_delegate_->GetCookieJar(); - if (!cookie_jar) { - DLOG(WARNING) << "No cookie jar!"; - return std::string(); - } - - return UTF16ToUTF8(cookie_jar->cookies(url, first_party_for_cookies)); -} - -void WebPluginImpl::ShowModalHTMLDialog(const GURL& url, int width, int height, - const std::string& json_arguments, - std::string* json_retval) { - if (page_delegate_) { - page_delegate_->ShowModalHTMLDialogForPlugin( - url, gfx::Size(width, height), json_arguments, json_retval); - } -} - -void WebPluginImpl::OnMissingPluginStatus(int status) { - NOTREACHED(); -} - -void WebPluginImpl::URLRedirectResponse(bool allow, int resource_id) { - for (size_t i = 0; i < clients_.size(); ++i) { - if (clients_[i].id == static_cast<unsigned long>(resource_id)) { - if (clients_[i].loader.get()) { - if (allow) { - clients_[i].loader->setDefersLoading(false); - } else { - clients_[i].loader->cancel(); - clients_[i].client->DidFail(); - } - } - break; - } - } -} - -void WebPluginImpl::Invalidate() { - if (container_) - container_->invalidate(); -} - -void WebPluginImpl::InvalidateRect(const gfx::Rect& rect) { - if (container_) - container_->invalidateRect(rect); -} - -void WebPluginImpl::OnDownloadPluginSrcUrl() { - HandleURLRequestInternal( - plugin_url_.spec().c_str(), "GET", NULL, NULL, 0, 0, false, DOCUMENT_URL, - false); -} - -WebPluginResourceClient* WebPluginImpl::GetClientFromLoader( - WebURLLoader* loader) { - ClientInfo* client_info = GetClientInfoFromLoader(loader); - if (client_info) - return client_info->client; - return NULL; -} - -WebPluginImpl::ClientInfo* WebPluginImpl::GetClientInfoFromLoader( - WebURLLoader* loader) { - for (size_t i = 0; i < clients_.size(); ++i) { - if (clients_[i].loader.get() == loader) - return &clients_[i]; - } - - NOTREACHED(); - return 0; -} - -void WebPluginImpl::willSendRequest(WebURLLoader* loader, - WebURLRequest& request, - const WebURLResponse& response) { - WebPluginImpl::ClientInfo* client_info = GetClientInfoFromLoader(loader); - if (client_info) { - if (net::HttpResponseHeaders::IsRedirectResponseCode( - response.httpStatusCode())) { - // If the plugin does not participate in url redirect notifications then - // just block cross origin 307 POST redirects. - if (!client_info->notify_redirects) { - if (response.httpStatusCode() == 307 && - LowerCaseEqualsASCII(request.httpMethod().utf8(), "post")) { - GURL original_request_url(response.url()); - GURL response_url(request.url()); - if (original_request_url.GetOrigin() != response_url.GetOrigin()) { - loader->setDefersLoading(true); - loader->cancel(); - client_info->client->DidFail(); - return; - } - } - } else { - loader->setDefersLoading(true); - } - } - client_info->client->WillSendRequest(request.url(), - response.httpStatusCode()); - } -} - -void WebPluginImpl::didSendData(WebURLLoader* loader, - unsigned long long bytes_sent, - unsigned long long total_bytes_to_be_sent) { -} - -void WebPluginImpl::didReceiveResponse(WebURLLoader* loader, - const WebURLResponse& response) { - static const int kHttpPartialResponseStatusCode = 206; - static const int kHttpResponseSuccessStatusCode = 200; - - WebPluginResourceClient* client = GetClientFromLoader(loader); - if (!client) - return; - - ResponseInfo response_info; - GetResponseInfo(response, &response_info); - - bool request_is_seekable = true; - if (client->IsMultiByteResponseExpected()) { - if (response.httpStatusCode() == kHttpPartialResponseStatusCode) { - HandleHttpMultipartResponse(response, client); - return; - } else if (response.httpStatusCode() == kHttpResponseSuccessStatusCode) { - // If the client issued a byte range request and the server responds with - // HTTP 200 OK, it indicates that the server does not support byte range - // requests. - // We need to emulate Firefox behavior by doing the following:- - // 1. Destroy the plugin instance in the plugin process. Ensure that - // existing resource requests initiated for the plugin instance - // continue to remain valid. - // 2. Create a new plugin instance and notify it about the response - // received here. - if (!ReinitializePluginForResponse(loader)) { - NOTREACHED(); - return; - } - - // The server does not support byte range requests. No point in creating - // seekable streams. - request_is_seekable = false; - - delete client; - client = NULL; - - // Create a new resource client for this request. - for (size_t i = 0; i < clients_.size(); ++i) { - if (clients_[i].loader.get() == loader) { - WebPluginResourceClient* resource_client = - delegate_->CreateResourceClient(clients_[i].id, plugin_url_, 0); - clients_[i].client = resource_client; - client = resource_client; - break; - } - } - - DCHECK(client != NULL); - } - } - - // Calling into a plugin could result in reentrancy if the plugin yields - // control to the OS like entering a modal loop etc. Prevent this by - // stopping further loading until the plugin notifies us that it is ready to - // accept data - loader->setDefersLoading(true); - - client->DidReceiveResponse( - response_info.mime_type, - GetAllHeaders(response), - response_info.expected_length, - response_info.last_modified, - request_is_seekable); - - if (WebDevToolsAgent* devtools_agent = GetDevToolsAgent()) { - ClientInfo* client_info = GetClientInfoFromLoader(loader); - if (client_info) - devtools_agent->didReceiveResponse(client_info->id, response); - } - - // Bug http://b/issue?id=925559. The flash plugin would not handle the HTTP - // error codes in the stream header and as a result, was unaware of the - // fate of the HTTP requests issued via NPN_GetURLNotify. Webkit and FF - // destroy the stream and invoke the NPP_DestroyStream function on the - // plugin if the HTTP request fails. - const GURL& url = response.url(); - if (url.SchemeIs("http") || url.SchemeIs("https")) { - if (response.httpStatusCode() < 100 || response.httpStatusCode() >= 400) { - // The plugin instance could be in the process of deletion here. - // Verify if the WebPluginResourceClient instance still exists before - // use. - ClientInfo* client_info = GetClientInfoFromLoader(loader); - if (client_info) { - client_info->pending_failure_notification = true; - } - } - } -} - -void WebPluginImpl::didReceiveData(WebURLLoader* loader, - const char *buffer, - int length) { - WebPluginResourceClient* client = GetClientFromLoader(loader); - if (!client) - return; - - // ClientInfo can be removed from clients_ vector by next statements. - if (WebDevToolsAgent* devtools_agent = GetDevToolsAgent()) { - ClientInfo* client_info = GetClientInfoFromLoader(loader); - if (client_info) - devtools_agent->didReceiveData(client_info->id, length); - } - MultiPartResponseHandlerMap::iterator index = - multi_part_response_map_.find(client); - if (index != multi_part_response_map_.end()) { - MultipartResponseDelegate* multi_part_handler = (*index).second; - DCHECK(multi_part_handler != NULL); - multi_part_handler->OnReceivedData(buffer, length); - } else { - loader->setDefersLoading(true); - client->DidReceiveData(buffer, length, 0); - } -} - -void WebPluginImpl::didFinishLoading(WebURLLoader* loader, double finishTime) { - ClientInfo* client_info = GetClientInfoFromLoader(loader); - if (client_info && client_info->client) { - MultiPartResponseHandlerMap::iterator index = - multi_part_response_map_.find(client_info->client); - if (index != multi_part_response_map_.end()) { - delete (*index).second; - multi_part_response_map_.erase(index); - if (page_delegate_) - page_delegate_->DidStopLoadingForPlugin(); - } - loader->setDefersLoading(true); - WebPluginResourceClient* resource_client = client_info->client; - // The ClientInfo can get deleted in the call to DidFinishLoading below. - // It is not safe to access this structure after that. - client_info->client = NULL; - resource_client->DidFinishLoading(); - - if (WebDevToolsAgent* devtools_agent = GetDevToolsAgent()) - devtools_agent->didFinishLoading(client_info->id); - } -} - -void WebPluginImpl::didFail(WebURLLoader* loader, - const WebURLError& error) { - ClientInfo* client_info = GetClientInfoFromLoader(loader); - if (client_info && client_info->client) { - loader->setDefersLoading(true); - WebPluginResourceClient* resource_client = client_info->client; - // The ClientInfo can get deleted in the call to DidFail below. - // It is not safe to access this structure after that. - client_info->client = NULL; - resource_client->DidFail(); - - if (WebDevToolsAgent* devtools_agent = GetDevToolsAgent()) - devtools_agent->didFailLoading(client_info->id, error); - } -} - -void WebPluginImpl::RemoveClient(size_t i) { - clients_.erase(clients_.begin() + i); -} - -void WebPluginImpl::RemoveClient(WebURLLoader* loader) { - for (size_t i = 0; i < clients_.size(); ++i) { - if (clients_[i].loader.get() == loader) { - RemoveClient(i); - return; - } - } -} - -void WebPluginImpl::SetContainer(WebPluginContainer* container) { - if (!container) - TearDownPluginInstance(NULL); - container_ = container; -} - -void WebPluginImpl::HandleURLRequest(const char* url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - int notify_id, - bool popups_allowed, - bool notify_redirects) { - // GetURL/PostURL requests initiated explicitly by plugins should specify the - // plugin SRC url as the referrer if it is available. - HandleURLRequestInternal( - url, method, target, buf, len, notify_id, popups_allowed, PLUGIN_SRC, - notify_redirects); -} - -void WebPluginImpl::HandleURLRequestInternal(const char* url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - int notify_id, - bool popups_allowed, - Referrer referrer_flag, - bool notify_redirects) { - // For this request, we either route the output to a frame - // because a target has been specified, or we handle the request - // here, i.e. by executing the script if it is a javascript url - // or by initiating a download on the URL, etc. There is one special - // case in that the request is a javascript url and the target is "_self", - // in which case we route the output to the plugin rather than routing it - // to the plugin's frame. - bool is_javascript_url = StartsWithASCII(url, "javascript:", false); - RoutingStatus routing_status = RouteToFrame( - url, is_javascript_url, method, target, buf, len, notify_id, - referrer_flag); - if (routing_status == ROUTED) - return; - - if (is_javascript_url) { - GURL gurl(url); - WebString result = container_->executeScriptURL(gurl, popups_allowed); - - // delegate_ could be NULL because executeScript caused the container to - // be deleted. - if (delegate_) { - delegate_->SendJavaScriptStream( - gurl, result.utf8(), !result.isNull(), notify_id); - } - - return; - } - - unsigned long resource_id = GetNextResourceId(); - if (!resource_id) - return; - - GURL complete_url = CompleteURL(url); - // Remove when flash bug is fixed. http://crbug.com/40016. - if (!WebPluginImpl::IsValidUrl(complete_url, referrer_flag)) - return; - - WebPluginResourceClient* resource_client = delegate_->CreateResourceClient( - resource_id, complete_url, notify_id); - if (!resource_client) - return; - - // If the RouteToFrame call returned a failure then inform the result - // back to the plugin asynchronously. - if ((routing_status == INVALID_URL) || - (routing_status == GENERAL_FAILURE)) { - resource_client->DidFail(); - return; - } - - // CreateResourceClient() sends a synchronous IPC message so it's possible - // that TearDownPluginInstance() may have been called in the nested - // message loop. If so, don't start the request. - if (!delegate_) - return; - - InitiateHTTPRequest(resource_id, resource_client, complete_url, method, buf, - len, NULL, referrer_flag, notify_redirects); -} - -unsigned long WebPluginImpl::GetNextResourceId() { - if (!webframe_) - return 0; - WebView* view = webframe_->view(); - if (!view) - return 0; - return view->createUniqueIdentifierForRequest(); -} - -bool WebPluginImpl::InitiateHTTPRequest(unsigned long resource_id, - WebPluginResourceClient* client, - const GURL& url, - const char* method, - const char* buf, - int buf_len, - const char* range_info, - Referrer referrer_flag, - bool notify_redirects) { - if (!client) { - NOTREACHED(); - return false; - } - - ClientInfo info; - info.id = resource_id; - info.client = client; - info.request.initialize(); - info.request.setURL(url); - info.request.setFirstPartyForCookies( - webframe_->document().firstPartyForCookies()); - info.request.setRequestorProcessID(delegate_->GetProcessId()); - info.request.setTargetType(WebURLRequest::TargetIsObject); - info.request.setHTTPMethod(WebString::fromUTF8(method)); - info.pending_failure_notification = false; - info.notify_redirects = notify_redirects; - - if (range_info) { - info.request.addHTTPHeaderField(WebString::fromUTF8("Range"), - WebString::fromUTF8(range_info)); - } - - if (strcmp(method, "POST") == 0) { - // Adds headers or form data to a request. This must be called before - // we initiate the actual request. - SetPostData(&info.request, buf, buf_len); - } - - SetReferrer(&info.request, referrer_flag); - - // Sets the routing id to associate the ResourceRequest with the RenderView. - webframe_->dispatchWillSendRequest(info.request); - - // Sets the appcache host id to allow retrieval from the appcache. - if (WebApplicationCacheHostImpl* appcache_host = - WebApplicationCacheHostImpl::FromFrame(webframe_)) { - appcache_host->willStartSubResourceRequest(info.request); - } - - if (WebDevToolsAgent* devtools_agent = GetDevToolsAgent()) { - devtools_agent->identifierForInitialRequest(resource_id, webframe_, - info.request); - devtools_agent->willSendRequest(resource_id, info.request); - } - - info.loader.reset(WebKit::webKitClient()->createURLLoader()); - if (!info.loader.get()) - return false; - info.loader->loadAsynchronously(info.request, this); - - clients_.push_back(info); - return true; -} - -void WebPluginImpl::CancelDocumentLoad() { - if (webframe_) { - ignore_response_error_ = true; - webframe_->stopLoading(); - } -} - -void WebPluginImpl::InitiateHTTPRangeRequest( - const char* url, const char* range_info, int range_request_id) { - unsigned long resource_id = GetNextResourceId(); - if (!resource_id) - return; - - GURL complete_url = CompleteURL(url); - // Remove when flash bug is fixed. http://crbug.com/40016. - if (!WebPluginImpl::IsValidUrl(complete_url, - load_manually_ ? NO_REFERRER : PLUGIN_SRC)) - return; - - WebPluginResourceClient* resource_client = - delegate_->CreateSeekableResourceClient(resource_id, range_request_id); - InitiateHTTPRequest( - resource_id, resource_client, complete_url, "GET", NULL, 0, range_info, - load_manually_ ? NO_REFERRER : PLUGIN_SRC, false); -} - -void WebPluginImpl::SetDeferResourceLoading(unsigned long resource_id, - bool defer) { - std::vector<ClientInfo>::iterator client_index = clients_.begin(); - while (client_index != clients_.end()) { - ClientInfo& client_info = *client_index; - - if (client_info.id == resource_id) { - client_info.loader->setDefersLoading(defer); - - // If we determined that the request had failed via the HTTP headers - // in the response then we send out a failure notification to the - // plugin process, as certain plugins don't handle HTTP failure codes - // correctly. - if (!defer && client_info.client && - client_info.pending_failure_notification) { - // The ClientInfo and the iterator can become invalid due to the call - // to DidFail below. - WebPluginResourceClient* resource_client = client_info.client; - client_info.loader->cancel(); - clients_.erase(client_index++); - resource_client->DidFail(); - - // Report that resource loading finished. - if (WebDevToolsAgent* devtools_agent = GetDevToolsAgent()) - devtools_agent->didFinishLoading(resource_id); - } - break; - } - client_index++; - } -} - -void WebPluginImpl::HandleHttpMultipartResponse( - const WebURLResponse& response, WebPluginResourceClient* client) { - std::string multipart_boundary; - if (!MultipartResponseDelegate::ReadMultipartBoundary( - response, &multipart_boundary)) { - NOTREACHED(); - return; - } - - if (page_delegate_) - page_delegate_->DidStartLoadingForPlugin(); - - MultiPartResponseClient* multi_part_response_client = - new MultiPartResponseClient(client); - - MultipartResponseDelegate* multi_part_response_handler = - new MultipartResponseDelegate(multi_part_response_client, NULL, - response, - multipart_boundary); - multi_part_response_map_[client] = multi_part_response_handler; -} - -bool WebPluginImpl::ReinitializePluginForResponse( - WebURLLoader* loader) { - WebFrame* webframe = webframe_; - if (!webframe) - return false; - - WebView* webview = webframe->view(); - if (!webview) - return false; - - WebPluginContainer* container_widget = container_; - - // Destroy the current plugin instance. - TearDownPluginInstance(loader); - - container_ = container_widget; - webframe_ = webframe; - - WebPluginDelegate* plugin_delegate = page_delegate_->CreatePluginDelegate( - file_path_, mime_type_); - - bool ok = plugin_delegate && plugin_delegate->Initialize( - plugin_url_, arg_names_, arg_values_, this, load_manually_); - - if (!ok) { - container_ = NULL; - // TODO(iyengar) Should we delete the current plugin instance here? - return false; - } - - delegate_ = plugin_delegate; - - // Force a geometry update to occur to ensure that the plugin becomes - // visible. - container_->reportGeometry(); - - // The plugin move sequences accumulated via DidMove are sent to the browser - // whenever the renderer paints. Force a paint here to ensure that changes - // to the plugin window are propagated to the browser. - container_->invalidate(); - return true; -} - -void WebPluginImpl::TearDownPluginInstance( - WebURLLoader* loader_to_ignore) { - // The container maintains a list of JSObjects which are related to this - // plugin. Tell the frame we're gone so that it can invalidate all of - // those sub JSObjects. - if (container_) - container_->clearScriptObjects(); - - if (delegate_) { - // Call PluginDestroyed() first to prevent the plugin from calling us back - // in the middle of tearing down the render tree. - delegate_->PluginDestroyed(); - delegate_ = NULL; - } - - // Cancel any pending requests because otherwise this deleted object will - // be called by the ResourceDispatcher. - std::vector<ClientInfo>::iterator client_index = clients_.begin(); - while (client_index != clients_.end()) { - ClientInfo& client_info = *client_index; - - if (loader_to_ignore == client_info.loader) { - client_index++; - continue; - } - - if (client_info.loader.get()) - client_info.loader->cancel(); - - client_index = clients_.erase(client_index); - } - - // This needs to be called now and not in the destructor since the - // webframe_ might not be valid anymore. - webframe_ = NULL; - method_factory_.RevokeAll(); -} - -void WebPluginImpl::SetReferrer(WebKit::WebURLRequest* request, - Referrer referrer_flag) { - switch (referrer_flag) { - case DOCUMENT_URL: - webframe_->setReferrerForRequest(*request, GURL()); - break; - - case PLUGIN_SRC: - webframe_->setReferrerForRequest(*request, plugin_url_); - break; - - default: - break; - } -} - -WebDevToolsAgent* WebPluginImpl::GetDevToolsAgent() { - if (!webframe_) - return NULL; - WebView* view = webframe_->view(); - if (!view) - return NULL; - return view->devToolsAgent(); -} - -} // namespace webkit_glue diff --git a/webkit/glue/plugins/webplugin_impl.h b/webkit/glue/plugins/webplugin_impl.h deleted file mode 100644 index 4f3b6c7..0000000 --- a/webkit/glue/plugins/webplugin_impl.h +++ /dev/null @@ -1,332 +0,0 @@ -// 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 WEBKIT_GLUE_WEBPLUGIN_IMPL_H_ -#define WEBKIT_GLUE_WEBPLUGIN_IMPL_H_ - -#include <string> -#include <map> -#include <vector> - -#include "base/basictypes.h" -#include "base/file_path.h" -#include "base/task.h" -#include "base/weak_ptr.h" -#include "gfx/native_widget_types.h" -#include "googleurl/src/gurl.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPlugin.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "third_party/WebKit/WebKit/chromium/public/WebVector.h" -#include "webkit/glue/plugins/webplugin.h" - -class WebViewDelegate; - -namespace WebKit { -class WebDevToolsAgent; -class WebFrame; -class WebPluginContainer; -class WebURLResponse; -class WebURLLoader; -class WebURLRequest; -} - -namespace webkit_glue { - -class MultipartResponseDelegate; -class WebPluginDelegate; -class WebPluginPageDelegate; - -// This is the WebKit side of the plugin implementation that forwards calls, -// after changing out of WebCore types, to a delegate. The delegate may -// be in a different process. -class WebPluginImpl : public WebPlugin, - public WebKit::WebPlugin, - public WebKit::WebURLLoaderClient { - public: - WebPluginImpl( - WebKit::WebFrame* frame, - const WebKit::WebPluginParams& params, - const FilePath& file_path, - const std::string& mime_type, - const base::WeakPtr<WebPluginPageDelegate>& page_delegate); - virtual ~WebPluginImpl(); - - // Helper function for sorting post data. - static bool SetPostData(WebKit::WebURLRequest* request, - const char* buf, - uint32 length); - - virtual WebPluginDelegate* delegate() { return delegate_; } - - private: - // WebKit::WebPlugin methods: - virtual bool initialize( - WebKit::WebPluginContainer* container); - virtual void destroy(); - virtual NPObject* scriptableObject(); - virtual void paint( - WebKit::WebCanvas* canvas, const WebKit::WebRect& paint_rect); - virtual void updateGeometry( - const WebKit::WebRect& frame_rect, const WebKit::WebRect& clip_rect, - const WebKit::WebVector<WebKit::WebRect>& cut_outs, bool is_visible); - virtual unsigned getBackingTextureId(); - virtual void updateFocus(bool focused); - virtual void updateVisibility(bool visible); - virtual bool acceptsInputEvents(); - virtual bool handleInputEvent( - const WebKit::WebInputEvent& event, WebKit::WebCursorInfo& cursor_info); - virtual void didReceiveResponse(const WebKit::WebURLResponse& response); - virtual void didReceiveData(const char* data, int data_length); - virtual void didFinishLoading(); - virtual void didFailLoading(const WebKit::WebURLError& error); - virtual void didFinishLoadingFrameRequest( - const WebKit::WebURL& url, void* notify_data); - virtual void didFailLoadingFrameRequest( - const WebKit::WebURL& url, void* notify_data, - const WebKit::WebURLError& error); - virtual bool supportsPaginatedPrint(); - virtual int printBegin(const WebKit::WebRect& printable_area, - int printer_dpi); - virtual bool printPage(int page_number, WebKit::WebCanvas* canvas); - virtual void printEnd(); - virtual bool hasSelection() const; - virtual WebKit::WebString selectionAsText() const; - virtual WebKit::WebString selectionAsMarkup() const; - virtual void setZoomFactor(float scale, bool text_only); - virtual bool startFind(const WebKit::WebString& search_text, - bool case_sensitive, - int identifier); - virtual void selectFindResult(bool forward); - virtual void stopFind(); - - // WebPlugin implementation: - void SetWindow(gfx::PluginWindowHandle window); - virtual void SetAcceptsInputEvents(bool accepts) { - accepts_input_events_ = accepts; - } - void WillDestroyWindow(gfx::PluginWindowHandle window); -#if defined(OS_WIN) - void SetWindowlessPumpEvent(HANDLE pump_messages_event) { } -#endif - virtual void CancelResource(unsigned long id); - virtual void Invalidate(); - virtual void InvalidateRect(const gfx::Rect& rect); - virtual NPObject* GetWindowScriptNPObject(); - virtual NPObject* GetPluginElement(); - virtual void SetCookie(const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie); - virtual std::string GetCookies(const GURL& url, - const GURL& first_party_for_cookies); - virtual void ShowModalHTMLDialog(const GURL& url, int width, int height, - const std::string& json_arguments, - std::string* json_retval); - virtual void OnMissingPluginStatus(int status); - - virtual void URLRedirectResponse(bool allow, int resource_id); - - // Given a (maybe partial) url, completes using the base url. - GURL CompleteURL(const char* url); - - // Executes the script passed in. The notify_needed and notify_data arguments - // are passed in by the plugin process. These indicate whether the plugin - // expects a notification on script execution. We pass them back to the - // plugin as is. This avoids having to track the notification arguments in - // the plugin process. - bool ExecuteScript(const std::string& url, const std::wstring& script, - bool notify_needed, intptr_t notify_data, - bool popups_allowed); - - enum RoutingStatus { - ROUTED, - NOT_ROUTED, - INVALID_URL, - GENERAL_FAILURE - }; - - // Determines the referrer value sent along with outgoing HTTP requests - // issued by plugins. - enum Referrer { - PLUGIN_SRC, - DOCUMENT_URL, - NO_REFERRER - }; - - // Given a download request, check if we need to route the output to a frame. - // Returns ROUTED if the load is done and routed to a frame, NOT_ROUTED or - // corresponding error codes otherwise. - RoutingStatus RouteToFrame(const char* url, - bool is_javascript_url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - int notify_id, - Referrer referrer_flag); - - // Returns the next avaiable resource id. Returns 0 if the operation fails. - // It may fail if the page has already been closed. - unsigned long GetNextResourceId(); - - // Initiates HTTP GET/POST requests. - // Returns true on success. - bool InitiateHTTPRequest(unsigned long resource_id, - WebPluginResourceClient* client, - const GURL& url, - const char* method, - const char* buf, - int len, - const char* range_info, - Referrer referrer_flag, - bool notify_redirects); - - gfx::Rect GetWindowClipRect(const gfx::Rect& rect); - - // Sets the actual Widget for the plugin. - void SetContainer(WebKit::WebPluginContainer* container); - - // Destroys the plugin instance. - // The response_handle_to_ignore parameter if not NULL indicates the - // resource handle to be left valid during plugin shutdown. - void TearDownPluginInstance(WebKit::WebURLLoader* loader_to_ignore); - - // WebURLLoaderClient implementation. We implement this interface in the - // renderer process, and then use the simple WebPluginResourceClient interface - // to relay the callbacks to the plugin. - virtual void willSendRequest(WebKit::WebURLLoader* loader, - WebKit::WebURLRequest& request, - const WebKit::WebURLResponse& response); - virtual void didSendData(WebKit::WebURLLoader* loader, - unsigned long long bytes_sent, - unsigned long long total_bytes_to_be_sent); - virtual void didReceiveResponse(WebKit::WebURLLoader* loader, - const WebKit::WebURLResponse& response); - virtual void didReceiveData(WebKit::WebURLLoader* loader, const char *buffer, - int length); - virtual void didFinishLoading(WebKit::WebURLLoader* loader, - double finishTime); - virtual void didFail(WebKit::WebURLLoader* loader, - const WebKit::WebURLError& error); - - // Helper function to remove the stored information about a resource - // request given its index in m_clients. - void RemoveClient(size_t i); - - // Helper function to remove the stored information about a resource - // request given a handle. - void RemoveClient(WebKit::WebURLLoader* loader); - - void HandleURLRequest(const char* url, - const char *method, - const char* target, - const char* buf, - unsigned int len, - int notify_id, - bool popups_allowed, - bool notify_redirects); - - void CancelDocumentLoad(); - - void InitiateHTTPRangeRequest( - const char* url, const char* range_info, int pending_request_id); - - void SetDeferResourceLoading(unsigned long resource_id, bool defer); - - // Ignore in-process plugins mode for this flag. - bool IsOffTheRecord() { return false; } - - // Handles HTTP multipart responses, i.e. responses received with a HTTP - // status code of 206. - void HandleHttpMultipartResponse(const WebKit::WebURLResponse& response, - WebPluginResourceClient* client); - - void HandleURLRequestInternal(const char* url, - const char* method, - const char* target, - const char* buf, - unsigned int len, - int notify_id, - bool popups_allowed, - Referrer referrer_flag, - bool notify_redirects); - - // Tears down the existing plugin instance and creates a new plugin instance - // to handle the response identified by the loader parameter. - bool ReinitializePluginForResponse(WebKit::WebURLLoader* loader); - - // Delayed task for downloading the plugin source URL. - void OnDownloadPluginSrcUrl(); - - struct ClientInfo; - - // Helper functions - WebPluginResourceClient* GetClientFromLoader(WebKit::WebURLLoader* loader); - ClientInfo* GetClientInfoFromLoader(WebKit::WebURLLoader* loader); - - // Helper function to set the referrer on the request passed in. - void SetReferrer(WebKit::WebURLRequest* request, Referrer referrer_flag); - - // Returns DevToolsAgent for the frame or 0. - WebKit::WebDevToolsAgent* GetDevToolsAgent(); - - // Check for invalid chars like @, ;, \ before the first / (in path). - bool IsValidUrl(const GURL& url, Referrer referrer_flag); - - std::vector<ClientInfo> clients_; - - bool windowless_; - gfx::PluginWindowHandle window_; - bool accepts_input_events_; - base::WeakPtr<WebPluginPageDelegate> page_delegate_; - WebKit::WebFrame* webframe_; - - WebPluginDelegate* delegate_; - - // This is just a weak reference. - WebKit::WebPluginContainer* container_; - - typedef std::map<WebPluginResourceClient*, - webkit_glue::MultipartResponseDelegate*> - MultiPartResponseHandlerMap; - // Tracks HTTP multipart response handlers instantiated for - // a WebPluginResourceClient instance. - MultiPartResponseHandlerMap multi_part_response_map_; - - // The plugin source URL. - GURL plugin_url_; - - // Indicates if the download would be initiated by the plugin or us. - bool load_manually_; - - // Indicates if this is the first geometry update received by the plugin. - bool first_geometry_update_; - - // Set to true if the next response error should be ignored. - bool ignore_response_error_; - - // The current plugin geometry and clip rectangle. - WebPluginGeometry geometry_; - - // The location of the plugin on disk. - FilePath file_path_; - - // The mime type of the plugin. - std::string mime_type_; - - // Holds the list of argument names and values passed to the plugin. We keep - // these so that we can re-initialize the plugin if we need to. - std::vector<std::string> arg_names_; - std::vector<std::string> arg_values_; - - ScopedRunnableMethodFactory<WebPluginImpl> method_factory_; - - DISALLOW_COPY_AND_ASSIGN(WebPluginImpl); -}; - -} // namespace webkit_glue - -#endif // #ifndef WEBKIT_GLUE_WEBPLUGIN_IMPL_H_ diff --git a/webkit/glue/plugins/webplugin_impl_unittest.cc b/webkit/glue/plugins/webplugin_impl_unittest.cc deleted file mode 100644 index e70e39a..0000000 --- a/webkit/glue/plugins/webplugin_impl_unittest.cc +++ /dev/null @@ -1,232 +0,0 @@ -// 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 "base/string_util.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "webkit/glue/plugins/webplugin_impl.h" - -using WebKit::WebHTTPBody; -using WebKit::WebString; -using WebKit::WebURLRequest; -using webkit_glue::WebPluginImpl; - -namespace { - -class WebPluginImplTest : public testing::Test { -}; - -} - -static std::string GetHeader(const WebURLRequest& request, const char* name) { - std::string result; - TrimWhitespace( - request.httpHeaderField(WebString::fromUTF8(name)).utf8(), - TRIM_ALL, - &result); - return result; -} - -static std::string GetBodyText(const WebURLRequest& request) { - const WebHTTPBody& body = request.httpBody(); - if (body.isNull()) - return std::string(); - - std::string result; - size_t i = 0; - WebHTTPBody::Element element; - while (body.elementAt(i++, element)) { - if (element.type == WebHTTPBody::Element::TypeData) { - result.append(element.data.data(), element.data.size()); - } else { - NOTREACHED() << "unexpected element type encountered!"; - } - } - return result; -} - -// The Host functions for NPN_PostURL and NPN_PostURLNotify -// need to parse out some HTTP headers. Make sure it works -// with the following tests - -TEST(WebPluginImplTest, PostParserSimple) { - // Test a simple case with headers & data - const char *ex1 = "foo: bar\nContent-length: 10\n\nabcdefghij"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ("bar", GetHeader(request, "foo")); - EXPECT_EQ(0U, GetHeader(request, "bar").length()); - EXPECT_EQ(0U, GetHeader(request, "Content-length").length()); - EXPECT_EQ("abcdefghij", GetBodyText(request)); -} - -TEST(WebPluginImplTest, PostParserLongHeader) { - // Test a simple case with long headers - const char *ex1 = "foo: 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n\nabcdefghij"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ(100U, GetHeader(request, "foo").length()); -} - -TEST(WebPluginImplTest, PostParserManyHeaders) { - // Test a simple case with long headers - const char *ex1 = "h1:h1\nh2:h2\nh3:h3\nh4:h4\nh5:h5\nh6:h6\nh7:h7\nh8:h8\nh9:h9\nh10:h10\n\nbody"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ("h1", GetHeader(request, "h1")); - EXPECT_EQ("h2", GetHeader(request, "h2")); - EXPECT_EQ("h3", GetHeader(request, "h3")); - EXPECT_EQ("h4", GetHeader(request, "h4")); - EXPECT_EQ("h5", GetHeader(request, "h5")); - EXPECT_EQ("h6", GetHeader(request, "h6")); - EXPECT_EQ("h7", GetHeader(request, "h7")); - EXPECT_EQ("h8", GetHeader(request, "h8")); - EXPECT_EQ("h9", GetHeader(request, "h9")); - EXPECT_EQ("h10", GetHeader(request, "h10")); - EXPECT_EQ("body", GetBodyText(request)); -} - -TEST(WebPluginImplTest, PostParserDuplicateHeaders) { - // Test a simple case with long headers - // What value gets returned doesn't really matter. It shouldn't error - // out. - const char *ex1 = "h1:h1\nh1:h2\n\nbody"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); -} - -TEST(WebPluginImplTest, PostParserNoHeaders) { - // Test a simple case with no headers but with data - const char *ex1 = "\nabcdefghij"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ(0U, GetHeader(request, "foo").length()); - EXPECT_EQ(0U, GetHeader(request, "bar").length()); - EXPECT_EQ(0U, GetHeader(request, "Content-length").length()); - EXPECT_EQ("abcdefghij", GetBodyText(request)); -} - -TEST(WebPluginImplTest, PostParserNoBody) { - // Test a simple case with headers and no body - const char *ex1 = "Foo:bar\n\n"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ("bar", GetHeader(request, "foo")); - EXPECT_EQ(0U, GetHeader(request, "bar").length()); - EXPECT_EQ(0U, GetHeader(request, "Content-length").length()); - EXPECT_EQ(0U, GetBodyText(request).length()); -} - -TEST(WebPluginImplTest, PostParserBodyWithNewLines) { - // Test a simple case with headers and no body - const char *ex1 = "Foo:bar\n\n\n\nabcdefg\n\nabcdefg"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ(GetBodyText(request), "\n\nabcdefg\n\nabcdefg"); -} - -TEST(WebPluginImplTest, PostParserErrorNoBody) { - // Test with headers and no body - const char *ex1 = "Foo:bar\n"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); -} - -TEST(WebPluginImplTest, PostParserErrorEmpty) { - // Test with an empty string - const char *ex1 = ""; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); -} - -TEST(WebPluginImplTest, PostParserEmptyName) { - // Test an error case with an empty header name field - const char *ex1 = "foo:bar\n:blat\n\nbody"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ("bar", GetHeader(request, "foo")); - EXPECT_EQ("body", GetBodyText(request)); -} - -TEST(WebPluginImplTest, PostParserEmptyValue) { - // Test an error case with an empty value field - const char *ex1 = "foo:bar\nbar:\n\nbody"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ("bar", GetHeader(request, "foo")); - EXPECT_EQ(0U, GetHeader(request, "bar").length()); - EXPECT_EQ("body", GetBodyText(request)); -} - -TEST(WebPluginImplTest, PostParserCRLF) { - // Test an error case with an empty value field - const char *ex1 = "foo: bar\r\nbar:\r\n\r\nbody\r\n\r\nbody2"; - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - static_cast<uint32>(strlen(ex1))); - EXPECT_EQ(true, rv); - EXPECT_EQ("bar", GetHeader(request, "foo")); - EXPECT_EQ(0U, GetHeader(request, "bar").length()); - EXPECT_EQ("body\r\n\r\nbody2", GetBodyText(request)); -} - -TEST(WebPluginImplTest, PostParserBodyWithBinaryData) { - // Test a simple case with headers and binary data. - char ex1[33] = "foo: bar\nContent-length: 10\n\n"; - unsigned int binary_data = 0xFFFFFFF0; - memcpy(ex1 + strlen("foo: bar\nContent-length: 10\n\n"), &binary_data, - sizeof(binary_data)); - - WebURLRequest request; - request.initialize(); - bool rv = WebPluginImpl::SetPostData(&request, ex1, - sizeof(ex1)/sizeof(ex1[0])); - EXPECT_EQ(true, rv); - EXPECT_EQ("bar", GetHeader(request, "foo")); - EXPECT_EQ(0U, GetHeader(request, "bar").length()); - EXPECT_EQ(0U, GetHeader(request, "Content-length").length()); - - std::string body = GetBodyText(request); - - EXPECT_EQ(0xF0, (unsigned char)body[0]); - EXPECT_EQ(0xFF, (unsigned char)body[1]); - EXPECT_EQ(0xFF, (unsigned char)body[2]); - EXPECT_EQ(0xFF, (unsigned char)body[3]); -} diff --git a/webkit/glue/plugins/webplugin_page_delegate.h b/webkit/glue/plugins/webplugin_page_delegate.h deleted file mode 100644 index d915fdd..0000000 --- a/webkit/glue/plugins/webplugin_page_delegate.h +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_WEBPLUGIN_PAGE_DELEGATE_ -#define WEBKIT_GLUE_WEBPLUGIN_PAGE_DELEGATE_ - -#include "gfx/native_widget_types.h" - -class FilePath; -class GURL; - -namespace WebKit { -class WebCookieJar; -} - -namespace webkit_glue { - -class WebPluginDelegate; -struct WebPluginGeometry; - -// Used by the WebPlugin to communicate back to the containing page. -class WebPluginPageDelegate { - public: - // This method is called to create a WebPluginDelegate implementation when a - // new plugin is instanced. See webkit_glue::CreateWebPluginDelegateHelper - // for a default WebPluginDelegate implementation. - virtual WebPluginDelegate* CreatePluginDelegate( - const FilePath& file_path, - const std::string& mime_type) = 0; - - // Called when a windowed plugin is created. - // Lets the view delegate create anything it is using to wrap the plugin. - virtual void CreatedPluginWindow( - gfx::PluginWindowHandle handle) = 0; - - // Called when a windowed plugin is closing. - // Lets the view delegate shut down anything it is using to wrap the plugin. - virtual void WillDestroyPluginWindow( - gfx::PluginWindowHandle handle) = 0; - - // Keeps track of the necessary window move for a plugin window that resulted - // from a scroll operation. That way, all plugin windows can be moved at the - // same time as each other and the page. - virtual void DidMovePlugin( - const WebPluginGeometry& move) = 0; - - // Notifies the parent view that a load has begun. - virtual void DidStartLoadingForPlugin() = 0; - - // Notifies the parent view that all loads are finished. - virtual void DidStopLoadingForPlugin() = 0; - - // Asks the browser to show a modal HTML dialog. The dialog is passed the - // given arguments as a JSON string, and returns its result as a JSON string - // through json_retval. - virtual void ShowModalHTMLDialogForPlugin( - const GURL& url, - const gfx::Size& size, - const std::string& json_arguments, - std::string* json_retval) = 0; - - // The WebCookieJar to use for this plugin. - virtual WebKit::WebCookieJar* GetCookieJar() = 0; -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_WEBPLUGIN_PAGE_DELEGATE_H_ diff --git a/webkit/glue/plugins/webplugin_print_delegate.h b/webkit/glue/plugins/webplugin_print_delegate.h deleted file mode 100644 index 040e58f..0000000 --- a/webkit/glue/plugins/webplugin_print_delegate.h +++ /dev/null @@ -1,49 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_WEBPLUGIN_PRINT_DELEGATE_H_ -#define WEBKIT_GLUE_PLUGINS_WEBPLUGIN_PRINT_DELEGATE_H_ - -#include "base/basictypes.h" -#include "third_party/npapi/bindings/npapi_extensions.h" - -namespace gfx { -class Rect; -} - -namespace webkit_glue { - -// Interface for the NPAPI print extension. This class implements "NOP" -// versions of all these functions so it can be used seamlessly by the -// "regular" plugin delegate while being overridden by the "pepper" one. -class WebPluginPrintDelegate { - public: - // If a plugin supports print extensions, then it gets to participate fully - // in the browser's print workflow by specifying the number of pages to be - // printed and providing a print output for specified pages. - virtual bool PrintSupportsPrintExtension() { - return false; - } - - // Note: printable_area is in points (a point is 1/72 of an inch). - virtual int PrintBegin(const gfx::Rect& printable_area, int printer_dpi) { - return 0; - } - - virtual bool PrintPage(int page_number, WebKit::WebCanvas* canvas) { - return false; - } - - virtual void PrintEnd() { - } - - protected: - WebPluginPrintDelegate() {} - virtual ~WebPluginPrintDelegate() {} -}; - -} // namespace webkit_glue - -#endif // WEBKIT_GLUE_PLUGINS_WEBPLUGIN_PRINT_DELEGATE_H_ - diff --git a/webkit/glue/plugins/webplugininfo.cc b/webkit/glue/plugins/webplugininfo.cc deleted file mode 100644 index 7d2b4e4..0000000 --- a/webkit/glue/plugins/webplugininfo.cc +++ /dev/null @@ -1,44 +0,0 @@ -// 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 "webkit/glue/plugins/webplugininfo.h" - -WebPluginMimeType::WebPluginMimeType() {} - -WebPluginMimeType::~WebPluginMimeType() {} - -WebPluginInfo::WebPluginInfo() : enabled(false) {} - -WebPluginInfo::WebPluginInfo(const WebPluginInfo& rhs) - : name(rhs.name), - path(rhs.path), - version(rhs.version), - desc(rhs.desc), - mime_types(rhs.mime_types), - enabled(rhs.enabled) { -} - -WebPluginInfo::~WebPluginInfo() {} - -WebPluginInfo& WebPluginInfo::operator=(const WebPluginInfo& rhs) { - name = rhs.name; - path = rhs.path; - version = rhs.version; - desc = rhs.desc; - mime_types = rhs.mime_types; - enabled = rhs.enabled; - return *this; -} - -WebPluginInfo::WebPluginInfo(const string16& fake_name, - const string16& fake_version, - const string16& fake_desc) - : name(fake_name), - path(), - version(fake_version), - desc(fake_desc), - mime_types(), - enabled(true) { -} - diff --git a/webkit/glue/plugins/webplugininfo.h b/webkit/glue/plugins/webplugininfo.h deleted file mode 100644 index 34eff3d..0000000 --- a/webkit/glue/plugins/webplugininfo.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef WEBKIT_GLUE_WEBPLUGININFO_H_ -#define WEBKIT_GLUE_WEBPLUGININFO_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/file_path.h" - -// Describes a mime type entry for a plugin. -struct WebPluginMimeType { - WebPluginMimeType(); - ~WebPluginMimeType(); - - // The name of the mime type (e.g., "application/x-shockwave-flash"). - std::string mime_type; - - // A list of all the file extensions for this mime type. - std::vector<std::string> file_extensions; - - // Description of the mime type. - string16 description; -}; - -// Describes an available NPAPI plugin. -struct WebPluginInfo { - WebPluginInfo(); - WebPluginInfo(const WebPluginInfo& rhs); - ~WebPluginInfo(); - WebPluginInfo& operator=(const WebPluginInfo& rhs); - - // Special constructor only used during unit testing: - WebPluginInfo(const string16& fake_name, - const string16& fake_version, - const string16& fake_desc); - - // The name of the plugin (i.e. Flash). - string16 name; - - // The path to the plugin file (DLL/bundle/library). - FilePath path; - - // The version number of the plugin file (may be OS-specific) - string16 version; - - // A description of the plugin that we get from its version info. - string16 desc; - - // A list of all the mime types that this plugin supports. - std::vector<WebPluginMimeType> mime_types; - - // Whether the plugin is enabled. - bool enabled; -}; - -#endif // WEBKIT_GLUE_WEBPLUGININFO_H_ diff --git a/webkit/glue/plugins/webview_plugin.cc b/webkit/glue/plugins/webview_plugin.cc deleted file mode 100644 index e1dc2c1..0000000 --- a/webkit/glue/plugins/webview_plugin.cc +++ /dev/null @@ -1,217 +0,0 @@ -// 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 "webkit/glue/plugins/webview_plugin.h" - -#include "base/message_loop.h" -#include "base/metrics/histogram.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebElement.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginContainer.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSize.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/webpreferences.h" - -#if WEBKIT_USING_CG -#include <CoreGraphics/CGContext.h> -#elif WEBKIT_USING_SKIA -#include "skia/ext/platform_canvas.h" -#endif - -using WebKit::WebCanvas; -using WebKit::WebCursorInfo; -using WebKit::WebDragData; -using WebKit::WebDragOperationsMask; -using WebKit::WebFrame; -using WebKit::WebImage; -using WebKit::WebInputEvent; -using WebKit::WebPlugin; -using WebKit::WebPluginContainer; -using WebKit::WebPoint; -using WebKit::WebRect; -using WebKit::WebSize; -using WebKit::WebURLError; -using WebKit::WebURLRequest; -using WebKit::WebURLResponse; -using WebKit::WebVector; -using WebKit::WebView; - -WebViewPlugin::WebViewPlugin(WebViewPlugin::Delegate* delegate) - : delegate_(delegate), - container_(NULL), - finished_loading_(false) { - web_view_ = WebView::create(this, NULL); - web_view_->initializeMainFrame(this); -} - -// static -WebViewPlugin* WebViewPlugin::Create(WebViewPlugin::Delegate* delegate, - const WebPreferences& preferences, - const std::string& html_data, - const GURL& url) { - WebViewPlugin* plugin = new WebViewPlugin(delegate); - WebView* web_view = plugin->web_view(); - preferences.Apply(web_view); - web_view->mainFrame()->loadHTMLString(html_data, url); - return plugin; -} - -WebViewPlugin::~WebViewPlugin() { - web_view_->close(); -} - -void WebViewPlugin::ReplayReceivedData(WebPlugin* plugin) { - if (!response_.isNull()) { - plugin->didReceiveResponse(response_); - size_t total_bytes = 0; - for (std::list<std::string>::iterator it = data_.begin(); - it != data_.end(); ++it) { - plugin->didReceiveData(it->c_str(), it->length()); - total_bytes += it->length(); - } - UMA_HISTOGRAM_MEMORY_KB("PluginDocument.Memory", (total_bytes / 1024)); - UMA_HISTOGRAM_COUNTS("PluginDocument.NumChunks", data_.size()); - } - if (finished_loading_) { - plugin->didFinishLoading(); - } - if (error_.get()) { - plugin->didFailLoading(*error_); - } -} - -void WebViewPlugin::RestoreTitleText() { - if (container_) - container_->element().setAttribute("title", old_title_); -} - - -bool WebViewPlugin::initialize(WebPluginContainer* container) { - container_ = container; - if (container_) - old_title_ = container_->element().getAttribute("title"); - return true; -} - -void WebViewPlugin::destroy() { - if (delegate_) { - delegate_->WillDestroyPlugin(); - delegate_ = NULL; - } - container_ = NULL; - MessageLoop::current()->DeleteSoon(FROM_HERE, this); -} - -void WebViewPlugin::paint(WebCanvas* canvas, const WebRect& rect) { - gfx::Rect paintRect(rect_.Intersect(rect)); - if (paintRect.IsEmpty()) - return; - - paintRect.Offset(-rect_.x(), -rect_.y()); - -#if WEBKIT_USING_CG - CGContextRef context = canvas; - CGContextTranslateCTM(context, rect_.x(), rect_.y()); - CGContextSaveGState(context); -#elif WEBKIT_USING_SKIA - skia::PlatformCanvas* platform_canvas = canvas; - platform_canvas->translate(SkIntToScalar(rect_.x()), - SkIntToScalar(rect_.y())); - platform_canvas->save(); -#endif - - web_view_->layout(); - web_view_->paint(canvas, paintRect); - -#if WEBKIT_USING_SKIA - platform_canvas->restore(); -#elif WEBKIT_USING_CG - CGContextRestoreGState(context); -#endif -} - -// Coordinates are relative to the containing window. -void WebViewPlugin::updateGeometry( - const WebRect& frame_rect, const WebRect& clip_rect, - const WebVector<WebRect>& cut_out_rects, bool is_visible) { - if (frame_rect != rect_) { - rect_ = frame_rect; - web_view_->resize(WebSize(frame_rect.width, frame_rect.height)); - } -} - -bool WebViewPlugin::handleInputEvent(const WebInputEvent& event, - WebCursorInfo& cursor) { - current_cursor_ = cursor; - bool handled = web_view_->handleInputEvent(event); - cursor = current_cursor_; - return handled; -} - -void WebViewPlugin::didReceiveResponse(const WebURLResponse& response) { - DCHECK(response_.isNull()); - response_ = response; -} - -void WebViewPlugin::didReceiveData(const char* data, int data_length) { - data_.push_back(std::string(data, data_length)); -} - -void WebViewPlugin::didFinishLoading() { - DCHECK(!finished_loading_); - finished_loading_ = true; -} - -void WebViewPlugin::didFailLoading(const WebURLError& error) { - DCHECK(!error_.get()); - error_.reset(new WebURLError(error)); -} - -void WebViewPlugin::setToolTipText(const WebKit::WebString& text, - WebKit::WebTextDirection hint) { - if (container_) - container_->element().setAttribute("title", text); -} - -void WebViewPlugin::startDragging(const WebDragData&, - WebDragOperationsMask, - const WebImage&, - const WebPoint&) { - // Immediately stop dragging. - web_view_->dragSourceSystemDragEnded(); -} - -void WebViewPlugin::didInvalidateRect(const WebRect& rect) { - if (container_) - container_->invalidateRect(rect); -} - -void WebViewPlugin::didChangeCursor(const WebCursorInfo& cursor) { - current_cursor_ = cursor; -} - -void WebViewPlugin::didClearWindowObject(WebFrame* frame) { - if (delegate_) - delegate_->BindWebFrame(frame); -} - -bool WebViewPlugin::canHandleRequest(WebFrame* frame, - const WebURLRequest& request) { - return GURL(request.url()).SchemeIs("chrome"); -} - -WebURLError WebViewPlugin::cancelledError(WebFrame* frame, - const WebURLRequest& request) { - // Return an error with a non-zero reason so isNull() on the corresponding - // ResourceError is false. - WebURLError error; - error.domain = "WebViewPlugin"; - error.reason = -1; - error.unreachableURL = request.url(); - return error; -} diff --git a/webkit/glue/plugins/webview_plugin.h b/webkit/glue/plugins/webview_plugin.h deleted file mode 100644 index ef85d77..0000000 --- a/webkit/glue/plugins/webview_plugin.h +++ /dev/null @@ -1,138 +0,0 @@ -// 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 WEBKIT_GLUE_PLUGINS_WEBVIEW_PLUGIN_H_ -#define WEBKIT_GLUE_PLUGINS_WEBVIEW_PLUGIN_H_ - -#include <list> - -#include "base/scoped_ptr.h" -#include "base/task.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrameClient.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPlugin.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebTextDirection.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" -#include "third_party/WebKit/WebKit/chromium/public/WebViewClient.h" - -struct WebPreferences; - -// This class implements the WebPlugin interface by forwarding drawing and -// handling input events to a WebView. -// It can be used as a placeholder for an actual plugin, using HTML for the UI. -// To show HTML data inside the WebViewPlugin, -// call web_view->mainFrame()->loadHTMLString() with the HTML data and a fake -// chrome:// URL as origin. - -class WebViewPlugin: public WebKit::WebPlugin, public WebKit::WebViewClient, - public WebKit::WebFrameClient { - public: - class Delegate { - public: - // Bind |frame| to a Javascript object, enabling the delegate to receive - // callback methods from Javascript inside the WebFrame. - // This method is called from WebFrameClient::didClearWindowObject. - virtual void BindWebFrame(WebKit::WebFrame* frame) = 0; - - // Called before the WebViewPlugin is destroyed. The delegate should delete - // itself here. - virtual void WillDestroyPlugin() = 0; - }; - - explicit WebViewPlugin(Delegate* delegate); - - // Convenience method to set up a new WebViewPlugin using |preferences| - // and displaying |html_data|. |url| should be a (fake) chrome:// URL; it is - // only used for navigation and never actually resolved. - static WebViewPlugin* Create(Delegate* delegate, - const WebPreferences& preferences, - const std::string& html_data, - const GURL& url); - - WebKit::WebView* web_view() { return web_view_; } - - WebKit::WebPluginContainer* container() { return container_; } - - // When loading a plug-in document (i.e. a full page plug-in not embedded in - // another page), we save all data that has been received, and replay it with - // this method on the actual plug-in. - void ReplayReceivedData(WebKit::WebPlugin* plugin); - - void RestoreTitleText(); - - // WebPlugin methods: - virtual bool initialize(WebKit::WebPluginContainer*); - virtual void destroy(); - - virtual NPObject* scriptableObject() { return NULL; } - - virtual void paint(WebKit::WebCanvas* canvas, const WebKit::WebRect& rect); - - // Coordinates are relative to the containing window. - virtual void updateGeometry( - const WebKit::WebRect& frame_rect, const WebKit::WebRect& clip_rect, - const WebKit::WebVector<WebKit::WebRect>& cut_out_rects, bool is_visible); - - virtual void updateFocus(bool) { } - virtual void updateVisibility(bool) { } - - virtual bool acceptsInputEvents() { return true; } - virtual bool handleInputEvent(const WebKit::WebInputEvent& event, - WebKit::WebCursorInfo& cursor_info); - - virtual void didReceiveResponse(const WebKit::WebURLResponse& response); - virtual void didReceiveData(const char* data, int data_length); - virtual void didFinishLoading(); - virtual void didFailLoading(const WebKit::WebURLError& error); - - // Called in response to WebPluginContainer::loadFrameRequest - virtual void didFinishLoadingFrameRequest( - const WebKit::WebURL& url, void* notifyData) { } - virtual void didFailLoadingFrameRequest(const WebKit::WebURL& url, - void* notify_data, - const WebKit::WebURLError& error) { } - - // WebViewClient methods: - virtual bool acceptsLoadDrops() { return false; } - - virtual void setToolTipText(const WebKit::WebString&, - WebKit::WebTextDirection); - - virtual void startDragging(const WebKit::WebDragData& drag_data, - WebKit::WebDragOperationsMask mask, - const WebKit::WebImage& image, - const WebKit::WebPoint& point); - - // WebWidgetClient methods: - virtual void didInvalidateRect(const WebKit::WebRect&); - virtual void didChangeCursor(const WebKit::WebCursorInfo& cursor); - - // WebFrameClient methods: - virtual void didClearWindowObject(WebKit::WebFrame* frame); - - virtual bool canHandleRequest(WebKit::WebFrame* frame, - const WebKit::WebURLRequest& request); - - virtual WebKit::WebURLError cancelledError( - WebKit::WebFrame* frame, const WebKit::WebURLRequest& request); - - private: - friend class DeleteTask<WebViewPlugin>; - virtual ~WebViewPlugin(); - - Delegate* delegate_; - WebKit::WebCursorInfo current_cursor_; - WebKit::WebPluginContainer* container_; - WebKit::WebView* web_view_; - gfx::Rect rect_; - - WebKit::WebURLResponse response_; - std::list<std::string> data_; - bool finished_loading_; - scoped_ptr<WebKit::WebURLError> error_; - WebKit::WebString old_title_; -}; - -#endif // WEBKIT_GLUE_PLUGINS_WEBVIEW_PLUGIN_H_ diff --git a/webkit/glue/resource_loader_bridge.cc b/webkit/glue/resource_loader_bridge.cc index 86029e2..3e9c9e8 100644 --- a/webkit/glue/resource_loader_bridge.cc +++ b/webkit/glue/resource_loader_bridge.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// 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. @@ -54,7 +54,8 @@ ResourceLoaderBridge::RequestInfo::RequestInfo() request_context(0), appcache_host_id(0), routing_id(0), - download_to_file(false) { + download_to_file(false), + has_user_gesture(false) { } ResourceLoaderBridge::RequestInfo::~RequestInfo() { diff --git a/webkit/glue/resource_loader_bridge.h b/webkit/glue/resource_loader_bridge.h index bd2f8b9..7257b0c 100644 --- a/webkit/glue/resource_loader_bridge.h +++ b/webkit/glue/resource_loader_bridge.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. // @@ -236,6 +236,9 @@ class ResourceLoaderBridge { // If true, then the response body will be downloaded to a file and the // path to that file will be provided in ResponseInfo::download_file_path. bool download_to_file; + + // True if the request was user initiated. + bool has_user_gesture; }; // See the SyncLoad method declared below. (The name of this struct is not @@ -259,9 +262,9 @@ class ResourceLoaderBridge { // within webkit. The Peer and it's bridge should have identical lifetimes // as they represent each end of a communication channel. // - // These callbacks mirror URLRequest::Delegate and the order and conditions - // in which they will be called are identical. See url_request.h for more - // information. + // These callbacks mirror net::URLRequest::Delegate and the order and + // conditions in which they will be called are identical. See url_request.h + // for more information. class Peer { public: virtual ~Peer() {} diff --git a/webkit/glue/resources/webkit_strings_am.xtb b/webkit/glue/resources/webkit_strings_am.xtb index 4f5108e..1a71058 100644 --- a/webkit/glue/resources/webkit_strings_am.xtb +++ b/webkit/glue/resources/webkit_strings_am.xtb @@ -8,7 +8,6 @@ <translation id="7658239707568436148">ሰርዝ</translation> <translation id="795667975304826397">ምንም ፋይል አልተመረጠም</translation> <translation id="8141602879876242471">ይህ ሊፈለግ የሚችል መረጃ ጠቋሚ ነው። የፍለጋ ቁልፍ ቃላት አስገባ፦</translation> -<translation id="370665806235115550">በመጫን ላይ...</translation> <translation id="6845533974506654842">ተጫን</translation> <translation id="8244226242650769279">የምስል ካርታ</translation> <translation id="2548326553472216322">የቅርብ ጊዜ ፍለጋዎች የሉም</translation> @@ -21,6 +20,7 @@ <translation id="5476505524087279545">አታመልክት</translation> <translation id="3789841737615482174">ጫን</translation> <translation id="6663448176199120256">የቅርብ ጊዜ ፍለጋዎችን</translation> +<translation id="6807599807928161586">የድር ክልል</translation> <translation id="5939518447894949180">ዳግም አስጀምር</translation> <translation id="1842960171412779397">ምረጥ</translation> <translation id="6119846243427417423">አንቃ</translation> diff --git a/webkit/glue/resources/webkit_strings_ar.xtb b/webkit/glue/resources/webkit_strings_ar.xtb index 0f2e739..6f454f7 100644 --- a/webkit/glue/resources/webkit_strings_ar.xtb +++ b/webkit/glue/resources/webkit_strings_ar.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="ar"> <translation id="4519964825805946997">أخفق تثبيت المكون الإضافي من <ph name="URL"/></translation> -<translation id="9186171386827445984">جارٍ تحميل المستند: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> من الصفحات...</translation> <translation id="1235745349614807883">محو آخر عمليات البحث</translation> <translation id="5048533449481078685">محدّد القائمة</translation> <translation id="372362261556059955">المكوّن الإضافي المطلوب</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">أخفق تثبيت المكون الإضافي</translation> <translation id="8141602879876242471">يمكن البحث في هذا الفهرس بإدخال كلمات مفتاحية:</translation> <translation id="5650795167354946011">بعد تثبيت المكون الإضافي، انقر هنا للتحديث</translation> -<translation id="370665806235115550">تحميل...</translation> <translation id="6845533974506654842">اضغط</translation> <translation id="8244226242650769279">مخطّط صورة</translation> <translation id="2548326553472216322">لا عمليات بحث حديثة</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">الرجاء التأكيد على أنك تريد تثبيت المكوّن الإضافي <ph name="PLUGIN"/>. يجب تثبيت المكونات الإضافية التي تثق فيها فقط.</translation> <translation id="6663448176199120256">آخر عمليات البحث</translation> <translation id="2597378329261239068">هذا المستند محمي بكلمة المرور. الرجاء إدخال كلمة مرور.</translation> -<translation id="7740050170769002709">محتوى HTML</translation> +<translation id="6807599807928161586">منطقة الويب</translation> <translation id="5939518447894949180">إعادة</translation> <translation id="1842960171412779397">الاختيار</translation> <translation id="7638452146404718955">انقر هنا لتنزيل المكون الإضافي</translation> diff --git a/webkit/glue/resources/webkit_strings_bg.xtb b/webkit/glue/resources/webkit_strings_bg.xtb index 09f4a71..4edbd69 100644 --- a/webkit/glue/resources/webkit_strings_bg.xtb +++ b/webkit/glue/resources/webkit_strings_bg.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="bg"> <translation id="4519964825805946997">Инсталирането на приставката от <ph name="URL"/> не бе успешно</translation> -<translation id="9186171386827445984">Документът се зарежда: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> страници...</translation> <translation id="1235745349614807883">Изчистване на скорошните търсения</translation> <translation id="5048533449481078685">списъчен показалец</translation> <translation id="372362261556059955">Необходима е допълнителна приставка</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Инсталирането на приставката не бе успешно</translation> <translation id="8141602879876242471">В този индекс може да се търси. Въведете ключови думи за търсене:</translation> <translation id="5650795167354946011">След инсталирането на приставката кликнете тук за опресняване</translation> -<translation id="370665806235115550">Зарежда се...</translation> <translation id="6845533974506654842">натискане</translation> <translation id="8244226242650769279">карта с изображения</translation> <translation id="2548326553472216322">Няма скорошни търсения</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Моля, потвърдете, че искате да инсталирате приставката <ph name="PLUGIN"/>. Трябва да инсталирате само приставки, на които имате доверие.</translation> <translation id="6663448176199120256">Скорошни търсения</translation> <translation id="2597378329261239068">Този документ е защитен с парола. Моля, въведете я.</translation> -<translation id="7740050170769002709">HTML съдържание</translation> +<translation id="6807599807928161586">уеб зона</translation> <translation id="5939518447894949180">Повторно задаване</translation> <translation id="1842960171412779397">Избиране</translation> <translation id="7638452146404718955">Кликнете тук, за да изтеглите приставката</translation> diff --git a/webkit/glue/resources/webkit_strings_bn.xtb b/webkit/glue/resources/webkit_strings_bn.xtb index 7143769..1a29278 100644 --- a/webkit/glue/resources/webkit_strings_bn.xtb +++ b/webkit/glue/resources/webkit_strings_bn.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="bn"> <translation id="4519964825805946997"><ph name="URL"/>-এর থেকে প্ল্যাগ-ইন ইনস্টল করতে ব্যর্থ হয়েছে</translation> -<translation id="9186171386827445984">নথি লোড হচ্ছে: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> পৃষ্ঠা...</translation> <translation id="1235745349614807883">সাম্প্রতিক অনুসন্ধানগুলি সাফ করুন</translation> <translation id="5048533449481078685">তালিকা নির্দেশক</translation> <translation id="372362261556059955">অতিরিক্ত প্লাগ-ইন দরকার</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">প্লাগ-ইন ইনস্টলেশান ব্যর্থ হয়েছে</translation> <translation id="8141602879876242471">এটি অনুসন্ধানযোগ্য সূচি৷ অনুসন্ধানের মূলশব্দ প্রবেশ করান:</translation> <translation id="5650795167354946011">প্ল্যাগ-ইন ইনস্টল করার পরে, রিফ্রেশ করার জন্য এখানে ক্লিক করুন</translation> -<translation id="370665806235115550">লোড হচ্ছে...</translation> <translation id="6845533974506654842">টিপুন</translation> <translation id="8244226242650769279">ছবি মানচিত্র</translation> <translation id="2548326553472216322">কোন সাম্প্রতিক অনুসন্ধান নেই</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">আপনি <ph name="PLUGIN"/> প্ল্যাগ-ইনটি ইনস্টল করতে চান কি না দয়া করে নিশ্চিত করুন৷ আপনার কেবল সেই প্ল্যাগ-ইনগুলি ইনস্টল করার উচিত যেগুলিকে আপনি বিশ্বাস করেন৷</translation> <translation id="6663448176199120256">সাম্প্রতিক অনুসন্ধানগুলি</translation> <translation id="2597378329261239068">এই দস্তাবেজটি পাসওয়ার্ড সুরক্ষিত৷ দয়া করে একটি পাসওয়ার্ড লিখুন৷</translation> -<translation id="7740050170769002709">HTML সামগ্রী</translation> +<translation id="6807599807928161586">ওয়েব এলাকা</translation> <translation id="5939518447894949180">রিসেট করুন</translation> <translation id="1842960171412779397">নির্বাচন করুন</translation> <translation id="7638452146404718955">প্ল্যাগ-ইন ডাউনলোড করার জন্য এখানে ক্লিক করুন</translation> diff --git a/webkit/glue/resources/webkit_strings_ca.xtb b/webkit/glue/resources/webkit_strings_ca.xtb index 59756a8..6f3dc90 100644 --- a/webkit/glue/resources/webkit_strings_ca.xtb +++ b/webkit/glue/resources/webkit_strings_ca.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="ca"> <translation id="4519964825805946997">S'ha produït un error en instal·lar el connector des de <ph name="URL"/></translation> -<translation id="9186171386827445984">S'està carregant el document: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> pàgines...</translation> <translation id="1235745349614807883">Esborra les cerques recents</translation> <translation id="5048533449481078685">marcador de llistes</translation> <translation id="372362261556059955">Es necessita un connector addicional</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">S'ha produït un error en instal·lar el connector </translation> <translation id="8141602879876242471">És un índex on es poden realitzar cerques. Introdueix els termes de cerca:</translation> <translation id="5650795167354946011">Després d'instal·lar el connector, feu clic aquí per actualitzar</translation> -<translation id="370665806235115550">S'està carregant...</translation> <translation id="6845533974506654842">prem</translation> <translation id="8244226242650769279">mapa d'imatges</translation> <translation id="2548326553472216322">No hi ha cerques recents</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Confirmeu que voleu instal·lar el connector <ph name="PLUGIN"/>. Us recomanem que només instal·leu connectors de la vostra confiança.</translation> <translation id="6663448176199120256">Cerques recents</translation> <translation id="2597378329261239068">Aquest document està protegit mitjançant contrasenya. Introduïu una contrasenya.</translation> -<translation id="7740050170769002709">Contingut HTML</translation> +<translation id="6807599807928161586">àrea web</translation> <translation id="5939518447894949180">Restablir</translation> <translation id="1842960171412779397">selecciona</translation> <translation id="7638452146404718955">Feu clic aquí per baixar el connector</translation> diff --git a/webkit/glue/resources/webkit_strings_cs.xtb b/webkit/glue/resources/webkit_strings_cs.xtb index 8d3784f..33a0d12 100644 --- a/webkit/glue/resources/webkit_strings_cs.xtb +++ b/webkit/glue/resources/webkit_strings_cs.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="cs"> <translation id="4519964825805946997">Instalace pluginu z adresy URL <ph name="URL"/> se nezdařila</translation> -<translation id="9186171386827445984">Načítání dokumentu: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> stran...</translation> <translation id="1235745349614807883">Smazat nedávná vyhledávání</translation> <translation id="5048533449481078685">značka seznamu</translation> <translation id="372362261556059955">Je zapotřebí další plugin</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Instalace pluginu selhala</translation> <translation id="8141602879876242471">Toto je prohledávatelný index. Zadejte hledaná klíčová slova:</translation> <translation id="5650795167354946011">Po instalaci pluginu obnovte okno kliknutím sem</translation> -<translation id="370665806235115550">Načítání...</translation> <translation id="6845533974506654842">zmáčknout</translation> <translation id="8244226242650769279">obrázková mapa</translation> <translation id="2548326553472216322">Žádná nedávná vyhledávání</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Potvrďte prosím, zda chcete nainstalovat plugin <ph name="PLUGIN"/>. Instalujte pouze pluginy, kterým důvěřujete.</translation> <translation id="6663448176199120256">Nedávná vyhledávání</translation> <translation id="2597378329261239068">Tento dokument je chráněn heslem. Zadejte prosím heslo.</translation> -<translation id="7740050170769002709">Obsah ve formátu HTML</translation> +<translation id="6807599807928161586">oblast webu</translation> <translation id="5939518447894949180">Resetovat</translation> <translation id="1842960171412779397">zvolit</translation> <translation id="7638452146404718955">Plugin můžete stáhnout kliknutím sem</translation> diff --git a/webkit/glue/resources/webkit_strings_da.xtb b/webkit/glue/resources/webkit_strings_da.xtb index 71d2a6a..78f06ff 100644 --- a/webkit/glue/resources/webkit_strings_da.xtb +++ b/webkit/glue/resources/webkit_strings_da.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="da"> <translation id="4519964825805946997">Installation af plugin fra <ph name="URL"/> mislykkedes</translation> -<translation id="9186171386827445984">Indlæser dokument: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> sider...</translation> <translation id="1235745349614807883">Slet nylige søgninger</translation> <translation id="5048533449481078685">listemarkering</translation> <translation id="372362261556059955">Ekstra plugin påkrævet</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Installation af plugin mislykkedes</translation> <translation id="8141602879876242471">Der kan søges i dette indeks. Indtast søge-nøgleord:</translation> <translation id="5650795167354946011">Når du har installeret plugin'et, skal du klikke her for at opdatere</translation> -<translation id="370665806235115550">Indlæser ...</translation> <translation id="6845533974506654842">tryk</translation> <translation id="8244226242650769279">billedekort</translation> <translation id="2548326553472216322">Ingen nylige søgninger</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Bekræft, at du vil installere dette <ph name="PLUGIN"/>-plugin. Du skal kun installere plugins, som du har tillid til.</translation> <translation id="6663448176199120256">Nylige søgninger</translation> <translation id="2597378329261239068">Dette dokument er adgangskodebeskyttet. Indtast en adgangskode.</translation> -<translation id="7740050170769002709">HTML-indhold</translation> +<translation id="6807599807928161586">webområde</translation> <translation id="5939518447894949180">Nulstil</translation> <translation id="1842960171412779397">vælg</translation> <translation id="7638452146404718955">Klik her for at downloade plugin</translation> diff --git a/webkit/glue/resources/webkit_strings_de.xtb b/webkit/glue/resources/webkit_strings_de.xtb index 6d27410..45fab1b 100644 --- a/webkit/glue/resources/webkit_strings_de.xtb +++ b/webkit/glue/resources/webkit_strings_de.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="de"> <translation id="4519964825805946997">Installation des Plug-ins von <ph name="URL"/> fehlgeschlagen</translation> -<translation id="9186171386827445984">Dokument wird geladen <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> Seiten...</translation> <translation id="1235745349614807883">Vor kurzem durchgeführte Suchanfragen löschen</translation> <translation id="5048533449481078685">Listenmarkierung</translation> <translation id="372362261556059955">Zusätzliches Plug-in erforderlich</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Plug-in-Installation fehlgeschlagen</translation> <translation id="8141602879876242471">Dieser Index kann durchsucht werden. Geben Sie Suchbegriffe ein:</translation> <translation id="5650795167354946011">Klicken Sie nach der Installation des Plug-ins hier, um eine Aktualisierung durchzuführen.</translation> -<translation id="370665806235115550">Wird geladen...</translation> <translation id="6845533974506654842">klicken</translation> <translation id="8244226242650769279">Imagemap</translation> <translation id="2548326553472216322">Keine vor kurzem durchgeführte Suchanfragen</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Bitte bestätigen Sie, dass Sie das Plug-in <ph name="PLUGIN"/> installieren möchten. Installieren Sie nur Plug-ins, denen Sie vertrauen.</translation> <translation id="6663448176199120256">Vor kurzem durchgeführte Suchanfragen</translation> <translation id="2597378329261239068">Dieses Dokument ist passwortgeschützt. Geben Sie ein Passwort ein.</translation> -<translation id="7740050170769002709">HTML-Inhalte</translation> +<translation id="6807599807928161586">Webbereich</translation> <translation id="5939518447894949180">Zurücksetzen</translation> <translation id="1842960171412779397">auswählen</translation> <translation id="7638452146404718955">Hier klicken, um das Plug-in herunterzuladen</translation> diff --git a/webkit/glue/resources/webkit_strings_el.xtb b/webkit/glue/resources/webkit_strings_el.xtb index c429294..509307e 100644 --- a/webkit/glue/resources/webkit_strings_el.xtb +++ b/webkit/glue/resources/webkit_strings_el.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="el"> <translation id="4519964825805946997">Η εγκατάσταση της προσθήκης από τη διεύθυνση <ph name="URL"/> απέτυχε</translation> -<translation id="9186171386827445984">Φόρτωση εγγράφου: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> σελίδες...</translation> <translation id="1235745349614807883">Εκκαθάριση πρόσφατων αναζητήσεων</translation> <translation id="5048533449481078685">δείκτης λίστας</translation> <translation id="372362261556059955">Απαιτείται επιπλέον προσθήκη</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Η εγκατάσταση προσθήκης απέτυχε</translation> <translation id="8141602879876242471">Πρόκειται για ευρετήριο με δυνατότητα αναζήτησης. Πληκτρολογήστε λέξεις-κλειδιά αναζήτησης:</translation> <translation id="5650795167354946011">Μετά την εγκατάσταση της προσθήκης, κάντε κλικ εδώ για ανανέωση των δεδομένων</translation> -<translation id="370665806235115550">Φόρτωση...</translation> <translation id="6845533974506654842">πατήστε</translation> <translation id="8244226242650769279">χάρτης εικόνας</translation> <translation id="2548326553472216322">Δεν υπάρχουν πρόσφατες αναζητήσεις</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Επιβεβαιώστε ότι θέλετε να εγκαταστήσετε την προσθήκη <ph name="PLUGIN"/>. Πρέπει να εγκαθιστάτε μόνο προσθήκες που θεωρείτε αξιόπιστες.</translation> <translation id="6663448176199120256">Πρόσφατες αναζητήσεις</translation> <translation id="2597378329261239068">Αυτό το έγγραφο προστατεύεται με κωδικό πρόσβασης. Πληκτρολογήστε έναν κωδικό πρόσβασης.</translation> -<translation id="7740050170769002709">Περιεχόμενο HTML</translation> +<translation id="6807599807928161586">περιοχή ιστού</translation> <translation id="5939518447894949180">Επαναφορά</translation> <translation id="1842960171412779397">επιλογή</translation> <translation id="7638452146404718955">Κάντε κλικ εδώ για να κάνετε λήψη της προσθήκης</translation> diff --git a/webkit/glue/resources/webkit_strings_en-GB.xtb b/webkit/glue/resources/webkit_strings_en-GB.xtb index 417f44a..14befa8 100644 --- a/webkit/glue/resources/webkit_strings_en-GB.xtb +++ b/webkit/glue/resources/webkit_strings_en-GB.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="en-GB"> <translation id="4519964825805946997">Failed to install plug-in from <ph name="URL"/></translation> -<translation id="9186171386827445984">Loading document: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> pages...</translation> <translation id="1235745349614807883">Clear Recent Searches</translation> <translation id="5048533449481078685">list marker</translation> <translation id="372362261556059955">Additional plug-in needed</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Plug-in installation failed</translation> <translation id="8141602879876242471">This is a searchable index. Enter search keywords:</translation> <translation id="5650795167354946011">After installing the plug-in, click here to refresh</translation> -<translation id="370665806235115550">Loading...</translation> <translation id="6845533974506654842">press</translation> <translation id="8244226242650769279">image map</translation> <translation id="2548326553472216322">No recent searches</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Please confirm that you would like to install the <ph name="PLUGIN"/> plug-in. You should only install plug-ins that you trust.</translation> <translation id="6663448176199120256">Recent Searches</translation> <translation id="2597378329261239068">This document is password-protected. Please enter a password.</translation> -<translation id="7740050170769002709">HTML content</translation> +<translation id="6807599807928161586">web area</translation> <translation id="5939518447894949180">Reset</translation> <translation id="1842960171412779397">select</translation> <translation id="7638452146404718955">Click here to download plug-in</translation> diff --git a/webkit/glue/resources/webkit_strings_es-419.xtb b/webkit/glue/resources/webkit_strings_es-419.xtb index 5ec0935..12bc57b 100644 --- a/webkit/glue/resources/webkit_strings_es-419.xtb +++ b/webkit/glue/resources/webkit_strings_es-419.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="es-419"> <translation id="4519964825805946997">Error al instalar el complemento desde <ph name="URL"/></translation> -<translation id="9186171386827445984">Cargando documento: páginas <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/>...</translation> <translation id="1235745349614807883">Eliminar búsquedas recientes</translation> <translation id="5048533449481078685">marcador de listas</translation> <translation id="372362261556059955">Se necesita un complemento adicional</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Error de instalación del complemento</translation> <translation id="8141602879876242471">Se trata de un índice que admite búsquedas. Escribe las palabras clave de búsqueda:</translation> <translation id="5650795167354946011">Después de instalar el complemento, haz clic aquí para actualizar</translation> -<translation id="370665806235115550">Cargando...</translation> <translation id="6845533974506654842">hacer clic</translation> <translation id="8244226242650769279">mapa de imágenes</translation> <translation id="2548326553472216322">No hay búsquedas recientes</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Confirma que deseas instalar el complemento <ph name="PLUGIN"/>. Sólo deberías instalar los complementos confiables.</translation> <translation id="6663448176199120256">Búsquedas recientes</translation> <translation id="2597378329261239068">Este documento está protegido por contraseña. Ingresa una contraseña.</translation> -<translation id="7740050170769002709">Contenido HTML</translation> +<translation id="6807599807928161586">área web</translation> <translation id="5939518447894949180">Restablecer</translation> <translation id="1842960171412779397">seleccionar</translation> <translation id="7638452146404718955">Haz clic aquí para descargar el complemento</translation> diff --git a/webkit/glue/resources/webkit_strings_es.xtb b/webkit/glue/resources/webkit_strings_es.xtb index 8315543..5f9a245 100644 --- a/webkit/glue/resources/webkit_strings_es.xtb +++ b/webkit/glue/resources/webkit_strings_es.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="es"> <translation id="4519964825805946997">Se ha producido un error al descargar el complemento de la página <ph name="URL"/>.</translation> -<translation id="9186171386827445984">Cargando documento: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> páginas...</translation> <translation id="1235745349614807883">Eliminar búsquedas recientes</translation> <translation id="5048533449481078685">marcador de listas</translation> <translation id="372362261556059955">Se necesita un complemento adicional</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Se ha producido un error al instalar el complemento.</translation> <translation id="8141602879876242471">Se trata de un índice que admite búsquedas. Introduce las palabras clave de búsqueda:</translation> <translation id="5650795167354946011">Una vez que hayas instalado el complemento, haz clic aquí para actualizar la ventana.</translation> -<translation id="370665806235115550">Cargando...</translation> <translation id="6845533974506654842">pulsar</translation> <translation id="8244226242650769279">mapa de imágenes</translation> <translation id="2548326553472216322">No hay búsquedas recientes</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Confirma que quieres instalar el complemento <ph name="PLUGIN"/>. Solo debes instalar complementos en los que confíes.</translation> <translation id="6663448176199120256">Búsquedas recientes</translation> <translation id="2597378329261239068">Este documento está protegido por contraseña. Introduce una contraseña.</translation> -<translation id="7740050170769002709">Contenido HTML</translation> +<translation id="6807599807928161586">área web</translation> <translation id="5939518447894949180">Restablecer</translation> <translation id="1842960171412779397">seleccionar</translation> <translation id="7638452146404718955">Haz clic aquí para descargar el complemento.</translation> diff --git a/webkit/glue/resources/webkit_strings_et.xtb b/webkit/glue/resources/webkit_strings_et.xtb index e5932ac..2ac3c7a 100644 --- a/webkit/glue/resources/webkit_strings_et.xtb +++ b/webkit/glue/resources/webkit_strings_et.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="et"> <translation id="4519964825805946997">Pistikprogrammi installimine asukohast <ph name="URL"/> ebaõnnestus.</translation> -<translation id="9186171386827445984">Dokumendi laadimine: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> lehte ...</translation> <translation id="1235745349614807883">Kustuta viimased otsingud</translation> <translation id="5048533449481078685">loendilooja</translation> <translation id="372362261556059955">Vaja on täiendavat pistikprogrammi</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Pistikprogrammi installimine nurjus</translation> <translation id="8141602879876242471">See on otsitav indeks. Sisestage otsingu jaoks märksõnad:</translation> <translation id="5650795167354946011">Pärast lisandmooduli installimist klõpsake värskendamiseks siin</translation> -<translation id="370665806235115550">Laadimine...</translation> <translation id="6845533974506654842">vajuta</translation> <translation id="8244226242650769279">hüperpilt</translation> <translation id="2548326553472216322">Pole viimaseid otsingud</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Palun kinnitage, et soovite pistikprogrammi <ph name="PLUGIN"/> installida. Peaksite installima vaid usaldusväärseid pistikprogramme.</translation> <translation id="6663448176199120256">Viimased otsingud</translation> <translation id="2597378329261239068">Dokument on parooliga kaitstud. Sisestage parool.</translation> -<translation id="7740050170769002709">HTML-sisu</translation> +<translation id="6807599807928161586">veebiala</translation> <translation id="5939518447894949180">Lähtesta</translation> <translation id="1842960171412779397">vali</translation> <translation id="7638452146404718955">Pistikprogrammi allalaadimiseks klõpsake siin</translation> diff --git a/webkit/glue/resources/webkit_strings_fa.xtb b/webkit/glue/resources/webkit_strings_fa.xtb index 094ad9f..870dcf6 100644 --- a/webkit/glue/resources/webkit_strings_fa.xtb +++ b/webkit/glue/resources/webkit_strings_fa.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="fa"> <translation id="4519964825805946997">نصب افزونه از <ph name="URL"/> ناموفق بود</translation> -<translation id="9186171386827445984">در حال بارگیری سند: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> صفحات...</translation> <translation id="1235745349614807883">پاک کردن جستجوهای اخیر</translation> <translation id="5048533449481078685">علامت گذار لیست</translation> <translation id="372362261556059955">افزونه دیگری مورد نیاز است</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">نصب افزونه انجام نشد</translation> <translation id="8141602879876242471">این نمایه قابل جستجو است. کلمات کلیدی جستجو را وارد کنید:</translation> <translation id="5650795167354946011">بعد از نصب افزونه، برای تازه کردن اینجا را کلیک کنید</translation> -<translation id="370665806235115550">درحال بارگیری...</translation> <translation id="6845533974506654842">فشار دادن</translation> <translation id="8244226242650769279">نقشه تصویر</translation> <translation id="2548326553472216322">جستجوی جدیدی وجود ندارد</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">لطفاً تأیید کنید که مایلید افزونه <ph name="PLUGIN"/> نصب شود. فقط باید افزونه هایی را نصب کنید که به آنها اعتماد دارید.</translation> <translation id="6663448176199120256">جستجوهای جدید</translation> <translation id="2597378329261239068">این سند توسط رمز ورود محافظت می شود. لطفاً یک رمز ورود وارد کنید.</translation> -<translation id="7740050170769002709">محتوای HTML</translation> +<translation id="6807599807928161586">حیطه وب</translation> <translation id="5939518447894949180">بازنشانی</translation> <translation id="1842960171412779397">انتخاب</translation> <translation id="7638452146404718955">برای دانلود کردن افزونه اینجا را کلیک کنید</translation> diff --git a/webkit/glue/resources/webkit_strings_fi.xtb b/webkit/glue/resources/webkit_strings_fi.xtb index 604021f..4a1b6a3 100644 --- a/webkit/glue/resources/webkit_strings_fi.xtb +++ b/webkit/glue/resources/webkit_strings_fi.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="fi"> <translation id="4519964825805946997">Laajennuksen asennus osoitteesta <ph name="URL"/> epäonnistui</translation> -<translation id="9186171386827445984">Ladataan asiakirjaa: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> sivua...</translation> <translation id="1235745349614807883">Poista viimeisimmät haut</translation> <translation id="5048533449481078685">luettelon merkitsijä</translation> <translation id="372362261556059955">Toinen laajennus vaaditaan</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Laajennuksen asennus epäonnistui</translation> <translation id="8141602879876242471">Tämä on haettavissa oleva hakemisto. Anna hakusanat:</translation> <translation id="5650795167354946011">Päivitä laajennuksen asennuksen jälkeen napsauttamalla tästä</translation> -<translation id="370665806235115550">Ladataan...</translation> <translation id="6845533974506654842">paina</translation> <translation id="8244226242650769279">kuvakartta</translation> <translation id="2548326553472216322">Ei viimeisimpiä hakuja</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Vahvista, että haluat asentaa laajennuksen <ph name="PLUGIN"/>. Suosittelemme asentamaan vain laajennuksia, joihin luotat.</translation> <translation id="6663448176199120256">Viimeisimmät haut</translation> <translation id="2597378329261239068">Tämä asiakirja on suojattu salasanalla. Anna salasana.</translation> -<translation id="7740050170769002709">HTML-sisältö</translation> +<translation id="6807599807928161586">verkkoalue</translation> <translation id="5939518447894949180">Tyhjennä</translation> <translation id="1842960171412779397">Valitse</translation> <translation id="7638452146404718955">Lataa laajennus napsauttamalla tätä</translation> diff --git a/webkit/glue/resources/webkit_strings_fil.xtb b/webkit/glue/resources/webkit_strings_fil.xtb index 8459aca..43f88c3 100644 --- a/webkit/glue/resources/webkit_strings_fil.xtb +++ b/webkit/glue/resources/webkit_strings_fil.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="fil"> <translation id="4519964825805946997">Nabigong ma-install ang plug-in mula sa <ph name="URL"/></translation> -<translation id="9186171386827445984">Nilo-load ang dokumento: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> (na) pahina...</translation> <translation id="1235745349614807883">Lisiman ang Kasalukuyang Mga Paghahanap</translation> <translation id="5048533449481078685">Ilista ang marker</translation> <translation id="372362261556059955">Kinakailangan ang karagdagang plug-in</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Nabigo ang pag-install ng plug-in</translation> <translation id="8141602879876242471">Isa itong paghahanap ng index. Ipasok ang paghahanap sa mga keyword:</translation> <translation id="5650795167354946011">Pagkatapos i-install ng plug-in, mag-click dito upang mag-refresh</translation> -<translation id="370665806235115550">Kumakarga...</translation> <translation id="6845533974506654842">pindutin</translation> <translation id="8244226242650769279">mapa ng imahe</translation> <translation id="2548326553472216322">Walang kamakailang mga paghahanap</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Pakikumpirma na gusto mong i-install ang <ph name="PLUGIN"/> plug-in na ito. Dapat mong i-install lamang ang mga plug-in na iyong pinagkakatiwalaan.</translation> <translation id="6663448176199120256">Kasalukuyang Mga Paghahanap</translation> <translation id="2597378329261239068">Protektado ng password ang dokumentong ito. Mangyaring magpasok ng password.</translation> -<translation id="7740050170769002709">HTML na nilalaman</translation> +<translation id="6807599807928161586">web area</translation> <translation id="5939518447894949180">I-reset</translation> <translation id="1842960171412779397">piliin</translation> <translation id="7638452146404718955">Mag-click dito upang ma-download ang plug-in</translation> diff --git a/webkit/glue/resources/webkit_strings_fr.xtb b/webkit/glue/resources/webkit_strings_fr.xtb index ab1e32f..00ab953 100644 --- a/webkit/glue/resources/webkit_strings_fr.xtb +++ b/webkit/glue/resources/webkit_strings_fr.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="fr"> <translation id="4519964825805946997">Échec de l'installation du plug-in depuis <ph name="URL"/></translation> -<translation id="9186171386827445984">Chargement du document : <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> pages...</translation> <translation id="1235745349614807883">Effacer les recherches récentes</translation> <translation id="5048533449481078685">marqueur de liste</translation> <translation id="372362261556059955">Plug-in supplémentaire requis</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Échec de l'installation du plug-in</translation> <translation id="8141602879876242471">Vous pouvez lancer des recherches dans cet index. Pour cela, entrez des mots clés de recherche :</translation> <translation id="5650795167354946011">Après l'installation du plug-in, cliquez ici pour actualiser.</translation> -<translation id="370665806235115550">Chargement...</translation> <translation id="6845533974506654842">appuyer</translation> <translation id="8244226242650769279">image map</translation> <translation id="2548326553472216322">Aucune recherche récente</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Merci de confirmer que vous souhaitez installer le plug-in <ph name="PLUGIN"/>. N'installez que les plug-ins que vous considérez fiables.</translation> <translation id="6663448176199120256">Recherches récentes</translation> <translation id="2597378329261239068">Ce document est protégé par mot de passe. Veuillez saisir ce dernier.</translation> -<translation id="7740050170769002709">Contenu HTML</translation> +<translation id="6807599807928161586">Zone Web</translation> <translation id="5939518447894949180">Réinitialiser</translation> <translation id="1842960171412779397">sélectionner</translation> <translation id="7638452146404718955">Cliquer ici pour télécharger le plug-in</translation> diff --git a/webkit/glue/resources/webkit_strings_gu.xtb b/webkit/glue/resources/webkit_strings_gu.xtb index ad48fa1..e7160bb 100644 --- a/webkit/glue/resources/webkit_strings_gu.xtb +++ b/webkit/glue/resources/webkit_strings_gu.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="gu"> <translation id="4519964825805946997"><ph name="URL"/> થી પ્લગ-ઇન ઇન્સ્ટોલ કરવામાં નિષ્ફળ રહ્યાં</translation> -<translation id="9186171386827445984">દસ્તાવેજ લોડ કરી રહ્યું છે: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> પૃષ્ઠ...</translation> <translation id="1235745349614807883">હાલની શોધને સાફ કરો</translation> <translation id="5048533449481078685">સૂચિ માર્કર</translation> <translation id="372362261556059955">વધારાનું પ્લગ-ઇન આવશ્યક છે </translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">પ્લગ-ઇન ઇન્સ્ટોલેશન નિષ્ફળ ગયું</translation> <translation id="8141602879876242471">આ એક શોધસક્ષમ અનુક્રમણિકા છે. શોધ કીવર્ડ્સ દાખલ કરો:</translation> <translation id="5650795167354946011">પ્લગ-ઇન ઇન્સ્ટોલ કર્યા પછી, રીફ્રેશ કરવા અહીં ક્લિક કરો</translation> -<translation id="370665806235115550">લોડ કરી રહ્યું છે...</translation> <translation id="6845533974506654842">દબાવો</translation> <translation id="8244226242650769279">છબી નકશો</translation> <translation id="2548326553472216322">હાલની શોધો નથી</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">કૃપા કરીને પુષ્ટી કરો કે તમે <ph name="PLUGIN"/> પ્લગ-ઇન ઇન્સ્ટોલ કરવાનું પસંદ કરશો. તમારે ફક્ત તે જ પ્લગ-ઇન્સ ઇન્સ્ટોલ કરવા જોઈએ જે વિશ્વસ્ત હોય.</translation> <translation id="6663448176199120256">તાજેતરની શોધ</translation> <translation id="2597378329261239068">આ દસ્તાવેજ પાસવર્ડ સુરક્ષિત છે. કૃપા કરીને પાસવર્ડ દાખલ કરો.</translation> -<translation id="7740050170769002709">HTML સામગ્રી</translation> +<translation id="6807599807928161586">વેબ ક્ષેત્ર</translation> <translation id="5939518447894949180">રીસેટ કરો</translation> <translation id="1842960171412779397">પસંદ કરો</translation> <translation id="7638452146404718955">પ્લગ-ઇન ડાઉનલોડ કરવા માટે અહીં ક્લિક કરો</translation> diff --git a/webkit/glue/resources/webkit_strings_hi.xtb b/webkit/glue/resources/webkit_strings_hi.xtb index e7ef77f..e9bf9e7 100644 --- a/webkit/glue/resources/webkit_strings_hi.xtb +++ b/webkit/glue/resources/webkit_strings_hi.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="hi"> <translation id="4519964825805946997"><ph name="URL"/> से प्लग-इन स्थापित करने में विफल हुआ</translation> -<translation id="9186171386827445984">दस्तावेज़ लोड कर रहा है: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> पृष्ठ...</translation> <translation id="1235745349614807883">हाल ही की खोजें साफ़ करें</translation> <translation id="5048533449481078685">सूची चिन्हक</translation> <translation id="372362261556059955">अतिरिक्त प्लग-इन की आवश्यकता है</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">प्लग-इन स्थापना विफल हुई</translation> <translation id="8141602879876242471">यह एक खोजने योग्य इंडेक्स है. खोज कुंजीशब्द प्रविष्ट करें :</translation> <translation id="5650795167354946011">प्लग-इन स्थापित करने के बाद, रीफ़्रेश करने के लिए यहां क्लिक करें</translation> -<translation id="370665806235115550">लोड हो रहा है ...</translation> <translation id="6845533974506654842">दबाएँ</translation> <translation id="8244226242650769279">चित्र मैप</translation> <translation id="2548326553472216322">हाल ही में कोई खोज नहीं</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">कृपया पुष्टि करें कि आप <ph name="PLUGIN"/> प्लग-इन स्थापित करना चाहेंगे. आपको केवल वे प्लग-इन स्थापित करने चाहिए जिन पर आप विश्वास करते हैं.</translation> <translation id="6663448176199120256">हाल ही में की गई खोजें</translation> <translation id="2597378329261239068">यह दस्तावेज़ पासवर्ड सुरक्षित है. कृपया एक पासवर्ड दर्ज करें.</translation> -<translation id="7740050170769002709">HTML सामग्री</translation> +<translation id="6807599807928161586">वेब क्षेत्र</translation> <translation id="5939518447894949180">पुन: सेट करें</translation> <translation id="1842960171412779397">चुनें</translation> <translation id="7638452146404718955">प्लग-इन डाउनलोड करने के लिए यहां क्लिक करें</translation> diff --git a/webkit/glue/resources/webkit_strings_hr.xtb b/webkit/glue/resources/webkit_strings_hr.xtb index dfef690..89458bb 100644 --- a/webkit/glue/resources/webkit_strings_hr.xtb +++ b/webkit/glue/resources/webkit_strings_hr.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="hr"> <translation id="4519964825805946997">Nije uspjela instalacija dodatka s adrese <ph name="URL"/></translation> -<translation id="9186171386827445984">Učitavanje dokumenta: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> stranica...</translation> <translation id="1235745349614807883">Obriši najnovija pretraživanja</translation> <translation id="5048533449481078685">oznaka popisa</translation> <translation id="372362261556059955">Potreban je dodatni dodatak</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Nije uspjela instalacija dodatka</translation> <translation id="8141602879876242471">Ovaj je indeks moguće pretraživati. Unesite ključne riječi za pretraživanje:</translation> <translation id="5650795167354946011">Nakon instalacije dodatka kliknite ovdje za osvježenje stranice</translation> -<translation id="370665806235115550">Učitavanje...</translation> <translation id="6845533974506654842">pritisni</translation> <translation id="8244226242650769279">karta slika</translation> <translation id="2548326553472216322">Nema najnovijih pretraživanja</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Potvrdite da želite instalirati dodatak <ph name="PLUGIN"/>. Instalirajte samo dodatke koje smatrate pouzdanima.</translation> <translation id="6663448176199120256">Najnovija pretraživanja</translation> <translation id="2597378329261239068">Ovaj je dokument zaštićen zaporkom. Unesite zaporku.</translation> -<translation id="7740050170769002709">HTML sadržaj</translation> +<translation id="6807599807928161586">web područje</translation> <translation id="5939518447894949180">Ponovno postavi</translation> <translation id="1842960171412779397">odaberi</translation> <translation id="7638452146404718955">Kliknite ovdje za preuzimanje dodatka</translation> diff --git a/webkit/glue/resources/webkit_strings_hu.xtb b/webkit/glue/resources/webkit_strings_hu.xtb index 1b43f0f..848f2df 100644 --- a/webkit/glue/resources/webkit_strings_hu.xtb +++ b/webkit/glue/resources/webkit_strings_hu.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="hu"> <translation id="4519964825805946997">A plug-in telepítése nem sikerült a következő helyről: <ph name="URL"/></translation> -<translation id="9186171386827445984">Dokumentum betöltése: <ph name="NUMBER_OF_PAGES"/>/<ph name="PAGE_NUMBER"/>. oldal...</translation> <translation id="1235745349614807883">Friss keresések törlése</translation> <translation id="5048533449481078685">listajelölő</translation> <translation id="372362261556059955">További plug-in szükséges</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">A plug-in telepítése sikertelen</translation> <translation id="8141602879876242471">Ez egy kereshető index. Írjon be keresési kulcsszavakat:</translation> <translation id="5650795167354946011">A plug-in telepítését követően kattintson ide a frissítéshez</translation> -<translation id="370665806235115550">Betöltés…</translation> <translation id="6845533974506654842">Gomb lenyomása</translation> <translation id="8244226242650769279">képtérkép</translation> <translation id="2548326553472216322">Nincsenek friss keresések</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Kérjük, erősítse meg, hogy valóban telepíteni szeretné a következő plug-int: <ph name="PLUGIN"/>. Csak azokat a plug-ineket telepítse, amelyekben megbízik.</translation> <translation id="6663448176199120256">Friss keresések</translation> <translation id="2597378329261239068">Ez a dokumentum jelszóval védett. Kérjük, adja meg a jelszót.</translation> -<translation id="7740050170769002709">HTML-tartalom</translation> +<translation id="6807599807928161586">internetes terület</translation> <translation id="5939518447894949180">Visszaállítás</translation> <translation id="1842960171412779397">Kiválasztás</translation> <translation id="7638452146404718955">Ide kattintva letöltheti a plug-int</translation> diff --git a/webkit/glue/resources/webkit_strings_id.xtb b/webkit/glue/resources/webkit_strings_id.xtb index 50c97a2..6451c08 100644 --- a/webkit/glue/resources/webkit_strings_id.xtb +++ b/webkit/glue/resources/webkit_strings_id.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="id"> <translation id="4519964825805946997">Gagal memasang pengaya dari <ph name="URL"/></translation> -<translation id="9186171386827445984">Memuat dokumen: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> halaman...</translation> <translation id="1235745349614807883">Hapus Penelusuran Barusan</translation> <translation id="5048533449481078685">penanda daftar</translation> <translation id="372362261556059955">Diperlukan pengaya tambahan</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Pemasangan pengaya gagal</translation> <translation id="8141602879876242471">Terdapat indeks yang dapat dicari. Masukkan kata kunci penelusuran:</translation> <translation id="5650795167354946011">Setelah memasang pengaya, klik di sini untuk menyegarkan</translation> -<translation id="370665806235115550">Membuka...</translation> <translation id="6845533974506654842">tekan</translation> <translation id="8244226242650769279">gambar peta</translation> <translation id="2548326553472216322">Tidak ada penelusuran terkini</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Konfirmasikan bahwa Anda ingin memasang pengaya <ph name="PLUGIN"/>. Anda harus memasang pengaya yang Anda percayai saja.</translation> <translation id="6663448176199120256">Penelusuran Barusan</translation> <translation id="2597378329261239068">Dokumen ini dilindungi sandi. Masukkan sandi.</translation> -<translation id="7740050170769002709">Konten HTML</translation> +<translation id="6807599807928161586">area Web</translation> <translation id="5939518447894949180">Atur ulang</translation> <translation id="1842960171412779397">pilih</translation> <translation id="7638452146404718955">Klik di sini untuk mengunduh pengaya</translation> diff --git a/webkit/glue/resources/webkit_strings_it.xtb b/webkit/glue/resources/webkit_strings_it.xtb index 1fae27f..61c1e79 100644 --- a/webkit/glue/resources/webkit_strings_it.xtb +++ b/webkit/glue/resources/webkit_strings_it.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="it"> <translation id="4519964825805946997">Installazione del plug-in da <ph name="URL"/> non riuscita</translation> -<translation id="9186171386827445984">Caricamento del documento in corso: pagine <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/>...</translation> <translation id="1235745349614807883">Cancella ricerche recenti</translation> <translation id="5048533449481078685">indicatore elenco</translation> <translation id="372362261556059955">È necessario un plug-in aggiuntivo</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Installazione del plug-in non riuscita</translation> <translation id="8141602879876242471">Questo è un indice di ricerca. Inserisci le parole chiave di ricerca:</translation> <translation id="5650795167354946011">Dopo aver installato il plug-in, fai clic qui per aggiornare</translation> -<translation id="370665806235115550">Caricamento in corso...</translation> <translation id="6845533974506654842">premi</translation> <translation id="8244226242650769279">image map</translation> <translation id="2548326553472216322">Nessuna ricerca recente</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Conferma che desideri installare il plug-in <ph name="PLUGIN"/>. Dovresti installare soltanto plug-in attendibili.</translation> <translation id="6663448176199120256">Ricerche recenti</translation> <translation id="2597378329261239068">Questo documento è protetto da password. Inserisci una password.</translation> -<translation id="7740050170769002709">Contenuti HTML</translation> +<translation id="6807599807928161586">area web</translation> <translation id="5939518447894949180">Ripristina</translation> <translation id="1842960171412779397">seleziona</translation> <translation id="7638452146404718955">Fai clic qui per scaricare il plug-in</translation> diff --git a/webkit/glue/resources/webkit_strings_iw.xtb b/webkit/glue/resources/webkit_strings_iw.xtb index f748311..436b298 100644 --- a/webkit/glue/resources/webkit_strings_iw.xtb +++ b/webkit/glue/resources/webkit_strings_iw.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="iw"> <translation id="4519964825805946997">התקנת הפלאגין מתוך <ph name="URL"/> נכשלה</translation> -<translation id="9186171386827445984">טוען מסמך: דפים <ph name="NUMBER_OF_PAGES"/>/<ph name="PAGE_NUMBER"/>...</translation> <translation id="1235745349614807883">הסר חיפושים אחרונים</translation> <translation id="5048533449481078685">סמן רשימה</translation> <translation id="372362261556059955">פלאגין נוסף נחוץ</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">התקנת הפלאגין נכשלה</translation> <translation id="8141602879876242471">זהו אינדקס שניתן לבצע בו חיפוש. הזן מילות מפתח לחיפוש:</translation> <translation id="5650795167354946011">לאחר התקנת הפלאגין, לחץ כאן לרענון</translation> -<translation id="370665806235115550">טוען...</translation> <translation id="6845533974506654842">לחץ</translation> <translation id="8244226242650769279">מפת תמונות</translation> <translation id="2548326553472216322">אין חיפושים אחרונים</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">אשר שברצונך להתקין את הפלאגין <ph name="PLUGIN"/>. יש להתקין רכיבי פלאגין שאתה בוטח בהם בלבד.</translation> <translation id="6663448176199120256">חיפושים אחרונים</translation> <translation id="2597378329261239068">מסמך זה מוגן באמצעות סיסמה. הזן סיסמה.</translation> -<translation id="7740050170769002709">תוכן HTML</translation> +<translation id="6807599807928161586">אזור אינטרנט</translation> <translation id="5939518447894949180">אפס</translation> <translation id="1842960171412779397">בחר</translation> <translation id="7638452146404718955">לחץ כאן להורדת פלאגין</translation> diff --git a/webkit/glue/resources/webkit_strings_ja.xtb b/webkit/glue/resources/webkit_strings_ja.xtb index 865979d..2eccba2 100644 --- a/webkit/glue/resources/webkit_strings_ja.xtb +++ b/webkit/glue/resources/webkit_strings_ja.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="ja"> <translation id="4519964825805946997"><ph name="URL"/> からプラグインをインストールできませんでした</translation> -<translation id="9186171386827445984">ドキュメントの読み込み中: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> ページ...</translation> <translation id="1235745349614807883">最近の検索履歴を消去</translation> <translation id="5048533449481078685">リスト マーカー</translation> <translation id="372362261556059955">追加のプラグインが必要です</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">プラグインをインストールできませんでした</translation> <translation id="8141602879876242471">このインデックスは検索できます。キーワードを入力してください:</translation> <translation id="5650795167354946011">プラグインをインストールした後は、ここをクリックして更新を行ってください</translation> -<translation id="370665806235115550">読み込み中...</translation> <translation id="6845533974506654842">押す</translation> <translation id="8244226242650769279">イメージ マップ</translation> <translation id="2548326553472216322">最近の検索はありません</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">この <ph name="PLUGIN"/> プラグインをインストールしてもよいかご確認ください。信頼できるプラグインのみをインストールする必要があります。</translation> <translation id="6663448176199120256">最近の検索</translation> <translation id="2597378329261239068">このドキュメントはパスワードで保護されています。パスワードを入力してください。</translation> -<translation id="7740050170769002709">HTML コンテンツ</translation> +<translation id="6807599807928161586">ウェブ領域</translation> <translation id="5939518447894949180">リセット</translation> <translation id="1842960171412779397">選択</translation> <translation id="7638452146404718955">ここをクリックしてプラグインをダウンロード</translation> diff --git a/webkit/glue/resources/webkit_strings_kn.xtb b/webkit/glue/resources/webkit_strings_kn.xtb index 9a8f827..61dbd2c 100644 --- a/webkit/glue/resources/webkit_strings_kn.xtb +++ b/webkit/glue/resources/webkit_strings_kn.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="kn"> <translation id="4519964825805946997"><ph name="URL"/> ನಿಂದ ಪ್ಲಗ್-ಇನ್ ಅನ್ನು ಸ್ಥಾಪಿಸುವಲ್ಲಿ ವಿಫಲವಾಗಿದೆ</translation> -<translation id="9186171386827445984">ಲೋಡಿಂಗ್ ಡಾಕ್ಯುಮೆಂಟ್: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> ಪುಟಗಳು...</translation> <translation id="1235745349614807883">ಇತ್ತೀಚಿನ ಹುಡುಕಾಟವನ್ನು ತೆರವುಗೊಳಿಸಿ</translation> <translation id="5048533449481078685">ಪಟ್ಟಿ ಗುರುತು</translation> <translation id="372362261556059955">ಹೆಚ್ಚುವರಿ ಪ್ಲಗ್-ಇನ್ ಅಗತ್ಯವಿದೆ</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">ಪ್ಲಗ್-ಇನ್ ಅಳವಡಿಸುವಿಕೆಯು ವಿಫಲವಾಗಿದೆ</translation> <translation id="8141602879876242471">ಇದು ಹುಡುಕಾಡಬಹುದಾದ ಸೂಚಿಕೆ ಹುಡುಕಾಟ ಕೀವರ್ಡ್ಗಳನ್ನು ನಮೂದಿಸಿ:</translation> <translation id="5650795167354946011">ಪ್ಲಗ್-ಇನ್ ಸ್ಥಾಪನೆ ಮಾಡಿದ ನಂತರ, ರಿಫ್ರೆಶ್ ಮಾಡಲು ಇಲ್ಲಿ ಕ್ಲಿಕ್ ಮಾಡಿ</translation> -<translation id="370665806235115550">ಲೋಡ್ ಮಾಡಲಾಗುತ್ತಿದೆ...</translation> <translation id="6845533974506654842">ಒತ್ತಿ</translation> <translation id="8244226242650769279">ಇಮೇಜ್ ನಕ್ಷೆ</translation> <translation id="2548326553472216322">ಇತ್ತೀಚಿನ ಹುಡುಕಾಟಗಳು ಇಲ್ಲ</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">ನೀವು <ph name="PLUGIN"/> ಪ್ಲಗ್-ಇನ್ ಅನ್ನು ಅಳವಡಿಸಲು ಬಯಸುವುದಾದಲ್ಲಿ ದಯವಿಟ್ಟು ಖಚಿತಪಡಿಸಿ. ನೀವು ನಂಬುವಂತಹ ಫ್ಲಗ್-ಇನ್ಗಳನ್ನು ಮಾತ್ರ ನೀವು ಅಳವಡಿಸಬೇಕು.</translation> <translation id="6663448176199120256">ಇತ್ತೀಚಿನ ಹುಡುಕಾಟಗಳು</translation> <translation id="2597378329261239068">ಈ ಡಾಕ್ಯುಮೆಂಟ್ ಅನ್ನು ಪಾಸ್ವರ್ಡ್ನಿಂದ ರಕ್ಷಿಸಲಾಗಿದೆ. ದಯವಿಟ್ಟು ಪಾಸ್ವರ್ಡ್ ಅನ್ನು ನಮೂದಿಸಿ.</translation> -<translation id="7740050170769002709">HTML ವಿಷಯ</translation> +<translation id="6807599807928161586">ವೆಬ್ ಪ್ರದೇಶ</translation> <translation id="5939518447894949180">ಮರುಹೊಂದಿಸು</translation> <translation id="1842960171412779397">ಆಯ್ಕೆ ಮಾಡಿ</translation> <translation id="7638452146404718955">ಪ್ಲಗ್-ಇನ್ ಅನ್ನು ಡೌನ್ಲೋಡ್ ಮಾಡಲು ಇಲ್ಲಿ ಕ್ಲಿಕ್ ಮಾಡಿ</translation> diff --git a/webkit/glue/resources/webkit_strings_ko.xtb b/webkit/glue/resources/webkit_strings_ko.xtb index f3e829e..819c8ce 100644 --- a/webkit/glue/resources/webkit_strings_ko.xtb +++ b/webkit/glue/resources/webkit_strings_ko.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="ko"> <translation id="4519964825805946997"><ph name="URL"/>의 플러그인 설치 실패</translation> -<translation id="9186171386827445984">문서 로드 중: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/>페이지</translation> <translation id="1235745349614807883">최근 검색 삭제</translation> <translation id="5048533449481078685">목록 표시기</translation> <translation id="372362261556059955">추가 플러그인 필요</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">플러그인 설치 실패</translation> <translation id="8141602879876242471">이것은 검색 색인합니다. 검색 키워드 입력:</translation> <translation id="5650795167354946011">플러그인 설치 후 여기를 클릭하여 새로고침</translation> -<translation id="370665806235115550">로드 중...</translation> <translation id="6845533974506654842">누르기</translation> <translation id="8244226242650769279">이미지 지도</translation> <translation id="2548326553472216322">최근 수행된 검색 없음</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419"><ph name="PLUGIN"/> 플러그인을 설치할지 여부를 확인하시기 바랍니다. 신뢰할 수 있는 플러그인만 설치해야 합니다.</translation> <translation id="6663448176199120256">최근 수행된 검색</translation> <translation id="2597378329261239068">문서가 비밀번호로 보호되고 있습니다. 비밀번호를 입력하세요.</translation> -<translation id="7740050170769002709">HTML 콘텐츠</translation> +<translation id="6807599807928161586">웹 영역</translation> <translation id="5939518447894949180">재설정</translation> <translation id="1842960171412779397">선택</translation> <translation id="7638452146404718955">여기를 클릭하여 플러그인 다운로드</translation> diff --git a/webkit/glue/resources/webkit_strings_lt.xtb b/webkit/glue/resources/webkit_strings_lt.xtb index 7138796..8e8a7a7 100644 --- a/webkit/glue/resources/webkit_strings_lt.xtb +++ b/webkit/glue/resources/webkit_strings_lt.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="lt"> <translation id="4519964825805946997">Nepavyko įdiegti papildinio iš <ph name="URL"/></translation> -<translation id="9186171386827445984">Įkeliamas dokumentas: <ph name="PAGE_NUMBER"/> / <ph name="NUMBER_OF_PAGES"/> psl...</translation> <translation id="1235745349614807883">Išvalyti pastarąsias paieškas</translation> <translation id="5048533449481078685">sąrašo žymeklis</translation> <translation id="372362261556059955">Reikia papildomo papildinio</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Papildinio diegimas nepavyko</translation> <translation id="8141602879876242471">Tai yra ieškotinas indeksas. Įveskite paieškos raktinių žodžių:</translation> <translation id="5650795167354946011">Įdiegę papildinį spustelėkite čia, kad puslapis būtų atnaujintas</translation> -<translation id="370665806235115550">Įkeliama...</translation> <translation id="6845533974506654842">paspausti</translation> <translation id="8244226242650769279">paveikslėlio žemėlapis</translation> <translation id="2548326553472216322">Pastaruoju metu paieškų nevykdyta</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Patvirtinkite, kad norite įdiegti šį „<ph name="PLUGIN"/>“ papildinį. Turėtumėte diegti tik tuos papildinius, kurie patikimi.</translation> <translation id="6663448176199120256">Naujausios paieškos</translation> <translation id="2597378329261239068">Šis dokumentas apsaugotas slaptažodžiu. Įveskite slaptažodį.</translation> -<translation id="7740050170769002709">HTML turinys</translation> +<translation id="6807599807928161586">interneto sritis</translation> <translation id="5939518447894949180">Nustatyti iš naujo</translation> <translation id="1842960171412779397">pasirinkti</translation> <translation id="7638452146404718955">Spustelėkite čia, kad atsisiųstumėte papildinį</translation> diff --git a/webkit/glue/resources/webkit_strings_lv.xtb b/webkit/glue/resources/webkit_strings_lv.xtb index f070834..c97eb32 100644 --- a/webkit/glue/resources/webkit_strings_lv.xtb +++ b/webkit/glue/resources/webkit_strings_lv.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="lv"> <translation id="4519964825805946997">Neizdevās instalēt spraudni no <ph name="URL"/></translation> -<translation id="9186171386827445984">Notiek dokumenta ielāde: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> lappuses...</translation> <translation id="1235745349614807883">Dzēst nesenos meklējumus</translation> <translation id="5048533449481078685">sarakstu marķieris</translation> <translation id="372362261556059955">Nepieciešams papildu spraudnis</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Spraudņa instalēšana neizdevās</translation> <translation id="8141602879876242471">Šis ir indekss ar meklēšanas iespējām. Ievadīt meklēšanas atslēgvārdus:</translation> <translation id="5650795167354946011">Pēc spraudņa instalēšanas noklikšķiniet šeit, lai atsvaidzinātu</translation> -<translation id="370665806235115550">Notiek ielāde...</translation> <translation id="6845533974506654842">nospiest</translation> <translation id="8244226242650769279">attēlu karte</translation> <translation id="2548326553472216322">Nav nesenu meklējumu</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Lūdzu, apstipriniet, ka vēlaties instalēt <ph name="PLUGIN"/> spraudni. Jums ir jāinstalē tikai tie spraudņi, kuriem uzticaties.</translation> <translation id="6663448176199120256">Neseni meklējumi</translation> <translation id="2597378329261239068">Šis dokuments ir aizsargāts ar paroli. Lūdzu, ievadiet paroli.</translation> -<translation id="7740050170769002709">HTML saturs</translation> +<translation id="6807599807928161586">tīmekļa apgabals</translation> <translation id="5939518447894949180">Atiestatīt</translation> <translation id="1842960171412779397">Atlasiet</translation> <translation id="7638452146404718955">Noklikšķiniet šeit, lai lejupielādētu spraudni</translation> diff --git a/webkit/glue/resources/webkit_strings_ml.xtb b/webkit/glue/resources/webkit_strings_ml.xtb index fdf0843..437330d 100644 --- a/webkit/glue/resources/webkit_strings_ml.xtb +++ b/webkit/glue/resources/webkit_strings_ml.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="ml"> <translation id="4519964825805946997"><ph name="URL"/> എന്നതില് നിന്നുള്ള പ്ലഗ്-ഇന് ഇന്സ്റ്റാളുചെയ്യുന്നതിന് പരാജയപ്പെട്ടു</translation> -<translation id="9186171386827445984">പ്രമാണങ്ങള് ലോഡുചെയ്യുന്നു: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> പേജുകള്...</translation> <translation id="1235745349614807883">അടുത്തിടെയുള്ള തിരയലുകള് മായ്ക്കുക</translation> <translation id="5048533449481078685">പട്ടിക മാര്ക്കര്</translation> <translation id="372362261556059955">കൂടുതല് പ്ലഗ്-ഇന് ആവശ്യമുണ്ട്</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">പ്ലഗ്-ഇന് ഇന്സ്റ്റാളേഷന് പരാജയപ്പെട്ടു</translation> <translation id="8141602879876242471">ഇത് തിരയാവുന്ന സൂചികയാണ്. തിരയല് കീവേഡുകള് നല്കുക:</translation> <translation id="5650795167354946011">പ്ലഗ്-ഇന് ഇന്സ്റ്റാളുചെയ്തതിനുശേഷം, പുതുക്കുന്നതിന് ഇവിടെ ക്ലിക്കുചെയ്യുക</translation> -<translation id="370665806235115550">ലോഡ്ചെയ്യുന്നു...</translation> <translation id="6845533974506654842">അമര്ത്തുക</translation> <translation id="8244226242650769279">ഇമേജ് മാപ്പ്</translation> <translation id="2548326553472216322">സമീപകാല തിരയലുകള് ഇല്ല</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">നിങ്ങള് ഈ <ph name="PLUGIN"/> പ്ലഗ്-ഇന് ഇന്സ്റ്റാളുചെയ്യാന് താല്പ്പര്യപ്പെടുന്നുവെന്നത് ദയവായി സ്ഥിരീകരിക്കുക. നിങ്ങള് വിശ്വസിക്കുന്ന പ്ലഗ്-ഇനുകള് മാത്രമേ ഇന്സ്റ്റാള് ചെയ്യാവൂ.</translation> <translation id="6663448176199120256">സമീപകാല തിരയലുകള്</translation> <translation id="2597378329261239068">ഈ പ്രമാണം പാസ്വേഡ് പരിരക്ഷിതമാണ്. ദയവായി ഒരു പാസ്വേഡ് നല്കുക.</translation> -<translation id="7740050170769002709">HTML ഉള്ളടക്കം</translation> +<translation id="6807599807928161586">വെബ് മേഖല</translation> <translation id="5939518447894949180">വീണ്ടും സജ്ജീകരിക്കുക</translation> <translation id="1842960171412779397">തിരഞ്ഞെടുക്കൂ</translation> <translation id="7638452146404718955">പ്ലഗ്-ഇന് ഡൌണ്ലോഡുചെയ്യുന്നതിന് ഇവിടെ ക്ലിക്കുചെയ്യുക</translation> diff --git a/webkit/glue/resources/webkit_strings_mr.xtb b/webkit/glue/resources/webkit_strings_mr.xtb index da03fe1..3061c16 100644 --- a/webkit/glue/resources/webkit_strings_mr.xtb +++ b/webkit/glue/resources/webkit_strings_mr.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="mr"> <translation id="4519964825805946997"><ph name="URL"/> वरून प्लग-इन स्थापित करणे अयशस्वी</translation> -<translation id="9186171386827445984">दस्तऐवज लोड करत आहे: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> पृष्ठे...</translation> <translation id="1235745349614807883">अलीकडील शोध साफ करा</translation> <translation id="5048533449481078685">सूची चिन्हक</translation> <translation id="372362261556059955">अतिरिक्त प्लग-इन आवश्यक</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">प्लग-इन स्थापना अयशस्वी</translation> <translation id="8141602879876242471">ही शोध घेण्यायोग्य अनुक्रमणिका आहे. शोध कीवर्ड प्रविष्ट करा:</translation> <translation id="5650795167354946011">प्लग-इन स्थापित केल्यानंतर, रीफ्रेश करण्यासाठी येथे क्लिक करा</translation> -<translation id="370665806235115550">लोड करीत आहे...</translation> <translation id="6845533974506654842">दाबा</translation> <translation id="8244226242650769279">प्रतिमा नकाशा</translation> <translation id="2548326553472216322">अलीकडील शोध नाहीत</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">कृपया आपल्याला प्लग-इन <ph name="PLUGIN"/> स्थापित करणे आवडत असल्याची पुष्टी करा. आपण आपला विश्वास असलेले प्लग-इन्स फक्त स्थापित करावे. </translation> <translation id="6663448176199120256">अलीकडील शोध</translation> <translation id="2597378329261239068">हा दस्तऐवज संकेतशब्द संरक्षित आहे. कृपया संकेतशब्द प्रविष्ट करा.</translation> -<translation id="7740050170769002709">HTML सामुग्री</translation> +<translation id="6807599807928161586">वेब क्षेत्र</translation> <translation id="5939518447894949180">रीसेट करा</translation> <translation id="1842960171412779397">निवडा</translation> <translation id="7638452146404718955">प्लग-इन डाउनलोड करण्यासाठी येथे क्लिक करा</translation> diff --git a/webkit/glue/resources/webkit_strings_nl.xtb b/webkit/glue/resources/webkit_strings_nl.xtb index d3b90a2..df39241 100644 --- a/webkit/glue/resources/webkit_strings_nl.xtb +++ b/webkit/glue/resources/webkit_strings_nl.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="nl"> <translation id="4519964825805946997">Het installeren van de invoegtoepassing van <ph name="URL"/> is mislukt</translation> -<translation id="9186171386827445984">Document wordt geladen: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> pagina's...</translation> <translation id="1235745349614807883">Recente zoekopdrachten wissen</translation> <translation id="5048533449481078685">lijstmarkering</translation> <translation id="372362261556059955">Aanvullende invoegtoepassing vereist</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">De installatie van de invoegtoepassing is mislukt</translation> <translation id="8141602879876242471">Dit is een doorzoekbare index. Geef zoekwoorden op:</translation> <translation id="5650795167354946011">Klik hier na het installeren van de invoegtoepassing om te vernieuwen</translation> -<translation id="370665806235115550">Laden...</translation> <translation id="6845533974506654842">Indrukken</translation> <translation id="8244226242650769279">image map</translation> <translation id="2548326553472216322">Geen recente zoekopdrachten</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Bevestig dat u de invoegtoepassing van <ph name="PLUGIN"/> wilt installeren. U moet alleen invoegtoepassingen installeren die u vertrouwt.</translation> <translation id="6663448176199120256">Recente zoekopdrachten</translation> <translation id="2597378329261239068">Dit document is beveiligd met een wachtwoord. Geef een wachtwoord op.</translation> -<translation id="7740050170769002709">HTML-inhoud</translation> +<translation id="6807599807928161586">webgedeelte</translation> <translation id="5939518447894949180">Herstellen</translation> <translation id="1842960171412779397">Selecteren</translation> <translation id="7638452146404718955">Klik hier om de invoegtoepassing te downloaden</translation> diff --git a/webkit/glue/resources/webkit_strings_no.xtb b/webkit/glue/resources/webkit_strings_no.xtb index 6346872..c94ad8f 100644 --- a/webkit/glue/resources/webkit_strings_no.xtb +++ b/webkit/glue/resources/webkit_strings_no.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="no"> <translation id="4519964825805946997">Kunne ikke installere programtillegget fra <ph name="URL"/></translation> -<translation id="9186171386827445984">Laster inn dokument: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> sider</translation> <translation id="1235745349614807883">Fjern nylige søk</translation> <translation id="5048533449481078685">listemarkør</translation> <translation id="372362261556059955">Ekstra programtillegg kreves</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Installering av programtillegg mislyktes</translation> <translation id="8141602879876242471">Dette er en søkbar indeks. Angi søkeordene:</translation> <translation id="5650795167354946011">Når programtillegget er installert, klikker du her for å oppdatere</translation> -<translation id="370665806235115550">Laster inn...</translation> <translation id="6845533974506654842">trykk</translation> <translation id="8244226242650769279">bildekart</translation> <translation id="2548326553472216322">Ingen nylige søk</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Bekreft at du ønsker å installere programtillegget <ph name="PLUGIN"/>. Du bør kun installere programtillegg du stoler på.</translation> <translation id="6663448176199120256">Nylige søk</translation> <translation id="2597378329261239068">Dette dokumentet er passordbeskyttet. Skriv inn et passord.</translation> -<translation id="7740050170769002709">HTML-innhold</translation> +<translation id="6807599807928161586">nettområde</translation> <translation id="5939518447894949180">Tilbakestill</translation> <translation id="1842960171412779397">velg</translation> <translation id="7638452146404718955">Klikk her for å laste ned programtillegget</translation> diff --git a/webkit/glue/resources/webkit_strings_pl.xtb b/webkit/glue/resources/webkit_strings_pl.xtb index b37ec7e..ea4f6cf 100644 --- a/webkit/glue/resources/webkit_strings_pl.xtb +++ b/webkit/glue/resources/webkit_strings_pl.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="pl"> <translation id="4519964825805946997">Nie można zainstalować wtyczki dostępnej pod adresem <ph name="URL"/></translation> -<translation id="9186171386827445984">Wczytywanie dokumentu: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> stron...</translation> <translation id="1235745349614807883">Wyczyść ostatnie wyszukiwania</translation> <translation id="5048533449481078685">znacznik listy</translation> <translation id="372362261556059955">Potrzebna jest dodatkowa wtyczka</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Instalacja wtyczki nie powiodła się</translation> <translation id="8141602879876242471">Ten indeks można przeszukiwać. Wprowadź wyszukiwane słowa kluczowe:</translation> <translation id="5650795167354946011">Po zainstalowaniu wtyczki kliknij tutaj, aby odświeżyć okno</translation> -<translation id="370665806235115550">Ładowanie...</translation> <translation id="6845533974506654842">naciśnij</translation> <translation id="8244226242650769279">mapa grafiki</translation> <translation id="2548326553472216322">Brak ostatnich wyszukiwań</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Potwierdź zamiar zainstalowania wtyczki <ph name="PLUGIN"/>. Należy instalować wyłącznie zaufane wtyczki.</translation> <translation id="6663448176199120256">Ostatnie wyszukiwania</translation> <translation id="2597378329261239068">Ten dokument jest chroniony hasłem. Wprowadź hasło.</translation> -<translation id="7740050170769002709">Treść HTML</translation> +<translation id="6807599807928161586">obszar sieci</translation> <translation id="5939518447894949180">Resetuj</translation> <translation id="1842960171412779397">wybierz</translation> <translation id="7638452146404718955">Kliknij tutaj, aby pobrać wtyczkę</translation> diff --git a/webkit/glue/resources/webkit_strings_pt-BR.xtb b/webkit/glue/resources/webkit_strings_pt-BR.xtb index 5233854..b34c7cb 100644 --- a/webkit/glue/resources/webkit_strings_pt-BR.xtb +++ b/webkit/glue/resources/webkit_strings_pt-BR.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="pt-BR"> <translation id="4519964825805946997">Falha ao instalar o plug-in de <ph name="URL"/></translation> -<translation id="9186171386827445984">Carregando documento: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> páginas...</translation> <translation id="1235745349614807883">Limpar pesquisas recentes</translation> <translation id="5048533449481078685">marcador de lista</translation> <translation id="372362261556059955">Plug-in adicional necessário</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Falha na instalação do plug-in</translation> <translation id="8141602879876242471">Este é um índice pesquisável. Insira palavras-chave de pesquisa:</translation> <translation id="5650795167354946011">Depois de instalar o plug-in, clique aqui para atualizar</translation> -<translation id="370665806235115550">Carregando...</translation> <translation id="6845533974506654842">pressione</translation> <translation id="8244226242650769279">mapa de imagens</translation> <translation id="2548326553472216322">Nenhuma pesquisa recente</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Confirme se você deseja instalar o plug-in do <ph name="PLUGIN"/>. Você deve instalar apenas plug-ins em que você confia.</translation> <translation id="6663448176199120256">Pesquisas recentes</translation> <translation id="2597378329261239068">Este documento está protegido por senha. Digite a senha.</translation> -<translation id="7740050170769002709">Conteúdo HTML</translation> +<translation id="6807599807928161586">área da web</translation> <translation id="5939518447894949180">Redefinir</translation> <translation id="1842960171412779397">selecione</translation> <translation id="7638452146404718955">Clique aqui para fazer download do plug-in</translation> diff --git a/webkit/glue/resources/webkit_strings_pt-PT.xtb b/webkit/glue/resources/webkit_strings_pt-PT.xtb index a93bd4f..817cdf4 100644 --- a/webkit/glue/resources/webkit_strings_pt-PT.xtb +++ b/webkit/glue/resources/webkit_strings_pt-PT.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="pt-PT"> <translation id="4519964825805946997">Falha ao instalar o plug-in de <ph name="URL"/></translation> -<translation id="9186171386827445984">A carregar o documento: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> páginas...</translation> <translation id="1235745349614807883">Limpar pesquisas recentes</translation> <translation id="5048533449481078685">marcador de lista</translation> <translation id="372362261556059955">Plug-in adicional requerido</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">A instalação do plug-in falhou</translation> <translation id="8141602879876242471">Este índice é pesquisável. Introduza palavras-chave de pesquisa:</translation> <translation id="5650795167354946011">Após instalar o plug-in, clique aqui para actualizar</translation> -<translation id="370665806235115550">A carregar...</translation> <translation id="6845533974506654842">premir</translation> <translation id="8244226242650769279">mapa de imagem</translation> <translation id="2548326553472216322">Nenhuma pesquisa recente</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Confirme se pretende instalar o plug-in do <ph name="PLUGIN"/>. Deve instalar apenas plug-ins fidedignos.</translation> <translation id="6663448176199120256">Pesquisas recentes</translation> <translation id="2597378329261239068">Este documento está protegido por palavra-passe. Introduza uma palavra-passe.</translation> -<translation id="7740050170769002709">Conteúdo HTML</translation> +<translation id="6807599807928161586">Área Web</translation> <translation id="5939518447894949180">Repor</translation> <translation id="1842960171412779397">seleccionar</translation> <translation id="7638452146404718955">Clique aqui para transferir o plug-in</translation> diff --git a/webkit/glue/resources/webkit_strings_ro.xtb b/webkit/glue/resources/webkit_strings_ro.xtb index eeebfc3..2f8ec55 100644 --- a/webkit/glue/resources/webkit_strings_ro.xtb +++ b/webkit/glue/resources/webkit_strings_ro.xtb @@ -1,46 +1,44 @@ <?xml version="1.0" ?> <!DOCTYPE translationbundle> <translationbundle lang="ro"> -<translation id="4519964825805946997">Instalarea pluginului de la <ph name="URL"/> a eșuat</translation> -<translation id="9186171386827445984">Se încarcă documentul: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> (de) pagini...</translation> -<translation id="1235745349614807883">Ștergeți căutările recente</translation> +<translation id="4519964825805946997">Instalarea pluginului de la <ph name="URL"/> a eşuat</translation> +<translation id="1235745349614807883">Ştergeţi căutările recente</translation> <translation id="5048533449481078685">marcator listă</translation> <translation id="372362261556059955">Este necesar un plugin suplimentar</translation> <translation id="4202807286478387388">Salt</translation> <translation id="4611115858363067980"><ph name="FILENAME"/><ph name="WIDTH"/>×<ph name="HEIGHT"/></translation> -<translation id="7658239707568436148">Anulați</translation> -<translation id="795667975304826397">Nu s-au ales fișiere</translation> -<translation id="1416462845279468967">Instalarea pluginului a eșuat</translation> -<translation id="8141602879876242471">Acesta este un index în care se poate căuta. Introduceți cuvintele cheie pentru căutare:</translation> -<translation id="5650795167354946011">După instalarea pluginului, faceți clic aici pentru a actualiza</translation> -<translation id="370665806235115550">Se încarcă...</translation> -<translation id="6845533974506654842">Apăsați</translation> +<translation id="7658239707568436148">Anulaţi</translation> +<translation id="795667975304826397">Nu s-au ales fişiere</translation> +<translation id="1416462845279468967">Instalarea pluginului a eşuat</translation> +<translation id="8141602879876242471">Acesta este un index în care se poate căuta. Introduceţi cuvintele cheie pentru căutare:</translation> +<translation id="5650795167354946011">După instalarea pluginului, faceţi clic aici pentru a actualiza</translation> +<translation id="6845533974506654842">Apăsaţi</translation> <translation id="8244226242650769279">hartă cu imagini</translation> <translation id="2548326553472216322">Nicio căutare recentă</translation> <translation id="5944544982112848342">2048 (Grad înalt)</translation> <translation id="3040011195152428237">link</translation> -<translation id="2745343197843472802">Descărcați pluginul</translation> -<translation id="5776402066334188252">Confirmați că doriți să instalați acest plugin. Vă recomandăm să instalați numai pluginuri în care aveți încredere.</translation> +<translation id="2745343197843472802">Descărcaţi pluginul</translation> +<translation id="5776402066334188252">Confirmaţi că doriţi să instalaţi acest plugin. Vă recomandăm să instalaţi numai pluginuri în care aveţi încredere.</translation> <translation id="4003986561708175844">Pluginul necesar nu este instalat</translation> <translation id="3018094406922859308">Se descarcă pluginul...</translation> -<translation id="7364796246159120393">Alegeți fișierul</translation> -<translation id="8964020114565522021">Trageți fișierul aici</translation> -<translation id="838869780401515933">Bifați</translation> +<translation id="7364796246159120393">Alegeţi fişierul</translation> +<translation id="8964020114565522021">Trageţi fişierul aici</translation> +<translation id="838869780401515933">Bifaţi</translation> <translation id="2846343701378493991">1024 (Grad mediu)</translation> -<translation id="5476505524087279545">Debifați</translation> -<translation id="3789841737615482174">Instalați</translation> -<translation id="5253117816378681419">Confirmați că doriți să instalați pluginul <ph name="PLUGIN"/>. Vă recomandăm să instalați numai pluginuri în care aveți încredere.</translation> +<translation id="5476505524087279545">Debifaţi</translation> +<translation id="3789841737615482174">Instalaţi</translation> +<translation id="5253117816378681419">Confirmaţi că doriţi să instalaţi pluginul <ph name="PLUGIN"/>. Vă recomandăm să instalaţi numai pluginuri în care aveţi încredere.</translation> <translation id="6663448176199120256">Căutări recente</translation> -<translation id="2597378329261239068">Acest document este protejat cu parolă. Introduceți o parolă.</translation> -<translation id="7740050170769002709">Conținut HTML</translation> -<translation id="5939518447894949180">Resetați</translation> -<translation id="1842960171412779397">Selectați</translation> -<translation id="7638452146404718955">Faceți clic aici pentru a descărca pluginul</translation> -<translation id="6119846243427417423">Activați</translation> -<translation id="8444882422881193423"><ph name="NUMBER_OF_FILES"/> fișiere</translation> +<translation id="2597378329261239068">Acest document este protejat cu parolă. Introduceţi o parolă.</translation> +<translation id="6807599807928161586">zona Web</translation> +<translation id="5939518447894949180">Resetaţi</translation> +<translation id="1842960171412779397">Selectaţi</translation> +<translation id="7638452146404718955">Faceţi clic aici pentru a descărca pluginul</translation> +<translation id="6119846243427417423">Activaţi</translation> +<translation id="8444882422881193423"><ph name="NUMBER_OF_FILES"/> fişiere</translation> <translation id="4470547978413275879">Pluginul <ph name="PLUGIN"/> nu este instalat</translation> -<translation id="6765711848403622008">Niciun plugin disponibil pentru a afișa acest conținut</translation> +<translation id="6765711848403622008">Niciun plugin disponibil pentru a afişa acest conţinut</translation> <translation id="8597182159515967513">titlu</translation> -<translation id="2653659639078652383">Trimiteți</translation> +<translation id="2653659639078652383">Trimiteţi</translation> <translation id="8475551193147984329">Este necesar pluginul <ph name="PLUGIN"/></translation> </translationbundle>
\ No newline at end of file diff --git a/webkit/glue/resources/webkit_strings_ru.xtb b/webkit/glue/resources/webkit_strings_ru.xtb index 5ea9049..97e2796 100644 --- a/webkit/glue/resources/webkit_strings_ru.xtb +++ b/webkit/glue/resources/webkit_strings_ru.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="ru"> <translation id="4519964825805946997">Не удалось установить подключаемый модуль с адреса <ph name="URL"/></translation> -<translation id="9186171386827445984">Загрузка документа: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> стр.</translation> <translation id="1235745349614807883">Очистить недавние поиски</translation> <translation id="5048533449481078685">маркер списка</translation> <translation id="372362261556059955">Необходим дополнительный подключаемый модуль</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Не удалось установить подключаемый модуль</translation> <translation id="8141602879876242471">Это индекс с возможностью поиска. Введите ключевые слова для поиска:</translation> <translation id="5650795167354946011">После установки подключаемого модуля нажмите здесь, чтобы обновить страницу</translation> -<translation id="370665806235115550">Загрузка...</translation> <translation id="6845533974506654842">нажать</translation> <translation id="8244226242650769279">графическая карта</translation> <translation id="2548326553472216322">Нет недавних поисков</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Подтвердите, что вы хотите установить подключаемый модуль <ph name="PLUGIN"/>. Вы доверяете ему?</translation> <translation id="6663448176199120256">Недавние поиски</translation> <translation id="2597378329261239068">Документ защищен паролем. Введите пароль.</translation> -<translation id="7740050170769002709">HTML-содержание</translation> +<translation id="6807599807928161586">область Интернетеа</translation> <translation id="5939518447894949180">Изменить</translation> <translation id="1842960171412779397">выбрать</translation> <translation id="7638452146404718955">Нажмите здесь, чтобы загрузить подключаемый модуль</translation> diff --git a/webkit/glue/resources/webkit_strings_sk.xtb b/webkit/glue/resources/webkit_strings_sk.xtb index a9b37ba..71e68a9 100644 --- a/webkit/glue/resources/webkit_strings_sk.xtb +++ b/webkit/glue/resources/webkit_strings_sk.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="sk"> <translation id="4519964825805946997">Inštalácia doplnku z adresy <ph name="URL"/> zlyhala</translation> -<translation id="9186171386827445984">Prebieha načítavanie dokumentu: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> stránok...</translation> <translation id="1235745349614807883">Vyčistiť posledné vyhľadávania</translation> <translation id="5048533449481078685">ukazovateľ v zozname</translation> <translation id="372362261556059955">Vyžaduje sa ďalší doplnok</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Inštalácia doplnku zlyhala</translation> <translation id="8141602879876242471">Tento index sa dá prehľadávať. Zadajte kľúčové slová na vyhľadanie:</translation> <translation id="5650795167354946011">Kliknutím sem po inštalácii doplnku obnovíte obsah</translation> -<translation id="370665806235115550">Načítava sa...</translation> <translation id="6845533974506654842">stlačiť</translation> <translation id="8244226242650769279">mapa obrázka</translation> <translation id="2548326553472216322">Žiadne posledné vyhľadávania</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Potvrďte, že chcete nainštalovať doplnok <ph name="PLUGIN"/>. Mali by ste inštalovať len doplnky, ktorým dôverujete.</translation> <translation id="6663448176199120256">Posledné vyhľadávania</translation> <translation id="2597378329261239068">Tento dokument je chránený heslom. Zadajte heslo.</translation> -<translation id="7740050170769002709">Obsah HTML</translation> +<translation id="6807599807928161586">webová oblasť</translation> <translation id="5939518447894949180">Vynulovať</translation> <translation id="1842960171412779397">vybrať</translation> <translation id="7638452146404718955">Kliknutím sem prevezmete doplnok</translation> diff --git a/webkit/glue/resources/webkit_strings_sl.xtb b/webkit/glue/resources/webkit_strings_sl.xtb index e3b1061..2ee1e5b 100644 --- a/webkit/glue/resources/webkit_strings_sl.xtb +++ b/webkit/glue/resources/webkit_strings_sl.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="sl"> <translation id="4519964825805946997">Namestitev vtičnika z naslova <ph name="URL"/> ni bila uspešna</translation> -<translation id="9186171386827445984">Nalaganje dokumenta: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> strani ...</translation> <translation id="1235745349614807883">Počisti zadnja iskanja</translation> <translation id="5048533449481078685">označevalnik seznama</translation> <translation id="372362261556059955">Potreben je dodaten vtičnik</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Namestitev vtičnika ni bila uspešna</translation> <translation id="8141602879876242471">To je kazalo, ki omogoča iskanje. Vnesite ključne besede za iskanje:</translation> <translation id="5650795167354946011">Po namestitvi vtičnika, kliknite tu, da osvežite</translation> -<translation id="370665806235115550">Nalagam ...</translation> <translation id="6845533974506654842">pritisni</translation> <translation id="8244226242650769279">slikovni zemljevid</translation> <translation id="2548326553472216322">Ni zadnjih iskanj</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Potrdite, da želite namestiti ta <ph name="PLUGIN"/> vtičnik. Nameščajte le vtičnike, ki jim zaupate.</translation> <translation id="6663448176199120256">Zadnja iskanja</translation> <translation id="2597378329261239068">Dokument je zaščiten z geslom. Vnesite geslo.</translation> -<translation id="7740050170769002709">Vsebina HTML</translation> +<translation id="6807599807928161586">spletno področje</translation> <translation id="5939518447894949180">Ponastavi</translation> <translation id="1842960171412779397">izberi</translation> <translation id="7638452146404718955">Če želite prenesti vtičnik, kliknite tukaj</translation> diff --git a/webkit/glue/resources/webkit_strings_sr.xtb b/webkit/glue/resources/webkit_strings_sr.xtb index 3b32e4d..a54c61b 100644 --- a/webkit/glue/resources/webkit_strings_sr.xtb +++ b/webkit/glue/resources/webkit_strings_sr.xtb @@ -2,18 +2,16 @@ <!DOCTYPE translationbundle> <translationbundle lang="sr"> <translation id="4519964825805946997">Инсталирање додатка са адресе <ph name="URL"/> није успело</translation> -<translation id="9186171386827445984">Учитавање документа: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> странице(а)...</translation> <translation id="1235745349614807883">Обриши недавне претраге</translation> <translation id="5048533449481078685">означивач листе</translation> <translation id="372362261556059955">Потребан је још један додатак</translation> <translation id="4202807286478387388">прескочи</translation> <translation id="4611115858363067980"><ph name="FILENAME"/><ph name="WIDTH"/>×<ph name="HEIGHT"/></translation> <translation id="7658239707568436148">Откажи</translation> -<translation id="795667975304826397">Није одабрано</translation> +<translation id="795667975304826397">Није одабрана датотека</translation> <translation id="1416462845279468967">Инсталација додатка није успела</translation> <translation id="8141602879876242471">Ово је индекс који може да се претражује. Унесите кључне речи за претрагу:</translation> <translation id="5650795167354946011">Након инсталирања додатка, кликните овде да бисте освежили</translation> -<translation id="370665806235115550">Учитавање...</translation> <translation id="6845533974506654842">притисни</translation> <translation id="8244226242650769279">мапа слике</translation> <translation id="2548326553472216322">Нема недавних претрага</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Потврдите да желите да инсталирате <ph name="PLUGIN"/> додатак. Инсталирајте само додатке у које имате поверења.</translation> <translation id="6663448176199120256">Недавне претраге</translation> <translation id="2597378329261239068">Овај документ је заштићен лозинком. Унесите лозинку.</translation> -<translation id="7740050170769002709">HTML садржај</translation> +<translation id="6807599807928161586">веб област</translation> <translation id="5939518447894949180">Ресетуј</translation> <translation id="1842960171412779397">изабери</translation> <translation id="7638452146404718955">Кликните овде да бисте преузели додатак</translation> diff --git a/webkit/glue/resources/webkit_strings_sv.xtb b/webkit/glue/resources/webkit_strings_sv.xtb index 7cbe67d..aa42d57 100644 --- a/webkit/glue/resources/webkit_strings_sv.xtb +++ b/webkit/glue/resources/webkit_strings_sv.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="sv"> <translation id="4519964825805946997">Det gick inte att installera plugin-program från <ph name="URL"/></translation> -<translation id="9186171386827445984">Läser in dokument: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> sidor...</translation> <translation id="1235745349614807883">Rensa senaste sökningar</translation> <translation id="5048533449481078685">listmarkör</translation> <translation id="372362261556059955">Ett ytterligare plugin-program krävs</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Installationen av plugin-programmet misslyckades</translation> <translation id="8141602879876242471">Det här är ett sökbart index. Skriv sökord:</translation> <translation id="5650795167354946011">Klicka här för att uppdatera när du har installerat plugin-programmet</translation> -<translation id="370665806235115550">Laddar...</translation> <translation id="6845533974506654842">tryck</translation> <translation id="8244226242650769279">bildkarta</translation> <translation id="2548326553472216322">Inga nya sökningar</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Bekräfta att du vill installera plugin-programmet <ph name="PLUGIN"/>. Installera bara plugin-program från tillförlitliga källor.</translation> <translation id="6663448176199120256">Senaste sökningar</translation> <translation id="2597378329261239068">Dokumentet är lösenordsskyddat. Ange ett lösenord.</translation> -<translation id="7740050170769002709">HTML-innehåll</translation> +<translation id="6807599807928161586">webbområde</translation> <translation id="5939518447894949180">Återställ</translation> <translation id="1842960171412779397">välj</translation> <translation id="7638452146404718955">Klicka här för att hämta plugin-programmet</translation> diff --git a/webkit/glue/resources/webkit_strings_sw.xtb b/webkit/glue/resources/webkit_strings_sw.xtb index 088048a..e507aa6 100644 --- a/webkit/glue/resources/webkit_strings_sw.xtb +++ b/webkit/glue/resources/webkit_strings_sw.xtb @@ -8,7 +8,6 @@ <translation id="7658239707568436148">Ghairi</translation> <translation id="795667975304826397">Hakuna faili lililochaguliwa</translation> <translation id="8141602879876242471">Hii ni fahirisi inayoweza kutafutwa. Weka maneno muhimu ya utafutaji.</translation> -<translation id="370665806235115550">Inapakia...</translation> <translation id="6845533974506654842">bofya</translation> <translation id="8244226242650769279">ramani ya picha</translation> <translation id="2548326553472216322">Hakuna utafutaji wa hivi karibuni</translation> @@ -21,6 +20,7 @@ <translation id="5476505524087279545">toa tiki</translation> <translation id="3789841737615482174">Sakinisha</translation> <translation id="6663448176199120256">Utafutaji wa hivi karibuni</translation> +<translation id="6807599807928161586">eneo wavuti</translation> <translation id="5939518447894949180">Weka upya</translation> <translation id="1842960171412779397">chagua</translation> <translation id="6119846243427417423">wezesha</translation> diff --git a/webkit/glue/resources/webkit_strings_ta.xtb b/webkit/glue/resources/webkit_strings_ta.xtb index f8dbf00..47d8547 100644 --- a/webkit/glue/resources/webkit_strings_ta.xtb +++ b/webkit/glue/resources/webkit_strings_ta.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="ta"> <translation id="4519964825805946997"><ph name="URL"/> இலிருந்து செருகுநிரலை நிறுவுதல் தோல்வியடைந்தது</translation> -<translation id="9186171386827445984">ஆவணத்தை ஏற்றுகிறது: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> பக்கங்கள்...</translation> <translation id="1235745349614807883">சமீபத்திய தேடல்களை சுத்தமாக்கு</translation> <translation id="5048533449481078685">பட்டியல் குறிப்பான்</translation> <translation id="372362261556059955">கூடுதல் செருகுநிரல் தேவைப்படுகிறது</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">செருகுநிரலை நிறுவுதல் தோல்வியடைந்தது</translation> <translation id="8141602879876242471">இது தேடக்கூடிய பொருளடக்கம். தேடல் சொற்களை உள்ளிடுக:</translation> <translation id="5650795167354946011">செருகுநிரலை நிறுவிய பின்பு புதுப்பிக்க இங்கு கிளிக்செய்க</translation> -<translation id="370665806235115550">நினைவேறுகிறது...</translation> <translation id="6845533974506654842">அழுத்துக</translation> <translation id="8244226242650769279">பட மேப்</translation> <translation id="2548326553472216322">சமீபத்திய தேடல்கள் எதுவுமில்லை</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419"><ph name="PLUGIN"/> செருகுநிரலை நிறுவ நீங்கள் விரும்புகிறீர்கள் என்பதை தயவுசெய்து உறுதிசெய்க. நீங்கள் நம்பும் செருகுநிரல்களை மட்டும் நிறுவ வேண்டும்.</translation> <translation id="6663448176199120256">சமீபத்திய தேடல்கள்</translation> <translation id="2597378329261239068">இந்த ஆவணம் கடவுச்சொல் பாதுகாக்கப்பட்ட ஒன்று. தயவுசெய்து ஒரு கடவுச்சொல்லை உள்ளிடுக.</translation> -<translation id="7740050170769002709">HTML உள்ளடக்கம்</translation> +<translation id="6807599807928161586">வலைப் பகுதி</translation> <translation id="5939518447894949180">மீட்டமை</translation> <translation id="1842960171412779397">தேர்ந்தெடு</translation> <translation id="7638452146404718955">செருகுநிரலைப் பதிவிறக்க இங்கே கிளிக் செய்க</translation> diff --git a/webkit/glue/resources/webkit_strings_te.xtb b/webkit/glue/resources/webkit_strings_te.xtb index a1f9fd6..3c1e875 100644 --- a/webkit/glue/resources/webkit_strings_te.xtb +++ b/webkit/glue/resources/webkit_strings_te.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="te"> <translation id="4519964825805946997"><ph name="URL"/> నుండి ప్లగ్-ఇన్ను వ్యవస్థాపించడానికి విఫలమైంది</translation> -<translation id="9186171386827445984">పత్రాన్ని లోడ్ చేస్తోంది: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> పేజీలు...</translation> <translation id="1235745349614807883">ఇటీవల శోధనలను క్లియర్ చెయ్యి</translation> <translation id="5048533449481078685">జాబితా మార్కర్</translation> <translation id="372362261556059955">అదనపు ప్లగ్-ఇన్ అవసరం</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">ప్లగ్-ఇన్ వ్యవస్థాపన విఫలమైంది</translation> <translation id="8141602879876242471">ఇది ఒక శోధించగల సూచిక. శోధన కీవర్డ్లను ఎంటర్ చెయ్యండి:</translation> <translation id="5650795167354946011">ప్లగ్-ఇన్ను వ్యవస్థాపించిన తర్వాత, రిఫ్రెష్ చెయ్యడానికి ఇక్కడ క్లిక్ చెయ్యండి.</translation> -<translation id="370665806235115550">లోడ్ అవుతోంది...</translation> <translation id="6845533974506654842">నొక్కండి</translation> <translation id="8244226242650769279">చిత్రం మాప్</translation> <translation id="2548326553472216322">ఇటీవల శోధనలు లేవు</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">దయచేసి మీరు <ph name="PLUGIN"/> ప్లగ్-ఇన్ను వ్యవస్థాపించాలనుకుంటున్నారని నిర్థారించండి. మీరు విశ్వసించే ప్లగ్-ఇన్లను మాత్రమే వ్యవస్థాపించాలి.</translation> <translation id="6663448176199120256">ఇటీవల శోధనలు</translation> <translation id="2597378329261239068">ఈ పత్రం అనుమతి పదంచే రక్షించబడింది. దయచేసి అనుమతి పదాన్ని నమోదు చేయండి.</translation> -<translation id="7740050170769002709">HTML కంటెంట్</translation> +<translation id="6807599807928161586">వెబ్ ప్రాంతం</translation> <translation id="5939518447894949180">తిరిగి అమర్చండి</translation> <translation id="1842960171412779397">ఎంచుకోండి</translation> <translation id="7638452146404718955">ప్లగ్-ఇన్ను డౌన్లోడ్ చేయడానికి ఇక్కడ క్లిక్ చేయండి</translation> diff --git a/webkit/glue/resources/webkit_strings_th.xtb b/webkit/glue/resources/webkit_strings_th.xtb index a6ffcc6..80dd787 100644 --- a/webkit/glue/resources/webkit_strings_th.xtb +++ b/webkit/glue/resources/webkit_strings_th.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="th"> <translation id="4519964825805946997">การติดตั้งปลั๊กอินจาก <ph name="URL"/> ล้มเหลว</translation> -<translation id="9186171386827445984">กำลังโหลดเอกสาร: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> หน้า...</translation> <translation id="1235745349614807883">ลบการค้นหาล่าสุด</translation> <translation id="5048533449481078685">ผู้สร้างรายการ</translation> <translation id="372362261556059955">ต้องการปลั๊กอินเพิ่มเติม</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">การติดตั้งปลั๊กอินล้มเหลว</translation> <translation id="8141602879876242471">นี่คือดัชนีที่สามารถค้นหาได้ ป้อนคำหลักในการค้นหา:</translation> <translation id="5650795167354946011">หลังจากติดตั้งปลั๊กอิน ให้คลิกที่นี่เพื่อรีเฟรช</translation> -<translation id="370665806235115550">กำลังโหลด...</translation> <translation id="6845533974506654842">กด</translation> <translation id="8244226242650769279">แผนที่รูปภาพ</translation> <translation id="2548326553472216322">ไม่พบการค้นหาล่าสุด</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">โปรดยืนยันว่าคุณต้องการติดตั้งปลั๊กอิน <ph name="PLUGIN"/> คุณควรติดตั้งเฉพาะปลั๊กอินที่คุณไว้ใจเท่านั้น</translation> <translation id="6663448176199120256">การค้นหาล่าสุด</translation> <translation id="2597378329261239068">เอกสารนี้ได้รับการป้องกันด้วยรหัสผ่าน โปรดป้อนรหัสผ่าน</translation> -<translation id="7740050170769002709">เนื้อหา HTML</translation> +<translation id="6807599807928161586">พื้นที่เว็บ</translation> <translation id="5939518447894949180">ตั้งค่าใหม่</translation> <translation id="1842960171412779397">เลือก</translation> <translation id="7638452146404718955">คลิกที่นี่เพื่อดาวน์โหลดปลั๊กอิน</translation> diff --git a/webkit/glue/resources/webkit_strings_tr.xtb b/webkit/glue/resources/webkit_strings_tr.xtb index 5a24891..a4d880d 100644 --- a/webkit/glue/resources/webkit_strings_tr.xtb +++ b/webkit/glue/resources/webkit_strings_tr.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="tr"> <translation id="4519964825805946997">Eklenti, <ph name="URL"/> kaynağından yüklenemedi</translation> -<translation id="9186171386827445984">Belge yükleniyor: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> sayfa...</translation> <translation id="1235745349614807883">Son Aramaları Temizle</translation> <translation id="5048533449481078685">liste işaretçisi</translation> <translation id="372362261556059955">Başka eklenti gerekiyor</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Eklenti yüklenemedi</translation> <translation id="8141602879876242471">Bu dizinde arama yapılabilir. Arama anahtar kelimeleri girin:</translation> <translation id="5650795167354946011">Eklentiyi yükledikten sonra yenilemek için burayı tıklayın</translation> -<translation id="370665806235115550">Yükleniyor...</translation> <translation id="6845533974506654842">bas</translation> <translation id="8244226242650769279">resim haritası</translation> <translation id="2548326553472216322">Yeni arama yok</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Lütfen <ph name="PLUGIN"/> eklentisini yüklemek istediğinizi onaylayın. Yalnızca güvendiğiniz eklentileri yüklemelisiniz.</translation> <translation id="6663448176199120256">Son Aramalar</translation> <translation id="2597378329261239068">Doküman şifre korumalı. Lütfen şifreyi girin.</translation> -<translation id="7740050170769002709">HTML içeriği</translation> +<translation id="6807599807928161586">web alanı</translation> <translation id="5939518447894949180">Sıfırla</translation> <translation id="1842960171412779397">seç</translation> <translation id="7638452146404718955">Eklentiyi indirmek için burayı tıklayın</translation> diff --git a/webkit/glue/resources/webkit_strings_uk.xtb b/webkit/glue/resources/webkit_strings_uk.xtb index 360c85f..a125fe2 100644 --- a/webkit/glue/resources/webkit_strings_uk.xtb +++ b/webkit/glue/resources/webkit_strings_uk.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="uk"> <translation id="4519964825805946997">Не вдалося встановити плагін із <ph name="URL"/></translation> -<translation id="9186171386827445984">Завантаження документа – сторінки: <ph name="PAGE_NUMBER"/> із <ph name="NUMBER_OF_PAGES"/>...</translation> <translation id="1235745349614807883">Очистити останні пошуки</translation> <translation id="5048533449481078685">маркер списку</translation> <translation id="372362261556059955">Потрібен додатковий плагін.</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Помилка встановлення плагіна</translation> <translation id="8141602879876242471">Цей доступний для пошуку індекс. Введіть ключові слова пошуку:</translation> <translation id="5650795167354946011">Після встановлення плагіна натисніть тут, щоб оновити</translation> -<translation id="370665806235115550">Завантаження...</translation> <translation id="6845533974506654842">натиснути</translation> <translation id="8244226242650769279">мапа зображення</translation> <translation id="2548326553472216322">Немає останніх пошуків</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Підтвердьте встановлення плагіна <ph name="PLUGIN"/>. Слід установлювати лише плагіни, яким ви довіряєте.</translation> <translation id="6663448176199120256">Останні пошуки</translation> <translation id="2597378329261239068">Цей документ захищено паролем. Введіть пароль.</translation> -<translation id="7740050170769002709">Вміст HTML</translation> +<translation id="6807599807928161586">область Інтернету</translation> <translation id="5939518447894949180">Скинути</translation> <translation id="1842960171412779397">вибрати</translation> <translation id="7638452146404718955">Натисніть тут, щоб завантажити плагін</translation> diff --git a/webkit/glue/resources/webkit_strings_vi.xtb b/webkit/glue/resources/webkit_strings_vi.xtb index 0ee2d09..84668c5 100644 --- a/webkit/glue/resources/webkit_strings_vi.xtb +++ b/webkit/glue/resources/webkit_strings_vi.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="vi"> <translation id="4519964825805946997">Cài đặt trình cắm từ <ph name="URL"/> không thành công</translation> -<translation id="9186171386827445984">Đang tải tài liệu: <ph name="PAGE_NUMBER"/>/<ph name="NUMBER_OF_PAGES"/> trang...</translation> <translation id="1235745349614807883">Xoá Tìm kiếm Gần đây</translation> <translation id="5048533449481078685">đánh dấu danh sách</translation> <translation id="372362261556059955">Cần trình cắm bổ sung</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">Cài đặt trình cắm không thành công</translation> <translation id="8141602879876242471">Đây là chỉ mục có thể tìm kiếm. Nhập từ khoá tìm kiếm vào:</translation> <translation id="5650795167354946011">Sau khi cài đặt trình cắm, hãy nhấp vào đây để làm mới</translation> -<translation id="370665806235115550">Đang tải...</translation> <translation id="6845533974506654842">nhấn</translation> <translation id="8244226242650769279">bản đồ hình ảnh</translation> <translation id="2548326553472216322">Không có tìm kiếm nào gần đây</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">Vui lòng xác nhận rằng bạn muốn cài đặt trình cắm <ph name="PLUGIN"/>. Bạn chỉ nên cài đặt những trình cắm mà bạn tin tưởng.</translation> <translation id="6663448176199120256">Tìm kiếm Gần đây</translation> <translation id="2597378329261239068">Tài liệu này được bảo vệ bằng mật khẩu. Vui lòng nhập mật khẩu.</translation> -<translation id="7740050170769002709">Nội dung HTML</translation> +<translation id="6807599807928161586">khu vực web</translation> <translation id="5939518447894949180">Đặt lại</translation> <translation id="1842960171412779397">chọn</translation> <translation id="7638452146404718955">Nhấp vào đây để tải xuống trình cắm</translation> diff --git a/webkit/glue/resources/webkit_strings_zh-CN.xtb b/webkit/glue/resources/webkit_strings_zh-CN.xtb index f931c5c..f5c0644 100644 --- a/webkit/glue/resources/webkit_strings_zh-CN.xtb +++ b/webkit/glue/resources/webkit_strings_zh-CN.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="zh-CN"> <translation id="4519964825805946997">无法从 <ph name="URL"/> 安装插件</translation> -<translation id="9186171386827445984">正在载入文档:已载入 <ph name="PAGE_NUMBER"/> 页,共 <ph name="NUMBER_OF_PAGES"/> 页...</translation> <translation id="1235745349614807883">清除最近的搜索</translation> <translation id="5048533449481078685">列表标记</translation> <translation id="372362261556059955">需要其他插件</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">插件安装失败</translation> <translation id="8141602879876242471">这是一个可搜索的索引。请输入搜索关键字:</translation> <translation id="5650795167354946011">安装插件后,点击此处可刷新</translation> -<translation id="370665806235115550">正在载入...</translation> <translation id="6845533974506654842">按</translation> <translation id="8244226242650769279">图片映射</translation> <translation id="2548326553472216322">最近未执行搜索</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">请确认您要安装 <ph name="PLUGIN"/> 插件。您应该只安装自己信任的插件。</translation> <translation id="6663448176199120256">近期搜索</translation> <translation id="2597378329261239068">本文档设置了密码保护,请输入密码。</translation> -<translation id="7740050170769002709">HTML 内容</translation> +<translation id="6807599807928161586">网络区域</translation> <translation id="5939518447894949180">重置</translation> <translation id="1842960171412779397">选中</translation> <translation id="7638452146404718955">点击此处可下载插件</translation> diff --git a/webkit/glue/resources/webkit_strings_zh-TW.xtb b/webkit/glue/resources/webkit_strings_zh-TW.xtb index 368a365..7d7eda3 100644 --- a/webkit/glue/resources/webkit_strings_zh-TW.xtb +++ b/webkit/glue/resources/webkit_strings_zh-TW.xtb @@ -2,7 +2,6 @@ <!DOCTYPE translationbundle> <translationbundle lang="zh-TW"> <translation id="4519964825805946997">無法從 <ph name="URL"/> 安裝外掛程式</translation> -<translation id="9186171386827445984">正在載入文件:第 <ph name="PAGE_NUMBER"/> 頁,共 <ph name="NUMBER_OF_PAGES"/> 頁...</translation> <translation id="1235745349614807883">清除最近的搜尋記錄</translation> <translation id="5048533449481078685">清單標記</translation> <translation id="372362261556059955">需要其他外掛程式</translation> @@ -13,7 +12,6 @@ <translation id="1416462845279468967">外掛程式安裝不成功</translation> <translation id="8141602879876242471">這是可搜尋的索引,輸入搜尋關鍵字:</translation> <translation id="5650795167354946011">安裝外掛程式後,請按一下這裡重新整理</translation> -<translation id="370665806235115550">載入中...</translation> <translation id="6845533974506654842">按下</translation> <translation id="8244226242650769279">影像地圖</translation> <translation id="2548326553472216322">沒有近期的搜尋</translation> @@ -32,7 +30,7 @@ <translation id="5253117816378681419">請確認您要安裝 <ph name="PLUGIN"/> 外掛程式,建議您僅安裝您所信任的外掛程式。</translation> <translation id="6663448176199120256">最近的搜尋</translation> <translation id="2597378329261239068">此文件受到密碼保護,請輸入密碼。</translation> -<translation id="7740050170769002709">HTML 內容</translation> +<translation id="6807599807928161586">網頁範圍</translation> <translation id="5939518447894949180">重設</translation> <translation id="1842960171412779397">選取</translation> <translation id="7638452146404718955">按一下這裡下載外掛程式</translation> diff --git a/webkit/glue/webaccessibility.cc b/webkit/glue/webaccessibility.cc index 0888a62..c3ef261 100644 --- a/webkit/glue/webaccessibility.cc +++ b/webkit/glue/webaccessibility.cc @@ -324,6 +324,8 @@ void WebAccessibility::Init(const WebKit::WebAccessibilityObject& src, attributes[ATTR_SHORTCUT] = src.keyboardShortcut(); if (src.hasComputedStyle()) attributes[ATTR_DISPLAY] = src.computedStyleDisplay(); + if (!src.url().isEmpty()) + attributes[ATTR_URL] = src.url().spec().utf16(); WebKit::WebNode node = src.node(); diff --git a/webkit/glue/webaccessibility.h b/webkit/glue/webaccessibility.h index a8e4b11..c073502 100644 --- a/webkit/glue/webaccessibility.h +++ b/webkit/glue/webaccessibility.h @@ -175,8 +175,8 @@ struct WebAccessibility { ATTR_DISPLAY, ATTR_HELP, ATTR_HTML_TAG, - ATTR_LINK_TARGET, ATTR_SHORTCUT, + ATTR_URL, NUM_ATTRIBUTES }; diff --git a/webkit/glue/webcursor.cc b/webkit/glue/webcursor.cc index 8f76ef9..fb67b6b 100644 --- a/webkit/glue/webcursor.cc +++ b/webkit/glue/webcursor.cc @@ -89,26 +89,28 @@ bool WebCursor::Deserialize(const Pickle* pickle, void** iter) { size_y > kMaxCursorDimension) return false; - if (type == WebCursorInfo::TypeCustom && (size_x == 0 || size_y == 0)) - return false; - - // The * 4 is because the expected format is an array of RGBA pixel values. - if (size_x * size_y * 4 > data_len) - return false; - type_ = type; - hotspot_.set_x(hotspot_x); - hotspot_.set_y(hotspot_y); - custom_size_.set_width(size_x); - custom_size_.set_height(size_y); - ClampHotspot(); - custom_data_.clear(); - if (data_len > 0) { - custom_data_.resize(data_len); - memcpy(&custom_data_[0], data, data_len); + if (type == WebCursorInfo::TypeCustom) { + if (size_x > 0 && size_y > 0) { + // The * 4 is because the expected format is an array of RGBA pixel + // values. + if (size_x * size_y * 4 > data_len) + return false; + + hotspot_.set_x(hotspot_x); + hotspot_.set_y(hotspot_y); + custom_size_.set_width(size_x); + custom_size_.set_height(size_y); + ClampHotspot(); + + custom_data_.clear(); + if (data_len > 0) { + custom_data_.resize(data_len); + memcpy(&custom_data_[0], data, data_len); + } + } } - return DeserializePlatformData(pickle, iter); } diff --git a/webkit/glue/webcursor_mac.mm b/webkit/glue/webcursor_mac.mm index 1aeb1e0..4c3d69a 100644 --- a/webkit/glue/webcursor_mac.mm +++ b/webkit/glue/webcursor_mac.mm @@ -1,14 +1,14 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. Use of this -// source code is governed by a BSD-style license that can be found in the -// LICENSE file. +// 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 "webkit/glue/webcursor.h" #import <AppKit/AppKit.h> #include <Carbon/Carbon.h> +#include "app/mac/nsimage_cache.h" #include "base/logging.h" -#include "base/nsimage_cache_mac.h" #include "base/mac/scoped_cftyperef.h" #include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" #include "third_party/WebKit/WebKit/chromium/public/WebImage.h" @@ -21,11 +21,11 @@ using WebKit::WebSize; namespace { // TODO: This image fetch can (and probably should) be serviced by the resource -// resource bundle instead of going through nsimage_cache. +// resource bundle instead of going through the image cache. NSCursor* LoadCursor(const char* name, int x, int y) { NSString* file_name = [NSString stringWithUTF8String:name]; DCHECK(file_name); - NSImage* cursor_image = nsimage_cache::ImageNamed(file_name); + NSImage* cursor_image = app::mac::GetCachedImageWithName(file_name); DCHECK(cursor_image); return [[[NSCursor alloc] initWithImage:cursor_image hotSpot:NSMakePoint(x, y)] autorelease]; diff --git a/webkit/glue/webcursor_unittest.cc b/webkit/glue/webcursor_unittest.cc index 6e7701d..f449515 100644 --- a/webkit/glue/webcursor_unittest.cc +++ b/webkit/glue/webcursor_unittest.cc @@ -15,7 +15,7 @@ TEST(WebCursorTest, CursorSerialization) { // This is a valid custom cursor. Pickle ok_custom_pickle; // Type and hotspots. - ok_custom_pickle.WriteInt(0); + ok_custom_pickle.WriteInt(WebCursorInfo::TypeCustom); ok_custom_pickle.WriteInt(0); ok_custom_pickle.WriteInt(0); // X & Y @@ -32,7 +32,7 @@ TEST(WebCursorTest, CursorSerialization) { // This custom cursor has not been send with enough data. Pickle short_custom_pickle; // Type and hotspots. - short_custom_pickle.WriteInt(0); + short_custom_pickle.WriteInt(WebCursorInfo::TypeCustom); short_custom_pickle.WriteInt(0); short_custom_pickle.WriteInt(0); // X & Y @@ -49,7 +49,7 @@ TEST(WebCursorTest, CursorSerialization) { // This custom cursor has enough data but is too big. Pickle large_custom_pickle; // Type and hotspots. - large_custom_pickle.WriteInt(0); + large_custom_pickle.WriteInt(WebCursorInfo::TypeCustom); large_custom_pickle.WriteInt(0); large_custom_pickle.WriteInt(0); // X & Y @@ -68,7 +68,7 @@ TEST(WebCursorTest, CursorSerialization) { // This custom cursor uses negative lengths. Pickle neg_custom_pickle; // Type and hotspots. - neg_custom_pickle.WriteInt(0); + neg_custom_pickle.WriteInt(WebCursorInfo::TypeCustom); neg_custom_pickle.WriteInt(0); neg_custom_pickle.WriteInt(0); // X & Y @@ -81,6 +81,17 @@ TEST(WebCursorTest, CursorSerialization) { neg_custom_pickle.WriteUInt32(0); iter = NULL; EXPECT_FALSE(custom_cursor.Deserialize(&neg_custom_pickle, &iter)); + +#if defined(OS_WIN) + Pickle win32_custom_pickle; + WebCursor win32_custom_cursor; + win32_custom_cursor.InitFromExternalCursor( + reinterpret_cast<HCURSOR>(1000)); + EXPECT_TRUE(win32_custom_cursor.Serialize(&win32_custom_pickle)); + iter = NULL; + EXPECT_TRUE(custom_cursor.Deserialize(&win32_custom_pickle, &iter)); + EXPECT_EQ(reinterpret_cast<HCURSOR>(1000), custom_cursor.GetCursor(NULL)); +#endif // OS_WIN } TEST(WebCursorTest, ClampHotspot) { diff --git a/webkit/glue/webkit_glue.cc b/webkit/glue/webkit_glue.cc index 67b61ba..fe3edd9 100644 --- a/webkit/glue/webkit_glue.cc +++ b/webkit/glue/webkit_glue.cc @@ -11,9 +11,9 @@ #include <sys/utsname.h> #endif +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/scoped_ptr.h" -#include "base/singleton.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/stringprintf.h" @@ -84,29 +84,29 @@ void EnableWebCoreNotImplementedLogging() { WebKit::enableLogChannel("NotYetImplemented"); } -std::wstring DumpDocumentText(WebFrame* web_frame) { +string16 DumpDocumentText(WebFrame* web_frame) { // We use the document element's text instead of the body text here because // not all documents have a body, such as XML documents. WebElement document_element = web_frame->document().documentElement(); if (document_element.isNull()) - return std::wstring(); + return string16(); - return UTF16ToWideHack(document_element.innerText()); + return document_element.innerText(); } -std::wstring DumpFramesAsText(WebFrame* web_frame, bool recursive) { - std::wstring result; +string16 DumpFramesAsText(WebFrame* web_frame, bool recursive) { + string16 result; // Add header for all but the main frame. Skip empty frames. if (web_frame->parent() && !web_frame->document().documentElement().isNull()) { - result.append(L"\n--------\nFrame: '"); - result.append(UTF16ToWideHack(web_frame->name())); - result.append(L"'\n--------\n"); + result.append(ASCIIToUTF16("\n--------\nFrame: '")); + result.append(web_frame->name()); + result.append(ASCIIToUTF16("'\n--------\n")); } result.append(DumpDocumentText(web_frame)); - result.append(L"\n"); + result.append(ASCIIToUTF16("\n")); if (recursive) { WebFrame* child = web_frame->firstChild(); @@ -117,18 +117,18 @@ std::wstring DumpFramesAsText(WebFrame* web_frame, bool recursive) { return result; } -std::wstring DumpRenderer(WebFrame* web_frame) { - return UTF16ToWideHack(web_frame->renderTreeAsText()); +string16 DumpRenderer(WebFrame* web_frame) { + return web_frame->renderTreeAsText(); } bool CounterValueForElementById(WebFrame* web_frame, const std::string& id, - std::wstring* counter_value) { + string16* counter_value) { WebString result = web_frame->counterValueForElementById(WebString::fromUTF8(id)); if (result.isNull()) return false; - *counter_value = UTF16ToWideHack(result); + *counter_value = result; return true; } @@ -151,19 +151,21 @@ int NumberOfPages(WebFrame* web_frame, return number_of_pages; } -std::wstring DumpFrameScrollPosition(WebFrame* web_frame, bool recursive) { +string16 DumpFrameScrollPosition(WebFrame* web_frame, bool recursive) { gfx::Size offset = web_frame->scrollOffset(); - std::wstring result; + std::string result_utf8; if (offset.width() > 0 || offset.height() > 0) { if (web_frame->parent()) { - base::StringAppendF(&result, L"frame '%ls' ", UTF16ToWide( - web_frame->name()).c_str()); + base::StringAppendF(&result_utf8, "frame '%s' ", + UTF16ToUTF8(web_frame->name()).c_str()); } - base::StringAppendF(&result, L"scrolled to %d,%d\n", + base::StringAppendF(&result_utf8, "scrolled to %d,%d\n", offset.width(), offset.height()); } + string16 result = UTF8ToUTF16(result_utf8); + if (recursive) { WebFrame* child = web_frame->firstChild(); for (; child; child = child->nextSibling()) @@ -183,16 +185,16 @@ static bool HistoryItemCompareLess(const WebHistoryItem& item1, return target1 < target2; } -// Writes out a HistoryItem into a string in a readable format. -static std::wstring DumpHistoryItem(const WebHistoryItem& item, - int indent, bool is_current) { - std::wstring result; +// Writes out a HistoryItem into a UTF-8 string in a readable format. +static std::string DumpHistoryItem(const WebHistoryItem& item, + int indent, bool is_current) { + std::string result; if (is_current) { - result.append(L"curr->"); - result.append(indent - 6, L' '); // 6 == L"curr->".length() + result.append("curr->"); + result.append(indent - 6, ' '); // 6 == "curr->".length() } else { - result.append(indent, L' '); + result.append(indent, ' '); } std::string url = item.urlString().utf8(); @@ -207,12 +209,12 @@ static std::wstring DumpHistoryItem(const WebHistoryItem& item, url.replace(kDataUrlPatternSize, url.length(), path); } - result.append(UTF8ToWide(url)); + result.append(url); if (!item.target().isEmpty()) - result.append(L" (in frame \"" + UTF16ToWide(item.target()) + L"\")"); + result.append(" (in frame \"" + UTF16ToUTF8(item.target()) + "\")"); if (item.isTargetItem()) - result.append(L" **nav target**"); - result.append(L"\n"); + result.append(" **nav target**"); + result.append("\n"); const WebVector<WebHistoryItem>& children = item.children(); if (!children.isEmpty()) { @@ -231,10 +233,11 @@ static std::wstring DumpHistoryItem(const WebHistoryItem& item, return result; } -std::wstring DumpHistoryState(const std::string& history_state, int indent, - bool is_current) { - return DumpHistoryItem(HistoryItemFromString(history_state), indent, - is_current); +string16 DumpHistoryState(const std::string& history_state, int indent, + bool is_current) { + return UTF8ToUTF16( + DumpHistoryItem(HistoryItemFromString(history_state), indent, + is_current)); } void ResetBeforeTestRun(WebView* view) { @@ -356,10 +359,11 @@ struct UserAgentState { bool user_agent_is_overridden; }; -Singleton<UserAgentState> g_user_agent; +static base::LazyInstance<UserAgentState> g_user_agent( + base::LINKER_INITIALIZED); void SetUserAgentToDefault() { - BuildUserAgent(false, &g_user_agent->user_agent); + BuildUserAgent(false, &g_user_agent.Get().user_agent); } } // namespace @@ -367,31 +371,31 @@ void SetUserAgentToDefault() { void SetUserAgent(const std::string& new_user_agent) { // If you combine this with the previous line, the function only works the // first time. - DCHECK(!g_user_agent->user_agent_requested) << + DCHECK(!g_user_agent.Get().user_agent_requested) << "Setting the user agent after someone has " "already requested it can result in unexpected behavior."; - g_user_agent->user_agent_is_overridden = true; - g_user_agent->user_agent = new_user_agent; + g_user_agent.Get().user_agent_is_overridden = true; + g_user_agent.Get().user_agent = new_user_agent; } const std::string& GetUserAgent(const GURL& url) { - if (g_user_agent->user_agent.empty()) + if (g_user_agent.Get().user_agent.empty()) SetUserAgentToDefault(); - g_user_agent->user_agent_requested = true; - if (!g_user_agent->user_agent_is_overridden) { + g_user_agent.Get().user_agent_requested = true; + if (!g_user_agent.Get().user_agent_is_overridden) { // Workarounds for sites that use misguided UA sniffing. #if defined(OS_POSIX) && !defined(OS_MACOSX) if (MatchPattern(url.host(), "*.mail.yahoo.com")) { // mail.yahoo.com is ok with Windows Chrome but not Linux Chrome. // http://bugs.chromium.org/11136 // TODO(evanm): remove this if Yahoo fixes their sniffing. - if (g_user_agent->mimic_windows_user_agent.empty()) - BuildUserAgent(true, &g_user_agent->mimic_windows_user_agent); - return g_user_agent->mimic_windows_user_agent; + if (g_user_agent.Get().mimic_windows_user_agent.empty()) + BuildUserAgent(true, &g_user_agent.Get().mimic_windows_user_agent); + return g_user_agent.Get().mimic_windows_user_agent; } #endif } - return g_user_agent->user_agent; + return g_user_agent.Get().user_agent; } void SetForcefullyTerminatePluginProcess(bool value) { diff --git a/webkit/glue/webkit_glue.gypi b/webkit/glue/webkit_glue.gypi index 8ed3e8b..959f4e1 100644 --- a/webkit/glue/webkit_glue.gypi +++ b/webkit/glue/webkit_glue.gypi @@ -147,7 +147,7 @@ '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/gpu/gpu.gyp:gles2_implementation', '<(DEPTH)/net/net.gyp:net', - '<(DEPTH)/ppapi/ppapi.gyp:ppapi_proxy', + '<(DEPTH)/ppapi/ppapi.gyp:ppapi_shared_impl', '<(DEPTH)/printing/printing.gyp:printing', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', @@ -168,10 +168,170 @@ # This list contains all .h, .cc, and .mm files in glue except for # those in the test subdirectory and those with unittest in in their # names. + '../plugins/npapi/carbon_plugin_window_tracker_mac.cc', + '../plugins/npapi/carbon_plugin_window_tracker_mac.h', + '../plugins/npapi/coregraphics_private_symbols_mac.h', + '../plugins/npapi/default_plugin_shared.h', + '../plugins/npapi/gtk_plugin_container.cc', + '../plugins/npapi/gtk_plugin_container.h', + '../plugins/npapi/gtk_plugin_container_manager.cc', + '../plugins/npapi/gtk_plugin_container_manager.h', + '../plugins/npapi/npapi_extension_thunk.cc', + '../plugins/npapi/npapi_extension_thunk.h', + '../plugins/npapi/nphostapi.h', + '../plugins/npapi/plugin_constants_win.cc', + '../plugins/npapi/plugin_constants_win.h', + '../plugins/npapi/plugin_group.cc', + '../plugins/npapi/plugin_group.h', + '../plugins/npapi/plugin_host.cc', + '../plugins/npapi/plugin_host.h', + '../plugins/npapi/plugin_instance.cc', + '../plugins/npapi/plugin_instance.h', + '../plugins/npapi/plugin_instance_mac.mm', + '../plugins/npapi/plugin_lib.cc', + '../plugins/npapi/plugin_lib.h', + '../plugins/npapi/plugin_lib_mac.mm', + '../plugins/npapi/plugin_lib_posix.cc', + '../plugins/npapi/plugin_lib_win.cc', + '../plugins/npapi/plugin_list.cc', + '../plugins/npapi/plugin_list.h', + '../plugins/npapi/plugin_list_mac.mm', + '../plugins/npapi/plugin_list_posix.cc', + '../plugins/npapi/plugin_list_win.cc', + '../plugins/npapi/plugin_stream.cc', + '../plugins/npapi/plugin_stream.h', + '../plugins/npapi/plugin_stream_posix.cc', + '../plugins/npapi/plugin_stream_url.cc', + '../plugins/npapi/plugin_stream_url.h', + '../plugins/npapi/plugin_stream_win.cc', + '../plugins/npapi/plugin_string_stream.cc', + '../plugins/npapi/plugin_string_stream.h', + '../plugins/npapi/plugin_web_event_converter_mac.h', + '../plugins/npapi/plugin_web_event_converter_mac.mm', + '../plugins/npapi/ppb_private.h', + '../plugins/npapi/quickdraw_drawing_manager_mac.cc', + '../plugins/npapi/quickdraw_drawing_manager_mac.h', + '../plugins/npapi/webplugin.cc', + '../plugins/npapi/webplugin.h', + '../plugins/npapi/webplugin_2d_device_delegate.cc', + '../plugins/npapi/webplugin_2d_device_delegate.h', + '../plugins/npapi/webplugin_3d_device_delegate.cc', + '../plugins/npapi/webplugin_3d_device_delegate.h', + '../plugins/npapi/webplugin_accelerated_surface_mac.h', + '../plugins/npapi/webplugin_audio_device_delegate.cc', + '../plugins/npapi/webplugin_audio_device_delegate.h', + '../plugins/npapi/webplugin_delegate.cc', + '../plugins/npapi/webplugin_delegate.h', + '../plugins/npapi/webplugin_delegate_impl.cc', + '../plugins/npapi/webplugin_delegate_impl.h', + '../plugins/npapi/webplugin_delegate_impl_gtk.cc', + '../plugins/npapi/webplugin_delegate_impl_mac.mm', + '../plugins/npapi/webplugin_delegate_impl_win.cc', + '../plugins/npapi/webplugin_file_delegate.cc', + '../plugins/npapi/webplugin_file_delegate.h', + '../plugins/npapi/webplugin_impl.cc', + '../plugins/npapi/webplugin_impl.h', + '../plugins/npapi/webplugin_print_delegate.cc', + '../plugins/npapi/webplugin_print_delegate.h', + '../plugins/npapi/webplugininfo.cc', + '../plugins/npapi/webplugininfo.h', + '../plugins/npapi/webview_plugin.cc', + '../plugins/npapi/webview_plugin.h', + '../plugins/plugin_switches.cc', + '../plugins/plugin_switches.h', + '../plugins/ppapi/callbacks.cc', + '../plugins/ppapi/callbacks.h', + '../plugins/ppapi/common.h', + '../plugins/ppapi/dir_contents.h', + '../plugins/ppapi/error_util.cc', + '../plugins/ppapi/error_util.h', + '../plugins/ppapi/event_conversion.cc', + '../plugins/ppapi/event_conversion.h', + '../plugins/ppapi/file_callbacks.cc', + '../plugins/ppapi/file_callbacks.h', + '../plugins/ppapi/fullscreen_container.h', + '../plugins/ppapi/npapi_glue.cc', + '../plugins/ppapi/npapi_glue.h', + '../plugins/ppapi/plugin_delegate.h', + '../plugins/ppapi/plugin_module.cc', + '../plugins/ppapi/plugin_module.h', + '../plugins/ppapi/plugin_object.cc', + '../plugins/ppapi/plugin_object.h', + '../plugins/ppapi/ppapi_plugin_instance.cc', + '../plugins/ppapi/ppapi_plugin_instance.h', + '../plugins/ppapi/ppapi_webplugin_impl.cc', + '../plugins/ppapi/ppapi_webplugin_impl.h', + '../plugins/ppapi/ppb_audio_impl.cc', + '../plugins/ppapi/ppb_audio_impl.h', + '../plugins/ppapi/ppb_buffer_impl.cc', + '../plugins/ppapi/ppb_buffer_impl.h', + '../plugins/ppapi/ppb_char_set_impl.cc', + '../plugins/ppapi/ppb_char_set_impl.h', + '../plugins/ppapi/ppb_context_3d_impl.cc', + '../plugins/ppapi/ppb_context_3d_impl.h', + '../plugins/ppapi/ppb_cursor_control_impl.cc', + '../plugins/ppapi/ppb_cursor_control_impl.h', + '../plugins/ppapi/ppb_directory_reader_impl.cc', + '../plugins/ppapi/ppb_directory_reader_impl.h', + '../plugins/ppapi/ppb_file_chooser_impl.cc', + '../plugins/ppapi/ppb_file_chooser_impl.h', + '../plugins/ppapi/ppb_file_io_impl.cc', + '../plugins/ppapi/ppb_file_io_impl.h', + '../plugins/ppapi/ppb_file_ref_impl.cc', + '../plugins/ppapi/ppb_file_ref_impl.h', + '../plugins/ppapi/ppb_file_system_impl.cc', + '../plugins/ppapi/ppb_file_system_impl.h', + '../plugins/ppapi/ppb_flash.h', + '../plugins/ppapi/ppb_flash_impl.cc', + '../plugins/ppapi/ppb_flash_impl.h', + '../plugins/ppapi/ppb_flash_impl_linux.cc', + '../plugins/ppapi/ppb_font_impl.cc', + '../plugins/ppapi/ppb_font_impl.h', + '../plugins/ppapi/ppb_graphics_2d_impl.cc', + '../plugins/ppapi/ppb_graphics_2d_impl.h', + '../plugins/ppapi/ppb_graphics_3d_impl.cc', + '../plugins/ppapi/ppb_graphics_3d_impl.h', + '../plugins/ppapi/ppb_image_data_impl.cc', + '../plugins/ppapi/ppb_image_data_impl.h', + '../plugins/ppapi/ppb_nacl_private_impl.cc', + '../plugins/ppapi/ppb_nacl_private_impl.h', + '../plugins/ppapi/ppb_opengles_impl.cc', + '../plugins/ppapi/ppb_opengles_impl.h', + '../plugins/ppapi/ppb_pdf.h', + '../plugins/ppapi/ppb_pdf_impl.cc', + '../plugins/ppapi/ppb_pdf_impl.h', + '../plugins/ppapi/ppb_scrollbar_impl.cc', + '../plugins/ppapi/ppb_scrollbar_impl.h', + '../plugins/ppapi/ppb_transport_impl.cc', + '../plugins/ppapi/ppb_transport_impl.h', + '../plugins/ppapi/ppb_url_loader_impl.cc', + '../plugins/ppapi/ppb_url_loader_impl.h', + '../plugins/ppapi/ppb_url_request_info_impl.cc', + '../plugins/ppapi/ppb_url_request_info_impl.h', + '../plugins/ppapi/ppb_url_response_info_impl.cc', + '../plugins/ppapi/ppb_url_response_info_impl.h', + '../plugins/ppapi/ppb_url_util_impl.cc', + '../plugins/ppapi/ppb_url_util_impl.h', + '../plugins/ppapi/ppb_video_decoder_impl.cc', + '../plugins/ppapi/ppb_video_decoder_impl.h', + '../plugins/ppapi/ppb_widget_impl.cc', + '../plugins/ppapi/ppb_widget_impl.h', + '../plugins/ppapi/resource.cc', + '../plugins/ppapi/resource.h', + '../plugins/ppapi/resource_tracker.cc', + '../plugins/ppapi/resource_tracker.h', + '../plugins/ppapi/string.cc', + '../plugins/ppapi/string.h', + '../plugins/ppapi/var.cc', + '../plugins/ppapi/var.h', + '../plugins/ppapi/var_object_class.cc', + '../plugins/ppapi/var_object_class.h', + 'media/audio_decoder.cc', + 'media/audio_decoder.h', 'media/buffered_data_source.cc', 'media/buffered_data_source.h', - 'media/media_resource_loader_bridge_factory.cc', - 'media/media_resource_loader_bridge_factory.h', + 'media/buffered_resource_loader.cc', + 'media/buffered_resource_loader.h', 'media/simple_data_source.cc', 'media/simple_data_source.h', 'media/video_renderer_impl.cc', @@ -179,137 +339,6 @@ 'media/web_data_source.cc', 'media/web_data_source.h', 'media/web_video_renderer.h', - 'plugins/carbon_plugin_window_tracker_mac.h', - 'plugins/carbon_plugin_window_tracker_mac.cc', - 'plugins/coregraphics_private_symbols_mac.h', - 'plugins/default_plugin_shared.h', - 'plugins/nphostapi.h', - 'plugins/gtk_plugin_container.h', - 'plugins/gtk_plugin_container.cc', - 'plugins/gtk_plugin_container_manager.h', - 'plugins/gtk_plugin_container_manager.cc', - 'plugins/npapi_extension_thunk.cc', - 'plugins/npapi_extension_thunk.h', - 'plugins/pepper_audio.cc', - 'plugins/pepper_audio.h', - 'plugins/pepper_buffer.cc', - 'plugins/pepper_buffer.h', - 'plugins/pepper_char_set.cc', - 'plugins/pepper_char_set.h', - 'plugins/pepper_class.h', - 'plugins/pepper_cursor_control.cc', - 'plugins/pepper_cursor_control.h', - 'plugins/pepper_directory_reader.cc', - 'plugins/pepper_directory_reader.h', - 'plugins/pepper_error_util.cc', - 'plugins/pepper_error_util.h', - 'plugins/pepper_event_conversion.cc', - 'plugins/pepper_event_conversion.h', - 'plugins/pepper_file_callbacks.cc', - 'plugins/pepper_file_callbacks.h', - 'plugins/pepper_file_chooser.cc', - 'plugins/pepper_file_chooser.h', - 'plugins/pepper_file_io.cc', - 'plugins/pepper_file_io.h', - 'plugins/pepper_file_ref.cc', - 'plugins/pepper_file_ref.h', - 'plugins/pepper_file_system.cc', - 'plugins/pepper_file_system.h', - 'plugins/pepper_font.cc', - 'plugins/pepper_font.h', - 'plugins/pepper_graphics_2d.cc', - 'plugins/pepper_graphics_2d.h', - 'plugins/pepper_image_data.cc', - 'plugins/pepper_image_data.h', - 'plugins/pepper_plugin_delegate.h', - 'plugins/pepper_plugin_instance.cc', - 'plugins/pepper_plugin_instance.h', - 'plugins/pepper_plugin_module.cc', - 'plugins/pepper_plugin_module.h', - 'plugins/pepper_plugin_object.cc', - 'plugins/pepper_plugin_object.h', - 'plugins/pepper_private.cc', - 'plugins/pepper_private.h', - 'plugins/pepper_private2.cc', - 'plugins/pepper_private2.h', - 'plugins/pepper_private2_linux.cc', - 'plugins/pepper_resource_tracker.cc', - 'plugins/pepper_resource_tracker.h', - 'plugins/pepper_resource.cc', - 'plugins/pepper_resource.h', - 'plugins/pepper_scrollbar.cc', - 'plugins/pepper_scrollbar.h', - 'plugins/pepper_string.cc', - 'plugins/pepper_string.h', - 'plugins/pepper_transport.cc', - 'plugins/pepper_transport.h', - 'plugins/pepper_url_loader.cc', - 'plugins/pepper_url_loader.h', - 'plugins/pepper_url_request_info.cc', - 'plugins/pepper_url_request_info.h', - 'plugins/pepper_url_response_info.cc', - 'plugins/pepper_url_response_info.h', - 'plugins/pepper_url_util.cc', - 'plugins/pepper_url_util.h', - 'plugins/pepper_var.cc', - 'plugins/pepper_var.h', - 'plugins/pepper_video_decoder.cc', - 'plugins/pepper_video_decoder.h', - 'plugins/pepper_webplugin_impl.cc', - 'plugins/pepper_webplugin_impl.h', - 'plugins/pepper_widget.cc', - 'plugins/pepper_widget.h', - 'plugins/plugin_constants_win.h', - 'plugins/plugin_group.cc', - 'plugins/plugin_group.h', - 'plugins/plugin_host.cc', - 'plugins/plugin_host.h', - 'plugins/plugin_instance.cc', - 'plugins/plugin_instance.h', - 'plugins/plugin_instance_mac.mm', - 'plugins/plugin_lib.cc', - 'plugins/plugin_lib.h', - 'plugins/plugin_lib_mac.mm', - 'plugins/plugin_lib_posix.cc', - 'plugins/plugin_lib_win.cc', - 'plugins/plugin_list.cc', - 'plugins/plugin_list.h', - 'plugins/plugin_list_mac.mm', - 'plugins/plugin_list_posix.cc', - 'plugins/plugin_list_win.cc', - 'plugins/plugin_stream.cc', - 'plugins/plugin_stream.h', - 'plugins/plugin_stream_posix.cc', - 'plugins/plugin_stream_url.cc', - 'plugins/plugin_stream_url.h', - 'plugins/plugin_stream_win.cc', - 'plugins/plugin_string_stream.cc', - 'plugins/plugin_string_stream.h', - 'plugins/plugin_stubs.cc', - 'plugins/plugin_switches.cc', - 'plugins/plugin_switches.h', - 'plugins/plugin_web_event_converter_mac.h', - 'plugins/plugin_web_event_converter_mac.mm', - 'plugins/ppb_private.h', - 'plugins/quickdraw_drawing_manager_mac.h', - 'plugins/quickdraw_drawing_manager_mac.cc', - 'plugins/webview_plugin.cc', - 'plugins/webview_plugin.h', - 'plugins/webplugin.cc', - 'plugins/webplugin.h', - 'plugins/webplugin_2d_device_delegate.h', - 'plugins/webplugin_3d_device_delegate.h', - 'plugins/webplugin_accelerated_surface_mac.h', - 'plugins/webplugin_delegate.h', - 'plugins/webplugin_delegate_impl.cc', - 'plugins/webplugin_delegate_impl.h', - 'plugins/webplugin_delegate_impl_gtk.cc', - 'plugins/webplugin_delegate_impl_mac.mm', - 'plugins/webplugin_delegate_impl_win.cc', - 'plugins/webplugin_impl.cc', - 'plugins/webplugin_impl.h', - 'plugins/webplugininfo.cc', - 'plugins/webplugininfo.h', 'alt_error_page_resource_fetcher.cc', 'alt_error_page_resource_fetcher.h', 'context_menu.cc', @@ -442,12 +471,14 @@ ], }, }], - ['enable_gpu==1', { - 'sources': [ - 'plugins/pepper_graphics_3d_gl.cc', - 'plugins/pepper_graphics_3d.cc', - 'plugins/pepper_graphics_3d.h', + ['enable_gpu!=1', { + 'sources!': [ + '../plugins/ppapi/ppb_graphics_3d_impl.cc', + '../plugins/ppapi/ppb_graphics_3d_impl.h', + '../plugins/ppapi/ppb_open_gl_es_impl.cc', ], + }], + ['enable_gpu==1', { 'dependencies': [ '<(DEPTH)/gpu/gpu.gyp:gpu_plugin', ], diff --git a/webkit/glue/webkit_glue.h b/webkit/glue/webkit_glue.h index 6cc55b2..38ea659 100644 --- a/webkit/glue/webkit_glue.h +++ b/webkit/glue/webkit_glue.h @@ -23,7 +23,6 @@ class GURL; class SkBitmap; -struct WebPluginInfo; namespace base { class StringPiece; @@ -39,6 +38,12 @@ class WebString; class WebView; } +namespace webkit { +namespace npapi { +struct WebPluginInfo; +} +} + namespace webkit_glue { @@ -50,21 +55,21 @@ void SetJavaScriptFlags(const std::string& flags); void EnableWebCoreNotImplementedLogging(); // Returns the text of the document element. -std::wstring DumpDocumentText(WebKit::WebFrame* web_frame); +string16 DumpDocumentText(WebKit::WebFrame* web_frame); // Returns the text of the document element and optionally its child frames. // If recursive is false, this is equivalent to DumpDocumentText followed by // a newline. If recursive is true, it recursively dumps all frames as text. -std::wstring DumpFramesAsText(WebKit::WebFrame* web_frame, bool recursive); +string16 DumpFramesAsText(WebKit::WebFrame* web_frame, bool recursive); // Returns the renderer's description of its tree (its externalRepresentation). -std::wstring DumpRenderer(WebKit::WebFrame* web_frame); +string16 DumpRenderer(WebKit::WebFrame* web_frame); // Fill the value of counter in the element specified by the id into // counter_value. Return false when the specified id doesn't exist. bool CounterValueForElementById(WebKit::WebFrame* web_frame, const std::string& id, - std::wstring* counter_value); + string16* counter_value); // Returns the number of page where the specified element will be put. int PageNumberForElementById(WebKit::WebFrame* web_frame, @@ -78,13 +83,12 @@ int NumberOfPages(WebKit::WebFrame* web_frame, float page_height_in_pixels); // Returns a dump of the scroll position of the webframe. -std::wstring DumpFrameScrollPosition(WebKit::WebFrame* web_frame, - bool recursive); +string16 DumpFrameScrollPosition(WebKit::WebFrame* web_frame, bool recursive); // Returns a dump of the given history state suitable for implementing the // dumpBackForwardList command of the layoutTestController. -std::wstring DumpHistoryState(const std::string& history_state, int indent, - bool is_current); +string16 DumpHistoryState(const std::string& history_state, int indent, + bool is_current); // Cleans up state left over from the previous test run. void ResetBeforeTestRun(WebKit::WebView* view); @@ -110,6 +114,10 @@ std::string CreateHistoryStateForURL(const GURL& url); // Removes any form data state from the history state string |content_state|. std::string RemoveFormDataFromHistoryState(const std::string& content_state); +// Removes scroll offset from the history state string |content_state|. +std::string RemoveScrollOffsetFromHistoryState( + const std::string& content_state); + #ifndef NDEBUG // Checks various important objects to see if there are any in memory, and // calls AppendToLog with any leaked objects. Designed to be called on shutdown @@ -222,7 +230,8 @@ bool GetApplicationDirectory(FilePath* path); bool GetExeDirectory(FilePath* path); // Embedders implement this function to return the list of plugins to Webkit. -void GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins); +void GetPlugins(bool refresh, + std::vector<webkit::npapi::WebPluginInfo>* plugins); // Returns true if the plugins run in the same process as the renderer, and // false otherwise. @@ -272,6 +281,12 @@ void EnableSpdy(bool enable); // Notifies the browser that the given action has been performed. void UserMetricsRecordAction(const std::string& action); +#if !defined(DISABLE_NACL) +// Launch NaCl's sel_ldr process. +bool LaunchSelLdr(const char* alleged_url, int socket_count, void* imc_handles, + void* nacl_process_handle, int* nacl_process_id); +#endif + #if defined(OS_LINUX) // Return a read-only file descriptor to the font which best matches the given // properties or -1 on failure. diff --git a/webkit/glue/webkitclient_impl.cc b/webkit/glue/webkitclient_impl.cc index 12d5702..844aae7 100644 --- a/webkit/glue/webkitclient_impl.cc +++ b/webkit/glue/webkitclient_impl.cc @@ -34,8 +34,9 @@ #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebVector.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "webkit/glue/plugins/plugin_instance.h" -#include "webkit/glue/plugins/webplugininfo.h" +#include "webkit/glue/media/audio_decoder.h" +#include "webkit/plugins/npapi/plugin_instance.h" +#include "webkit/plugins/npapi/webplugininfo.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/websocketstreamhandle_impl.h" #include "webkit/glue/weburlloader_impl.h" @@ -44,6 +45,7 @@ #include "v8/include/v8.h" #endif +using WebKit::WebAudioBus; using WebKit::WebCookie; using WebKit::WebData; using WebKit::WebLocalizedString; @@ -61,7 +63,7 @@ namespace { class MemoryUsageCache { public: // Retrieves the Singleton. - static MemoryUsageCache* Get() { + static MemoryUsageCache* GetInstance() { return Singleton<MemoryUsageCache>::get(); } @@ -223,18 +225,18 @@ WebString WebKitClientImpl::userAgent(const WebURL& url) { void WebKitClientImpl::getPluginList(bool refresh, WebPluginListBuilder* builder) { - std::vector<WebPluginInfo> plugins; + std::vector<webkit::npapi::WebPluginInfo> plugins; GetPlugins(refresh, &plugins); for (size_t i = 0; i < plugins.size(); ++i) { - const WebPluginInfo& plugin = plugins[i]; + const webkit::npapi::WebPluginInfo& plugin = plugins[i]; builder->addPlugin( plugin.name, plugin.desc, FilePathStringToWebString(plugin.path.BaseName().value())); for (size_t j = 0; j < plugin.mime_types.size(); ++j) { - const WebPluginMimeType& mime_type = plugin.mime_types[j]; + const webkit::npapi::WebPluginMimeType& mime_type = plugin.mime_types[j]; builder->addMediaTypeToLastPlugin( WebString::fromUTF8(mime_type.mime_type), mime_type.description); @@ -352,6 +354,15 @@ WebData WebKitClientImpl::loadResource(const char* name) { return WebData(); } +bool WebKitClientImpl::loadAudioResource( + WebKit::WebAudioBus* destination_bus, const char* audio_file_data, + size_t data_size, double sample_rate) { + return DecodeAudioFileData(destination_bus, + audio_file_data, + data_size, + sample_rate); +} + WebString WebKitClientImpl::queryLocalizedString( WebLocalizedString::Name name) { int message_id = ToMessageID(name); @@ -499,7 +510,7 @@ static size_t memoryUsageMBGeneric() { static size_t getMemoryUsageMB(bool bypass_cache) { size_t current_mem_usage = 0; - MemoryUsageCache* mem_usage_cache_singleton = MemoryUsageCache::Get(); + MemoryUsageCache* mem_usage_cache_singleton = MemoryUsageCache::GetInstance(); if (!bypass_cache && mem_usage_cache_singleton->IsCachedValueValid(¤t_mem_usage)) return current_mem_usage; diff --git a/webkit/glue/webkitclient_impl.h b/webkit/glue/webkitclient_impl.h index 2836e8e..cc361d3 100644 --- a/webkit/glue/webkitclient_impl.h +++ b/webkit/glue/webkitclient_impl.h @@ -52,6 +52,9 @@ class WebKitClientImpl : public WebKit::WebKitClient { virtual void traceEventBegin(const char* name, void* id, const char* extra); virtual void traceEventEnd(const char* name, void* id, const char* extra); virtual WebKit::WebData loadResource(const char* name); + virtual bool loadAudioResource( + WebKit::WebAudioBus* destination_bus, const char* audio_file_data, + size_t data_size, double sample_rate); virtual WebKit::WebString queryLocalizedString( WebKit::WebLocalizedString::Name name); virtual WebKit::WebString queryLocalizedString( diff --git a/webkit/glue/webmediaplayer_impl.cc b/webkit/glue/webmediaplayer_impl.cc index 58489cc..4a64b0f 100644 --- a/webkit/glue/webmediaplayer_impl.cc +++ b/webkit/glue/webmediaplayer_impl.cc @@ -8,6 +8,7 @@ #include "base/callback.h" #include "base/command_line.h" +#include "media/base/filter_collection.h" #include "media/base/limits.h" #include "media/base/media_format.h" #include "media/base/media_switches.h" @@ -23,7 +24,6 @@ #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" #include "third_party/WebKit/WebKit/chromium/public/WebVideoFrame.h" #include "webkit/glue/media/buffered_data_source.h" -#include "webkit/glue/media/media_resource_loader_bridge_factory.h" #include "webkit/glue/media/simple_data_source.h" #include "webkit/glue/media/video_renderer_impl.h" #include "webkit/glue/media/web_video_renderer.h" @@ -225,7 +225,7 @@ void WebMediaPlayerImpl::Proxy::PutCurrentFrame( WebMediaPlayerImpl::WebMediaPlayerImpl( WebKit::WebMediaPlayerClient* client, - media::MediaFilterCollection* collection) + media::FilterCollection* collection) : network_state_(WebKit::WebMediaPlayer::Empty), ready_state_(WebKit::WebMediaPlayer::HaveNothing), main_loop_(NULL), @@ -233,6 +233,7 @@ WebMediaPlayerImpl::WebMediaPlayerImpl( pipeline_(NULL), pipeline_thread_("PipelineThread"), paused_(true), + seeking_(false), playback_rate_(0.0f), client_(client), proxy_(NULL), @@ -243,8 +244,7 @@ WebMediaPlayerImpl::WebMediaPlayerImpl( } bool WebMediaPlayerImpl::Initialize( - MediaResourceLoaderBridgeFactory* bridge_factory_simple, - MediaResourceLoaderBridgeFactory* bridge_factory_buffered, + WebKit::WebFrame* frame, bool use_simple_data_source, scoped_refptr<WebVideoRenderer> web_video_renderer) { // Create the pipeline and its thread. @@ -274,11 +274,11 @@ bool WebMediaPlayerImpl::Initialize( // A simple data source that keeps all data in memory. scoped_refptr<SimpleDataSource> simple_data_source( - new SimpleDataSource(MessageLoop::current(), bridge_factory_simple)); + new SimpleDataSource(MessageLoop::current(), frame)); // A sophisticated data source that does memory caching. scoped_refptr<BufferedDataSource> buffered_data_source( - new BufferedDataSource(MessageLoop::current(), bridge_factory_buffered)); + new BufferedDataSource(MessageLoop::current(), frame)); proxy_->SetDataSource(buffered_data_source); if (use_simple_data_source) { @@ -369,11 +369,6 @@ void WebMediaPlayerImpl::seek(float seconds) { return; } - // Drop our ready state if the media file isn't fully loaded. - if (!pipeline_->IsLoaded()) { - SetReadyState(WebKit::WebMediaPlayer::HaveMetadata); - } - // Try to preserve as much accuracy as possible. float microseconds = seconds * base::Time::kMicrosecondsPerSecond; base::TimeDelta seek_time = @@ -384,6 +379,8 @@ void WebMediaPlayerImpl::seek(float seconds) { paused_time_ = seek_time; } + seeking_ = true; + // Kick off the asynchronous seek! pipeline_->Seek( seek_time, @@ -477,7 +474,7 @@ bool WebMediaPlayerImpl::seeking() const { if (ready_state_ == WebKit::WebMediaPlayer::HaveNothing) return false; - return ready_state_ == WebKit::WebMediaPlayer::HaveMetadata; + return seeking_; } float WebMediaPlayerImpl::duration() const { @@ -505,6 +502,14 @@ int WebMediaPlayerImpl::dataRate() const { return 0; } +WebKit::WebMediaPlayer::NetworkState WebMediaPlayerImpl::networkState() const { + return network_state_; +} + +WebKit::WebMediaPlayer::ReadyState WebMediaPlayerImpl::readyState() const { + return ready_state_; +} + const WebKit::WebTimeRanges& WebMediaPlayerImpl::buffered() { DCHECK(MessageLoop::current() == main_loop_); @@ -698,6 +703,7 @@ void WebMediaPlayerImpl::OnPipelineSeek() { } SetReadyState(WebKit::WebMediaPlayer::HaveEnoughData); + seeking_ = false; GetClient()->timeChanged(); } } diff --git a/webkit/glue/webmediaplayer_impl.h b/webkit/glue/webmediaplayer_impl.h index 26825da..bae0d9b 100644 --- a/webkit/glue/webmediaplayer_impl.h +++ b/webkit/glue/webmediaplayer_impl.h @@ -69,6 +69,10 @@ class GURL; +namespace WebKit { +class WebFrame; +} + namespace webkit_glue { class MediaResourceLoaderBridgeFactory; @@ -91,12 +95,12 @@ class WebMediaPlayerImpl : public WebKit::WebMediaPlayer, Proxy(MessageLoop* render_loop, WebMediaPlayerImpl* webmediaplayer); - // Methods for MediaFilter -> WebMediaPlayerImpl communication. + // Methods for Filter -> WebMediaPlayerImpl communication. void Repaint(); void SetVideoRenderer(scoped_refptr<WebVideoRenderer> video_renderer); void SetDataSource(scoped_refptr<WebDataSource> data_source); - // Methods for WebMediaPlayerImpl -> MediaFilter communication. + // Methods for WebMediaPlayerImpl -> Filter communication. void Paint(skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect); void SetSize(const gfx::Rect& rect); void Detach(); @@ -171,13 +175,12 @@ class WebMediaPlayerImpl : public WebKit::WebMediaPlayer, // // Callers must call |Initialize()| before they can use the object. WebMediaPlayerImpl(WebKit::WebMediaPlayerClient* client, - media::MediaFilterCollection* collection); + media::FilterCollection* collection); virtual ~WebMediaPlayerImpl(); // Finalizes initialization of the object. bool Initialize( - MediaResourceLoaderBridgeFactory* bridge_factory_simple, - MediaResourceLoaderBridgeFactory* bridge_factory_buffered, + WebKit::WebFrame* frame, bool use_simple_data_source, scoped_refptr<WebVideoRenderer> web_video_renderer); @@ -223,12 +226,8 @@ class WebMediaPlayerImpl : public WebKit::WebMediaPlayer, // Internal states of loading and network. // TODO(hclam): Ask the pipeline about the state rather than having reading // them from members which would cause race conditions. - virtual WebKit::WebMediaPlayer::NetworkState networkState() const { - return network_state_; - } - virtual WebKit::WebMediaPlayer::ReadyState readyState() const { - return ready_state_; - } + virtual WebKit::WebMediaPlayer::NetworkState networkState() const; + virtual WebKit::WebMediaPlayer::ReadyState readyState() const; virtual unsigned long long bytesLoaded() const; virtual unsigned long long totalBytes() const; @@ -285,7 +284,7 @@ class WebMediaPlayerImpl : public WebKit::WebMediaPlayer, MessageLoop* main_loop_; // A collection of filters. - scoped_ptr<media::MediaFilterCollection> filter_collection_; + scoped_ptr<media::FilterCollection> filter_collection_; // The actual pipeline and the thread it runs on. scoped_refptr<media::Pipeline> pipeline_; @@ -304,6 +303,7 @@ class WebMediaPlayerImpl : public WebKit::WebMediaPlayer, // clock can creep forward a little bit while the asynchronous // SetPlaybackRate(0) is being executed. bool paused_; + bool seeking_; float playback_rate_; base::TimeDelta paused_time_; diff --git a/webkit/glue/webpreferences.cc b/webkit/glue/webpreferences.cc index afc39bd..abe5903 100644 --- a/webkit/glue/webpreferences.cc +++ b/webkit/glue/webpreferences.cc @@ -21,11 +21,11 @@ using WebKit::WebURL; using WebKit::WebView; WebPreferences::WebPreferences() - : standard_font_family(L"Times New Roman"), - fixed_font_family(L"Courier New"), - serif_font_family(L"Times New Roman"), - sans_serif_font_family(L"Arial"), - cursive_font_family(L"Script"), + : standard_font_family(ASCIIToUTF16("Times New Roman")), + fixed_font_family(ASCIIToUTF16("Courier New")), + serif_font_family(ASCIIToUTF16("Times New Roman")), + sans_serif_font_family(ASCIIToUTF16("Arial")), + cursive_font_family(ASCIIToUTF16("Script")), fantasy_font_family(), // Not sure what to use on Windows. default_font_size(16), default_fixed_font_size(13), @@ -73,12 +73,12 @@ WebPreferences::~WebPreferences() { void WebPreferences::Apply(WebView* web_view) const { WebSettings* settings = web_view->settings(); - settings->setStandardFontFamily(WideToUTF16Hack(standard_font_family)); - settings->setFixedFontFamily(WideToUTF16Hack(fixed_font_family)); - settings->setSerifFontFamily(WideToUTF16Hack(serif_font_family)); - settings->setSansSerifFontFamily(WideToUTF16Hack(sans_serif_font_family)); - settings->setCursiveFontFamily(WideToUTF16Hack(cursive_font_family)); - settings->setFantasyFontFamily(WideToUTF16Hack(fantasy_font_family)); + settings->setStandardFontFamily(standard_font_family); + settings->setFixedFontFamily(fixed_font_family); + settings->setSerifFontFamily(serif_font_family); + settings->setSansSerifFontFamily(sans_serif_font_family); + settings->setCursiveFontFamily(cursive_font_family); + settings->setFantasyFontFamily(fantasy_font_family); settings->setDefaultFontSize(default_font_size); settings->setDefaultFixedFontSize(default_fixed_font_size); settings->setMinimumFontSize(minimum_font_size); @@ -142,7 +142,7 @@ void WebPreferences::Apply(WebView* web_view) const { // Enable experimental WebGL support if requested on command line // and support is compiled in. bool enable_webgl = - WebRuntimeFeatures::isWebGLEnabled() || experimental_webgl_enabled; + WebRuntimeFeatures::isWebGLEnabled() && experimental_webgl_enabled; settings->setExperimentalWebGLEnabled(enable_webgl); // Display colored borders around composited render layers if requested diff --git a/webkit/glue/webpreferences.h b/webkit/glue/webpreferences.h index 6cb8044..8ee4ce8 100644 --- a/webkit/glue/webpreferences.h +++ b/webkit/glue/webpreferences.h @@ -13,6 +13,8 @@ #include <string> #include <vector> + +#include "base/string16.h" #include "googleurl/src/gurl.h" namespace WebKit { @@ -20,12 +22,12 @@ class WebView; } struct WebPreferences { - std::wstring standard_font_family; - std::wstring fixed_font_family; - std::wstring serif_font_family; - std::wstring sans_serif_font_family; - std::wstring cursive_font_family; - std::wstring fantasy_font_family; + string16 standard_font_family; + string16 fixed_font_family; + string16 serif_font_family; + string16 sans_serif_font_family; + string16 cursive_font_family; + string16 fantasy_font_family; int default_font_size; int default_fixed_font_size; int minimum_font_size; diff --git a/webkit/glue/weburlloader_impl.cc b/webkit/glue/weburlloader_impl.cc index a7f219d..0372567 100644 --- a/webkit/glue/weburlloader_impl.cc +++ b/webkit/glue/weburlloader_impl.cc @@ -14,6 +14,7 @@ #include "base/time.h" #include "net/base/data_url.h" #include "net/base/load_flags.h" +#include "net/base/mime_util.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/http/http_response_headers.h" @@ -302,6 +303,8 @@ class WebURLLoaderImpl::Context : public base::RefCounted<Context>, friend class base::RefCounted<Context>; ~Context() {} + // We can optimize the handling of data URLs in most cases. + bool CanHandleDataURL(const GURL& url) const; void HandleDataURL(); WebURLLoaderImpl* loader_; @@ -350,7 +353,7 @@ void WebURLLoaderImpl::Context::Start( request_ = request; // Save the request. GURL url = request.url(); - if (url.SchemeIs("data")) { + if (url.SchemeIs("data") && CanHandleDataURL(url)) { if (sync_load_response) { // This is a sync load. Do the work now. sync_load_response->url = url; @@ -432,6 +435,7 @@ void WebURLLoaderImpl::Context::Start( request_info.appcache_host_id = request.appCacheHostID(); request_info.routing_id = request.requestorID(); request_info.download_to_file = request.downloadToFile(); + request_info.has_user_gesture = request.hasUserGesture(); bridge_.reset(ResourceLoaderBridge::Create(request_info)); if (!request.httpBody().isNull()) { @@ -662,6 +666,29 @@ void WebURLLoaderImpl::Context::OnCompletedRequest( Release(); } +bool WebURLLoaderImpl::Context::CanHandleDataURL(const GURL& url) const { + DCHECK(url.SchemeIs("data")); + + // Optimize for the case where we can handle a data URL locally. We must + // skip this for data URLs targetted at frames since those could trigger a + // download. + // + // NOTE: We special case MIME types we can render both for performance + // reasons as well as to support unit tests, which do not have an underlying + // ResourceLoaderBridge implementation. + + if (request_.targetType() != WebURLRequest::TargetIsMainFrame && + request_.targetType() != WebURLRequest::TargetIsSubframe) + return true; + + std::string mime_type, unused_charset; + if (net::DataURL::Parse(url, &mime_type, &unused_charset, NULL) && + net::IsSupportedMimeType(mime_type)) + return true; + + return false; +} + void WebURLLoaderImpl::Context::HandleDataURL() { ResourceResponseInfo info; URLRequestStatus status; |