diff options
142 files changed, 7563 insertions, 7025 deletions
diff --git a/chrome/browser/nacl_host/nacl_process_host.cc b/chrome/browser/nacl_host/nacl_process_host.cc index 18b727e..138bb08 100644 --- a/chrome/browser/nacl_host/nacl_process_host.cc +++ b/chrome/browser/nacl_host/nacl_process_host.cc @@ -20,6 +20,7 @@ #include "chrome/common/nacl_messages.h" #include "chrome/common/render_messages.h" #include "ipc/ipc_switches.h" +#include "native_client/src/shared/imc/nacl_imc.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" @@ -42,12 +43,18 @@ void SetCloseOnExec(nacl::Handle fd) { } // namespace +struct NaClProcessHost::NaClInternal { + std::vector<nacl::Handle> sockets_for_renderer; + std::vector<nacl::Handle> sockets_for_sel_ldr; +}; + NaClProcessHost::NaClProcessHost( ResourceDispatcherHost *resource_dispatcher_host, const std::wstring& url) : BrowserChildProcessHost(NACL_LOADER_PROCESS, resource_dispatcher_host), resource_dispatcher_host_(resource_dispatcher_host), reply_msg_(NULL), + internal_(new NaClInternal()), running_on_wow64_(false) { set_name(url); #if defined(OS_WIN) @@ -63,11 +70,11 @@ NaClProcessHost::~NaClProcessHost() { // defined, but we still compile a bunch of other code from this // file anyway. TODO(mseaborn): Make this less messy. #ifndef DISABLE_NACL - for (size_t i = 0; i < sockets_for_renderer_.size(); i++) { - nacl::Close(sockets_for_renderer_[i]); + for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) { + nacl::Close(internal_->sockets_for_renderer[i]); } - for (size_t i = 0; i < sockets_for_sel_ldr_.size(); i++) { - nacl::Close(sockets_for_sel_ldr_[i]); + for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) { + nacl::Close(internal_->sockets_for_sel_ldr[i]); } #endif @@ -105,8 +112,8 @@ bool NaClProcessHost::Launch(RenderMessageFilter* render_message_filter, // Create a connected socket if (nacl::SocketPair(pair) == -1) return false; - sockets_for_renderer_.push_back(pair[0]); - sockets_for_sel_ldr_.push_back(pair[1]); + internal_->sockets_for_renderer.push_back(pair[0]); + internal_->sockets_for_sel_ldr.push_back(pair[1]); SetCloseOnExec(pair[0]); SetCloseOnExec(pair[1]); } @@ -183,12 +190,13 @@ void NaClProcessHost::OnProcessLaunched() { std::vector<nacl::FileDescriptor> handles_for_renderer; base::ProcessHandle nacl_process_handle; - for (size_t i = 0; i < sockets_for_renderer_.size(); i++) { + for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) { #if defined(OS_WIN) // Copy the handle into the renderer process. HANDLE handle_in_renderer; DuplicateHandle(base::GetCurrentProcessHandle(), - reinterpret_cast<HANDLE>(sockets_for_renderer_[i]), + reinterpret_cast<HANDLE>( + internal_->sockets_for_renderer[i]), render_message_filter_->peer_handle(), &handle_in_renderer, GENERIC_READ | GENERIC_WRITE, @@ -200,7 +208,7 @@ void NaClProcessHost::OnProcessLaunched() { // No need to dup the imc_handle - we don't pass it anywhere else so // it cannot be closed. nacl::FileDescriptor imc_handle; - imc_handle.fd = sockets_for_renderer_[i]; + imc_handle.fd = internal_->sockets_for_renderer[i]; imc_handle.auto_close = true; handles_for_renderer.push_back(imc_handle); #endif @@ -228,18 +236,19 @@ void NaClProcessHost::OnProcessLaunched() { render_message_filter_->Send(reply_msg_); render_message_filter_ = NULL; reply_msg_ = NULL; - sockets_for_renderer_.clear(); + internal_->sockets_for_renderer.clear(); SendStartMessage(); } void NaClProcessHost::SendStartMessage() { std::vector<nacl::FileDescriptor> handles_for_sel_ldr; - for (size_t i = 0; i < sockets_for_sel_ldr_.size(); i++) { + for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) { #if defined(OS_WIN) HANDLE channel; if (!DuplicateHandle(GetCurrentProcess(), - reinterpret_cast<HANDLE>(sockets_for_sel_ldr_[i]), + reinterpret_cast<HANDLE>( + internal_->sockets_for_sel_ldr[i]), handle(), &channel, GENERIC_READ | GENERIC_WRITE, @@ -250,7 +259,7 @@ void NaClProcessHost::SendStartMessage() { reinterpret_cast<nacl::FileDescriptor>(channel)); #else nacl::FileDescriptor channel; - channel.fd = dup(sockets_for_sel_ldr_[i]); + channel.fd = dup(internal_->sockets_for_sel_ldr[i]); if (channel.fd < 0) { LOG(ERROR) << "Failed to dup() a file descriptor"; return; @@ -281,7 +290,7 @@ void NaClProcessHost::SendStartMessage() { #endif Send(new NaClProcessMsg_Start(handles_for_sel_ldr)); - sockets_for_sel_ldr_.clear(); + internal_->sockets_for_sel_ldr.clear(); } bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) { diff --git a/chrome/browser/nacl_host/nacl_process_host.h b/chrome/browser/nacl_host/nacl_process_host.h index c0d5731..c54f6ba 100644 --- a/chrome/browser/nacl_host/nacl_process_host.h +++ b/chrome/browser/nacl_host/nacl_process_host.h @@ -11,7 +11,6 @@ #include "base/ref_counted.h" #include "chrome/browser/browser_child_process_host.h" #include "chrome/common/nacl_types.h" -#include "native_client/src/shared/imc/nacl_imc.h" class RenderMessageFilter; @@ -41,6 +40,12 @@ class NaClProcessHost : public BrowserChildProcessHost { virtual void OnChildDied(); private: + // Internal class that holds the nacl::Handle objecs so that + // nacl_process_host.h doesn't include NaCl headers. Needed since it's + // included by src\content, which can't depend on the NaCl gyp file because it + // depends on chrome.gyp (circular dependency). + struct NaClInternal; + bool LaunchSelLdr(); void SendStartMessage(); @@ -65,8 +70,7 @@ class NaClProcessHost : public BrowserChildProcessHost { IPC::Message* reply_msg_; // Socket pairs for the NaCl process and renderer. - std::vector<nacl::Handle> sockets_for_renderer_; - std::vector<nacl::Handle> sockets_for_sel_ldr_; + scoped_ptr<NaClInternal> internal_; // Windows platform flag bool running_on_wow64_; diff --git a/chrome/browser/renderer_host/accelerated_surface_container_mac.h b/chrome/browser/renderer_host/accelerated_surface_container_mac.h index 02d43d1..c555807 100644 --- a/chrome/browser/renderer_host/accelerated_surface_container_mac.h +++ b/chrome/browser/renderer_host/accelerated_surface_container_mac.h @@ -6,148 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MAC_H_ #pragma once -// The "GPU plugin" is currently implemented as a special kind of -// NPAPI plugin to provide high-performance on-screen 3D rendering for -// Pepper 3D. -// -// On Windows and X11 platforms the GPU plugin relies on cross-process -// parenting of windows, which is not supported via any public APIs in -// the Mac OS X window system. -// -// To achieve full hardware acceleration we use the new IOSurface APIs -// introduced in Mac OS X 10.6. The GPU plugin's process produces an -// IOSurface and renders into it using OpenGL. It uses the -// IOSurfaceGetID and IOSurfaceLookup APIs to pass a reference to this -// surface to the browser process for on-screen rendering. The GPU -// plugin essentially looks like a windowless plugin; the browser -// process gets all of the mouse events, because the plugin process -// does not have an on-screen window. -// -// This class encapsulates some of the management of these data -// structures, in conjunction with the AcceleratedSurfaceContainerManagerMac. - -#include <CoreFoundation/CoreFoundation.h> -#include <OpenGL/OpenGL.h> - -#include "app/surface/transport_dib.h" -#include "base/basictypes.h" -#include "base/mac/scoped_cftyperef.h" -#include "base/scoped_ptr.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect.h" - -namespace webkit { -namespace npapi { -struct WebPluginGeometry; -} -} - -class AcceleratedSurfaceContainerManagerMac; - -class AcceleratedSurfaceContainerMac { - public: - AcceleratedSurfaceContainerMac( - AcceleratedSurfaceContainerManagerMac* manager, - bool opaque); - virtual ~AcceleratedSurfaceContainerMac(); - - // Sets the backing store and size of this accelerated surface container. - // There are two versions: the IOSurface version is used on systems where the - // IOSurface API is supported (Mac OS X 10.6 and later); the TransportDIB is - // used on Mac OS X 10.5 and earlier. - void SetSizeAndIOSurface(int32 width, - int32 height, - uint64 io_surface_identifier); - void SetSizeAndTransportDIB(int32 width, - int32 height, - TransportDIB::Handle transport_dib); - - // Tells the accelerated surface container that its geometry has changed, - // for example because of a scroll event. (Note that the container - // currently only pays attention to the clip width and height, since the - // view in which it is hosted is responsible for positioning it on the - // page.) - void SetGeometry(const webkit::npapi::WebPluginGeometry& geom); - - // Draws this accelerated surface's contents, texture mapped onto a quad in - // the given OpenGL context. TODO(kbr): figure out and define exactly how the - // coordinate system will work out. - void Draw(CGLContextObj context); - - // Causes the next Draw call to trigger a texture upload. Should be called any - // time the drawing context has changed. - void ForceTextureReload() { texture_needs_upload_ = true; } - - // Returns if the surface should be shown. - bool ShouldBeVisible() const; - - // Notifies the the container that its surface was painted to. - void set_was_painted_to(uint64 surface_id); - - // Notifies the container that its surface is invalid. - void set_surface_invalid() { was_painted_to_ = false; } - private: - // The manager of this accelerated surface container. - AcceleratedSurfaceContainerManagerMac* manager_; - - // Whether this accelerated surface's content is supposed to be opaque. - bool opaque_; - - // The IOSurfaceRef, if any, that has been handed from the GPU - // plugin process back to the browser process for drawing. - // This is held as a CFTypeRef because we can't refer to the - // IOSurfaceRef type when building on 10.5. - base::mac::ScopedCFTypeRef<CFTypeRef> surface_; - - // The id of |surface_|, or 0 if |surface_| is NULL. - uint64 surface_id_; - - // The width and height of the io surface. During resizing, this is different - // from |width_| and |height_|. - int32 surface_width_; - int32 surface_height_; - - // The TransportDIB which is used in pre-10.6 systems where the IOSurface - // API is not supported. This is a weak reference to the actual TransportDIB - // whic is owned by the GPU process. - scoped_ptr<TransportDIB> transport_dib_; - - // The width and height of the container. - int32 width_; - int32 height_; - - // The clip rectangle, relative to the (x_, y_) origin. - gfx::Rect clip_rect_; - - // The "live" OpenGL texture referring to this IOSurfaceRef. Note - // that per the CGLTexImageIOSurface2D API we do not need to - // explicitly update this texture's contents once created. All we - // need to do is ensure it is re-bound before attempting to draw - // with it. - GLuint texture_; - - // True if we need to upload the texture again during the next draw. - bool texture_needs_upload_; - - // This may refer to an old version of the texture if the container is - // resized, for example. - GLuint texture_pending_deletion_; - - // Stores if the plugin has a visible state. - bool visible_; - - // Stores if the plugin's IOSurface has been swapped before. Used to not show - // it before it hasn't been painted to at least once. - bool was_painted_to_; - - // Releases the IOSurface reference, if any, retained by this object. - void ReleaseIOSurface(); - - // Enqueue our texture for later deletion. - void EnqueueTextureForDeletion(); - - DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerMac); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/accelerated_surface_container_mac.h" #endif // CHROME_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MAC_H_ - diff --git a/chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h b/chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h index 8f963e6..6d94516 100644 --- a/chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h +++ b/chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h @@ -6,120 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MANAGER_MAC_H_ #pragma once -#include <OpenGL/OpenGL.h> -#include <map> - -#include "app/surface/transport_dib.h" -#include "base/basictypes.h" -#include "base/synchronization/lock.h" -#include "ui/gfx/native_widget_types.h" - -namespace webkit { -namespace npapi { -struct WebPluginGeometry; -} -} - -class AcceleratedSurfaceContainerMac; - -// Helper class that manages the backing store and on-screen rendering -// of instances of the GPU plugin on the Mac. -class AcceleratedSurfaceContainerManagerMac { - public: - AcceleratedSurfaceContainerManagerMac(); - - // Allocates a new "fake" PluginWindowHandle, which is used as the - // key for the other operations. - gfx::PluginWindowHandle AllocateFakePluginWindowHandle(bool opaque, - bool root); - - // Destroys a fake PluginWindowHandle and associated storage. - void DestroyFakePluginWindowHandle(gfx::PluginWindowHandle id); - - // Indicates whether the given PluginWindowHandle is "root", which - // means that we are using accelerated compositing and that this one - // contains the compositor's output. - bool IsRootContainer(gfx::PluginWindowHandle id) const; - - // Returns the handle of the compositor surface, or kNullPluginWindow if no - // compositor surface is active. - gfx::PluginWindowHandle root_container_handle() const { - return root_container_handle_; - } - - // Informs the manager if gpu rendering is active. - void set_gpu_rendering_active(bool active); - - // Sets the size and backing store of the plugin instance. There are two - // versions: the IOSurface version is used on systems where the IOSurface - // API is supported (Mac OS X 10.6 and later); the TransportDIB is used on - // Mac OS X 10.5 and earlier. - void SetSizeAndIOSurface(gfx::PluginWindowHandle id, - int32 width, - int32 height, - uint64 io_surface_identifier); - void SetSizeAndTransportDIB(gfx::PluginWindowHandle id, - int32 width, - int32 height, - TransportDIB::Handle transport_dib); - - // Takes an update from WebKit about a plugin's position and size and moves - // the plugin accordingly. - void SetPluginContainerGeometry( - const webkit::npapi::WebPluginGeometry& move); - - // Draws the plugin container associated with the given id into the given - // OpenGL context, which must already be current. - void Draw(CGLContextObj context, gfx::PluginWindowHandle id); - - // Causes the next Draw call on each container to trigger a texture upload. - // Should be called any time the drawing context has changed. - void ForceTextureReload(); - - // Notifies a surface that it has been painted to. - void SetSurfaceWasPaintedTo(gfx::PluginWindowHandle id, uint64 surface_id); - - // Notifies the root container that its surface is invalid. - void SetRootSurfaceInvalid(); - - // Returns if a given surface should be shown. - bool SurfaceShouldBeVisible(gfx::PluginWindowHandle id) const; - private: - uint32 current_id_; - - // Maps a "fake" plugin window handle to the corresponding container. - AcceleratedSurfaceContainerMac* - MapIDToContainer(gfx::PluginWindowHandle id) const; - - // A map that associates plugin window handles with their containers. - typedef std::map<gfx::PluginWindowHandle, AcceleratedSurfaceContainerMac*> - PluginWindowToContainerMap; - PluginWindowToContainerMap plugin_window_to_container_map_; - - // The "root" container, which is only used to draw the output of - // the accelerated compositor if it is active. Currently, - // accelerated plugins (Core Animation and Pepper 3D) are drawn on - // top of the page's contents rather than transformed and composited - // with the rest of the page. At some point we would like them to be - // treated uniformly with other page elements; when this is done, - // the separate treatment of the root container can go away because - // there will only be one container active when the accelerated - // compositor is active. - AcceleratedSurfaceContainerMac* root_container_; - gfx::PluginWindowHandle root_container_handle_; - - // True if gpu rendering is active. The root container is created on demand - // and destroyed only when a renderer process exits. When the compositor was - // created, this is set to |false| while the compositor is not needed. - bool gpu_rendering_active_; - - // Both |plugin_window_to_container_map_| and the - // AcceleratedSurfaceContainerMac in it are not threadsafe, but accessed from - // multiple threads. All these accesses are guarded by this lock. - mutable base::Lock lock_; - - DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerManagerMac); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/accelerated_surface_container_manager_mac.h" #endif // CHROME_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MANAGER_MAC_H_ - diff --git a/chrome/browser/renderer_host/async_resource_handler.h b/chrome/browser/renderer_host/async_resource_handler.h index d5fa704..961ea96 100644 --- a/chrome/browser/renderer_host/async_resource_handler.h +++ b/chrome/browser/renderer_host/async_resource_handler.h @@ -6,56 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_ASYNC_RESOURCE_HANDLER_H_ #pragma once -#include <string> - -#include "chrome/browser/renderer_host/resource_handler.h" - -class ResourceDispatcherHost; -class ResourceMessageFilter; -class SharedIOBuffer; - -// Used to complete an asynchronous resource request in response to resource -// load events from the resource dispatcher host. -class AsyncResourceHandler : public ResourceHandler { - public: - AsyncResourceHandler(ResourceMessageFilter* filter, - int routing_id, - const GURL& url, - ResourceDispatcherHost* resource_dispatcher_host); - - // ResourceHandler implementation: - virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); - virtual bool OnRequestRedirected(int request_id, const GURL& new_url, - ResourceResponse* response, bool* defer); - virtual bool OnResponseStarted(int request_id, ResourceResponse* response); - virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); - virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, - int min_size); - virtual bool OnReadCompleted(int request_id, int* bytes_read); - virtual bool OnResponseCompleted(int request_id, - const net::URLRequestStatus& status, - const std::string& security_info); - virtual void OnRequestClosed(); - virtual void OnDataDownloaded(int request_id, int bytes_downloaded); - - static void GlobalCleanup(); - - private: - virtual ~AsyncResourceHandler(); - - scoped_refptr<SharedIOBuffer> read_buffer_; - ResourceMessageFilter* filter_; - int routing_id_; - ResourceDispatcherHost* rdh_; - - // |next_buffer_size_| is the size of the buffer to be allocated on the next - // OnWillRead() call. We exponentially grow the size of the buffer allocated - // when our owner fills our buffers. On the first OnWillRead() call, we - // allocate a buffer of 32k and double it in OnReadCompleted() if the buffer - // was filled, up to a maximum size of 512k. - int next_buffer_size_; - - DISALLOW_COPY_AND_ASSIGN(AsyncResourceHandler); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/async_resource_handler.h" #endif // CHROME_BROWSER_RENDERER_HOST_ASYNC_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/audio_renderer_host.h b/chrome/browser/renderer_host/audio_renderer_host.h index b91be77..ca577c6 100644 --- a/chrome/browser/renderer_host/audio_renderer_host.h +++ b/chrome/browser/renderer_host/audio_renderer_host.h @@ -1,223 +1,12 @@ // 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. -// -// AudioRendererHost serves audio related requests from AudioRenderer which -// lives inside the render process and provide access to audio hardware. -// -// This class is owned by BrowserRenderProcessHost, and instantiated on UI -// thread, but all other operations and method calls happen on IO thread, so we -// need to be extra careful about the lifetime of this object. AudioManager is a -// singleton and created in IO thread, audio output streams are also created in -// the IO thread, so we need to destroy them also in IO thread. After this class -// is created, a task of OnInitialized() is posted on IO thread in which -// singleton of AudioManager is created and. -// -// Here's an example of a typical IPC dialog for audio: -// -// Renderer AudioRendererHost -// | | -// | CreateStream > | -// | < Created | -// | | -// | Play > | -// | < Playing | time -// | | -// | < RequestAudioPacket | -// | AudioPacketReady > | -// | ... | -// | < RequestAudioPacket | -// | AudioPacketReady > | -// | | -// | ... | -// | < RequestAudioPacket | -// | AudioPacketReady > | -// | ... | -// | Pause > | -// | < Paused | -// | ... | -// | Start > | -// | < Started | -// | ... | -// | Close > | -// v v - -// The above mode of operation uses relatively big buffers and has latencies -// of 50 ms or more. There is a second mode of operation which is low latency. -// For low latency audio, the picture above is modified by not having the -// RequestAudioPacket and the AudioPacketReady messages, instead a SyncSocket -// pair is used to signal buffer readiness without having to route messages -// using the IO thread. #ifndef CHROME_BROWSER_RENDERER_HOST_AUDIO_RENDERER_HOST_H_ #define CHROME_BROWSER_RENDERER_HOST_AUDIO_RENDERER_HOST_H_ #pragma once -#include <map> - -#include "base/gtest_prod_util.h" -#include "base/process.h" -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "base/shared_memory.h" -#include "chrome/browser/browser_message_filter.h" -#include "chrome/browser/browser_thread.h" -#include "ipc/ipc_message.h" -#include "media/audio/audio_io.h" -#include "media/audio/audio_output_controller.h" -#include "media/audio/simple_sources.h" - -class AudioManager; -struct ViewHostMsg_Audio_CreateStream_Params; - -class AudioRendererHost : public BrowserMessageFilter, - public media::AudioOutputController::EventHandler { - public: - typedef std::pair<int32, int> AudioEntryId; - - struct AudioEntry { - AudioEntry(); - ~AudioEntry(); - - // The AudioOutputController that manages the audio stream. - scoped_refptr<media::AudioOutputController> controller; - - // Render view ID that requested the audio stream. - int32 render_view_id; - - // The audio stream ID in the render view. - int stream_id; - - // Shared memory for transmission of the audio data. - base::SharedMemory shared_memory; - - // The synchronous reader to be used by the controller. We have the - // ownership of the reader. - scoped_ptr<media::AudioOutputController::SyncReader> reader; - - bool pending_buffer_request; - - // Set to true after we called Close() for the controller. - bool pending_close; - }; - - typedef std::map<AudioEntryId, AudioEntry*> AudioEntryMap; - - // Called from UI thread from the owner of this object. - AudioRendererHost(); - - - // BrowserMessageFilter implementation. - virtual void OnChannelClosing(); - virtual void OnDestruct() const; - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - - ///////////////////////////////////////////////////////////////////////////// - // AudioOutputController::EventHandler implementations. - virtual void OnCreated(media::AudioOutputController* controller); - virtual void OnPlaying(media::AudioOutputController* controller); - virtual void OnPaused(media::AudioOutputController* controller); - virtual void OnError(media::AudioOutputController* controller, - int error_code); - virtual void OnMoreData(media::AudioOutputController* controller, - AudioBuffersState buffers_state); - - private: - friend class AudioRendererHostTest; - friend class BrowserThread; - friend class DeleteTask<AudioRendererHost>; - friend class MockAudioRendererHost; - FRIEND_TEST_ALL_PREFIXES(AudioRendererHostTest, CreateMockStream); - FRIEND_TEST_ALL_PREFIXES(AudioRendererHostTest, MockStreamDataConversation); - - virtual ~AudioRendererHost(); - - //////////////////////////////////////////////////////////////////////////// - // Methods called on IO thread. - // Returns true if the message is an audio related message and should be - // handled by this class. - bool IsAudioRendererHostMessage(const IPC::Message& message); - - // Audio related IPC message handlers. - // Creates an audio output stream with the specified format. If this call is - // successful this object would keep an internal entry of the stream for the - // required properties. - void OnCreateStream(const IPC::Message& msg, int stream_id, - const ViewHostMsg_Audio_CreateStream_Params& params, - bool low_latency); - - // Play the audio stream referenced by |stream_id|. - void OnPlayStream(const IPC::Message& msg, int stream_id); - - // Pause the audio stream referenced by |stream_id|. - void OnPauseStream(const IPC::Message& msg, int stream_id); - - // Discard all audio data in stream referenced by |stream_id|. - void OnFlushStream(const IPC::Message& msg, int stream_id); - - // Close the audio stream referenced by |stream_id|. - void OnCloseStream(const IPC::Message& msg, int stream_id); - - // Set the volume of the audio stream referenced by |stream_id|. - void OnSetVolume(const IPC::Message& msg, int stream_id, double volume); - - // Get the volume of the audio stream referenced by |stream_id|. - void OnGetVolume(const IPC::Message& msg, int stream_id); - - // Notify packet has been prepared for the audio stream. - void OnNotifyPacketReady(const IPC::Message& msg, int stream_id, - uint32 packet_size); - - // Complete the process of creating an audio stream. This will set up the - // shared memory or shared socket in low latency mode. - void DoCompleteCreation(media::AudioOutputController* controller); - - // Send a state change message to the renderer. - void DoSendPlayingMessage(media::AudioOutputController* controller); - void DoSendPausedMessage(media::AudioOutputController* controller); - - // Request more data from the renderer. This method is used only in normal - // latency mode. - void DoRequestMoreData(media::AudioOutputController* controller, - AudioBuffersState buffers_state); - - // Handle error coming from audio stream. - void DoHandleError(media::AudioOutputController* controller, int error_code); - - // Send an error message to the renderer. - void SendErrorMessage(int32 render_view_id, int32 stream_id); - - // Delete all audio entry and all audio streams - void DeleteEntries(); - - // Closes the stream. The stream is then deleted in DeleteEntry() after it - // is closed. - void CloseAndDeleteStream(AudioEntry* entry); - - // Called on the audio thread after the audio stream is closed. - void OnStreamClosed(AudioEntry* entry); - - // Delete an audio entry and close the related audio stream. - void DeleteEntry(AudioEntry* entry); - - // Delete audio entry and close the related audio stream due to an error, - // and error message is send to the renderer. - void DeleteEntryOnError(AudioEntry* entry); - - // A helper method to look up a AudioEntry with a tuple of render view - // id and stream id. Returns NULL if not found. - AudioEntry* LookupById(int render_view_id, int stream_id); - - // Search for a AudioEntry having the reference to |controller|. - // This method is used to look up an AudioEntry after a controller - // event is received. - AudioEntry* LookupByController(media::AudioOutputController* controller); - - // A map of id to audio sources. - AudioEntryMap audio_entries_; - - DISALLOW_COPY_AND_ASSIGN(AudioRendererHost); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/audio_renderer_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_AUDIO_RENDERER_HOST_H_ diff --git a/chrome/browser/renderer_host/audio_sync_reader.h b/chrome/browser/renderer_host/audio_sync_reader.h index 65c9a1c..b339d68 100644 --- a/chrome/browser/renderer_host/audio_sync_reader.h +++ b/chrome/browser/renderer_host/audio_sync_reader.h @@ -6,51 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_AUDIO_SYNC_READER_H_ #pragma once -#include "base/file_descriptor_posix.h" -#include "base/process.h" -#include "base/sync_socket.h" -#include "media/audio/audio_output_controller.h" - -namespace base { - -class SharedMemory; - -} - -// A AudioOutputController::SyncReader implementation using SyncSocket. This -// is used by AudioOutputController to provide a low latency data source for -// transmitting audio packets between the browser process and the renderer -// process. -class AudioSyncReader : public media::AudioOutputController::SyncReader { - public: - explicit AudioSyncReader(base::SharedMemory* shared_memory); - - virtual ~AudioSyncReader(); - - // media::AudioOutputController::SyncReader implementations. - virtual void UpdatePendingBytes(uint32 bytes); - virtual uint32 Read(void* data, uint32 size); - virtual void Close(); - - bool Init(); - bool PrepareForeignSocketHandle(base::ProcessHandle process_handle, -#if defined(OS_WIN) - base::SyncSocket::Handle* foreign_handle); -#else - base::FileDescriptor* foreign_handle); -#endif - - private: - base::SharedMemory* shared_memory_; - - // A pair of SyncSocket for transmitting audio data. - scoped_ptr<base::SyncSocket> socket_; - - // SyncSocket to be used by the renderer. The reference is released after - // PrepareForeignSocketHandle() is called and ran successfully. - scoped_ptr<base::SyncSocket> foreign_socket_; - - DISALLOW_COPY_AND_ASSIGN(AudioSyncReader); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/audio_sync_reader.h" #endif // CHROME_BROWSER_RENDERER_HOST_AUDIO_SYNC_READER_H_ diff --git a/chrome/browser/renderer_host/backing_store.h b/chrome/browser/renderer_host/backing_store.h index 6df3209..3741df6 100644 --- a/chrome/browser/renderer_host/backing_store.h +++ b/chrome/browser/renderer_host/backing_store.h @@ -6,70 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_H_ #pragma once -#include <vector> - -#include "app/surface/transport_dib.h" -#include "base/basictypes.h" -#include "ui/gfx/size.h" - -class RenderProcessHost; -class RenderWidgetHost; - -namespace gfx { -class Rect; -} - -namespace skia { -class PlatformCanvas; -} - -// Represents a backing store for the pixels in a RenderWidgetHost. -class BackingStore { - public: - virtual ~BackingStore(); - - RenderWidgetHost* render_widget_host() const { return render_widget_host_; } - const gfx::Size& size() { return size_; } - - // The number of bytes that this backing store consumes. The default - // implementation just assumes there's 32 bits per pixel over the current - // size of the screen. Implementations may override this if they have more - // information about the color depth. - virtual size_t MemorySize(); - - // Paints the bitmap from the renderer onto the backing store. bitmap_rect - // gives the location of bitmap, and copy_rects specifies the subregion(s) of - // the backingstore to be painted from the bitmap. - virtual void PaintToBackingStore( - RenderProcessHost* process, - TransportDIB::Id bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects) = 0; - - // Extracts the gives subset of the backing store and copies it to the given - // PlatformCanvas. The PlatformCanvas should not be initialized. This function - // will call initialize() with the correct size. The return value indicates - // success. - virtual bool CopyFromBackingStore(const gfx::Rect& rect, - skia::PlatformCanvas* output) = 0; - - // Scrolls the contents of clip_rect in the backing store by dx or dy (but dx - // and dy cannot both be non-zero). - virtual void ScrollBackingStore(int dx, int dy, - const gfx::Rect& clip_rect, - const gfx::Size& view_size) = 0; - protected: - // Can only be constructed via subclasses. - BackingStore(RenderWidgetHost* widget, const gfx::Size& size); - - private: - // The owner of this backing store. - RenderWidgetHost* render_widget_host_; - - // The size of the backing store. - gfx::Size size_; - - DISALLOW_COPY_AND_ASSIGN(BackingStore); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/backing_store.h" #endif // CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_H_ diff --git a/chrome/browser/renderer_host/backing_store_mac.h b/chrome/browser/renderer_host/backing_store_mac.h index 9c4cc6d..e8f4fa2 100644 --- a/chrome/browser/renderer_host/backing_store_mac.h +++ b/chrome/browser/renderer_host/backing_store_mac.h @@ -6,51 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_MAC_H_ #pragma once -#include "base/basictypes.h" -#include "base/mac/scoped_cftyperef.h" -#include "chrome/browser/renderer_host/backing_store.h" - -class BackingStoreMac : public BackingStore { - public: - BackingStoreMac(RenderWidgetHost* widget, const gfx::Size& size); - virtual ~BackingStoreMac(); - - // A CGLayer that stores the contents of the backing store, cached in GPU - // memory if possible. - CGLayerRef cg_layer() { return cg_layer_; } - - // A CGBitmapContext that stores the contents of the backing store if the - // corresponding Cocoa view has not been inserted into an NSWindow yet. - CGContextRef cg_bitmap() { return cg_bitmap_; } - - // BackingStore implementation. - virtual void PaintToBackingStore( - RenderProcessHost* process, - TransportDIB::Id bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects); - virtual bool CopyFromBackingStore(const gfx::Rect& rect, - skia::PlatformCanvas* output); - virtual void ScrollBackingStore(int dx, int dy, - const gfx::Rect& clip_rect, - const gfx::Size& view_size); - - private: - // Creates a CGLayer associated with its owner view's window's graphics - // context, sized properly for the backing store. Returns NULL if the owner - // is not in a window with a CGContext. cg_layer_ is assigned this method's - // result. - CGLayerRef CreateCGLayer(); - - // Creates a CGBitmapContext sized properly for the backing store. The - // owner view need not be in a window. cg_bitmap_ is assigned this method's - // result. - CGContextRef CreateCGBitmapContext(); - - base::mac::ScopedCFTypeRef<CGContextRef> cg_bitmap_; - base::mac::ScopedCFTypeRef<CGLayerRef> cg_layer_; - - DISALLOW_COPY_AND_ASSIGN(BackingStoreMac); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/backing_store_mac.h" #endif // CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_MAC_H_ diff --git a/chrome/browser/renderer_host/backing_store_manager.h b/chrome/browser/renderer_host/backing_store_manager.h index 63f7bdb..9957106 100644 --- a/chrome/browser/renderer_host/backing_store_manager.h +++ b/chrome/browser/renderer_host/backing_store_manager.h @@ -6,74 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_MANAGER_H_ #pragma once -#include <vector> - -#include "app/surface/transport_dib.h" -#include "base/basictypes.h" -#include "base/process.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/size.h" - -class BackingStore; -class RenderWidgetHost; - -// This class manages backing stores in the browsr. Every RenderWidgetHost is -// associated with a backing store which it requests from this class. The -// hosts don't maintain any references to the backing stores. These backing -// stores are maintained in a cache which can be trimmed as needed. -class BackingStoreManager { - public: - // Returns a backing store which matches the desired dimensions. - // - // backing_store_rect - // The desired backing store dimensions. - // Returns a pointer to the backing store on success, NULL on failure. - static BackingStore* GetBackingStore(RenderWidgetHost* host, - const gfx::Size& desired_size); - - // Makes a backing store which is fully ready for consumption, i.e. the - // bitmap from the renderer has been copied into the backing store. - // - // backing_store_size - // The desired backing store dimensions. - // bitmap_section - // The bitmap section from the renderer. - // bitmap_rect - // The rect to be painted into the backing store - // needs_full_paint - // Set if we need to send out a request to paint the view - // to the renderer. - static void PrepareBackingStore( - RenderWidgetHost* host, - const gfx::Size& backing_store_size, - TransportDIB::Id bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects, - bool* needs_full_paint); - - // Returns a matching backing store for the host. - // Returns NULL if we fail to find one. - static BackingStore* Lookup(RenderWidgetHost* host); - - // Removes the backing store for the host. - static void RemoveBackingStore(RenderWidgetHost* host); - - // Removes all backing stores. - static void RemoveAllBackingStores(); - - // Expires the given backing store. This emulates something getting evicted - // from the cache for the purpose of testing. Returns true if the host was - // removed, false if it wasn't found. - static bool ExpireBackingStoreForTest(RenderWidgetHost* host); - - // Current size in bytes of the backing store cache. - static size_t MemorySize(); - - private: - // Not intended for instantiation. - BackingStoreManager() {} - - DISALLOW_COPY_AND_ASSIGN(BackingStoreManager); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/backing_store_manager.h" #endif // CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_MANAGER_H_ diff --git a/chrome/browser/renderer_host/backing_store_skia.h b/chrome/browser/renderer_host/backing_store_skia.h index 4185496..338e1b3 100644 --- a/chrome/browser/renderer_host/backing_store_skia.h +++ b/chrome/browser/renderer_host/backing_store_skia.h @@ -6,46 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_SKIA_H_ #pragma once -#include "base/scoped_ptr.h" -#include "chrome/browser/renderer_host/backing_store.h" -#include "third_party/skia/include/core/SkBitmap.h" - -class SkCanvas; - -namespace gfx { -class Point; -class Canvas; -} - -// A backing store that uses skia. This is a temporary backing store used by -// RenderWidgetHostViewViews. In time, only GPU rendering will be used for -// RWHVV, and then this backing store will be removed. -class BackingStoreSkia : public BackingStore { - public: - BackingStoreSkia(RenderWidgetHost* widget, const gfx::Size& size); - virtual ~BackingStoreSkia(); - - void SkiaShowRect(const gfx::Point& point, gfx::Canvas* canvas); - - // BackingStore implementation. - virtual size_t MemorySize(); - virtual void PaintToBackingStore( - RenderProcessHost* process, - TransportDIB::Id bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects); - virtual bool CopyFromBackingStore(const gfx::Rect& rect, - skia::PlatformCanvas* output); - virtual void ScrollBackingStore(int dx, int dy, - const gfx::Rect& clip_rect, - const gfx::Size& view_size); - - private: - SkBitmap bitmap_; - - scoped_ptr<SkCanvas> canvas_; - - DISALLOW_COPY_AND_ASSIGN(BackingStoreSkia); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/backing_store_skia.h" #endif // CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_SKIA_H_ diff --git a/chrome/browser/renderer_host/backing_store_win.h b/chrome/browser/renderer_host/backing_store_win.h index ce4c419..69b4458 100644 --- a/chrome/browser/renderer_host/backing_store_win.h +++ b/chrome/browser/renderer_host/backing_store_win.h @@ -6,47 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_WIN_H_ #pragma once -#include <windows.h> - -#include "base/basictypes.h" -#include "chrome/browser/renderer_host/backing_store.h" - -class BackingStoreWin : public BackingStore { - public: - BackingStoreWin(RenderWidgetHost* widget, const gfx::Size& size); - virtual ~BackingStoreWin(); - - HDC hdc() { return hdc_; } - - // Returns true if we should convert to the monitor profile when painting. - static bool ColorManagementEnabled(); - - // BackingStore implementation. - virtual size_t MemorySize(); - virtual void PaintToBackingStore(RenderProcessHost* process, - TransportDIB::Id bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects); - virtual bool CopyFromBackingStore(const gfx::Rect& rect, - skia::PlatformCanvas* output); - virtual void ScrollBackingStore(int dx, int dy, - const gfx::Rect& clip_rect, - const gfx::Size& view_size); - - private: - // The backing store dc. - HDC hdc_; - - // Handle to the backing store dib. - HANDLE backing_store_dib_; - - // Handle to the original bitmap in the dc. - HANDLE original_bitmap_; - - // Number of bits per pixel of the screen. - int color_depth_; - - DISALLOW_COPY_AND_ASSIGN(BackingStoreWin); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/backing_store_win.h" #endif // CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_WIN_H_ diff --git a/chrome/browser/renderer_host/backing_store_x.h b/chrome/browser/renderer_host/backing_store_x.h index ad0db60..e70acef 100644 --- a/chrome/browser/renderer_host/backing_store_x.h +++ b/chrome/browser/renderer_host/backing_store_x.h @@ -6,96 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_X_H_ #pragma once -#include "base/basictypes.h" -#include "build/build_config.h" -#include "chrome/browser/renderer_host/backing_store.h" -#include "ui/base/x/x11_util.h" - -namespace gfx { -class Point; -class Rect; -} // namespace gfx - -typedef struct _GdkDrawable GdkDrawable; -class SkBitmap; - -class BackingStoreX : public BackingStore { - public: - // Create a backing store on the X server. The visual is an Xlib Visual - // describing the format of the target window and the depth is the color - // depth of the X window which will be drawn into. - BackingStoreX(RenderWidgetHost* widget, - const gfx::Size& size, - void* visual, - int depth); - - // This is for unittesting only. An object constructed using this constructor - // will silently ignore all paints - BackingStoreX(RenderWidgetHost* widget, const gfx::Size& size); - - virtual ~BackingStoreX(); - - Display* display() const { return display_; } - XID root_window() const { return root_window_; } - - // Copy from the server-side backing store to the target window - // origin: the destination rectangle origin - // damage: the area to copy - // target: the X id of the target window - void XShowRect(const gfx::Point &origin, const gfx::Rect& damage, - XID target); - - // As above, but use Cairo instead of Xlib. - void CairoShowRect(const gfx::Rect& damage, GdkDrawable* drawable); - -#if defined(TOOLKIT_GTK) - // Paint the backing store into the target's |dest_rect|. - void PaintToRect(const gfx::Rect& dest_rect, GdkDrawable* target); -#endif - - // BackingStore implementation. - virtual size_t MemorySize(); - virtual void PaintToBackingStore( - RenderProcessHost* process, - TransportDIB::Id bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects); - virtual bool CopyFromBackingStore(const gfx::Rect& rect, - skia::PlatformCanvas* output); - virtual void ScrollBackingStore(int dx, int dy, - const gfx::Rect& clip_rect, - const gfx::Size& view_size); - - private: - // Paints the bitmap from the renderer onto the backing store without - // using Xrender to composite the pixmaps. - void PaintRectWithoutXrender(TransportDIB* bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects); - - // This is the connection to the X server where this backing store will be - // displayed. - Display* const display_; - // What flavor, if any, MIT-SHM (X shared memory) support we have. - const ui::SharedMemorySupport shared_memory_support_; - // If this is true, then we can use Xrender to composite our pixmaps. - const bool use_render_; - // If |use_render_| is false, this is the number of bits-per-pixel for |depth| - int pixmap_bpp_; - // if |use_render_| is false, we need the Visual to get the RGB masks. - void* const visual_; - // This is the depth of the target window. - const int visual_depth_; - // The parent window (probably a GtkDrawingArea) for this backing store. - const XID root_window_; - // This is a handle to the server side pixmap which is our backing store. - XID pixmap_; - // This is the RENDER picture pointing at |pixmap_|. - XID picture_; - // This is a default graphic context, used in XCopyArea - void* pixmap_gc_; - - DISALLOW_COPY_AND_ASSIGN(BackingStoreX); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/backing_store_x.h" #endif // CHROME_BROWSER_RENDERER_HOST_BACKING_STORE_X_H_ diff --git a/chrome/browser/renderer_host/blob_message_filter.h b/chrome/browser/renderer_host/blob_message_filter.h index 2809763..af6728e 100644 --- a/chrome/browser/renderer_host/blob_message_filter.h +++ b/chrome/browser/renderer_host/blob_message_filter.h @@ -5,47 +5,7 @@ #ifndef CHROME_BROWSER_RENDERER_HOST_BLOB_MESSAGE_FILTER_H_ #define CHROME_BROWSER_RENDERER_HOST_BLOB_MESSAGE_FILTER_H_ -#include "base/hash_tables.h" -#include "chrome/browser/browser_message_filter.h" - -class ChromeBlobStorageContext; -class GURL; - -namespace IPC { -class Message; -} - -namespace webkit_blob { -class BlobData; -} - -class BlobMessageFilter : public BrowserMessageFilter { - public: - BlobMessageFilter(int process_id, - ChromeBlobStorageContext* blob_storage_context); - ~BlobMessageFilter(); - - // BrowserMessageFilter implementation. - virtual void OnChannelClosing(); - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - - private: - void OnRegisterBlobUrl(const GURL& url, - const scoped_refptr<webkit_blob::BlobData>& blob_data); - void OnRegisterBlobUrlFrom(const GURL& url, const GURL& src_url); - void OnUnregisterBlobUrl(const GURL& url); - - bool CheckPermission(webkit_blob::BlobData* blob_data) const; - - int process_id_; - scoped_refptr<ChromeBlobStorageContext> blob_storage_context_; - - // Keep track of blob URLs registered in this process. Need to unregister - // all of them when the renderer process dies. - base::hash_set<std::string> blob_urls_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(BlobMessageFilter); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/blob_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_BLOB_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/buffered_resource_handler.h b/chrome/browser/renderer_host/buffered_resource_handler.h index 029db3f..b18fed5 100644 --- a/chrome/browser/renderer_host/buffered_resource_handler.h +++ b/chrome/browser/renderer_host/buffered_resource_handler.h @@ -6,94 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_BUFFERED_RESOURCE_HANDLER_H_ #pragma once -#include <string> - -#include "chrome/browser/renderer_host/resource_handler.h" - -class MessageLoop; -class ResourceDispatcherHost; - -namespace net { -class URLRequest; -} // namespace net - -// Used to buffer a request until enough data has been received. -class BufferedResourceHandler : public ResourceHandler { - public: - BufferedResourceHandler(ResourceHandler* handler, - ResourceDispatcherHost* host, - net::URLRequest* request); - - // ResourceHandler implementation: - virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); - virtual bool OnRequestRedirected(int request_id, const GURL& new_url, - ResourceResponse* response, bool* defer); - virtual bool OnResponseStarted(int request_id, ResourceResponse* response); - virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); - virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, - int min_size); - virtual bool OnReadCompleted(int request_id, int* bytes_read); - virtual bool OnResponseCompleted(int request_id, - const net::URLRequestStatus& status, - const std::string& security_info); - virtual void OnRequestClosed(); - - private: - virtual ~BufferedResourceHandler(); - - // Returns true if we should delay OnResponseStarted forwarding. - bool DelayResponse(); - - // Returns true if there will be a need to parse the DocType of the document - // to determine the right way to handle it. - bool ShouldBuffer(const GURL& url, const std::string& mime_type); - - // Returns true if there is enough information to process the DocType. - bool DidBufferEnough(int bytes_read); - - // Returns true if we have to keep buffering data. - bool KeepBuffering(int bytes_read); - - // Sends a pending OnResponseStarted notification. |in_complete| is true if - // this is invoked from |OnResponseCompleted|. - bool CompleteResponseStarted(int request_id, bool in_complete); - - // Returns true if we have to wait until the plugin list is generated. - bool ShouldWaitForPlugins(); - - // A test to determining whether the request should be forwarded to the - // download thread. If need_plugin_list was passed in and was set to true, - // that means that the check couldn't be fully done because the plugins aren't - // loaded. The function should be called again after the plugin list is - // loaded. - bool ShouldDownload(bool* need_plugin_list); - - // Informs the original ResourceHandler |real_handler_| that the response will - // be handled entirely by the new ResourceHandler |handler|. - // A reference to |handler| is acquired. - void UseAlternateResourceHandler(int request_id, ResourceHandler* handler); - - // Called on the file thread to load the list of plugins. - void LoadPlugins(); - - // Called on the IO thread once the list of plugins has been loaded. - void OnPluginsLoaded(); - - scoped_refptr<ResourceHandler> real_handler_; - scoped_refptr<ResourceResponse> response_; - ResourceDispatcherHost* host_; - net::URLRequest* request_; - scoped_refptr<net::IOBuffer> read_buffer_; - scoped_refptr<net::IOBuffer> my_buffer_; - int read_buffer_size_; - int bytes_read_; - bool sniff_content_; - bool should_buffer_; - bool wait_for_plugins_; - bool buffering_; - bool finished_; - - DISALLOW_COPY_AND_ASSIGN(BufferedResourceHandler); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/buffered_resource_handler.h" #endif // CHROME_BROWSER_RENDERER_HOST_BUFFERED_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/cross_site_resource_handler.h b/chrome/browser/renderer_host/cross_site_resource_handler.h index 00006bf..c7ab914 100644 --- a/chrome/browser/renderer_host/cross_site_resource_handler.h +++ b/chrome/browser/renderer_host/cross_site_resource_handler.h @@ -6,66 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_CROSS_SITE_RESOURCE_HANDLER_H_ #pragma once -#include "chrome/browser/renderer_host/resource_handler.h" -#include "net/url_request/url_request_status.h" - -class ResourceDispatcherHost; -struct GlobalRequestID; - -// Ensures that cross-site responses are delayed until the onunload handler of -// the previous page is allowed to run. This handler wraps an -// AsyncEventHandler, and it sits inside SafeBrowsing and Buffered event -// handlers. This is important, so that it can intercept OnResponseStarted -// after we determine that a response is safe and not a download. -class CrossSiteResourceHandler : public ResourceHandler { - public: - CrossSiteResourceHandler(ResourceHandler* handler, - int render_process_host_id, - int render_view_id, - ResourceDispatcherHost* resource_dispatcher_host); - - // ResourceHandler implementation: - virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); - virtual bool OnRequestRedirected(int request_id, const GURL& new_url, - ResourceResponse* response, bool* defer); - virtual bool OnResponseStarted(int request_id, - ResourceResponse* response); - virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); - virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, - int min_size); - virtual bool OnReadCompleted(int request_id, int* bytes_read); - virtual bool OnResponseCompleted(int request_id, - const net::URLRequestStatus& status, - const std::string& security_info); - virtual void OnRequestClosed(); - - // We can now send the response to the new renderer, which will cause - // TabContents to swap in the new renderer and destroy the old one. - void ResumeResponse(); - - private: - virtual ~CrossSiteResourceHandler(); - - // Prepare to render the cross-site response in a new RenderViewHost, by - // telling the old RenderViewHost to run its onunload handler. - void StartCrossSiteTransition( - int request_id, - ResourceResponse* response, - const GlobalRequestID& global_id); - - scoped_refptr<ResourceHandler> next_handler_; - int render_process_host_id_; - int render_view_id_; - bool has_started_response_; - bool in_cross_site_transition_; - int request_id_; - bool completed_during_transition_; - net::URLRequestStatus completed_status_; - std::string completed_security_info_; - ResourceResponse* response_; - ResourceDispatcherHost* rdh_; - - DISALLOW_COPY_AND_ASSIGN(CrossSiteResourceHandler); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/cross_site_resource_handler.h" #endif // CHROME_BROWSER_RENDERER_HOST_CROSS_SITE_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/database_message_filter.h b/chrome/browser/renderer_host/database_message_filter.h index 4bd9994..a941e6a 100644 --- a/chrome/browser/renderer_host/database_message_filter.h +++ b/chrome/browser/renderer_host/database_message_filter.h @@ -6,98 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_DATABASE_MESSAGE_FILTER_H_ #pragma once -#include "base/hash_tables.h" -#include "base/string16.h" -#include "chrome/browser/browser_message_filter.h" -#include "chrome/common/content_settings.h" -#include "webkit/database/database_connections.h" -#include "webkit/database/database_tracker.h" - -class HostContentSettingsMap; - -class DatabaseMessageFilter - : public BrowserMessageFilter, - public webkit_database::DatabaseTracker::Observer { - public: - DatabaseMessageFilter( - webkit_database::DatabaseTracker* db_tracker, - HostContentSettingsMap *host_content_settings_map); - - // BrowserMessageFilter implementation. - virtual void OnChannelClosing(); - virtual void OverrideThreadForMessage(const IPC::Message& message, - BrowserThread::ID* thread); - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - - webkit_database::DatabaseTracker* database_tracker() const { - return db_tracker_.get(); - } - - private: - virtual ~DatabaseMessageFilter(); - - class PromptDelegate; - - void AddObserver(); - void RemoveObserver(); - - // VFS message handlers (file thread) - void OnDatabaseOpenFile(const string16& vfs_file_name, - int desired_flags, - IPC::Message* reply_msg); - void OnDatabaseDeleteFile(const string16& vfs_file_name, - const bool& sync_dir, - IPC::Message* reply_msg); - void OnDatabaseGetFileAttributes(const string16& vfs_file_name, - IPC::Message* reply_msg); - void OnDatabaseGetFileSize(const string16& vfs_file_name, - IPC::Message* reply_msg); - - // Database tracker message handlers (file thread) - void OnDatabaseOpened(const string16& origin_identifier, - const string16& database_name, - const string16& description, - int64 estimated_size); - void OnDatabaseModified(const string16& origin_identifier, - const string16& database_name); - void OnDatabaseClosed(const string16& origin_identifier, - const string16& database_name); - void OnAllowDatabase(const std::string& origin_url, - const string16& name, - const string16& display_name, - unsigned long estimated_size, - IPC::Message* reply_msg); - - // DatabaseTracker::Observer callbacks (file thread) - virtual void OnDatabaseSizeChanged(const string16& origin_identifier, - const string16& database_name, - int64 database_size, - int64 space_available); - virtual void OnDatabaseScheduledForDeletion(const string16& origin_identifier, - const string16& database_name); - - void DatabaseDeleteFile(const string16& vfs_file_name, - bool sync_dir, - IPC::Message* reply_msg, - int reschedule_count); - - // CookiePromptModalDialog response handler (io thread) - void AllowDatabaseResponse(IPC::Message* reply_msg, - ContentSetting content_setting); - - // The database tracker for the current profile. - scoped_refptr<webkit_database::DatabaseTracker> db_tracker_; - - // True if and only if this instance was added as an observer - // to DatabaseTracker. - bool observer_added_; - - // Keeps track of all DB connections opened by this renderer - webkit_database::DatabaseConnections database_connections_; - - // Used to look up permissions at database creation time. - scoped_refptr<HostContentSettingsMap> host_content_settings_map_; -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/database_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_DATABASE_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/file_utilities_message_filter.h b/chrome/browser/renderer_host/file_utilities_message_filter.h index 9a1c9af..ab7a89a 100644 --- a/chrome/browser/renderer_host/file_utilities_message_filter.h +++ b/chrome/browser/renderer_host/file_utilities_message_filter.h @@ -5,44 +5,7 @@ #ifndef CHROME_BROWSER_RENDERER_HOST_FILE_UTILITIES_MESSAGE_FILTER_H_ #define CHROME_BROWSER_RENDERER_HOST_FILE_UTILITIES_MESSAGE_FILTER_H_ -#include "base/basictypes.h" -#include "base/file_path.h" -#include "chrome/browser/browser_message_filter.h" -#include "ipc/ipc_platform_file.h" - -namespace base { -struct PlatformFileInfo; -} - -namespace IPC { -class Message; -} - -class FileUtilitiesMessageFilter : public BrowserMessageFilter { - public: - explicit FileUtilitiesMessageFilter(int process_id); - - // BrowserMessageFilter implementation. - virtual void OverrideThreadForMessage(const IPC::Message& message, - BrowserThread::ID* thread); - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - private: - ~FileUtilitiesMessageFilter(); - - typedef void (*FileInfoWriteFunc)(IPC::Message* reply_msg, - const base::PlatformFileInfo& file_info); - - void OnGetFileSize(const FilePath& path, int64* result); - void OnGetFileModificationTime(const FilePath& path, base::Time* result); - void OnOpenFile(const FilePath& path, - int mode, - IPC::PlatformFileForTransit* result); - - // The ID of this process. - int process_id_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(FileUtilitiesMessageFilter); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/file_utilities_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_FILE_UTILITIES_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/global_request_id.h b/chrome/browser/renderer_host/global_request_id.h index cb87c39..e269969 100644 --- a/chrome/browser/renderer_host/global_request_id.h +++ b/chrome/browser/renderer_host/global_request_id.h @@ -6,27 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_GLOBAL_REQUEST_ID_H_ #pragma once -// Uniquely identifies a net::URLRequest. -struct GlobalRequestID { - GlobalRequestID() : child_id(-1), request_id(-1) { - } - - GlobalRequestID(int child_id, int request_id) - : child_id(child_id), - request_id(request_id) { - } - - // The unique ID of the child process (different from OS's PID). - int child_id; - - // The request ID (unique for the child). - int request_id; - - bool operator<(const GlobalRequestID& other) const { - if (child_id == other.child_id) - return request_id < other.request_id; - return child_id < other.child_id; - } -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/global_request_id.h" #endif // CHROME_BROWSER_RENDERER_HOST_GLOBAL_REQUEST_ID_H_ diff --git a/chrome/browser/renderer_host/gpu_message_filter.h b/chrome/browser/renderer_host/gpu_message_filter.h index 12e42d0..251602a 100644 --- a/chrome/browser/renderer_host/gpu_message_filter.h +++ b/chrome/browser/renderer_host/gpu_message_filter.h @@ -6,46 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_GPU_MESSAGE_FILTER_H_ #pragma once -#include "chrome/browser/browser_message_filter.h" - -struct GPUCreateCommandBufferConfig; -class GPUInfo; - -namespace IPC { -struct ChannelHandle; -} - -// A message filter for messages from the renderer to the GpuProcessHost -// in the browser. Such messages are typically destined for the GPU process, -// but need to be mediated by the browser. -class GpuMessageFilter : public BrowserMessageFilter, - public base::SupportsWeakPtr<GpuMessageFilter> { - public: - explicit GpuMessageFilter(int render_process_id); - - // BrowserMessageFilter methods: - virtual void OverrideThreadForMessage(const IPC::Message& message, - BrowserThread::ID* thread); - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - virtual void OnDestruct() const; - - private: - friend class BrowserThread; - friend class DeleteTask<GpuMessageFilter>; - virtual ~GpuMessageFilter(); - - // Message handlers called on the browser IO thread: - void OnEstablishGpuChannel(); - void OnSynchronizeGpu(IPC::Message* reply); - void OnCreateViewCommandBuffer( - int32 render_view_id, - const GPUCreateCommandBufferConfig& init_params, - IPC::Message* reply); - - int render_process_id_; - - DISALLOW_COPY_AND_ASSIGN(GpuMessageFilter); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/gpu_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_GPU_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/mock_render_process_host.h b/chrome/browser/renderer_host/mock_render_process_host.h index 0e67224..92b333a 100644 --- a/chrome/browser/renderer_host/mock_render_process_host.h +++ b/chrome/browser/renderer_host/mock_render_process_host.h @@ -6,97 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_MOCK_RENDER_PROCESS_HOST_H_ #pragma once -#include "base/basictypes.h" -#include "base/scoped_vector.h" -#include "chrome/browser/renderer_host/render_process_host.h" -#include "ipc/ipc_test_sink.h" - -class MockRenderProcessHostFactory; -class TransportDIB; -class URLRequestContextGetter; - -// A mock render process host that has no corresponding renderer process. All -// IPC messages are sent into the message sink for inspection by tests. -class MockRenderProcessHost : public RenderProcessHost { - public: - explicit MockRenderProcessHost(Profile* profile); - virtual ~MockRenderProcessHost(); - - // Provides access to all IPC messages that would have been sent to the - // renderer via this RenderProcessHost. - IPC::TestSink& sink() { return sink_; } - - // Provides tests access to the max page ID currently used for this process. - int max_page_id() const { return max_page_id_; } - - // Provides test access to how many times a bad message has been received. - int bad_msg_count() const { return bad_msg_count_; } - - // RenderProcessHost implementation (public portion). - virtual bool Init(bool is_accessibility_enabled, bool is_extensions_process); - virtual int GetNextRoutingID(); - virtual void CancelResourceRequests(int render_widget_id); - virtual void CrossSiteClosePageACK(const ViewMsg_ClosePage_Params& params); - virtual bool WaitForUpdateMsg(int render_widget_id, - const base::TimeDelta& max_delay, - IPC::Message* msg); - virtual void ReceivedBadMessage(); - virtual void WidgetRestored(); - virtual void WidgetHidden(); - virtual void ViewCreated(); - virtual void AddWord(const string16& word); - virtual void SendVisitedLinkTable(base::SharedMemory* table_memory); - virtual void AddVisitedLinks( - const VisitedLinkCommon::Fingerprints& visited_links); - virtual void ResetVisitedLinks(); - virtual bool FastShutdownIfPossible(); - virtual bool SendWithTimeout(IPC::Message* msg, int timeout_ms); - virtual base::ProcessHandle GetHandle(); - - virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id); - - // IPC::Channel::Sender via RenderProcessHost. - virtual bool Send(IPC::Message* msg); - - // IPC::Channel::Listener via RenderProcessHost. - virtual bool OnMessageReceived(const IPC::Message& msg); - virtual void OnChannelConnected(int32 peer_pid); - - // Attaches the factory object so we can remove this object in its destructor - // and prevent MockRenderProcessHostFacotry from deleting it. - void SetFactory(const MockRenderProcessHostFactory* factory) { - factory_ = factory; - } - - private: - // Stores IPC messages that would have been sent to the renderer. - IPC::TestSink sink_; - TransportDIB* transport_dib_; - int bad_msg_count_; - const MockRenderProcessHostFactory* factory_; - - DISALLOW_COPY_AND_ASSIGN(MockRenderProcessHost); -}; - -class MockRenderProcessHostFactory : public RenderProcessHostFactory { - public: - MockRenderProcessHostFactory(); - virtual ~MockRenderProcessHostFactory(); - - virtual RenderProcessHost* CreateRenderProcessHost(Profile* profile) const; - - // Removes the given MockRenderProcessHost from the MockRenderProcessHost list - // without deleting it. When a test deletes a MockRenderProcessHost, we need - // to remove it from |processes_| to prevent it from being deleted twice. - void Remove(MockRenderProcessHost* host) const; - - private: - // A list of MockRenderProcessHosts created by this object. This list is used - // for deleting all MockRenderProcessHosts that have not deleted by a test in - // the destructor and prevent them from being leaked. - mutable ScopedVector<MockRenderProcessHost> processes_; - - DISALLOW_COPY_AND_ASSIGN(MockRenderProcessHostFactory); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/mock_render_process_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_MOCK_RENDER_PROCESS_HOST_H_ diff --git a/chrome/browser/renderer_host/pepper_file_message_filter.h b/chrome/browser/renderer_host/pepper_file_message_filter.h index fbcd5e5..7ab4648 100644 --- a/chrome/browser/renderer_host/pepper_file_message_filter.h +++ b/chrome/browser/renderer_host/pepper_file_message_filter.h @@ -6,67 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_PEPPER_FILE_MESSAGE_FILTER_H_ #pragma once -#include <string> -#include <vector> - -#include "base/file_path.h" -#include "base/process.h" -#include "base/ref_counted.h" -#include "base/task.h" -#include "build/build_config.h" -#include "chrome/browser/browser_message_filter.h" -#include "ipc/ipc_platform_file.h" -#include "webkit/plugins/ppapi/dir_contents.h" - -class Profile; - -// A message filter for Pepper-specific File I/O messages. -class PepperFileMessageFilter : public BrowserMessageFilter { - public: - PepperFileMessageFilter(int child_id, Profile* profile); - - // BrowserMessageFilter methods: - virtual void OverrideThreadForMessage(const IPC::Message& message, - BrowserThread::ID* thread); - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - virtual void OnDestruct() const; - - private: - friend class BrowserThread; - friend class DeleteTask<PepperFileMessageFilter>; - virtual ~PepperFileMessageFilter(); - - // Called on the FILE thread: - void OnPepperOpenFile(const FilePath& path, - int flags, - base::PlatformFileError* error, - IPC::PlatformFileForTransit* file); - void OnPepperRenameFile(const FilePath& path_from, - const FilePath& path_to, - base::PlatformFileError* error); - void OnPepperDeleteFileOrDir(const FilePath& path, - bool recursive, - base::PlatformFileError* error); - void OnPepperCreateDir(const FilePath& path, - base::PlatformFileError* error); - void OnPepperQueryFile(const FilePath& path, - base::PlatformFileInfo* info, - base::PlatformFileError* error); - void OnPepperGetDirContents(const FilePath& path, - webkit::ppapi::DirContents* contents, - base::PlatformFileError* error); - - FilePath MakePepperPath(const FilePath& base_path); - - // The channel associated with the renderer connection. This pointer is not - // owned by this class. - IPC::Channel* channel_; - - // The base path for the pepper data. - FilePath pepper_path_; - - DISALLOW_COPY_AND_ASSIGN(PepperFileMessageFilter); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/pepper_file_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_PEPPER_FILE_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/pepper_message_filter.h b/chrome/browser/renderer_host/pepper_message_filter.h index 17ccf11..0022fa6 100644 --- a/chrome/browser/renderer_host/pepper_message_filter.h +++ b/chrome/browser/renderer_host/pepper_message_filter.h @@ -6,65 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_PEPPER_MESSAGE_FILTER_H_ #pragma once -#include <string> - -#include "base/basictypes.h" -#include "base/process.h" -#include "chrome/browser/browser_message_filter.h" -#include "ipc/ipc_channel_proxy.h" -#include "ppapi/c/private/ppb_flash.h" - -class Profile; -class URLRequestContextGetter; - -namespace net { -class AddressList; -} - -class PepperMessageFilter : public BrowserMessageFilter { - public: - explicit PepperMessageFilter(Profile* profile); - virtual ~PepperMessageFilter(); - - private: - // BrowserMessageFilter methods. - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - -#if defined(ENABLE_FLAPPER_HACKS) - // Message handlers. - void OnConnectTcp(int routing_id, - int request_id, - const std::string& host, - uint16 port); - void OnConnectTcpAddress(int routing_id, - int request_id, - const PP_Flash_NetAddress& address); - - // |Send()| a |PepperMsg_ConnectTcpACK|, which reports an error. - bool SendConnectTcpACKError(int routing_id, - int request_id); - - // Used by |OnConnectTcp()| (below). - class LookupRequest; - friend class LookupRequest; - - // Continuation of |OnConnectTcp()|. - void ConnectTcpLookupFinished(int routing_id, - int request_id, - const net::AddressList& addresses); - void ConnectTcpOnWorkerThread(int routing_id, - int request_id, - net::AddressList addresses); - - // Continuation of |OnConnectTcpAddress()|. - void ConnectTcpAddressOnWorkerThread(int routing_id, - int request_id, - PP_Flash_NetAddress addr); -#endif // ENABLE_FLAPPER_HACKS - - Profile* profile_; - scoped_refptr<URLRequestContextGetter> request_context_; -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/pepper_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_PEPPER_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/redirect_to_file_resource_handler.h b/chrome/browser/renderer_host/redirect_to_file_resource_handler.h index 2d7ceed..23ad4cb 100644 --- a/chrome/browser/renderer_host/redirect_to_file_resource_handler.h +++ b/chrome/browser/renderer_host/redirect_to_file_resource_handler.h @@ -5,85 +5,7 @@ #ifndef CHROME_BROWSER_RENDERER_HOST_REDIRECT_TO_FILE_RESOURCE_HANDLER_H_ #define CHROME_BROWSER_RENDERER_HOST_REDIRECT_TO_FILE_RESOURCE_HANDLER_H_ -#include "base/file_path.h" -#include "base/platform_file.h" -#include "base/ref_counted.h" -#include "base/scoped_callback_factory.h" -#include "base/scoped_ptr.h" -#include "chrome/browser/renderer_host/resource_handler.h" -#include "net/base/completion_callback.h" - -class RefCountedPlatformFile; -class ResourceDispatcherHost; - -namespace net { -class FileStream; -class GrowableIOBuffer; -} - -namespace webkit_blob { -class DeletableFileReference; -} - -// Redirects network data to a file. This is intended to be layered in front -// of either the AsyncResourceHandler or the SyncResourceHandler. -class RedirectToFileResourceHandler : public ResourceHandler { - public: - RedirectToFileResourceHandler( - ResourceHandler* next_handler, - int process_id, - ResourceDispatcherHost* resource_dispatcher_host); - - // ResourceHandler implementation: - virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); - virtual bool OnRequestRedirected(int request_id, const GURL& new_url, - ResourceResponse* response, bool* defer); - virtual bool OnResponseStarted(int request_id, ResourceResponse* response); - virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); - virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, - int min_size); - virtual bool OnReadCompleted(int request_id, int* bytes_read); - virtual bool OnResponseCompleted(int request_id, - const net::URLRequestStatus& status, - const std::string& security_info); - virtual void OnRequestClosed(); - - private: - virtual ~RedirectToFileResourceHandler(); - void DidCreateTemporaryFile(base::PlatformFileError error_code, - base::PassPlatformFile file_handle, - FilePath file_path); - void DidWriteToFile(int result); - bool WriteMore(); - bool BufIsFull() const; - - base::ScopedCallbackFactory<RedirectToFileResourceHandler> callback_factory_; - - ResourceDispatcherHost* host_; - scoped_refptr<ResourceHandler> next_handler_; - int process_id_; - int request_id_; - - // We allocate a single, fixed-size IO buffer (buf_) used to read from the - // network (buf_write_pending_ is true while the system is copying data into - // buf_), and then write this buffer out to disk (write_callback_pending_ is - // true while writing to disk). Reading from the network is suspended while - // the buffer is full (BufIsFull returns true). The write_cursor_ member - // tracks the offset into buf_ that we are writing to disk. - - scoped_refptr<net::GrowableIOBuffer> buf_; - bool buf_write_pending_; - int write_cursor_; - - scoped_ptr<net::FileStream> file_stream_; - net::CompletionCallbackImpl<RedirectToFileResourceHandler> write_callback_; - bool write_callback_pending_; - - // We create a DeletableFileReference for the temp file created as - // a result of the download. - scoped_refptr<webkit_blob::DeletableFileReference> deletable_file_; - - DISALLOW_COPY_AND_ASSIGN(RedirectToFileResourceHandler); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/redirect_to_file_resource_handler.h" #endif // CHROME_BROWSER_RENDERER_HOST_REDIRECT_TO_FILE_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/render_message_filter.h b/chrome/browser/renderer_host/render_message_filter.h index de80fa2..f05119c 100644 --- a/chrome/browser/renderer_host/render_message_filter.h +++ b/chrome/browser/renderer_host/render_message_filter.h @@ -6,493 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_MESSAGE_FILTER_H_ #pragma once -#if defined(OS_WIN) -#include <windows.h> -#endif - -#include <string> -#include <vector> - -#include "app/surface/transport_dib.h" -#include "base/file_path.h" -#include "base/linked_ptr.h" -#include "base/string16.h" -#include "base/task.h" -#include "build/build_config.h" -#include "chrome/browser/browser_message_filter.h" -#include "chrome/browser/in_process_webkit/webkit_context.h" -#include "chrome/browser/net/resolve_proxy_msg_helper.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/common/content_settings.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebCache.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/gfx/native_widget_types.h" - -class ChromeURLRequestContext; -struct FontDescriptor; -class HostContentSettingsMap; -class HostZoomMap; -class NotificationsPrefsCache; -class Profile; -class RenderWidgetHelper; -class URLRequestContextGetter; -struct ViewHostMsg_CreateWindow_Params; -struct ViewHostMsg_CreateWorker_Params; - -namespace webkit { -namespace npapi { -struct WebPluginInfo; -} -} - -namespace base { -class SharedMemory; -} - -namespace net { -class CookieStore; -} - -namespace printing { -class PrinterQuery; -class PrintJobManager; -} - -struct ViewHostMsg_ScriptedPrint_Params; - -// This class filters out incoming IPC messages for the renderer process on the -// IPC thread. -class RenderMessageFilter : public BrowserMessageFilter, - public ResolveProxyMsgHelper::Delegate { - public: - // Create the filter. - RenderMessageFilter(int render_process_id, - PluginService* plugin_service, - Profile* profile, - RenderWidgetHelper* render_widget_helper); - - // BrowserMessageFilter methods: - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - virtual void OnDestruct() const; - - int render_process_id() const { return render_process_id_; } - ResourceDispatcherHost* resource_dispatcher_host() { - return resource_dispatcher_host_; - } - bool off_the_record() { return off_the_record_; } - - // Returns either the extension net::URLRequestContext or regular - // net::URLRequestContext depending on whether |url| is an extension URL. - // Only call on the IO thread. - ChromeURLRequestContext* GetRequestContextForURL(const GURL& url); - - private: - friend class BrowserThread; - friend class DeleteTask<RenderMessageFilter>; - - virtual ~RenderMessageFilter(); - - void OnMsgCreateWindow(const ViewHostMsg_CreateWindow_Params& params, - int* route_id, - int64* cloned_session_storage_namespace_id); - void OnMsgCreateWidget(int opener_id, - WebKit::WebPopupType popup_type, - int* route_id); - void OnMsgCreateFullscreenWidget(int opener_id, int* route_id); - void OnSetCookie(const IPC::Message& message, - const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie); - void OnGetCookies(const GURL& url, - const GURL& first_party_for_cookies, - IPC::Message* reply_msg); - void OnGetRawCookies(const GURL& url, - const GURL& first_party_for_cookies, - IPC::Message* reply_msg); - void OnDeleteCookie(const GURL& url, - const std::string& cookieName); - void OnCookiesEnabled(const GURL& url, - const GURL& first_party_for_cookies, - IPC::Message* reply_msg); - void OnPluginFileDialog(const IPC::Message& msg, - bool multiple_files, - const std::wstring& title, - const std::wstring& filter, - uint32 user_data); - -#if defined(OS_MACOSX) - void OnLoadFont(const FontDescriptor& font, - uint32* handle_size, - base::SharedMemoryHandle* handle); -#endif - -#if defined(OS_WIN) // This hack is Windows-specific. - // Cache fonts for the renderer. See RenderMessageFilter::OnPreCacheFont - // implementation for more details. - void OnPreCacheFont(LOGFONT font); -#endif - -#if !defined(OS_MACOSX) - // Not handled in the IO thread on Mac. - void OnGetScreenInfo(gfx::NativeViewId window, IPC::Message* reply); -#endif - void OnGetPlugins(bool refresh, IPC::Message* reply_msg); - void OnGetPluginsOnFileThread(bool refresh, IPC::Message* reply_msg); - void OnGetPluginInfo(int routing_id, - const GURL& url, - const GURL& policy_url, - const std::string& mime_type, - IPC::Message* reply_msg); - void OnGetPluginInfoOnFileThread(int render_view_id, - const GURL& url, - const GURL& policy_url, - const std::string& mime_type, - IPC::Message* reply_msg); - void OnGotPluginInfo(bool found, - const webkit::npapi::WebPluginInfo& info, - const std::string& actual_mime_type, - const GURL& policy_url, - IPC::Message* reply_msg); - void OnOpenChannelToPlugin(int routing_id, - const GURL& url, - const std::string& mime_type, - IPC::Message* reply_msg); - void OnOpenChannelToPepperPlugin(const FilePath& path, - IPC::Message* reply_msg); - void OnLaunchNaCl(const std::wstring& url, - int channel_descriptor, - IPC::Message* reply_msg); - void OnGenerateRoutingID(int* route_id); - void OnDownloadUrl(const IPC::Message& message, - const GURL& url, - const GURL& referrer); - void OnPlatformCheckSpelling(const string16& word, int tag, bool* correct); - void OnPlatformFillSuggestionList(const string16& word, - std::vector<string16>* suggestions); - void OnGetDocumentTag(IPC::Message* reply_msg); - void OnDocumentWithTagClosed(int tag); - void OnShowSpellingPanel(bool show); - void OnUpdateSpellingPanelWithMisspelledWord(const string16& word); - void OnDnsPrefetch(const std::vector<std::string>& hostnames); - void OnRendererHistograms(int sequence_number, - const std::vector<std::string>& histogram_info); -#if defined(USE_TCMALLOC) - void OnRendererTcmalloc(base::ProcessId pid, const std::string& output); -#endif - void OnReceiveContextMenuMsg(const IPC::Message& msg); - // Clipboard messages - void OnClipboardWriteObjectsAsync(const ui::Clipboard::ObjectMap& objects); - void OnClipboardWriteObjectsSync(const ui::Clipboard::ObjectMap& objects, - base::SharedMemoryHandle bitmap_handle); - - void OnClipboardIsFormatAvailable(ui::Clipboard::FormatType format, - ui::Clipboard::Buffer buffer, - IPC::Message* reply); - void OnClipboardReadText(ui::Clipboard::Buffer buffer, IPC::Message* reply); - void OnClipboardReadAsciiText(ui::Clipboard::Buffer buffer, - IPC::Message* reply); - void OnClipboardReadHTML(ui::Clipboard::Buffer buffer, IPC::Message* reply); -#if defined(OS_MACOSX) - void OnClipboardFindPboardWriteString(const string16& text); -#endif - void OnClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer, - IPC::Message* reply); - void OnClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type, - IPC::Message* reply); - void OnClipboardReadFilenames(ui::Clipboard::Buffer buffer, - IPC::Message* reply); - - void OnCheckNotificationPermission(const GURL& source_url, - int* permission_level); - -#if !defined(OS_MACOSX) - // Not handled in the IO thread on Mac. - void OnGetWindowRect(gfx::NativeViewId window, IPC::Message* reply); - void OnGetRootWindowRect(gfx::NativeViewId window, IPC::Message* reply); -#endif - - void OnRevealFolderInOS(const FilePath& path); - void OnGetCPBrowsingContext(uint32* context); - -#if defined(OS_WIN) - // Used to pass resulting EMF from renderer to browser in printing. - void OnDuplicateSection(base::SharedMemoryHandle renderer_handle, - base::SharedMemoryHandle* browser_handle); -#endif - -#if defined(OS_CHROMEOS) - // Used to ask the browser allocate a temporary file for the renderer - // to fill in resulting PDF in renderer. - void OnAllocateTempFileForPrinting(IPC::Message* reply_msg); - void OnTempFileForPrintingWritten(int sequence_number); -#endif - -#if defined(OS_POSIX) - // Used to ask the browser to allocate a block of shared memory for the - // renderer to send back data in, since shared memory can't be created - // in the renderer on POSIX due to the sandbox. - void OnAllocateSharedMemoryBuffer(uint32 buffer_size, - base::SharedMemoryHandle* handle); -#endif - - void OnResourceTypeStats(const WebKit::WebCache::ResourceTypeStats& stats); - static void OnResourceTypeStatsOnUIThread( - const WebKit::WebCache::ResourceTypeStats&, - base::ProcessId renderer_id); - - void OnV8HeapStats(int v8_memory_allocated, int v8_memory_used); - static void OnV8HeapStatsOnUIThread(int v8_memory_allocated, - int v8_memory_used, - base::ProcessId renderer_id); - - void OnDidZoomURL(const IPC::Message& message, - double zoom_level, - bool remember, - const GURL& url); - void UpdateHostZoomLevelsOnUIThread(double zoom_level, - bool remember, - const GURL& url, - int render_process_id, - int render_view_id); - - void OnResolveProxy(const GURL& url, IPC::Message* reply_msg); - - // ResolveProxyMsgHelper::Delegate implementation: - virtual void OnResolveProxyCompleted(IPC::Message* reply_msg, - int result, - const std::string& proxy_list); - - // A javascript code requested to print the current page. This is done in two - // steps and this is the first step. Get the print setting right here - // synchronously. It will hang the I/O completely. - void OnGetDefaultPrintSettings(IPC::Message* reply_msg); - void OnGetDefaultPrintSettingsReply( - scoped_refptr<printing::PrinterQuery> printer_query, - IPC::Message* reply_msg); - - // A javascript code requested to print the current page. The renderer host - // have to show to the user the print dialog and returns the selected print - // settings. - void OnScriptedPrint(const ViewHostMsg_ScriptedPrint_Params& params, - IPC::Message* reply_msg); - void OnScriptedPrintReply( - scoped_refptr<printing::PrinterQuery> printer_query, - int routing_id, - IPC::Message* reply_msg); - - // Browser side transport DIB allocation - void OnAllocTransportDIB(size_t size, - bool cache_in_browser, - TransportDIB::Handle* result); - void OnFreeTransportDIB(TransportDIB::Id dib_id); - - void OnOpenChannelToExtension(int routing_id, - const std::string& source_extension_id, - const std::string& target_extension_id, - const std::string& channel_name, int* port_id); - void OpenChannelToExtensionOnUIThread(int source_process_id, - int source_routing_id, - int receiver_port_id, - const std::string& source_extension_id, - const std::string& target_extension_id, - const std::string& channel_name); - void OnOpenChannelToTab(int routing_id, int tab_id, - const std::string& extension_id, - const std::string& channel_name, int* port_id); - void OpenChannelToTabOnUIThread(int source_process_id, int source_routing_id, - int receiver_port_id, - int tab_id, const std::string& extension_id, - const std::string& channel_name); - - void OnCloseCurrentConnections(); - void OnSetCacheMode(bool enabled); - void OnClearCache(bool preserve_ssl_host_info, IPC::Message* reply_msg); - void OnCacheableMetadataAvailable(const GURL& url, - double expected_response_time, - const std::vector<char>& data); - void OnEnableSpdy(bool enable); - void OnKeygen(uint32 key_size_index, const std::string& challenge_string, - const GURL& url, IPC::Message* reply_msg); - void OnKeygenOnWorkerThread( - int key_size_in_bits, - const std::string& challenge_string, - const GURL& url, - IPC::Message* reply_msg); - void OnGetExtensionMessageBundle(const std::string& extension_id, - IPC::Message* reply_msg); - void OnGetExtensionMessageBundleOnFileThread( - const FilePath& extension_path, - const std::string& extension_id, - const std::string& default_locale, - IPC::Message* reply_msg); - void OnAsyncOpenFile(const IPC::Message& msg, - const FilePath& path, - int flags, - int message_id); - void AsyncOpenFileOnFileThread(const FilePath& path, - int flags, - int message_id, - int routing_id); - -#if defined(USE_X11) - void DoOnGetScreenInfo(gfx::NativeViewId view, IPC::Message* reply_msg); - void DoOnGetWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg); - void DoOnGetRootWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg); - void DoOnClipboardIsFormatAvailable(ui::Clipboard::FormatType format, - ui::Clipboard::Buffer buffer, - IPC::Message* reply_msg); - void DoOnClipboardReadText(ui::Clipboard::Buffer buffer, - IPC::Message* reply_msg); - void DoOnClipboardReadAsciiText(ui::Clipboard::Buffer buffer, - IPC::Message* reply_msg); - void DoOnClipboardReadHTML(ui::Clipboard::Buffer buffer, - IPC::Message* reply_msg); - void DoOnClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer, - IPC::Message* reply_msg); - void DoOnClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type, - IPC::Message* reply_msg); - void DoOnClipboardReadFilenames(ui::Clipboard::Buffer buffer, - IPC::Message* reply_msg); - void DoOnAllocateTempFileForPrinting(IPC::Message* reply_msg); - void DoOnTempFileForPrintingWritten(int sequence_number); -#endif - - bool CheckBenchmarkingEnabled() const; - bool CheckPreparsedJsCachingEnabled() const; - - // We have our own clipboard because we want to access the clipboard on the - // IO thread instead of forwarding (possibly synchronous) messages to the UI - // thread. This instance of the clipboard should be accessed only on the IO - // thread. - static ui::Clipboard* GetClipboard(); - - // Cached resource request dispatcher host and plugin service, guaranteed to - // be non-null if Init succeeds. We do not own the objects, they are managed - // by the BrowserProcess, which has a wider scope than we do. - ResourceDispatcherHost* resource_dispatcher_host_; - PluginService* plugin_service_; - printing::PrintJobManager* print_job_manager_; - - // The Profile associated with our renderer process. This should only be - // accessed on the UI thread! - Profile* profile_; - - // The host content settings map. Stored separately from the profile so we can - // access it on other threads. - HostContentSettingsMap* content_settings_; - - // Helper class for handling PluginProcessHost_ResolveProxy messages (manages - // the requests to the proxy service). - ResolveProxyMsgHelper resolve_proxy_msg_helper_; - - // Contextual information to be used for requests created here. - scoped_refptr<URLRequestContextGetter> request_context_; - - // A request context that holds a cookie store for chrome-extension URLs. - scoped_refptr<URLRequestContextGetter> extensions_request_context_; - - scoped_refptr<RenderWidgetHelper> render_widget_helper_; - - // A cache of notifications preferences which is used to handle - // Desktop Notifications permission messages. - scoped_refptr<NotificationsPrefsCache> notification_prefs_; - - // Handles zoom-related messages. - scoped_refptr<HostZoomMap> host_zoom_map_; - - // Whether this process is used for off the record tabs. - bool off_the_record_; - - bool cloud_print_enabled_; - - base::TimeTicks last_plugin_refresh_time_; // Initialized to 0. - - scoped_refptr<WebKitContext> webkit_context_; - - int render_process_id_; - - DISALLOW_COPY_AND_ASSIGN(RenderMessageFilter); -}; - -// These classes implement completion callbacks for getting and setting -// cookies. -class SetCookieCompletion : public net::CompletionCallback { - public: - SetCookieCompletion(int render_process_id, - int render_view_id, - const GURL& url, - const std::string& cookie_line, - ChromeURLRequestContext* context); - virtual ~SetCookieCompletion(); - - virtual void RunWithParams(const Tuple1<int>& params); - - int render_process_id() const { - return render_process_id_; - } - - int render_view_id() const { - return render_view_id_; - } - - private: - int render_process_id_; - int render_view_id_; - GURL url_; - std::string cookie_line_; - scoped_refptr<ChromeURLRequestContext> context_; -}; - -class GetCookiesCompletion : public net::CompletionCallback { - public: - GetCookiesCompletion(int render_process_id, - int render_view_id, - const GURL& url, IPC::Message* reply_msg, - RenderMessageFilter* filter, - ChromeURLRequestContext* context, - bool raw_cookies); - virtual ~GetCookiesCompletion(); - - virtual void RunWithParams(const Tuple1<int>& params); - - int render_process_id() const { - return render_process_id_; - } - - int render_view_id() const { - return render_view_id_; - } - - void set_cookie_store(net::CookieStore* cookie_store); - - net::CookieStore* cookie_store() { - return cookie_store_.get(); - } - - private: - GURL url_; - IPC::Message* reply_msg_; - scoped_refptr<RenderMessageFilter> filter_; - scoped_refptr<ChromeURLRequestContext> context_; - int render_process_id_; - int render_view_id_; - bool raw_cookies_; - scoped_refptr<net::CookieStore> cookie_store_; -}; - -class CookiesEnabledCompletion : public net::CompletionCallback { - public: - CookiesEnabledCompletion(IPC::Message* reply_msg, - RenderMessageFilter* filter); - virtual ~CookiesEnabledCompletion(); - - virtual void RunWithParams(const Tuple1<int>& params); - - private: - IPC::Message* reply_msg_; - scoped_refptr<RenderMessageFilter> filter_; -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/render_process_host.h b/chrome/browser/renderer_host/render_process_host.h index fa58495..41af810 100644 --- a/chrome/browser/renderer_host/render_process_host.h +++ b/chrome/browser/renderer_host/render_process_host.h @@ -6,322 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ #pragma once -#include <set> - -#include "app/surface/transport_dib.h" -#include "base/id_map.h" -#include "base/process.h" -#include "base/process_util.h" -#include "base/scoped_ptr.h" -#include "base/time.h" -#include "chrome/common/visitedlink_common.h" -#include "ipc/ipc_sync_channel.h" - -class Profile; -class URLRequestContextGetter; -struct ViewMsg_ClosePage_Params; - -namespace base { -class SharedMemory; -} - -// Virtual interface that represents the browser side of the browser <-> -// renderer communication channel. There will generally be one -// RenderProcessHost per renderer process. -// -// The concrete implementation of this class for normal use is the -// BrowserRenderProcessHost. It may also be implemented by a testing interface -// for mocking purposes. -class RenderProcessHost : public IPC::Channel::Sender, - public IPC::Channel::Listener { - public: - typedef IDMap<RenderProcessHost>::iterator iterator; - - // We classify renderers according to their highest privilege, and try - // to group pages into renderers with similar privileges. - // Note: it may be possible for a renderer to have multiple privileges, - // in which case we call it an "extension" renderer. - enum Type { - TYPE_NORMAL, // Normal renderer, no extra privileges. - TYPE_WEBUI, // Renderer with WebUI privileges, like New Tab. - TYPE_EXTENSION, // Renderer with extension privileges. - }; - - // Details for RENDERER_PROCESS_CLOSED notifications. - struct RendererClosedDetails { - RendererClosedDetails(base::TerminationStatus status, - int exit_code, - bool was_extension_renderer) { - this->status = status; - this->exit_code = exit_code; - this->was_extension_renderer = was_extension_renderer; - } - base::TerminationStatus status; - int exit_code; - bool was_extension_renderer; - }; - - explicit RenderProcessHost(Profile* profile); - virtual ~RenderProcessHost(); - - // Returns the user profile associated with this renderer process. - Profile* profile() const { return profile_; } - - // Returns the unique ID for this child process. This can be used later in - // a call to FromID() to get back to this object (this is used to avoid - // sending non-threadsafe pointers to other threads). - // - // This ID will be unique for all child processes, including workers, plugins, - // etc. It is generated by ChildProcessInfo. - int id() const { return id_; } - - // Returns true iff channel_ has been set to non-NULL. Use this for checking - // if there is connection or not. - bool HasConnection() { return channel_.get() != NULL; } - - bool sudden_termination_allowed() const { - return sudden_termination_allowed_; - } - void set_sudden_termination_allowed(bool enabled) { - sudden_termination_allowed_ = enabled; - } - - // Used for refcounting, each holder of this object must Attach and Release - // just like it would for a COM object. This object should be allocated on - // the heap; when no listeners own it any more, it will delete itself. - void Attach(IPC::Channel::Listener* listener, int routing_id); - - // See Attach() - void Release(int listener_id); - - // Listeners should call this when they've sent a "Close" message and - // they're waiting for a "Close_ACK", so that if the renderer process - // goes away we'll know that it was intentional rather than a crash. - void ReportExpectingClose(int32 listener_id); - - // Allows iteration over this RenderProcessHost's RenderViewHost listeners. - // Use from UI thread only. - typedef IDMap<IPC::Channel::Listener>::const_iterator listeners_iterator; - - listeners_iterator ListenersIterator() { - return listeners_iterator(&listeners_); - } - - IPC::Channel::Listener* GetListenerByID(int routing_id) { - return listeners_.Lookup(routing_id); - } - - // Called to inform the render process host of a new "max page id" for a - // render view host. The render process host computes the largest page id - // across all render view hosts and uses the value when it needs to - // initialize a new renderer in place of the current one. - void UpdateMaxPageID(int32 page_id); - - void set_ignore_input_events(bool ignore_input_events) { - ignore_input_events_ = ignore_input_events; - } - bool ignore_input_events() { - return ignore_input_events_; - } - - // Returns how long the child has been idle. The definition of idle - // depends on when a derived class calls mark_child_process_activity_time(). - // This is a rough indicator and its resolution should not be better than - // 10 milliseconds. - base::TimeDelta get_child_process_idle_time() const { - return base::TimeTicks::Now() - child_process_activity_time_; - } - - // Call this function when it is evident that the child process is actively - // performing some operation, for example if we just received an IPC message. - void mark_child_process_activity_time() { - child_process_activity_time_ = base::TimeTicks::Now(); - } - - // Try to shutdown the associated render process as fast as possible, but - // only if |count| matches the number of render widgets that this process - // controls. - bool FastShutdownForPageCount(size_t count); - - bool fast_shutdown_started() { - return fast_shutdown_started_; - } - - // Virtual interface --------------------------------------------------------- - - // Initialize the new renderer process, returning true on success. This must - // be called once before the object can be used, but can be called after - // that with no effect. Therefore, if the caller isn't sure about whether - // the process has been created, it should just call Init(). - virtual bool Init( - bool is_accessibility_enabled, bool is_extensions_process) = 0; - - // Gets the next available routing id. - virtual int GetNextRoutingID() = 0; - - // Called on the UI thread to cancel any outstanding resource requests for - // the specified render widget. - virtual void CancelResourceRequests(int render_widget_id) = 0; - - // Called on the UI thread to simulate a ClosePage_ACK message to the - // ResourceDispatcherHost. Necessary for a cross-site request, in the case - // that the original RenderViewHost is not live and thus cannot run an - // onunload handler. - virtual void CrossSiteClosePageACK( - const ViewMsg_ClosePage_Params& params) = 0; - - // Called on the UI thread to wait for the next UpdateRect message for the - // specified render widget. Returns true if successful, and the msg out- - // param will contain a copy of the received UpdateRect message. - virtual bool WaitForUpdateMsg(int render_widget_id, - const base::TimeDelta& max_delay, - IPC::Message* msg) = 0; - - // Called when a received message cannot be decoded. - virtual void ReceivedBadMessage() = 0; - - // Track the count of visible widgets. Called by listeners to register and - // unregister visibility. - virtual void WidgetRestored() = 0; - virtual void WidgetHidden() = 0; - - // Called when RenderView is created by a listener. - virtual void ViewCreated() = 0; - - // Informs the renderer about a new visited link table. - virtual void SendVisitedLinkTable(base::SharedMemory* table_memory) = 0; - - // Notify the renderer that a link was visited. - virtual void AddVisitedLinks( - const VisitedLinkCommon::Fingerprints& links) = 0; - - // Clear internal visited links buffer and ask the renderer to update link - // coloring state for all of its links. - virtual void ResetVisitedLinks() = 0; - - // Try to shutdown the associated renderer process as fast as possible. - // If this renderer has any RenderViews with unload handlers, then this - // function does nothing. The current implementation uses TerminateProcess. - // Returns True if it was able to do fast shutdown. - virtual bool FastShutdownIfPossible() = 0; - - // Synchronously sends the message, waiting for the specified timeout. The - // implementor takes ownership of the given Message regardless of whether or - // not this method succeeds. Returns true on success. - virtual bool SendWithTimeout(IPC::Message* msg, int timeout_ms) = 0; - - // Returns the process object associated with the child process. In certain - // tests or single-process mode, this will actually represent the current - // process. - // - // NOTE: this is not necessarily valid immediately after calling Init, as - // Init starts the process asynchronously. It's guaranteed to be valid after - // the first IPC arrives. - virtual base::ProcessHandle GetHandle() = 0; - - // Transport DIB functions --------------------------------------------------- - - // Return the TransportDIB for the given id. On Linux, this can involve - // mapping shared memory. On Mac, the shared memory is created in the browser - // process and the cached metadata is returned. On Windows, this involves - // duplicating the handle from the remote process. The RenderProcessHost - // still owns the returned DIB. - virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) = 0; - - // Static management functions ----------------------------------------------- - - // Flag to run the renderer in process. This is primarily - // for debugging purposes. When running "in process", the - // browser maintains a single RenderProcessHost which communicates - // to a RenderProcess which is instantiated in the same process - // with the Browser. All IPC between the Browser and the - // Renderer is the same, it's just not crossing a process boundary. - static bool run_renderer_in_process() { - return run_renderer_in_process_; - } - static void set_run_renderer_in_process(bool value) { - run_renderer_in_process_ = value; - } - - // Allows iteration over all the RenderProcessHosts in the browser. Note - // that each host may not be active, and therefore may have NULL channels. - static iterator AllHostsIterator(); - - // Returns the RenderProcessHost given its ID. Returns NULL if the ID does - // not correspond to a live RenderProcessHost. - static RenderProcessHost* FromID(int render_process_id); - - // Returns true if the caller should attempt to use an existing - // RenderProcessHost rather than creating a new one. - static bool ShouldTryToUseExistingProcessHost(); - - // Get an existing RenderProcessHost associated with the given profile, if - // possible. The renderer process is chosen randomly from suitable renderers - // that share the same profile and type. - // Returns NULL if no suitable renderer process is available, in which case - // the caller is free to create a new renderer. - static RenderProcessHost* GetExistingProcessHost(Profile* profile, Type type); - - // Overrides the default heuristic for limiting the max renderer process - // count. This is useful for unit testing process limit behaviors. - // A value of zero means to use the default heuristic. - static void SetMaxRendererProcessCount(size_t count); - - protected: - // A proxy for our IPC::Channel that lives on the IO thread (see - // browser_process.h) - scoped_ptr<IPC::SyncChannel> channel_; - - // The registered listeners. When this list is empty or all NULL, we should - // delete ourselves - IDMap<IPC::Channel::Listener> listeners_; - - // The maximum page ID we've ever seen from the renderer process. - int32 max_page_id_; - - // True if fast shutdown has been performed on this RPH. - bool fast_shutdown_started_; - - // True if we've posted a DeleteTask and will be deleted soon. - bool deleting_soon_; - - private: - // The globally-unique identifier for this RPH. - int id_; - - Profile* profile_; - - // set of listeners that expect the renderer process to close - std::set<int> listeners_expecting_close_; - - // True if the process can be shut down suddenly. If this is true, then we're - // sure that all the RenderViews in the process can be shutdown suddenly. If - // it's false, then specific RenderViews might still be allowed to be shutdown - // suddenly by checking their SuddenTerminationAllowed() flag. This can occur - // if one tab has an unload event listener but another tab in the same process - // doesn't. - bool sudden_termination_allowed_; - - // Set to true if we shouldn't send input events. We actually do the - // filtering for this at the render widget level. - bool ignore_input_events_; - - // See getter above. - static bool run_renderer_in_process_; - - // Records the last time we regarded the child process active. - base::TimeTicks child_process_activity_time_; - - DISALLOW_COPY_AND_ASSIGN(RenderProcessHost); -}; - -// Factory object for RenderProcessHosts. Using this factory allows tests to -// swap out a different one to use a TestRenderProcessHost. -class RenderProcessHostFactory { - public: - virtual ~RenderProcessHostFactory() {} - virtual RenderProcessHost* CreateRenderProcessHost( - Profile* profile) const = 0; -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_process_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ diff --git a/chrome/browser/renderer_host/render_sandbox_host_linux.h b/chrome/browser/renderer_host/render_sandbox_host_linux.h index 2cb0604..e1a2c84fc 100644 --- a/chrome/browser/renderer_host/render_sandbox_host_linux.h +++ b/chrome/browser/renderer_host/render_sandbox_host_linux.h @@ -2,51 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// http://code.google.com/p/chromium/wiki/LinuxSandboxIPC - #ifndef CHROME_BROWSER_RENDERER_HOST_RENDER_SANDBOX_HOST_LINUX_H_ #define CHROME_BROWSER_RENDERER_HOST_RENDER_SANDBOX_HOST_LINUX_H_ #pragma once -#include <string> - -#include "base/logging.h" - -template <typename T> struct DefaultSingletonTraits; - -// This is a singleton object which handles sandbox requests from the -// renderers. -class RenderSandboxHostLinux { - public: - // Returns the singleton instance. - static RenderSandboxHostLinux* GetInstance(); - - // Get the file descriptor which renderers should be given in order to signal - // crashes to the browser. - int GetRendererSocket() const { - DCHECK(initialized_); - return renderer_socket_; - } - pid_t pid() const { - DCHECK(initialized_); - return pid_; - } - void Init(const std::string& sandbox_path); - - private: - friend struct DefaultSingletonTraits<RenderSandboxHostLinux>; - // This object must be constructed on the main thread. - RenderSandboxHostLinux(); - ~RenderSandboxHostLinux(); - - // Whether Init() has been called yet. - bool initialized_; - - int renderer_socket_; - int childs_lifeline_fd_; - pid_t pid_; - - DISALLOW_COPY_AND_ASSIGN(RenderSandboxHostLinux); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_sandbox_host_linux.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_SANDBOX_HOST_LINUX_H_ diff --git a/chrome/browser/renderer_host/render_view_host.h b/chrome/browser/renderer_host/render_view_host.h index c5daa69..8fe145d 100644 --- a/chrome/browser/renderer_host/render_view_host.h +++ b/chrome/browser/renderer_host/render_view_host.h @@ -6,736 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_H_ #pragma once -#include <string> -#include <vector> - -#include "base/process_util.h" -#include "base/scoped_ptr.h" -#include "chrome/browser/renderer_host/render_widget_host.h" -#include "chrome/browser/ui/find_bar/find_bar_controller.h" -#include "chrome/common/content_settings_types.h" -#include "chrome/common/page_zoom.h" -#include "chrome/common/render_view_commands.h" -#include "chrome/common/translate_errors.h" -#include "chrome/common/view_types.h" -#include "chrome/common/window_container_type.h" -#include "net/base/load_states.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebConsoleMessage.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextDirection.h" -#include "webkit/glue/webaccessibility.h" -#include "webkit/glue/window_open_disposition.h" - -class ChildProcessSecurityPolicy; -class FilePath; -class GURL; -class ListValue; -class RenderViewHostDelegate; -class SessionStorageNamespace; -class SiteInstance; -class SkBitmap; -class ViewMsg_Navigate; -struct ContentSettings; -struct ContextMenuParams; -struct MediaPlayerAction; -struct ThumbnailScore; -struct ViewHostMsg_AccessibilityNotification_Params; -struct ViewHostMsg_CreateWindow_Params; -struct ViewHostMsg_DomMessage_Params; -struct ViewHostMsg_ShowPopup_Params; -struct ViewMsg_Navigate_Params; -struct WebApplicationInfo; -struct WebDropData; -struct WebPreferences; -struct UserMetricsAction; - -namespace gfx { -class Point; -} // namespace gfx - -namespace webkit_glue { -struct CustomContextMenuContext; -struct WebAccessibility; -} // namespace webkit_glue - -namespace WebKit { -struct WebMediaPlayerAction; -} // namespace WebKit - -class URLRequestContextGetter; - -// -// RenderViewHost -// -// A RenderViewHost is responsible for creating and talking to a RenderView -// object in a child process. It exposes a high level API to users, for things -// like loading pages, adjusting the display and other browser functionality, -// which it translates into IPC messages sent over the IPC channel with the -// RenderView. It responds to all IPC messages sent by that RenderView and -// cracks them, calling a delegate object back with higher level types where -// possible. -// -// The intent of this class is to provide a view-agnostic communication -// conduit with a renderer. This is so we can build HTML views not only as -// TabContents (see TabContents for an example) but also as views, etc. -// -// The exact API of this object needs to be more thoroughly designed. Right -// now it mimics what TabContents exposed, which is a fairly large API and may -// contain things that are not relevant to a common subset of views. See also -// the comment in render_view_host_delegate.h about the size and scope of the -// delegate API. -// -// Right now, the concept of page navigation (both top level and frame) exists -// in the TabContents still, so if you instantiate one of these elsewhere, you -// will not be able to traverse pages back and forward. We need to determine -// if we want to bring that and other functionality down into this object so -// it can be shared by others. -// -class RenderViewHost : public RenderWidgetHost { - public: - // Returns the RenderViewHost given its ID and the ID of its render process. - // Returns NULL if the IDs do not correspond to a live RenderViewHost. - static RenderViewHost* FromID(int render_process_id, int render_view_id); - - // routing_id could be a valid route id, or it could be MSG_ROUTING_NONE, in - // which case RenderWidgetHost will create a new one. - // - // The session storage namespace parameter allows multiple render views and - // tab contentses to share the same session storage (part of the WebStorage - // spec) space. This is useful when restoring tabs, but most callers should - // pass in NULL which will cause a new SessionStorageNamespace to be created. - RenderViewHost(SiteInstance* instance, - RenderViewHostDelegate* delegate, - int routing_id, - SessionStorageNamespace* session_storage_namespace); - virtual ~RenderViewHost(); - - SiteInstance* site_instance() const { return instance_; } - RenderViewHostDelegate* delegate() const { return delegate_; } - void set_delegate(RenderViewHostDelegate* d) { delegate_ = d; } - - // Set up the RenderView child process. Virtual because it is overridden by - // TestRenderViewHost. If the |frame_name| parameter is non-empty, it is used - // as the name of the new top-level frame. - virtual bool CreateRenderView(const string16& frame_name); - - // Returns true if the RenderView is active and has not crashed. Virtual - // because it is overridden by TestRenderViewHost. - virtual bool IsRenderViewLive() const; - - base::TerminationStatus render_view_termination_status() const { - return render_view_termination_status_; - } - - // Send the renderer process the current preferences supplied by the - // RenderViewHostDelegate. - void SyncRendererPrefs(); - - // Sends the given navigation message. Use this rather than sending it - // yourself since this does the internal bookkeeping described below. This - // function takes ownership of the provided message pointer. - // - // If a cross-site request is in progress, we may be suspended while waiting - // for the onbeforeunload handler, so this function might buffer the message - // rather than sending it. - void Navigate(const ViewMsg_Navigate_Params& message); - - // Load the specified URL, this is a shortcut for Navigate(). - void NavigateToURL(const GURL& url); - - // Returns whether navigation messages are currently suspended for this - // RenderViewHost. Only true during a cross-site navigation, while waiting - // for the onbeforeunload handler. - bool are_navigations_suspended() const { return navigations_suspended_; } - - // Suspends (or unsuspends) any navigation messages from being sent from this - // RenderViewHost. This is called when a pending RenderViewHost is created - // for a cross-site navigation, because we must suspend any navigations until - // we hear back from the old renderer's onbeforeunload handler. Note that it - // is important that only one navigation event happen after calling this - // method with |suspend| equal to true. If |suspend| is false and there is - // a suspended_nav_message_, this will send the message. This function - // should only be called to toggle the state; callers should check - // are_navigations_suspended() first. - void SetNavigationsSuspended(bool suspend); - - // Causes the renderer to invoke the onbeforeunload event handler. The - // result will be returned via ViewMsg_ShouldClose. See also ClosePage which - // will fire the PageUnload event. - // - // Set bool for_cross_site_transition when this close is just for the current - // RenderView in the case of a cross-site transition. False means we're - // closing the entire tab. - void FirePageBeforeUnload(bool for_cross_site_transition); - - // Causes the renderer to close the current page, including running its - // onunload event handler. A ClosePage_ACK message will be sent to the - // ResourceDispatcherHost when it is finished. - // - // Please see ViewMsg_ClosePage in resource_messages_internal.h for a - // description of the parameters. - void ClosePage(bool for_cross_site_transition, - int new_render_process_host_id, - int new_request_id); - - // Close the page ignoring whether it has unload events registers. - // This is called after the beforeunload and unload events have fired - // and the user has agreed to continue with closing the page. - void ClosePageIgnoringUnloadEvents(); - - // Sets whether this RenderViewHost has an outstanding cross-site request, - // for which another renderer will need to run an onunload event handler. - // This is called before the first navigation event for this RenderViewHost, - // and again after the corresponding OnCrossSiteResponse. - void SetHasPendingCrossSiteRequest(bool has_pending_request, int request_id); - - // Returns the request_id for the pending cross-site request. - // This is just needed in case the unload of the current page - // hangs, in which case we need to swap to the pending RenderViewHost. - int GetPendingRequestId(); - - struct CommandState { - bool is_enabled; - RenderViewCommandCheckedState checked_state; - }; - CommandState GetStateForCommand(RenderViewCommand command) const; - - // Stops the current load. - void Stop(); - - // Reloads the current frame. - void ReloadFrame(); - - // Asks the renderer to "render" printed pages and initiate printing on our - // behalf. - bool PrintPages(); - - // Asks the renderer to render pages for print preview. - bool PrintPreview(); - - // Notify renderer of success/failure of print job. - void PrintingDone(int document_cookie, bool success); - - // Start looking for a string within the content of the page, with the - // specified options. - void StartFinding(int request_id, - const string16& search_string, - bool forward, - bool match_case, - bool find_next); - - // Cancel a pending find operation. - void StopFinding(FindBarController::SelectionAction selection_action); - - // Increment, decrement, or reset the zoom level of a page. - void Zoom(PageZoom::Function function); - - // Change the zoom level of a page to a specific value. - void SetZoomLevel(double zoom_level); - - // Change the encoding of the page. - void SetPageEncoding(const std::string& encoding); - - // Reset any override encoding on the page and change back to default. - void ResetPageEncodingToDefault(); - - // Change the alternate error page URL. An empty GURL disables the use of - // alternate error pages. - void SetAlternateErrorPageURL(const GURL& url); - - // D&d drop target messages that get sent to WebKit. - void DragTargetDragEnter(const WebDropData& drop_data, - const gfx::Point& client_pt, - const gfx::Point& screen_pt, - WebKit::WebDragOperationsMask operations_allowed); - void DragTargetDragOver(const gfx::Point& client_pt, - const gfx::Point& screen_pt, - WebKit::WebDragOperationsMask operations_allowed); - void DragTargetDragLeave(); - void DragTargetDrop(const gfx::Point& client_pt, - const gfx::Point& screen_pt); - - // Tell the RenderView to reserve a range of page ids of the given size. - void ReservePageIDRange(int size); - - // Runs some javascript within the context of a frame in the page. - void ExecuteJavascriptInWebFrame(const string16& frame_xpath, - const string16& jscript); - - // Runs some javascript within the context of a frame in the page. The result - // is sent back via the notification EXECUTE_JAVASCRIPT_RESULT. - int ExecuteJavascriptInWebFrameNotifyResult(const string16& frame_xpath, - const string16& jscript); - - // Insert some css into a frame in the page. |id| is optional, and specifies - // the element id given when inserting/replacing the style element. - void InsertCSSInWebFrame(const std::wstring& frame_xpath, - const std::string& css, - const std::string& id); - - // Logs a message to the console of a frame in the page. - void AddMessageToConsole(const string16& frame_xpath, - const string16& message, - const WebKit::WebConsoleMessage::Level&); - - // Edit operations. - void Undo(); - void Redo(); - void Cut(); - void Copy(); - void CopyToFindPboard(); - void Paste(); - void ToggleSpellCheck(); - void Delete(); - void SelectAll(); - void ToggleSpellPanel(bool is_currently_visible); - - // Downloads an image notifying the FavIcon delegate appropriately. The - // returned integer uniquely identifies the download for the lifetime of the - // browser. - int DownloadFavIcon(const GURL& url, int image_size); - - // Requests application info for the specified page. This is an asynchronous - // request. The delegate is notified by way of OnDidGetApplicationInfo when - // the data is available. - void GetApplicationInfo(int32 page_id); - - // Captures a thumbnail representation of the page. - void CaptureThumbnail(); - - // Captures a snapshot of the page. - void CaptureSnapshot(); - - // Notifies the RenderView that the JavaScript message that was shown was - // closed by the user. - void JavaScriptMessageBoxClosed(IPC::Message* reply_msg, - bool success, - const std::wstring& prompt); - - // Notifies the RenderView that the modal html dialog has been closed. - void ModalHTMLDialogClosed(IPC::Message* reply_msg, - const std::string& json_retval); - - // Send an action to the media player element located at |location|. - void MediaPlayerActionAt(const gfx::Point& location, - const WebKit::WebMediaPlayerAction& action); - - // Notifies the renderer that the context menu has closed. - void ContextMenuClosed( - const webkit_glue::CustomContextMenuContext& custom_context); - - // Prints the node that's under the context menu. - void PrintNodeUnderContextMenu(); - - // Triggers printing of the preview PDF. - void PrintForPrintPreview(); - - // Copies the image at the specified point. - void CopyImageAt(int x, int y); - - // Notifies the renderer that a a drag operation that it started has ended, - // either in a drop or by being cancelled. - void DragSourceEndedAt( - int client_x, int client_y, int screen_x, int screen_y, - WebKit::WebDragOperation operation); - - // Notifies the renderer that a drag and drop operation is in progress, with - // droppable items positioned over the renderer's view. - void DragSourceMovedTo( - int client_x, int client_y, int screen_x, int screen_y); - - // Notifies the renderer that we're done with the drag and drop operation. - // This allows the renderer to reset some state. - void DragSourceSystemDragEnded(); - - // Tell the render view to enable a set of javascript bindings. The argument - // should be a combination of values from BindingsPolicy. - void AllowBindings(int binding_flags); - - // Returns a bitwise OR of bindings types that have been enabled for this - // RenderView. See BindingsPolicy for details. - int enabled_bindings() const { return enabled_bindings_; } - - // See variable comment. - bool is_extension_process() const { return is_extension_process_; } - void set_is_extension_process(bool is_extension_process) { - is_extension_process_ = is_extension_process; - } - - // Sets a property with the given name and value on the Web UI binding object. - // Must call AllowWebUIBindings() on this renderer first. - void SetWebUIProperty(const std::string& name, const std::string& value); - - // Tells the renderer view to focus the first (last if reverse is true) node. - void SetInitialFocus(bool reverse); - - // Clears the node that is currently focused (if any). - void ClearFocusedNode(); - - // Tells the renderer view to scroll to the focused node. - void ScrollFocusedEditableNodeIntoView(); - - // Update render view specific (WebKit) preferences. - void UpdateWebPreferences(const WebPreferences& prefs); - - // Request the Renderer to ask the default plugin to start installation of - // missing plugin. Called by PluginInstallerInfoBarDelegate. - void InstallMissingPlugin(); - - // Load all blocked plugins in the RenderView. - void LoadBlockedPlugins(); - - // Get all script and frame urls from all frames in the current document. - // Called when a malware interstitial page is shown. - void GetMalwareDOMDetails(); - - // Get all savable resource links from current webpage, include main - // frame and sub-frame. - void GetAllSavableResourceLinksForCurrentPage(const GURL& page_url); - - // Get html data by serializing all frames of current page with lists - // which contain all resource links that have local copy. - // The parameter links contain original URLs of all saved links. - // The parameter local_paths contain corresponding local file paths of - // all saved links, which matched with vector:links one by one. - // The parameter local_directory_name is relative path of directory which - // contain all saved auxiliary files included all sub frames and resouces. - void GetSerializedHtmlDataForCurrentPageWithLocalLinks( - const std::vector<GURL>& links, - const std::vector<FilePath>& local_paths, - const FilePath& local_directory_name); - - // Notifies the Listener that one or more files have been chosen by the user - // from an Open File dialog for the form. - void FilesSelectedInChooser(const std::vector<FilePath>& files); - - // Notifies the RenderViewHost that its load state changed. - void LoadStateChanged(const GURL& url, net::LoadState load_state, - uint64 upload_position, uint64 upload_size); - - bool SuddenTerminationAllowed() const; - void set_sudden_termination_allowed(bool enabled) { - sudden_termination_allowed_ = enabled; - } - - // Forward a message from external host to chrome renderer. - void ForwardMessageFromExternalHost(const std::string& message, - const std::string& origin, - const std::string& target); - - // Message the renderer that we should be counted as a new document and not - // as a popup. - void DisassociateFromPopupCount(); - - // Tells the renderer whether it should allow window.close. This is initially - // set to false when creating a renderer-initiated window via window.open. - void AllowScriptToClose(bool visible); - - // Notifies the Renderer that a move or resize of its containing window has - // started (this is used to hide the autocomplete popups if any). - void WindowMoveOrResizeStarted(); - - // RenderWidgetHost public overrides. - virtual void Shutdown(); - virtual bool IsRenderView() const; - virtual bool OnMessageReceived(const IPC::Message& msg); - virtual void GotFocus(); - virtual void LostCapture(); - virtual void ForwardMouseEvent(const WebKit::WebMouseEvent& mouse_event); - virtual void OnMouseActivate(); - virtual void ForwardKeyboardEvent(const NativeWebKeyboardEvent& key_event); - virtual void ForwardEditCommand(const std::string& name, - const std::string& value); - virtual void ForwardEditCommandsForNextKeyEvent( - const EditCommands& edit_commands); - - // Creates a new RenderView with the given route id. - void CreateNewWindow(int route_id, - const ViewHostMsg_CreateWindow_Params& params); - - // Creates a new RenderWidget with the given route id. |popup_type| indicates - // if this widget is a popup and what kind of popup it is (select, autofill). - void CreateNewWidget(int route_id, WebKit::WebPopupType popup_type); - - // Creates a full screen RenderWidget. - void CreateNewFullscreenWidget(int route_id); - - // Sends the response to an extension api call. - void SendExtensionResponse(int request_id, bool success, - const std::string& response, - const std::string& error); - - // Sends a response to an extension api call that it was blocked for lack of - // permission. - void BlockExtensionRequest(int request_id); - - // Tells the renderer which browser window it is being attached to. - void UpdateBrowserWindowId(int window_id); - - // Tells the render view that a custom context action has been selected. - void PerformCustomContextMenuAction( - const webkit_glue::CustomContextMenuContext& custom_context, - unsigned action); - - // Informs renderer of updated content settings. - void SendContentSettings(const GURL& url, - const ContentSettings& settings); - - // Tells the renderer to notify us when the page contents preferred size - // changed. |flags| is a combination of - // |ViewHostMsg_EnablePreferredSizeChangedMode_Flags| values, which is defined - // in render_messages.h. - void EnablePreferredSizeChangedMode(int flags); - -#if defined(OS_MACOSX) - // Select popup menu related methods (for external popup menus). - void DidSelectPopupMenuItem(int selected_index); - void DidCancelPopupMenu(); -#endif - - // SearchBox notifications. - void SearchBoxChange(const string16& value, - bool verbatim, - int selection_start, - int selection_end); - void SearchBoxSubmit(const string16& value, - bool verbatim); - void SearchBoxCancel(); - void SearchBoxResize(const gfx::Rect& search_box_bounds); - void DetermineIfPageSupportsInstant(const string16& value, - bool verbatim, - int selection_start, - int selection_end); - - // Send a notification to the V8 JavaScript engine to change its parameters - // while performing stress testing. |cmd| is one of the values defined by - // |ViewHostMsg_JavaScriptStressTestControl_Commands|, which is defined - // in render_messages.h. - void JavaScriptStressTestControl(int cmd, int param); - -#if defined(UNIT_TEST) - // These functions shouldn't be necessary outside of testing. - - void set_save_accessibility_tree_for_testing(bool save) { - save_accessibility_tree_for_testing_ = save; - } - - const webkit_glue::WebAccessibility& accessibility_tree() { - return accessibility_tree_; - } - - bool is_waiting_for_unload_ack() { return is_waiting_for_unload_ack_; } -#endif - - // Checks that the given renderer can request |url|, if not it sets it to an - // empty url. - static void FilterURL(ChildProcessSecurityPolicy* policy, - int renderer_id, - GURL* url); - - protected: - // RenderWidgetHost protected overrides. - virtual bool PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, - bool* is_keyboard_shortcut); - virtual void UnhandledKeyboardEvent(const NativeWebKeyboardEvent& event); - virtual void OnUserGesture(); - virtual void NotifyRendererUnresponsive(); - virtual void NotifyRendererResponsive(); - virtual void OnMsgFocusedNodeChanged(bool is_editable_node); - virtual void OnMsgFocus(); - virtual void OnMsgBlur(); - - // IPC message handlers. - void OnMsgShowView(int route_id, - WindowOpenDisposition disposition, - const gfx::Rect& initial_pos, - bool user_gesture); - void OnMsgShowWidget(int route_id, const gfx::Rect& initial_pos); - void OnMsgShowFullscreenWidget(int route_id); - void OnMsgRunModal(IPC::Message* reply_msg); - void OnMsgRenderViewReady(); - void OnMsgRenderViewGone(int status, int error_code); - void OnMsgNavigate(const IPC::Message& msg); - void OnMsgUpdateState(int32 page_id, - const std::string& state); - void OnMsgUpdateTitle(int32 page_id, const std::wstring& title); - void OnMsgUpdateEncoding(const std::string& encoding); - void OnMsgUpdateTargetURL(int32 page_id, const GURL& url); - void OnMsgThumbnail(const GURL& url, - const ThumbnailScore& score, - const SkBitmap& bitmap); - void OnMsgScreenshot(const SkBitmap& bitmap); - void OnMsgClose(); - void OnMsgRequestMove(const gfx::Rect& pos); - void OnMsgDidStartLoading(); - void OnMsgDidStopLoading(); - void OnMsgDidChangeLoadProgress(double load_progress); - void OnMsgDocumentAvailableInMainFrame(); - void OnMsgDocumentOnLoadCompletedInMainFrame(int32 page_id); - void OnExecuteCodeFinished(int request_id, bool success); - void OnMsgUpdateFavIconURL(int32 page_id, const GURL& icon_url); - void OnMsgDidDownloadFavIcon(int id, - const GURL& image_url, - bool errored, - const SkBitmap& image_data); - void OnMsgContextMenu(const ContextMenuParams& params); - void OnMsgOpenURL(const GURL& url, const GURL& referrer, - WindowOpenDisposition disposition); - void OnMsgDidContentsPreferredSizeChange(const gfx::Size& new_size); - void OnMsgDomOperationResponse(const std::string& json_string, - int automation_id); - void OnMsgWebUISend(const GURL& source_url, - const std::string& message, - const std::string& content); - void OnMsgForwardMessageToExternalHost(const std::string& message, - const std::string& origin, - const std::string& target); - void OnMsgSetTooltipText(const std::wstring& tooltip_text, - WebKit::WebTextDirection text_direction_hint); - void OnMsgSelectionChanged(const std::string& text); - void OnMsgPasteFromSelectionClipboard(); - void OnMsgRunJavaScriptMessage(const std::wstring& message, - const std::wstring& default_prompt, - const GURL& frame_url, - const int flags, - IPC::Message* reply_msg); - void OnMsgRunBeforeUnloadConfirm(const GURL& frame_url, - const std::wstring& message, - IPC::Message* reply_msg); - void OnMsgShowModalHTMLDialog(const GURL& url, int width, int height, - const std::string& json_arguments, - IPC::Message* reply_msg); - void OnMsgStartDragging(const WebDropData& drop_data, - WebKit::WebDragOperationsMask operations_allowed, - const SkBitmap& image, - const gfx::Point& image_offset); - void OnUpdateDragCursor(WebKit::WebDragOperation drag_operation); - void OnTakeFocus(bool reverse); - void OnAddMessageToConsole(const std::wstring& message, - int32 line_no, - const std::wstring& source_id); - void OnUpdateInspectorSetting(const std::string& key, - const std::string& value); - void OnForwardToDevToolsAgent(const IPC::Message& message); - void OnForwardToDevToolsClient(const IPC::Message& message); - void OnActivateDevToolsWindow(); - void OnCloseDevToolsWindow(); - void OnRequestDockDevToolsWindow(); - void OnRequestUndockDevToolsWindow(); - void OnDevToolsRuntimePropertyChanged(const std::string& name, - const std::string& value); - void OnMsgShouldCloseACK(bool proceed); - - void OnExtensionRequest(const ViewHostMsg_DomMessage_Params& params); - void OnExtensionPostMessage(int port_id, const std::string& message); - void OnAccessibilityNotifications( - const std::vector<ViewHostMsg_AccessibilityNotification_Params>& params); - void OnCSSInserted(); - void OnContentBlocked(ContentSettingsType type, - const std::string& resource_identifier); - void OnAppCacheAccessed(const GURL& manifest_url, bool blocked_by_policy); - void OnWebDatabaseAccessed(const GURL& url, - const string16& name, - const string16& display_name, - unsigned long estimated_size, - bool blocked_by_policy); - void OnUpdateZoomLimits(int minimum_percent, - int maximum_percent, - bool remember); - void OnScriptEvalResponse(int id, const ListValue& result); - void OnCommandStateChanged(int command, - bool is_enabled, - int checked_state); - -#if defined(OS_MACOSX) - void OnMsgShowPopup(const ViewHostMsg_ShowPopup_Params& params); -#endif - - private: - friend class TestRenderViewHost; - - // The SiteInstance associated with this RenderViewHost. All pages drawn - // in this RenderViewHost are part of this SiteInstance. Should not change - // over time. - scoped_refptr<SiteInstance> instance_; - - // Our delegate, which wants to know about changes in the RenderView. - RenderViewHostDelegate* delegate_; - - // true if we are currently waiting for a response for drag context - // information. - bool waiting_for_drag_context_response_; - - // A bitwise OR of bindings types that have been enabled for this RenderView. - // See BindingsPolicy for details. - int enabled_bindings_; - - // The request_id for the pending cross-site request. Set to -1 if - // there is a pending request, but we have not yet started the unload - // for the current page. Set to the request_id value of the pending - // request once we have gotten the some data for the pending page - // and thus started the unload process. - int pending_request_id_; - - // Whether we should buffer outgoing Navigate messages rather than sending - // them. This will be true when a RenderViewHost is created for a cross-site - // request, until we hear back from the onbeforeunload handler of the old - // RenderViewHost. - bool navigations_suspended_; - - // We only buffer a suspended navigation message while we a pending RVH for a - // TabContents. There will only ever be one suspended navigation, because - // TabContents will destroy the pending RVH and create a new one if a second - // navigation occurs. - scoped_ptr<ViewMsg_Navigate> suspended_nav_message_; - - // If we were asked to RunModal, then this will hold the reply_msg that we - // must return to the renderer to unblock it. - IPC::Message* run_modal_reply_msg_; - - // Set to true when there is a pending ViewMsg_ShouldClose message. This - // ensures we don't spam the renderer with multiple beforeunload requests. - // When either this value or is_waiting_for_unload_ack_ is true, the value of - // unload_ack_is_for_cross_site_transition_ indicates whether this is for a - // cross-site transition or a tab close attempt. - bool is_waiting_for_beforeunload_ack_; - - // Set to true when there is a pending ViewMsg_Close message. Also see - // is_waiting_for_beforeunload_ack_, unload_ack_is_for_cross_site_transition_. - bool is_waiting_for_unload_ack_; - - // Valid only when is_waiting_for_beforeunload_ack_ or - // is_waiting_for_unload_ack_ is true. This tells us if the unload request - // is for closing the entire tab ( = false), or only this RenderViewHost in - // the case of a cross-site transition ( = true). - bool unload_ack_is_for_cross_site_transition_; - - bool are_javascript_messages_suppressed_; - - // True if the render view can be shut down suddenly. - bool sudden_termination_allowed_; - - // The session storage namespace to be used by the associated render view. - scoped_refptr<SessionStorageNamespace> session_storage_namespace_; - - // Whether this render view will get extension api bindings. This controls - // what process type we use. - bool is_extension_process_; - - // Whether the accessibility tree should be saved, for unit testing. - bool save_accessibility_tree_for_testing_; - - // The most recently received accessibility tree - for unit testing only. - webkit_glue::WebAccessibility accessibility_tree_; - - // The termination status of the last render view that terminated. - base::TerminationStatus render_view_termination_status_; - - // The enabled/disabled states of various commands. - std::map<RenderViewCommand, CommandState> command_states_; - - DISALLOW_COPY_AND_ASSIGN(RenderViewHost); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_view_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_H_ diff --git a/chrome/browser/renderer_host/render_view_host_delegate.h b/chrome/browser/renderer_host/render_view_host_delegate.h index b98e7ea..d7e26f8 100644 --- a/chrome/browser/renderer_host/render_view_host_delegate.h +++ b/chrome/browser/renderer_host/render_view_host_delegate.h @@ -6,579 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_DELEGATE_H_ #pragma once -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/process_util.h" -#include "base/ref_counted.h" -#include "base/string16.h" -#include "chrome/common/content_settings_types.h" -#include "chrome/common/dom_storage_common.h" -#include "chrome/common/translate_errors.h" -#include "chrome/common/view_types.h" -#include "chrome/common/window_container_type.h" -#include "ipc/ipc_channel.h" -#include "net/base/load_states.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" -#include "webkit/glue/window_open_disposition.h" - - -class AutomationResourceRoutingDelegate; -class BackgroundContents; -struct BookmarkNodeData; -class BookmarkNode; -struct ContextMenuParams; -class FilePath; -class GURL; -class ListValue; -struct NativeWebKeyboardEvent; -class NavigationEntry; -class Profile; -struct RendererPreferences; -class RenderProcessHost; -class RenderViewHost; -class ResourceRedirectDetails; -class ResourceRequestDetails; -class SkBitmap; -class SSLClientAuthHandler; -class SSLAddCertHandler; -class TabContents; -struct ThumbnailScore; -struct ViewHostMsg_CreateWindow_Params; -struct ViewHostMsg_DomMessage_Params; -struct ViewHostMsg_FrameNavigate_Params; -struct WebApplicationInfo; -struct WebDropData; -struct WebMenuItem; -class WebKeyboardEvent; -struct WebPreferences; - -namespace base { -class WaitableEvent; -} - -namespace gfx { -class Point; -class Rect; -class Size; -} - -namespace IPC { -class Message; -} - -namespace net { -class CookieList; -class CookieOptions; -} - -namespace webkit_glue { -struct FormData; -class FormField; -struct PasswordForm; -} - -// -// RenderViewHostDelegate -// -// An interface implemented by an object interested in knowing about the state -// of the RenderViewHost. -// -// This interface currently encompasses every type of message that was -// previously being sent by TabContents itself. Some of these notifications -// may not be relevant to all users of RenderViewHost and we should consider -// exposing a more generic Send function on RenderViewHost and a response -// listener here to serve that need. -// -class RenderViewHostDelegate : public IPC::Channel::Listener { - public: - // View ---------------------------------------------------------------------- - // Functions that can be routed directly to a view-specific class. - - class View { - public: - // The page is trying to open a new page (e.g. a popup window). The window - // should be created associated with the given route, but it should not be - // shown yet. That should happen in response to ShowCreatedWindow. - // |params.window_container_type| describes the type of RenderViewHost - // container that is requested -- in particular, the window.open call may - // have specified 'background' and 'persistent' in the feature string. - // - // The passed |params.frame_name| parameter is the name parameter that was - // passed to window.open(), and will be empty if none was passed. - // - // Note: this is not called "CreateWindow" because that will clash with - // the Windows function which is actually a #define. - // - // NOTE: this takes ownership of @modal_dialog_event - virtual void CreateNewWindow( - int route_id, - const ViewHostMsg_CreateWindow_Params& params) = 0; - - // The page is trying to open a new widget (e.g. a select popup). The - // widget should be created associated with the given route, but it should - // not be shown yet. That should happen in response to ShowCreatedWidget. - // |popup_type| indicates if the widget is a popup and what kind of popup it - // is (select, autofill...). - virtual void CreateNewWidget(int route_id, - WebKit::WebPopupType popup_type) = 0; - - // Creates a full screen RenderWidget. Similar to above. - virtual void CreateNewFullscreenWidget(int route_id) = 0; - - // Show a previously created page with the specified disposition and bounds. - // The window is identified by the route_id passed to CreateNewWindow. - // - // Note: this is not called "ShowWindow" because that will clash with - // the Windows function which is actually a #define. - virtual void ShowCreatedWindow(int route_id, - WindowOpenDisposition disposition, - const gfx::Rect& initial_pos, - bool user_gesture) = 0; - - // Show the newly created widget with the specified bounds. - // The widget is identified by the route_id passed to CreateNewWidget. - virtual void ShowCreatedWidget(int route_id, - const gfx::Rect& initial_pos) = 0; - - // Show the newly created full screen widget. Similar to above. - virtual void ShowCreatedFullscreenWidget(int route_id) = 0; - - // A context menu should be shown, to be built using the context information - // provided in the supplied params. - virtual void ShowContextMenu(const ContextMenuParams& params) = 0; - - // Shows a popup menu with the specified items. - // This method should call RenderViewHost::DidSelectPopupMenuItemAt() or - // RenderViewHost::DidCancelPopupMenu() ased on the user action. - virtual void ShowPopupMenu(const gfx::Rect& bounds, - int item_height, - double item_font_size, - int selected_item, - const std::vector<WebMenuItem>& items, - bool right_aligned) = 0; - - // The user started dragging content of the specified type within the - // RenderView. Contextual information about the dragged content is supplied - // by WebDropData. - virtual void StartDragging(const WebDropData& drop_data, - WebKit::WebDragOperationsMask allowed_ops, - const SkBitmap& image, - const gfx::Point& image_offset) = 0; - - // The page wants to update the mouse cursor during a drag & drop operation. - // |operation| describes the current operation (none, move, copy, link.) - virtual void UpdateDragCursor(WebKit::WebDragOperation operation) = 0; - - // Notification that view for this delegate got the focus. - virtual void GotFocus() = 0; - - // Callback to inform the browser that the page is returning the focus to - // the browser's chrome. If reverse is true, it means the focus was - // retrieved by doing a Shift-Tab. - virtual void TakeFocus(bool reverse) = 0; - - // Notification that the view has lost capture. - virtual void LostCapture() = 0; - - // The page wants the hosting window to activate/deactivate itself (it - // called the JavaScript window.focus()/blur() method). - virtual void Activate() = 0; - virtual void Deactivate() = 0; - - // Callback to give the browser a chance to handle the specified keyboard - // event before sending it to the renderer. - // Returns true if the |event| was handled. Otherwise, if the |event| would - // be handled in HandleKeyboardEvent() method as a normal keyboard shortcut, - // |*is_keyboard_shortcut| should be set to true. - virtual bool PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, - bool* is_keyboard_shortcut) = 0; - - // Callback to inform the browser that the renderer did not process the - // specified events. This gives an opportunity to the browser to process the - // event (used for keyboard shortcuts). - virtual void HandleKeyboardEvent(const NativeWebKeyboardEvent& event) = 0; - - // Notifications about mouse events in this view. This is useful for - // implementing global 'on hover' features external to the view. - virtual void HandleMouseMove() = 0; - virtual void HandleMouseDown() = 0; - virtual void HandleMouseLeave() = 0; - virtual void HandleMouseUp() = 0; - virtual void HandleMouseActivate() = 0; - - // The contents' preferred size changed. - virtual void UpdatePreferredSize(const gfx::Size& pref_size) = 0; - - protected: - virtual ~View() {} - }; - - // RendererManagerment ------------------------------------------------------- - // Functions for managing switching of Renderers. For TabContents, this is - // implemented by the RenderViewHostManager - - class RendererManagement { - public: - // Notification whether we should close the page, after an explicit call to - // AttemptToClosePage. This is called before a cross-site request or before - // a tab/window is closed (as indicated by the first parameter) to allow the - // appropriate renderer to approve or deny the request. |proceed| indicates - // whether the user chose to proceed. - virtual void ShouldClosePage(bool for_cross_site_transition, - bool proceed) = 0; - - // Called by ResourceDispatcherHost when a response for a pending cross-site - // request is received. The ResourceDispatcherHost will pause the response - // until the onunload handler of the previous renderer is run. - virtual void OnCrossSiteResponse(int new_render_process_host_id, - int new_request_id) = 0; - - // Called the ResourceDispatcherHost's associate CrossSiteRequestHandler - // when a cross-site navigation has been canceled. - virtual void OnCrossSiteNavigationCanceled() = 0; - - protected: - virtual ~RendererManagement() {} - }; - - // ContentSettings------------------------------------------------------------ - // Interface for content settings related events. - - class ContentSettings { - public: - // Called when content in the current page was blocked due to the user's - // content settings. - virtual void OnContentBlocked(ContentSettingsType type, - const std::string& resource_identifier) = 0; - - // Called when cookies for the given URL were read either from within the - // current page or while loading it. |blocked_by_policy| should be true, if - // reading cookies was blocked due to the user's content settings. In that - // case, this function should invoke OnContentBlocked. - virtual void OnCookiesRead( - const GURL& url, - const net::CookieList& cookie_list, - bool blocked_by_policy) = 0; - - // Called when a specific cookie in the current page was changed. - // |blocked_by_policy| should be true, if the cookie was blocked due to the - // user's content settings. In that case, this function should invoke - // OnContentBlocked. - virtual void OnCookieChanged(const GURL& url, - const std::string& cookie_line, - const net::CookieOptions& options, - bool blocked_by_policy) = 0; - - // Called when a specific indexed db factory in the current page was - // accessed. If access was blocked due to the user's content settings, - // |blocked_by_policy| should be true, and this function should invoke - // OnContentBlocked. - virtual void OnIndexedDBAccessed(const GURL& url, - const string16& description, - bool blocked_by_policy) = 0; - - // Called when a specific local storage area in the current page was - // accessed. If access was blocked due to the user's content settings, - // |blocked_by_policy| should be true, and this function should invoke - // OnContentBlocked. - virtual void OnLocalStorageAccessed(const GURL& url, - DOMStorageType storage_type, - bool blocked_by_policy) = 0; - - // Called when a specific Web database in the current page was accessed. If - // access was blocked due to the user's content settings, - // |blocked_by_policy| should eb true, and this function should invoke - // OnContentBlocked. - virtual void OnWebDatabaseAccessed(const GURL& url, - const string16& name, - const string16& display_name, - unsigned long estimated_size, - bool blocked_by_policy) = 0; - - // Called when a specific appcache in the current page was accessed. If - // access was blocked due to the user's content settings, - // |blocked_by_policy| should eb true, and this function should invoke - // OnContentBlocked. - virtual void OnAppCacheAccessed(const GURL& manifest_url, - bool blocked_by_policy) = 0; - - // Called when geolocation permission was set in a frame on the current - // page. - virtual void OnGeolocationPermissionSet(const GURL& requesting_frame, - bool allowed) = 0; - - protected: - virtual ~ContentSettings() {} - }; - - // BookmarkDrag -------------------------------------------------------------- - // Interface for forwarding bookmark drag and drop to extenstions. - - class BookmarkDrag { - public: - virtual void OnDragEnter(const BookmarkNodeData& data) = 0; - virtual void OnDragOver(const BookmarkNodeData& data) = 0; - virtual void OnDragLeave(const BookmarkNodeData& data) = 0; - virtual void OnDrop(const BookmarkNodeData& data) = 0; - - protected: - virtual ~BookmarkDrag() {} - }; - - // SSL ----------------------------------------------------------------------- - // Interface for UI and other RenderViewHost-specific interactions with SSL. - - class SSL { - public: - // Displays a dialog to select client certificates from |request_info|, - // returning them to |handler|. - virtual void ShowClientCertificateRequestDialog( - scoped_refptr<SSLClientAuthHandler> handler) = 0; - - // Called when |handler| encounters an error in verifying a - // received client certificate. Note that, because CAs often will - // not send us intermediate certificates, the verification we can - // do is minimal: we verify the certificate is parseable, that we - // have the corresponding private key, and that the certificate - // has not expired. - virtual void OnVerifyClientCertificateError( - scoped_refptr<SSLAddCertHandler> handler, int error_code) = 0; - - // Called when |handler| requests the user's confirmation in adding a - // client certificate. - virtual void AskToAddClientCertificate( - scoped_refptr<SSLAddCertHandler> handler) = 0; - - // Called when |handler| successfully adds a client certificate. - virtual void OnAddClientCertificateSuccess( - scoped_refptr<SSLAddCertHandler> handler) = 0; - - // Called when |handler| encounters an error adding a client certificate. - virtual void OnAddClientCertificateError( - scoped_refptr<SSLAddCertHandler> handler, int error_code) = 0; - - // Called when |handler| has completed, so the delegate may release any - // state accumulated. - virtual void OnAddClientCertificateFinished( - scoped_refptr<SSLAddCertHandler> handler) = 0; - - protected: - virtual ~SSL() {} - }; - - // --------------------------------------------------------------------------- - - // Returns the current delegate associated with a feature. May return NULL if - // there is no corresponding delegate. - virtual View* GetViewDelegate(); - virtual RendererManagement* GetRendererManagementDelegate(); - virtual ContentSettings* GetContentSettingsDelegate(); - - virtual BookmarkDrag* GetBookmarkDragDelegate(); - virtual SSL* GetSSLDelegate(); - - // Return the delegate for registering RenderViewHosts for automation resource - // routing. - virtual AutomationResourceRoutingDelegate* - GetAutomationResourceRoutingDelegate(); - - // IPC::Channel::Listener implementation. - // This is used to give the delegate a chance to filter IPC messages. - virtual bool OnMessageReceived(const IPC::Message& message); - - // Gets the URL that is currently being displayed, if there is one. - virtual const GURL& GetURL() const; - - // Return this object cast to a TabContents, if it is one. If the object is - // not a TabContents, returns NULL. DEPRECATED: Be sure to include brettw and - // jam as reviewers before you use this method. - virtual TabContents* GetAsTabContents(); - - // Return this object cast to a BackgroundContents, if it is one. If the - // object is not a BackgroundContents, returns NULL. - virtual BackgroundContents* GetAsBackgroundContents(); - - // Return id number of browser window which this object is attached to. If no - // browser window is attached to, just return -1. - virtual int GetBrowserWindowID() const = 0; - - // Return type of RenderView which is attached with this object. - virtual ViewType::Type GetRenderViewType() const = 0; - - // The RenderView is being constructed (message sent to the renderer process - // to construct a RenderView). Now is a good time to send other setup events - // to the RenderView. This precedes any other commands to the RenderView. - virtual void RenderViewCreated(RenderViewHost* render_view_host) {} - - // The RenderView has been constructed. - virtual void RenderViewReady(RenderViewHost* render_view_host) {} - - // The RenderView died somehow (crashed or was killed by the user). - virtual void RenderViewGone(RenderViewHost* render_view_host, - base::TerminationStatus status, - int error_code) {} - - // The RenderView is going to be deleted. This is called when each - // RenderView is going to be destroyed - virtual void RenderViewDeleted(RenderViewHost* render_view_host) {} - - // The RenderView was navigated to a different page. - virtual void DidNavigate(RenderViewHost* render_view_host, - const ViewHostMsg_FrameNavigate_Params& params) {} - - // The state for the page changed and should be updated. - virtual void UpdateState(RenderViewHost* render_view_host, - int32 page_id, - const std::string& state) {} - - // The page's title was changed and should be updated. - virtual void UpdateTitle(RenderViewHost* render_view_host, - int32 page_id, - const std::wstring& title) {} - - // The page's encoding was changed and should be updated. - virtual void UpdateEncoding(RenderViewHost* render_view_host, - const std::string& encoding) {} - - // The destination URL has changed should be updated - virtual void UpdateTargetURL(int32 page_id, const GURL& url) {} - - // The thumbnail representation of the page changed and should be updated. - virtual void UpdateThumbnail(const GURL& url, - const SkBitmap& bitmap, - const ThumbnailScore& score) {} - - // Inspector setting was changed and should be persisted. - virtual void UpdateInspectorSetting(const std::string& key, - const std::string& value) = 0; - - virtual void ClearInspectorSettings() = 0; - - // The page is trying to close the RenderView's representation in the client. - virtual void Close(RenderViewHost* render_view_host) {} - - // The page is trying to move the RenderView's representation in the client. - virtual void RequestMove(const gfx::Rect& new_bounds) {} - - // The RenderView began loading a new page. This corresponds to WebKit's - // notion of the throbber starting. - virtual void DidStartLoading() {} - - // The RenderView stopped loading a page. This corresponds to WebKit's - // notion of the throbber stopping. - virtual void DidStopLoading() {} - - // The RenderView made progress loading a page's top frame. - // |progress| is a value between 0 (nothing loaded) to 1.0 (top frame - // entirely loaded). - virtual void DidChangeLoadProgress(double progress) {} - - // The RenderView's main frame document element is ready. This happens when - // the document has finished parsing. - virtual void DocumentAvailableInMainFrame(RenderViewHost* render_view_host) {} - - // The onload handler in the RenderView's main frame has completed. - virtual void DocumentOnLoadCompletedInMainFrame( - RenderViewHost* render_view_host, - int32 page_id) {} - - // The page wants to open a URL with the specified disposition. - virtual void RequestOpenURL(const GURL& url, - const GURL& referrer, - WindowOpenDisposition disposition) {} - - // A DOM automation operation completed. The result of the operation is - // expressed in a json string. - virtual void DomOperationResponse(const std::string& json_string, - int automation_id) {} - - // A message was sent from HTML-based UI. - // By default we ignore such messages. - virtual void ProcessWebUIMessage( - const ViewHostMsg_DomMessage_Params& params) {} - - // A message for external host. By default we ignore such messages. - // |receiver| can be a receiving script and |message| is any - // arbitrary string that makes sense to the receiver. - virtual void ProcessExternalHostMessage(const std::string& message, - const std::string& origin, - const std::string& target) {} - - // A javascript message, confirmation or prompt should be shown. - virtual void RunJavaScriptMessage(const std::wstring& message, - const std::wstring& default_prompt, - const GURL& frame_url, - const int flags, - IPC::Message* reply_msg, - bool* did_suppress_message) {} - - virtual void RunBeforeUnloadConfirm(const std::wstring& message, - IPC::Message* reply_msg) {} - - virtual void ShowModalHTMLDialog(const GURL& url, int width, int height, - const std::string& json_arguments, - IPC::Message* reply_msg) {} - - // |url| is assigned to a server that can provide alternate error pages. If - // the returned URL is empty, the default error page built into WebKit will - // be used. - virtual GURL GetAlternateErrorPageURL() const; - - // Return a dummy RendererPreferences object that will be used by the renderer - // associated with the owning RenderViewHost. - virtual RendererPreferences GetRendererPrefs(Profile* profile) const = 0; - - // Returns a WebPreferences object that will be used by the renderer - // associated with the owning render view host. - virtual WebPreferences GetWebkitPrefs(); - - // Notification the user has made a gesture while focus was on the - // page. This is used to avoid uninitiated user downloads (aka carpet - // bombing), see DownloadRequestLimiter for details. - virtual void OnUserGesture() {} - - // Notification from the renderer host that blocked UI event occurred. - // This happens when there are tab-modal dialogs. In this case, the - // notification is needed to let us draw attention to the dialog (i.e. - // refocus on the modal dialog, flash title etc). - virtual void OnIgnoredUIEvent() {} - - // Notification that the renderer has become unresponsive. The - // delegate can use this notification to show a warning to the user. - virtual void RendererUnresponsive(RenderViewHost* render_view_host, - bool is_during_unload) {} - - // Notification that a previously unresponsive renderer has become - // responsive again. The delegate can use this notification to end the - // warning shown to the user. - virtual void RendererResponsive(RenderViewHost* render_view_host) {} - - // Notification that the RenderViewHost's load state changed. - virtual void LoadStateChanged(const GURL& url, net::LoadState load_state, - uint64 upload_position, uint64 upload_size) {} - - // Returns true if this view is used to host an external tab container. - virtual bool IsExternalTabContainer() const; - - // The RenderView has inserted one css file into page. - virtual void DidInsertCSS() {} - - // A different node in the page got focused. - virtual void FocusedNodeChanged(bool is_editable_node) {} - - // Updates the minimum and maximum zoom percentages. - virtual void UpdateZoomLimits(int minimum_percent, - int maximum_percent, - bool remember) {} - - // Notification that a worker process has crashed. - void WorkerCrashed() {} - - protected: - virtual ~RenderViewHostDelegate() {} -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_view_host_delegate.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_DELEGATE_H_ diff --git a/chrome/browser/renderer_host/render_view_host_factory.h b/chrome/browser/renderer_host/render_view_host_factory.h index 1a5f5a9..c846fc3 100644 --- a/chrome/browser/renderer_host/render_view_host_factory.h +++ b/chrome/browser/renderer_host/render_view_host_factory.h @@ -6,63 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_ #pragma once -#include "base/basictypes.h" - -class RenderViewHost; -class RenderViewHostDelegate; -class SessionStorageNamespace; -class SiteInstance; - -namespace base { -class WaitableEvent; -} // namespace base - -// A factory for creating RenderViewHosts. There is a global factory function -// that can be installed for the purposes of testing to provide a specialized -// RenderViewHost class. -class RenderViewHostFactory { - public: - // Creates a RenderViewHost using the currently registered factory, or the - // default one if no factory is registered. Ownership of the returned - // pointer will be passed to the caller. - static RenderViewHost* Create(SiteInstance* instance, - RenderViewHostDelegate* delegate, - int routing_id, - SessionStorageNamespace* session_storage); - - // Returns true if there is currently a globally-registered factory. - static bool has_factory() { - return !!factory_; - } - - protected: - RenderViewHostFactory() {} - virtual ~RenderViewHostFactory() {} - - // You can derive from this class and specify an implementation for this - // function to create a different kind of RenderViewHost for testing. - virtual RenderViewHost* CreateRenderViewHost( - SiteInstance* instance, - RenderViewHostDelegate* delegate, - int routing_id, - SessionStorageNamespace* session_storage_namespace) = 0; - - // Registers your factory to be called when new RenderViewHosts are created. - // We have only one global factory, so there must be no factory registered - // before the call. This class does NOT take ownership of the pointer. - static void RegisterFactory(RenderViewHostFactory* factory); - - // Unregister the previously registered factory. With no factory registered, - // the default RenderViewHosts will be created. - static void UnregisterFactory(); - - private: - // The current globally registered factory. This is NULL when we should - // create the default RenderViewHosts. - static RenderViewHostFactory* factory_; - - DISALLOW_COPY_AND_ASSIGN(RenderViewHostFactory); -}; - +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_view_host_factory.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_ diff --git a/chrome/browser/renderer_host/render_view_host_notification_task.h b/chrome/browser/renderer_host/render_view_host_notification_task.h index fb06112..abccbe05b 100644 --- a/chrome/browser/renderer_host/render_view_host_notification_task.h +++ b/chrome/browser/renderer_host/render_view_host_notification_task.h @@ -2,336 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// This file defines utility functions for sending notifications (calling -// methods that return void and do not have out params) to the RenderViewHost -// or one of its delegate interfaces. The notifications are dispatched -// asynchronously, and only if the specified RenderViewHost still exists. - #ifndef CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_NOTIFICATION_TASK_H_ #define CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_NOTIFICATION_TASK_H_ #pragma once -#include "base/callback.h" -#include "base/task.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "chrome/browser/renderer_host/render_view_host_delegate.h" - -// ---------------------------------------------------------------------------- - -namespace internal { - -// The simplest Mapper, used when proxying calls to a RenderViewHost. -class RenderViewHostIdentityMapper { - public: - typedef RenderViewHost MappedType; - static MappedType* Map(RenderViewHost* rvh) { return rvh; } -}; - -template <typename Method, typename Params, - typename Mapper = RenderViewHostIdentityMapper> -class RenderViewHostNotificationTask : public Task { - public: - RenderViewHostNotificationTask(int render_process_id, - int render_view_id, - Method method, - const Params& params) - : render_process_id_(render_process_id), - render_view_id_(render_view_id), - unbound_method_(method, params) { - } - - virtual void Run() { - RenderViewHost* rvh = RenderViewHost::FromID(render_process_id_, - render_view_id_); - typename Mapper::MappedType* obj = Mapper::Map(rvh); - if (obj) - unbound_method_.Run(obj); - } - - private: - int render_process_id_; - int render_view_id_; - UnboundMethod<typename Mapper::MappedType, Method, Params> unbound_method_; - - DISALLOW_COPY_AND_ASSIGN(RenderViewHostNotificationTask); -}; - -// For proxying calls to RenderViewHost - -template <typename Method, typename Params> -inline void CallRenderViewHostHelper(int render_process_id, int render_view_id, - Method method, const Params& params) { - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - new RenderViewHostNotificationTask<Method, Params>(render_process_id, - render_view_id, - method, - params)); -} - -// For proxying calls to RenderViewHostDelegate::ContentSettings - -class RenderViewHostToContentSettingsDelegate { - public: - typedef RenderViewHostDelegate::ContentSettings MappedType; - static MappedType* Map(RenderViewHost* rvh) { - return rvh ? rvh->delegate()->GetContentSettingsDelegate() : NULL; - } -}; - -template <typename Method, typename Params> -inline void CallRenderViewHostContentSettingsDelegateHelper( - int render_process_id, - int render_view_id, - Method method, - const Params& params) { - - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - new RenderViewHostNotificationTask< - Method, Params, RenderViewHostToContentSettingsDelegate>( - render_process_id, - render_view_id, - method, - params)); -} - -// For proxying calls to RenderViewHostDelegate::RendererManagement - -class RenderViewHostToRendererManagementDelegate { - public: - typedef RenderViewHostDelegate::RendererManagement MappedType; - static MappedType* Map(RenderViewHost* rvh) { - return rvh ? rvh->delegate()->GetRendererManagementDelegate() : NULL; - } -}; - -template <typename Method, typename Params> -inline void CallRenderViewHostRendererManagementDelegateHelper( - int render_process_id, - int render_view_id, - Method method, - const Params& params) { - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - new RenderViewHostNotificationTask< - Method, Params, RenderViewHostToRendererManagementDelegate>( - render_process_id, - render_view_id, - method, - params)); -} - -// For proxying calls to RenderViewHostDelegate::SSL - -class RenderViewHostToSSLDelegate { - public: - typedef RenderViewHostDelegate::SSL MappedType; - static MappedType* Map(RenderViewHost* rvh) { - return rvh ? rvh->delegate()->GetSSLDelegate() : NULL; - } -}; - -template <typename Method, typename Params> -inline void CallRenderViewHostSSLDelegateHelper( - int render_process_id, - int render_view_id, - Method method, - const Params& params) { - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - new RenderViewHostNotificationTask< - Method, Params, RenderViewHostToSSLDelegate>( - render_process_id, - render_view_id, - method, - params)); -} - -} // namespace internal - -// ---------------------------------------------------------------------------- -// Proxy calls to the specified RenderViewHost. - -template <typename Method> -inline void CallRenderViewHost(int render_process_id, - int render_view_id, - Method method) { - internal::CallRenderViewHostHelper(render_process_id, - render_view_id, - method, - MakeTuple()); -} - -template <typename Method, typename A> -inline void CallRenderViewHost(int render_process_id, - int render_view_id, - Method method, - const A& a) { - internal::CallRenderViewHostHelper(render_process_id, - render_view_id, - method, - MakeTuple(a)); -} - -template <typename Method, typename A, typename B> -inline void CallRenderViewHost(int render_process_id, - int render_view_id, - Method method, - const A& a, - const B& b) { - internal::CallRenderViewHostHelper(render_process_id, - render_view_id, - method, - MakeTuple(a, b)); -} - -// ---------------------------------------------------------------------------- -// Proxy calls to the specified RenderViewHost's ContentSettings delegate. - -template <typename Method> -inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, - int render_view_id, - Method method) { - internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, - render_view_id, - method, - MakeTuple()); -} - -template <typename Method, typename A> -inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a) { - internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, - render_view_id, - method, - MakeTuple(a)); - } - -template <typename Method, typename A, typename B> -inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a, - const B& b) { - internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, - render_view_id, - method, - MakeTuple(a, b)); -} - -template <typename Method, typename A, typename B, typename C> -inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a, - const B& b, - const C& c) { - internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, - render_view_id, - method, - MakeTuple(a, b, c)); -} - -template <typename Method, typename A, typename B, typename C, typename D> -inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a, - const B& b, - const C& c, - const D& d) { - internal::CallRenderViewHostContentSettingsDelegateHelper( - render_process_id, - render_view_id, - method, - MakeTuple(a, b, c, d)); -} - -template <typename Method, - typename A, typename B, typename C, typename D, typename E> -inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a, - const B& b, - const C& c, - const D& d, - const E& e) { - internal::CallRenderViewHostContentSettingsDelegateHelper( - render_process_id, render_view_id, method, MakeTuple(a, b, c, d, e)); -} - -// ---------------------------------------------------------------------------- -// Proxy calls to the specified RenderViewHost's RendererManagement delegate. - -template <typename Method> -inline void CallRenderViewHostRendererManagementDelegate(int render_process_id, - int render_view_id, - Method method) { - internal::CallRenderViewHostRendererManagementDelegateHelper( - render_process_id, - render_view_id, - method, - MakeTuple()); -} - -template <typename Method, typename A> -inline void CallRenderViewHostRendererManagementDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a) { - internal::CallRenderViewHostRendererManagementDelegateHelper( - render_process_id, - render_view_id, - method, - MakeTuple(a)); -} - -template <typename Method, typename A, typename B> -inline void CallRenderViewHostRendererManagementDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a, - const B& b) { - internal::CallRenderViewHostRendererManagementDelegateHelper( - render_process_id, - render_view_id, - method, - MakeTuple(a, b)); -} - -// ---------------------------------------------------------------------------- -// Proxy calls to the specified RenderViewHost's SSL delegate. - -template <typename Method, typename A> -inline void CallRenderViewHostSSLDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a) { - internal::CallRenderViewHostSSLDelegateHelper( - render_process_id, - render_view_id, - method, - MakeTuple(a)); -} - -template <typename Method, typename A, typename B> -inline void CallRenderViewHostSSLDelegate(int render_process_id, - int render_view_id, - Method method, - const A& a, - const B& b) { - internal::CallRenderViewHostSSLDelegateHelper( - render_process_id, - render_view_id, - method, - MakeTuple(a, b)); -} - -// ---------------------------------------------------------------------------- +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_view_host_notification_task.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_NOTIFICATION_TASK_H_ diff --git a/chrome/browser/renderer_host/render_widget_fullscreen_host.h b/chrome/browser/renderer_host/render_widget_fullscreen_host.h index 1906b4b..3a39d5f 100644 --- a/chrome/browser/renderer_host/render_widget_fullscreen_host.h +++ b/chrome/browser/renderer_host/render_widget_fullscreen_host.h @@ -7,9 +7,7 @@ #include "chrome/browser/renderer_host/render_widget_host.h" -class RenderWidgetFullscreenHost : public RenderWidgetHost { - public: - RenderWidgetFullscreenHost(RenderProcessHost* process, int routing_id); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_widget_fullscreen_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_FULLSCREEN_HOST_H_ diff --git a/chrome/browser/renderer_host/render_widget_helper.h b/chrome/browser/renderer_host/render_widget_helper.h index 3ac67ad..9e356d3 100644 --- a/chrome/browser/renderer_host/render_widget_helper.h +++ b/chrome/browser/renderer_host/render_widget_helper.h @@ -6,211 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HELPER_H_ #pragma once -#include <map> - -#include "app/surface/transport_dib.h" -#include "base/atomic_sequence_num.h" -#include "base/hash_tables.h" -#include "base/process.h" -#include "base/ref_counted.h" -#include "base/synchronization/lock.h" -#include "base/synchronization/waitable_event.h" -#include "chrome/common/window_container_type.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" - -namespace IPC { -class Message; -} - -namespace base { -class TimeDelta; -} - -class ResourceDispatcherHost; -struct ViewHostMsg_CreateWindow_Params; -struct ViewMsg_ClosePage_Params; - - -// Instantiated per RenderProcessHost to provide various optimizations on -// behalf of a RenderWidgetHost. This class bridges between the IO thread -// where the RenderProcessHost's MessageFilter lives and the UI thread where -// the RenderWidgetHost lives. -// -// -// OPTIMIZED RESIZE -// -// RenderWidgetHelper is used to implement optimized resize. When the -// RenderWidgetHost is resized, it sends a Resize message to its RenderWidget -// counterpart in the renderer process. The RenderWidget generates a -// UpdateRect message in response to the Resize message, and it sets the -// IS_RESIZE_ACK flag in the UpdateRect message to true. -// -// Back in the browser process, when the RenderProcessHost's MessageFilter -// sees a UpdateRect message, it directs it to the RenderWidgetHelper by -// calling the DidReceiveUpdateMsg method. That method stores the data for -// the UpdateRect message in a map, where it can be directly accessed by the -// RenderWidgetHost on the UI thread during a call to RenderWidgetHost's -// GetBackingStore method. -// -// When the RenderWidgetHost's GetBackingStore method is called, it first -// checks to see if it is waiting for a resize ack. If it is, then it calls -// the RenderWidgetHelper's WaitForUpdateMsg to check if there is already a -// resulting UpdateRect message (or to wait a short amount of time for one to -// arrive). The main goal of this mechanism is to short-cut the usual way in -// which IPC messages are proxied over to the UI thread via InvokeLater. -// This approach is necessary since window resize is followed up immediately -// by a request to repaint the window. -// -// -// OPTIMIZED TAB SWITCHING -// -// When a RenderWidgetHost is in a background tab, it is flagged as hidden. -// This causes the corresponding RenderWidget to stop sending UpdateRect -// messages. The RenderWidgetHost also discards its backingstore when it is -// hidden, which helps free up memory. As a result, when a RenderWidgetHost -// is restored, it can be momentarily without a backingstore. (Restoring a -// RenderWidgetHost results in a WasRestored message being sent to the -// RenderWidget, which triggers a full UpdateRect message.) This can lead to -// an observed rendering glitch as the TabContents will just have to fill -// white overtop the RenderWidgetHost until the RenderWidgetHost receives a -// UpdateRect message to refresh its backingstore. -// -// To avoid this 'white flash', the RenderWidgetHost again makes use of the -// RenderWidgetHelper's WaitForUpdateMsg method. When the RenderWidgetHost's -// GetBackingStore method is called, it will call WaitForUpdateMsg if it has -// no backingstore. -// -// TRANSPORT DIB CREATION -// -// On some platforms (currently the Mac) the renderer cannot create transport -// DIBs because of sandbox limitations. Thus, it has to make synchronous IPCs -// to the browser for them. Since these requests are synchronous, they cannot -// terminate on the UI thread. Thus, in this case, this object performs the -// allocation and maintains the set of allocated transport DIBs which the -// renderers can refer to. -// -class RenderWidgetHelper - : public base::RefCountedThreadSafe<RenderWidgetHelper> { - public: - RenderWidgetHelper(); - - void Init(int render_process_id, - ResourceDispatcherHost* resource_dispatcher_host); - - // Gets the next available routing id. This is thread safe. - int GetNextRoutingID(); - - - // UI THREAD ONLY ----------------------------------------------------------- - - // These three functions provide the backend implementation of the - // corresponding functions in RenderProcessHost. See those declarations - // for documentation. - void CancelResourceRequests(int render_widget_id); - void CrossSiteClosePageACK(const ViewMsg_ClosePage_Params& params); - bool WaitForUpdateMsg(int render_widget_id, - const base::TimeDelta& max_delay, - IPC::Message* msg); - -#if defined(OS_MACOSX) - // Given the id of a transport DIB, return a mapping to it or NULL on error. - TransportDIB* MapTransportDIB(TransportDIB::Id dib_id); -#endif - - - // IO THREAD ONLY ----------------------------------------------------------- - - // Called on the IO thread when a UpdateRect message is received. - void DidReceiveUpdateMsg(const IPC::Message& msg); - - void CreateNewWindow(const ViewHostMsg_CreateWindow_Params& params, - base::ProcessHandle render_process, - int* route_id); - void CreateNewWidget(int opener_id, - WebKit::WebPopupType popup_type, - int* route_id); - void CreateNewFullscreenWidget(int opener_id, int* route_id); - -#if defined(OS_MACOSX) - // Called on the IO thread to handle the allocation of a TransportDIB. If - // |cache_in_browser| is |true|, then a copy of the shmem is kept by the - // browser, and it is the caller's repsonsibility to call - // FreeTransportDIB(). In all cases, the caller is responsible for deleting - // the resulting TransportDIB. - void AllocTransportDIB(size_t size, - bool cache_in_browser, - TransportDIB::Handle* result); - - // Called on the IO thread to handle the freeing of a transport DIB - void FreeTransportDIB(TransportDIB::Id dib_id); -#endif - - private: - // A class used to proxy a paint message. PaintMsgProxy objects are created - // on the IO thread and destroyed on the UI thread. - class UpdateMsgProxy; - friend class UpdateMsgProxy; - friend class base::RefCountedThreadSafe<RenderWidgetHelper>; - - // Map from render_widget_id to live PaintMsgProxy instance. - typedef base::hash_map<int, UpdateMsgProxy*> UpdateMsgProxyMap; - - ~RenderWidgetHelper(); - - // Called on the UI thread to discard a paint message. - void OnDiscardUpdateMsg(UpdateMsgProxy* proxy); - - // Called on the UI thread to dispatch a paint message if necessary. - void OnDispatchUpdateMsg(UpdateMsgProxy* proxy); - - // Called on the UI thread to finish creating a window. - void OnCreateWindowOnUI(const ViewHostMsg_CreateWindow_Params& params, - int route_id); - - // Called on the IO thread after a window was created on the UI thread. - void OnCreateWindowOnIO(int route_id); - - // Called on the UI thread to finish creating a widget. - void OnCreateWidgetOnUI(int opener_id, - int route_id, - WebKit::WebPopupType popup_type); - - // Called on the UI thread to create a fullscreen widget. - void OnCreateFullscreenWidgetOnUI(int opener_id, int route_id); - - // Called on the IO thread to cancel resource requests for the render widget. - void OnCancelResourceRequests(int render_widget_id); - - // Called on the IO thread to resume a cross-site response. - void OnCrossSiteClosePageACK(const ViewMsg_ClosePage_Params& params); - -#if defined(OS_MACOSX) - // Called on destruction to release all allocated transport DIBs - void ClearAllocatedDIBs(); - - // On OSX we keep file descriptors to all the allocated DIBs around until - // the renderer frees them. - base::Lock allocated_dibs_lock_; - std::map<TransportDIB::Id, int> allocated_dibs_; -#endif - - // A map of live paint messages. Must hold pending_paints_lock_ to access. - // The UpdateMsgProxy objects are not owned by this map. (See UpdateMsgProxy - // for details about how the lifetime of instances are managed.) - UpdateMsgProxyMap pending_paints_; - base::Lock pending_paints_lock_; - - int render_process_id_; - - // Event used to implement WaitForUpdateMsg. - base::WaitableEvent event_; - - // The next routing id to use. - base::AtomicSequenceNumber next_routing_id_; - - ResourceDispatcherHost* resource_dispatcher_host_; - - DISALLOW_COPY_AND_ASSIGN(RenderWidgetHelper); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_widget_helper.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HELPER_H_ diff --git a/chrome/browser/renderer_host/render_widget_host.h b/chrome/browser/renderer_host/render_widget_host.h index f6b22ac..ae5f360 100644 --- a/chrome/browser/renderer_host/render_widget_host.h +++ b/chrome/browser/renderer_host/render_widget_host.h @@ -6,672 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_H_ #pragma once -#include <deque> -#include <string> -#include <vector> - -#include "app/surface/transport_dib.h" -#include "base/gtest_prod_util.h" -#include "base/process_util.h" -#include "base/scoped_ptr.h" -#include "base/string16.h" -#include "base/timer.h" -#include "chrome/common/edit_command.h" -#include "chrome/common/native_web_keyboard_event.h" -#include "chrome/common/property_bag.h" -#include "ipc/ipc_channel.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextDirection.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextInputType.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/size.h" - -namespace gfx { -class Rect; -} - -namespace WebKit { -class WebInputEvent; -class WebMouseEvent; -struct WebCompositionUnderline; -struct WebScreenInfo; -} - -class BackingStore; -class PaintObserver; -class RenderProcessHost; -class RenderWidgetHostView; -class TransportDIB; -class WebCursor; -struct ViewHostMsg_UpdateRect_Params; - -// This class manages the browser side of a browser<->renderer HWND connection. -// The HWND lives in the browser process, and windows events are sent over -// IPC to the corresponding object in the renderer. The renderer paints into -// shared memory, which we transfer to a backing store and blit to the screen -// when Windows sends us a WM_PAINT message. -// -// How Shutdown Works -// -// There are two situations in which this object, a RenderWidgetHost, can be -// instantiated: -// -// 1. By a TabContents as the communication conduit for a rendered web page. -// The TabContents instantiates a derived class: RenderViewHost. -// 2. By a TabContents as the communication conduit for a select widget. The -// TabContents instantiates the RenderWidgetHost directly. -// -// For every TabContents there are several objects in play that need to be -// properly destroyed or cleaned up when certain events occur. -// -// - TabContents - the TabContents itself, and its associated HWND. -// - RenderViewHost - representing the communication conduit with the child -// process. -// - RenderWidgetHostView - the view of the web page content, message handler, -// and plugin root. -// -// Normally, the TabContents contains a child RenderWidgetHostView that renders -// the contents of the loaded page. It has a WS_CLIPCHILDREN style so that it -// does no painting of its own. -// -// The lifetime of the RenderWidgetHostView is tied to the render process. If -// the render process dies, the RenderWidgetHostView goes away and all -// references to it must become NULL. If the TabContents finds itself without a -// RenderWidgetHostView, it paints Sad Tab instead. -// -// RenderViewHost (a RenderWidgetHost subclass) is the conduit used to -// communicate with the RenderView and is owned by the TabContents. If the -// render process crashes, the RenderViewHost remains and restarts the render -// process if needed to continue navigation. -// -// The TabContents is itself owned by the NavigationController in which it -// resides. -// -// Some examples of how shutdown works: -// -// When a tab is closed (either by the user, the web page calling window.close, -// etc) the TabStrip destroys the associated NavigationController, which calls -// Destroy on each TabContents it owns. -// -// For a TabContents, its Destroy method tells the RenderViewHost to -// shut down the render process and die. -// -// When the render process is destroyed it destroys the View: the -// RenderWidgetHostView, which destroys its HWND and deletes that object. -// -// For select popups, the situation is a little different. The RenderWidgetHost -// associated with the select popup owns the view and itself (is responsible -// for destroying itself when the view is closed). The TabContents's only -// responsibility is to select popups is to create them when it is told to. When -// the View is destroyed via an IPC message (for when WebCore destroys the -// popup, e.g. if the user selects one of the options), or because -// WM_CANCELMODE is received by the view, the View schedules the destruction of -// the render process. However in this case since there's no TabContents -// container, when the render process is destroyed, the RenderWidgetHost just -// deletes itself, which is safe because no one else should have any references -// to it (the TabContents does not). -// -// It should be noted that the RenderViewHost, not the RenderWidgetHost, -// handles IPC messages relating to the render process going away, since the -// way a RenderViewHost (TabContents) handles the process dying is different to -// the way a select popup does. As such the RenderWidgetHostView handles these -// messages for select popups. This placement is more out of convenience than -// anything else. When the view is live, these messages are forwarded to it by -// the RenderWidgetHost's IPC message map. -// -class RenderWidgetHost : public IPC::Channel::Listener, - public IPC::Channel::Sender { - public: - // Used as the details object for a - // RENDER_WIDGET_HOST_DID_RECEIVE_PAINT_AT_SIZE_ACK notification. - struct PaintAtSizeAckDetails { - // The tag that was passed to the PaintAtSize() call that triggered this - // ack. - int tag; - gfx::Size size; - }; - - // routing_id can be MSG_ROUTING_NONE, in which case the next available - // routing id is taken from the RenderProcessHost. - RenderWidgetHost(RenderProcessHost* process, int routing_id); - virtual ~RenderWidgetHost(); - - // Gets/Sets the View of this RenderWidgetHost. Can be NULL, e.g. if the - // RenderWidget is being destroyed or the render process crashed. You should - // never cache this pointer since it can become NULL if the renderer crashes, - // instead you should always ask for it using the accessor. - void set_view(RenderWidgetHostView* view) { view_ = view; } - RenderWidgetHostView* view() const { return view_; } - - RenderProcessHost* process() const { return process_; } - int routing_id() const { return routing_id_; } - bool renderer_accessible() { return renderer_accessible_; } - - // Returns the property bag for this widget, where callers can add extra data - // they may wish to associate with it. Returns a pointer rather than a - // reference since the PropertyAccessors expect this. - const PropertyBag* property_bag() const { return &property_bag_; } - PropertyBag* property_bag() { return &property_bag_; } - - // Called when a renderer object already been created for this host, and we - // just need to be attached to it. Used for window.open, <select> dropdown - // menus, and other times when the renderer initiates creating an object. - void Init(); - - // Tells the renderer to die and then calls Destroy(). - virtual void Shutdown(); - - // Manual RTTI FTW. We are not hosting a web page. - virtual bool IsRenderView() const; - - // IPC::Channel::Listener - virtual bool OnMessageReceived(const IPC::Message& msg); - - // Sends a message to the corresponding object in the renderer. - virtual bool Send(IPC::Message* msg); - - // Called to notify the RenderWidget that it has been hidden or restored from - // having been hidden. - void WasHidden(); - void WasRestored(); - - // Called to notify the RenderWidget that it has been resized. - void WasResized(); - - // Called to notify the RenderWidget that its associated native window got - // focused. - virtual void GotFocus(); - - // Tells the renderer it got/lost focus. - void Focus(); - void Blur(); - virtual void LostCapture(); - - // Tells us whether the page is rendered directly via the GPU process. - bool is_accelerated_compositing_active() { - return is_accelerated_compositing_active_; - } - - // Notifies the RenderWidgetHost that the View was destroyed. - void ViewDestroyed(); - - // Indicates if the page has finished loading. - void SetIsLoading(bool is_loading); - - // This tells the renderer to paint into a bitmap and return it, - // regardless of whether the tab is hidden or not. It resizes the - // web widget to match the |page_size| and then returns the bitmap - // scaled so it matches the |desired_size|, so that the scaling - // happens on the rendering thread. When the bitmap is ready, the - // renderer sends a PaintAtSizeACK to this host, and a - // RENDER_WIDGET_HOST_DID_RECEIVE_PAINT_AT_SIZE_ACK notification is issued. - // Note that this bypasses most of the update logic that is normally invoked, - // and doesn't put the results into the backing store. - void PaintAtSize(TransportDIB::Handle dib_handle, - int tag, - const gfx::Size& page_size, - const gfx::Size& desired_size); - - // Get access to the widget's backing store. If a resize is in progress, - // then the current size of the backing store may be less than the size of - // the widget's view. If you pass |force_create| as true, then the backing - // store will be created if it doesn't exist. Otherwise, NULL will be returned - // if the backing store doesn't already exist. It will also return NULL if the - // backing store could not be created. - BackingStore* GetBackingStore(bool force_create); - - // Allocate a new backing store of the given size. Returns NULL on failure - // (for example, if we don't currently have a RenderWidgetHostView.) - BackingStore* AllocBackingStore(const gfx::Size& size); - - // When a backing store does asynchronous painting, it will call this function - // when it is done with the DIB. We will then forward a message to the - // renderer to send another paint. - void DonePaintingToBackingStore(); - - // GPU accelerated version of GetBackingStore function. This will - // trigger a re-composite to the view. If a resize is pending, it will - // block briefly waiting for an ack from the renderer. - void ScheduleComposite(); - - // Starts a hang monitor timeout. If there's already a hang monitor timeout - // the new one will only fire if it has a shorter delay than the time - // left on the existing timeouts. - void StartHangMonitorTimeout(base::TimeDelta delay); - - // Restart the active hang monitor timeout. Clears all existing timeouts and - // starts with a new one. This can be because the renderer has become - // active, the tab is being hidden, or the user has chosen to wait some more - // to give the tab a chance to become active and we don't want to display a - // warning too soon. - void RestartHangMonitorTimeout(); - - // Stops all existing hang monitor timeouts and assumes the renderer is - // responsive. - void StopHangMonitorTimeout(); - - // Called when the system theme changes. At this time all existing native - // theme handles are invalid and the renderer must obtain new ones and - // repaint. - void SystemThemeChanged(); - - // Forwards the given message to the renderer. These are called by the view - // when it has received a message. - virtual void ForwardMouseEvent(const WebKit::WebMouseEvent& mouse_event); - // Called when a mouse click activates the renderer. - virtual void OnMouseActivate(); - void ForwardWheelEvent(const WebKit::WebMouseWheelEvent& wheel_event); - virtual void ForwardKeyboardEvent(const NativeWebKeyboardEvent& key_event); - virtual void ForwardEditCommand(const std::string& name, - const std::string& value); - virtual void ForwardEditCommandsForNextKeyEvent( - const EditCommands& edit_commands); -#if defined(TOUCH_UI) - virtual void ForwardTouchEvent(const WebKit::WebTouchEvent& touch_event); -#endif - - - // Update the text direction of the focused input element and notify it to a - // renderer process. - // These functions have two usage scenarios: changing the text direction - // from a menu (as Safari does), and; changing the text direction when a user - // presses a set of keys (as IE and Firefox do). - // 1. Change the text direction from a menu. - // In this scenario, we receive a menu event only once and we should update - // the text direction immediately when a user chooses a menu item. So, we - // should call both functions at once as listed in the following snippet. - // void RenderViewHost::SetTextDirection(WebTextDirection direction) { - // UpdateTextDirection(direction); - // NotifyTextDirection(); - // } - // 2. Change the text direction when pressing a set of keys. - // Because of auto-repeat, we may receive the same key-press event many - // times while we presses the keys and it is nonsense to send the same IPC - // message every time when we receive a key-press event. - // To suppress the number of IPC messages, we just update the text direction - // when receiving a key-press event and send an IPC message when we release - // the keys as listed in the following snippet. - // if (key_event.type == WebKeyboardEvent::KEY_DOWN) { - // if (key_event.windows_key_code == 'A' && - // key_event.modifiers == WebKeyboardEvent::CTRL_KEY) { - // UpdateTextDirection(dir); - // } else { - // CancelUpdateTextDirection(); - // } - // } else if (key_event.type == WebKeyboardEvent::KEY_UP) { - // NotifyTextDirection(); - // } - // Once we cancel updating the text direction, we have to ignore all - // succeeding UpdateTextDirection() requests until calling - // NotifyTextDirection(). (We may receive keydown events even after we - // canceled updating the text direction because of auto-repeat.) - // Note: we cannot undo this change for compatibility with Firefox and IE. - void UpdateTextDirection(WebKit::WebTextDirection direction); - void CancelUpdateTextDirection(); - void NotifyTextDirection(); - - // Notifies the renderer whether or not the input method attached to this - // process is activated. - // When the input method is activated, a renderer process sends IPC messages - // to notify the status of its composition node. (This message is mainly used - // for notifying the position of the input cursor so that the browser can - // display input method windows under the cursor.) - void SetInputMethodActive(bool activate); - - // Update the composition node of the renderer (or WebKit). - // WebKit has a special node (a composition node) for input method to change - // its text without affecting any other DOM nodes. When the input method - // (attached to the browser) updates its text, the browser sends IPC messages - // to update the composition node of the renderer. - // (Read the comments of each function for its detail.) - - // Sets the text of the composition node. - // This function can also update the cursor position and mark the specified - // range in the composition node. - // A browser should call this function: - // * when it receives a WM_IME_COMPOSITION message with a GCS_COMPSTR flag - // (on Windows); - // * when it receives a "preedit_changed" signal of GtkIMContext (on Linux); - // * when markedText of NSTextInput is called (on Mac). - void ImeSetComposition( - const string16& text, - const std::vector<WebKit::WebCompositionUnderline>& underlines, - int selection_start, - int selection_end); - - // Finishes an ongoing composition with the specified text. - // A browser should call this function: - // * when it receives a WM_IME_COMPOSITION message with a GCS_RESULTSTR flag - // (on Windows); - // * when it receives a "commit" signal of GtkIMContext (on Linux); - // * when insertText of NSTextInput is called (on Mac). - void ImeConfirmComposition(const string16& text); - - // Finishes an ongoing composition with the composition text set by last - // SetComposition() call. - void ImeConfirmComposition(); - - // Cancels an ongoing composition. - void ImeCancelComposition(); - - // Makes an IPC call to toggle the spelling panel. - void ToggleSpellPanel(bool is_currently_visible); - - // Makes an IPC call to tell webkit to replace the currently selected word - // or a word around the cursor. - void Replace(const string16& word); - - // Makes an IPC call to tell webkit to advance to the next misspelling. - void AdvanceToNextMisspelling(); - - // Enable renderer accessibility. This should only be called when a - // screenreader is detected. - void EnableRendererAccessibility(); - - // Relays a request from assistive technology to set focus to the - // node with this accessibility object id. - void SetAccessibilityFocus(int acc_obj_id); - - // Relays a request from assistive technology to perform the default action - // on a node with this accessibility object id. - void AccessibilityDoDefaultAction(int acc_obj_id); - - // Acknowledges a ViewHostMsg_AccessibilityNotifications message. - void AccessibilityNotificationsAck(); - - // Sets the active state (i.e., control tints). - virtual void SetActive(bool active); - - void set_ignore_input_events(bool ignore_input_events) { - ignore_input_events_ = ignore_input_events; - } - bool ignore_input_events() const { - return ignore_input_events_; - } - - // Activate deferred plugin handles. - void ActivateDeferredPluginHandles(); - - const gfx::Point& last_scroll_offset() const { return last_scroll_offset_; } - - protected: - // Internal implementation of the public Forward*Event() methods. - void ForwardInputEvent(const WebKit::WebInputEvent& input_event, - int event_size, bool is_keyboard_shortcut); - - // Called when we receive a notification indicating that the renderer - // process has gone. This will reset our state so that our state will be - // consistent if a new renderer is created. - void RendererExited(base::TerminationStatus status, int exit_code); - - // Retrieves an id the renderer can use to refer to its view. - // This is used for various IPC messages, including plugins. - gfx::NativeViewId GetNativeViewId(); - - // Called to handled a keyboard event before sending it to the renderer. - // This is overridden by RenderView to send upwards to its delegate. - // Returns true if the event was handled, and then the keyboard event will - // not be sent to the renderer anymore. Otherwise, if the |event| would - // be handled in HandleKeyboardEvent() method as a normal keyboard shortcut, - // |*is_keyboard_shortcut| should be set to true. - virtual bool PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, - bool* is_keyboard_shortcut); - - // Called when a keyboard event was not processed by the renderer. This is - // overridden by RenderView to send upwards to its delegate. - virtual void UnhandledKeyboardEvent(const NativeWebKeyboardEvent& event) {} - - // Notification that the user has made some kind of input that could - // perform an action. The render view host overrides this to forward the - // information to its delegate (see corresponding function in - // RenderViewHostDelegate). The gestures that count are 1) any mouse down - // event and 2) enter or space key presses. - virtual void OnUserGesture() {} - - // Callbacks for notification when the renderer becomes unresponsive to user - // input events, and subsequently responsive again. RenderViewHost overrides - // these to tell its delegate to show the user a warning. - virtual void NotifyRendererUnresponsive() {} - virtual void NotifyRendererResponsive() {} - - protected: - // true if a renderer has once been valid. We use this flag to display a sad - // tab only when we lose our renderer and not if a paint occurs during - // initialization. - bool renderer_initialized_; - - private: - FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, Resize); - FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, ResizeThenCrash); - FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, HiddenPaint); - FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, PaintAtSize); - - // Tell this object to destroy itself. - void Destroy(); - - // Checks whether the renderer is hung and calls NotifyRendererUnresponsive - // if it is. - void CheckRendererIsUnresponsive(); - - // Called if we know the renderer is responsive. When we currently think the - // renderer is unresponsive, this will clear that state and call - // NotifyRendererResponsive. - void RendererIsResponsive(); - - // IPC message handlers - void OnMsgRenderViewReady(); - void OnMsgRenderViewGone(int status, int error_code); - void OnMsgClose(); - void OnMsgRequestMove(const gfx::Rect& pos); - void OnMsgPaintAtSizeAck(int tag, const gfx::Size& size); - void OnMsgUpdateRect(const ViewHostMsg_UpdateRect_Params& params); - void OnMsgInputEventAck(const IPC::Message& message); - virtual void OnMsgFocus(); - virtual void OnMsgBlur(); - - void OnMsgSetCursor(const WebCursor& cursor); - void OnMsgImeUpdateTextInputState(WebKit::WebTextInputType type, - const gfx::Rect& caret_rect); - void OnMsgImeCancelComposition(); - - void OnMsgDidActivateAcceleratedCompositing(bool activated); - -#if defined(OS_MACOSX) - void OnMsgGetScreenInfo(gfx::NativeViewId view, - WebKit::WebScreenInfo* results); - void OnMsgGetWindowRect(gfx::NativeViewId window_id, gfx::Rect* results); - void OnMsgGetRootWindowRect(gfx::NativeViewId window_id, gfx::Rect* results); - void OnMsgPluginFocusChanged(bool focused, int plugin_id); - void OnMsgStartPluginIme(); - void OnAllocateFakePluginWindowHandle(bool opaque, - bool root, - gfx::PluginWindowHandle* id); - void OnDestroyFakePluginWindowHandle(gfx::PluginWindowHandle id); - void OnAcceleratedSurfaceSetIOSurface(gfx::PluginWindowHandle window, - int32 width, - int32 height, - uint64 mach_port); - void OnAcceleratedSurfaceSetTransportDIB(gfx::PluginWindowHandle window, - int32 width, - int32 height, - TransportDIB::Handle transport_dib); - void OnAcceleratedSurfaceBuffersSwapped(gfx::PluginWindowHandle window, - uint64 surface_id); -#elif defined(OS_POSIX) - void OnMsgCreatePluginContainer(gfx::PluginWindowHandle id); - void OnMsgDestroyPluginContainer(gfx::PluginWindowHandle id); -#endif - - // Paints the given bitmap to the current backing store at the given location. - void PaintBackingStoreRect(TransportDIB::Id bitmap, - const gfx::Rect& bitmap_rect, - const std::vector<gfx::Rect>& copy_rects, - const gfx::Size& view_size); - - // Scrolls the given |clip_rect| in the backing by the given dx/dy amount. The - // |dib| and its corresponding location |bitmap_rect| in the backing store - // is the newly painted pixels by the renderer. - void ScrollBackingStoreRect(int dx, int dy, const gfx::Rect& clip_rect, - const gfx::Size& view_size); - - // Called by OnMsgInputEventAck() to process a keyboard event ack message. - void ProcessKeyboardEventAck(int type, bool processed); - - // Called by OnMsgInputEventAck() to process a wheel event ack message. - // This could result in a task being posted to allow additional wheel - // input messages to be coalesced. - void ProcessWheelAck(); - - // True if renderer accessibility is enabled. This should only be set when a - // screenreader is detected as it can potentially slow down Chrome. - bool renderer_accessible_; - - // The View associated with the RenderViewHost. The lifetime of this object - // is associated with the lifetime of the Render process. If the Renderer - // crashes, its View is destroyed and this pointer becomes NULL, even though - // render_view_host_ lives on to load another URL (creating a new View while - // doing so). - RenderWidgetHostView* view_; - - // Created during construction but initialized during Init*(). Therefore, it - // is guaranteed never to be NULL, but its channel may be NULL if the - // renderer crashed, so you must always check that. - RenderProcessHost* process_; - - // Stores random bits of data for others to associate with this object. - PropertyBag property_bag_; - - // The ID of the corresponding object in the Renderer Instance. - int routing_id_; - - // Indicates whether a page is loading or not. - bool is_loading_; - - // Indicates whether a page is hidden or not. - bool is_hidden_; - - // True when a page is rendered directly via the GPU process. - bool is_accelerated_compositing_active_; - - // Set if we are waiting for a repaint ack for the view. - bool repaint_ack_pending_; - - // True when waiting for RESIZE_ACK. - bool resize_ack_pending_; - - // The current size of the RenderWidget. - gfx::Size current_size_; - - // The current reserved area of the RenderWidget where contents should not be - // rendered to draw the resize corner, sidebar mini tabs etc. - gfx::Rect current_reserved_rect_; - - // The size we last sent as requested size to the renderer. |current_size_| - // is only updated once the resize message has been ack'd. This on the other - // hand is updated when the resize message is sent. This is very similar to - // |resize_ack_pending_|, but the latter is not set if the new size has width - // or height zero, which is why we need this too. - gfx::Size in_flight_size_; - - // The reserved area we last sent to the renderer. |current_reserved_rect_| - // is only updated once the resize message has been ack'd. This on the other - // hand is updated when the resize message is sent. - gfx::Rect in_flight_reserved_rect_; - - // True if a mouse move event was sent to the render view and we are waiting - // for a corresponding ViewHostMsg_HandleInputEvent_ACK message. - bool mouse_move_pending_; - - // The next mouse move event to send (only non-null while mouse_move_pending_ - // is true). - scoped_ptr<WebKit::WebMouseEvent> next_mouse_move_; - - // (Similar to |mouse_move_pending_|.) True if a mouse wheel event was sent - // and we are waiting for a corresponding ack. - bool mouse_wheel_pending_; - - typedef std::deque<WebKit::WebMouseWheelEvent> WheelEventQueue; - - // (Similar to |next_mouse_move_|.) The next mouse wheel events to send. - // Unlike mouse moves, mouse wheel events received while one is pending are - // coalesced (by accumulating deltas) if they match the previous event in - // modifiers. On the Mac, in particular, mouse wheel events are received at a - // high rate; not waiting for the ack results in jankiness, and using the same - // mechanism as for mouse moves (just dropping old events when multiple ones - // would be queued) results in very slow scrolling. - WheelEventQueue coalesced_mouse_wheel_events_; - - // The time when an input event was sent to the RenderWidget. - base::TimeTicks input_event_start_time_; - - // If true, then we should repaint when restoring even if we have a - // backingstore. This flag is set to true if we receive a paint message - // while is_hidden_ to true. Even though we tell the render widget to hide - // itself, a paint message could already be in flight at that point. - bool needs_repainting_on_restore_; - - // This is true if the renderer is currently unresponsive. - bool is_unresponsive_; - - // The following value indicates a time in the future when we would consider - // the renderer hung if it does not generate an appropriate response message. - base::Time time_when_considered_hung_; - - // This timer runs to check if time_when_considered_hung_ has past. - base::OneShotTimer<RenderWidgetHost> hung_renderer_timer_; - - // Flag to detect recursive calls to GetBackingStore(). - bool in_get_backing_store_; - - // Set when we call DidPaintRect/DidScrollRect on the view. - bool view_being_painted_; - - // Used for UMA histogram logging to measure the time for a repaint view - // operation to finish. - base::TimeTicks repaint_start_time_; - - // Queue of keyboard events that we need to track. - typedef std::deque<NativeWebKeyboardEvent> KeyQueue; - - // A queue of keyboard events. We can't trust data from the renderer so we - // stuff key events into a queue and pop them out on ACK, feeding our copy - // back to whatever unhandled handler instead of the returned version. - KeyQueue key_queue_; - - // Set to true if we shouldn't send input events from the render widget. - bool ignore_input_events_; - - // Set when we update the text direction of the selected input element. - bool text_direction_updated_; - WebKit::WebTextDirection text_direction_; - - // Set when we cancel updating the text direction. - // This flag also ignores succeeding update requests until we call - // NotifyTextDirection(). - bool text_direction_canceled_; - - // Indicates if the next sequence of Char events should be suppressed or not. - // System may translate a RawKeyDown event into zero or more Char events, - // usually we send them to the renderer directly in sequence. However, If a - // RawKeyDown event was not handled by the renderer but was handled by - // our UnhandledKeyboardEvent() method, e.g. as an accelerator key, then we - // shall not send the following sequence of Char events, which was generated - // by this RawKeyDown event, to the renderer. Otherwise the renderer may - // handle the Char events and cause unexpected behavior. - // For example, pressing alt-2 may let the browser switch to the second tab, - // but the Char event generated by alt-2 may also activate a HTML element - // if its accesskey happens to be "2", then the user may get confused when - // switching back to the original tab, because the content may already be - // changed. - bool suppress_next_char_events_; - - std::vector<gfx::PluginWindowHandle> deferred_plugin_handles_; - - // The last scroll offset of the render widget. - gfx::Point last_scroll_offset_; - - DISALLOW_COPY_AND_ASSIGN(RenderWidgetHost); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_widget_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_H_ diff --git a/chrome/browser/renderer_host/render_widget_host_view.h b/chrome/browser/renderer_host/render_widget_host_view.h index b6137ff..9b95550 100644 --- a/chrome/browser/renderer_host/render_widget_host_view.h +++ b/chrome/browser/renderer_host/render_widget_host_view.h @@ -6,321 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_H_ #pragma once -#if defined(OS_MACOSX) -#include <OpenGL/OpenGL.h> -#endif - -#include <string> -#include <vector> - -#include "app/surface/transport_dib.h" -#include "base/process_util.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" -#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextInputType.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect.h" - -namespace gfx { -class Rect; -class Size; -} -namespace IPC { -class Message; -} - -class BackingStore; -class RenderProcessHost; -class RenderWidgetHost; -class WebCursor; -struct NativeWebKeyboardEvent; -struct ViewHostMsg_AccessibilityNotification_Params; - -namespace webkit_glue { -struct WebAccessibility; -} - -namespace webkit { -namespace npapi { -struct WebPluginGeometry; -} -} - -// RenderWidgetHostView is an interface implemented by an object that acts as -// the "View" portion of a RenderWidgetHost. The RenderWidgetHost and its -// associated RenderProcessHost own the "Model" in this case which is the -// child renderer process. The View is responsible for receiving events from -// the surrounding environment and passing them to the RenderWidgetHost, and -// for actually displaying the content of the RenderWidgetHost when it -// changes. -class RenderWidgetHostView { - public: - virtual ~RenderWidgetHostView(); - - // Platform-specific creator. Use this to construct new RenderWidgetHostViews - // rather than using RenderWidgetHostViewWin & friends. - // - // This function must NOT size it, because the RenderView in the renderer - // wounldn't have been created yet. The widget would set its "waiting for - // resize ack" flag, and the ack would never come becasue no RenderView - // received it. - // - // The RenderWidgetHost must already be created (because we can't know if it's - // going to be a regular RenderWidgetHost or a RenderViewHost (a subclass). - static RenderWidgetHostView* CreateViewForWidget(RenderWidgetHost* widget); - - // Retrieves the RenderWidgetHostView corresponding to the specified - // |native_view|, or NULL if there is no such instance. - static RenderWidgetHostView* GetRenderWidgetHostViewFromNativeView( - gfx::NativeView native_view); - - // Perform all the initialization steps necessary for this object to represent - // a popup (such as a <select> dropdown), then shows the popup at |pos|. - virtual void InitAsPopup(RenderWidgetHostView* parent_host_view, - const gfx::Rect& pos) = 0; - - // Perform all the initialization steps necessary for this object to represent - // a full screen window. - virtual void InitAsFullscreen() = 0; - - // Returns the associated RenderWidgetHost. - virtual RenderWidgetHost* GetRenderWidgetHost() const = 0; - - // Notifies the View that it has become visible. - virtual void DidBecomeSelected() = 0; - - // Notifies the View that it has been hidden. - virtual void WasHidden() = 0; - - // Tells the View to size itself to the specified size. - virtual void SetSize(const gfx::Size& size) = 0; - - // Retrieves the native view used to contain plugins and identify the - // renderer in IPC messages. - virtual gfx::NativeView GetNativeView() = 0; - - // Moves all plugin windows as described in the given list. - virtual void MovePluginWindows( - const std::vector<webkit::npapi::WebPluginGeometry>& moves) = 0; - - // Actually set/take focus to/from the associated View component. - virtual void Focus() = 0; - virtual void Blur() = 0; - - // Returns true if the View currently has the focus. - virtual bool HasFocus() = 0; - - // Shows/hides the view. These must always be called together in pairs. - // It is not legal to call Hide() multiple times in a row. - virtual void Show() = 0; - virtual void Hide() = 0; - - // Whether the view is showing. - virtual bool IsShowing() = 0; - - // Retrieve the bounds of the View, in screen coordinates. - virtual gfx::Rect GetViewBounds() const = 0; - - // Sets the cursor to the one associated with the specified cursor_type - virtual void UpdateCursor(const WebCursor& cursor) = 0; - - // Indicates whether the page has finished loading. - virtual void SetIsLoading(bool is_loading) = 0; - - // Updates the state of the input method attached to the view. - virtual void ImeUpdateTextInputState(WebKit::WebTextInputType type, - const gfx::Rect& caret_rect) = 0; - - // Cancel the ongoing composition of the input method attached to the view. - virtual void ImeCancelComposition() = 0; - - // Informs the view that a portion of the widget's backing store was scrolled - // and/or painted. The view should ensure this gets copied to the screen. - // - // If the scroll_rect is non-empty, then a portion of the widget's backing - // store was scrolled by dx pixels horizontally and dy pixels vertically. - // The exposed rect from the scroll operation is included in copy_rects. - // - // There are subtle performance implications here. The RenderWidget gets sent - // a paint ack after this returns, so if the view only ever invalidates in - // response to this, then on Windows, where WM_PAINT has lower priority than - // events which can cause renderer resizes/paint rect updates, e.g. - // drag-resizing can starve painting; this function thus provides the view its - // main chance to ensure it stays painted and not just invalidated. On the - // other hand, if this always blindly paints, then if we're already in the - // midst of a paint on the callstack, we can double-paint unnecessarily. - // (Worse, we might recursively call RenderWidgetHost::GetBackingStore().) - // Thus implementers should generally paint as much of |rect| as possible - // synchronously with as little overpainting as possible. - virtual void DidUpdateBackingStore( - const gfx::Rect& scroll_rect, int scroll_dx, int scroll_dy, - const std::vector<gfx::Rect>& copy_rects) = 0; - - // Notifies the View that the renderer has ceased to exist. - virtual void RenderViewGone(base::TerminationStatus status, - int error_code) = 0; - - // Notifies the View that the renderer will be delete soon. - virtual void WillDestroyRenderWidget(RenderWidgetHost* rwh) = 0; - - // Tells the View to destroy itself. - virtual void Destroy() = 0; - - // Tells the View that the tooltip text for the current mouse position over - // the page has changed. - virtual void SetTooltipText(const std::wstring& tooltip_text) = 0; - - // Notifies the View that the renderer text selection has changed. - virtual void SelectionChanged(const std::string& text) {} - - // Tells the View whether the context menu is showing. This is used on Linux - // to suppress updates to webkit focus for the duration of the show. - virtual void ShowingContextMenu(bool showing) {} - - // Allocate a backing store for this view - virtual BackingStore* AllocBackingStore(const gfx::Size& size) = 0; - -#if defined(OS_MACOSX) - // Tells the view whether or not to accept first responder status. If |flag| - // is true, the view does not accept first responder status and instead - // manually becomes first responder when it receives a mouse down event. If - // |flag| is false, the view participates in the key-view chain as normal. - virtual void SetTakesFocusOnlyOnMouseDown(bool flag) = 0; - - // Retrieve the bounds of the view, in cocoa view coordinates. - // If the UI scale factor is 2, |GetViewBounds()| will return a size of e.g. - // (400, 300) in pixels, while this method will return (200, 150). - // Even though this returns an gfx::Rect, the result is NOT IN PIXELS. - virtual gfx::Rect GetViewCocoaBounds() const = 0; - - // Get the view's window's position on the screen. - virtual gfx::Rect GetRootWindowRect() = 0; - - // Set the view's active state (i.e., tint state of controls). - virtual void SetActive(bool active) = 0; - - // Notifies the view that its enclosing window has changed visibility - // (minimized/unminimized, app hidden/unhidden, etc). - // TODO(stuartmorgan): This is a temporary plugin-specific workaround for - // <http://crbug.com/34266>. Once that is fixed, this (and the corresponding - // message and renderer-side handling) can be removed in favor of using - // WasHidden/DidBecomeSelected. - virtual void SetWindowVisibility(bool visible) = 0; - - // Informs the view that its containing window's frame changed. - virtual void WindowFrameChanged() = 0; - - // Informs the view that a plugin gained or lost focus. - virtual void PluginFocusChanged(bool focused, int plugin_id) = 0; - - // Start plugin IME. - virtual void StartPluginIme() = 0; - - // Does any event handling necessary for plugin IME; should be called after - // the plugin has already had a chance to process the event. If plugin IME is - // not enabled, this is a no-op, so it is always safe to call. - // Returns true if the event was handled by IME. - virtual bool PostProcessEventForPluginIme( - const NativeWebKeyboardEvent& event) = 0; - - // Methods associated with GPU-accelerated plug-in instances. - virtual gfx::PluginWindowHandle AllocateFakePluginWindowHandle( - bool opaque, bool root) = 0; - virtual void DestroyFakePluginWindowHandle( - gfx::PluginWindowHandle window) = 0; - virtual void AcceleratedSurfaceSetIOSurface( - gfx::PluginWindowHandle window, - int32 width, - int32 height, - uint64 io_surface_identifier) = 0; - virtual void AcceleratedSurfaceSetTransportDIB( - gfx::PluginWindowHandle window, - int32 width, - int32 height, - TransportDIB::Handle transport_dib) = 0; - // |window| and |surface_id| indicate which accelerated surface's - // buffers swapped. |renderer_id|, |route_id| and - // |swap_buffers_count| are used to formulate a reply to the GPU - // process to prevent it from getting too far ahead. They may all be - // zero, in which case no flow control is enforced; this case is - // currently used for accelerated plugins. - virtual void AcceleratedSurfaceBuffersSwapped( - gfx::PluginWindowHandle window, - uint64 surface_id, - int renderer_id, - int32 route_id, - uint64 swap_buffers_count) = 0; - virtual void GpuRenderingStateDidChange() = 0; -#endif - -#if defined(TOOLKIT_USES_GTK) - virtual void CreatePluginContainer(gfx::PluginWindowHandle id) = 0; - virtual void DestroyPluginContainer(gfx::PluginWindowHandle id) = 0; - virtual void AcceleratedCompositingActivated(bool activated) = 0; -#endif - -#if defined(OS_WIN) - virtual void WillWmDestroy() = 0; - virtual void ShowCompositorHostWindow(bool show) = 0; -#endif - - virtual gfx::PluginWindowHandle AcquireCompositingSurface() = 0; - virtual void ReleaseCompositingSurface(gfx::PluginWindowHandle surface) = 0; - - // Toggles visual muting of the render view area. This is on when a - // constrained window is showing, for example. |color| is the shade of - // the overlay that covers the render view. If |animate| is true, the overlay - // gradually fades in; otherwise it takes effect immediately. To remove the - // fade effect, pass a NULL value for |color|. In this case, |animate| is - // ignored. - virtual void SetVisuallyDeemphasized(const SkColor* color, bool animate) = 0; - - void set_popup_type(WebKit::WebPopupType popup_type) { - popup_type_ = popup_type; - } - WebKit::WebPopupType popup_type() const { return popup_type_; } - - // Subclasses should override this method to do what is appropriate to set - // the custom background for their platform. - virtual void SetBackground(const SkBitmap& background); - const SkBitmap& background() const { return background_; } - - // Returns true if the native view, |native_view|, is contained within in the - // widget associated with this RenderWidgetHostView. - virtual bool ContainsNativeView(gfx::NativeView native_view) const = 0; - - virtual void UpdateAccessibilityTree( - const webkit_glue::WebAccessibility& tree) { } - virtual void OnAccessibilityNotifications( - const std::vector<ViewHostMsg_AccessibilityNotification_Params>& params) { - } - - gfx::Rect reserved_contents_rect() const { - return reserved_rect_; - } - void set_reserved_contents_rect(const gfx::Rect& reserved_rect) { - reserved_rect_ = reserved_rect; - } - - protected: - // Interface class only, do not construct. - RenderWidgetHostView() : popup_type_(WebKit::WebPopupTypeNone) {} - - // Whether this view is a popup and what kind of popup it is (select, - // autofill...). - WebKit::WebPopupType popup_type_; - - // A custom background to paint behind the web content. This will be tiled - // horizontally. Can be null, in which case we fall back to painting white. - SkBitmap background_; - - // The current reserved area in view coordinates where contents should not be - // rendered to draw the resize corner, sidebar mini tabs etc. - gfx::Rect reserved_rect_; - - private: - DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostView); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/render_widget_host_view.h" #endif // CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_H_ diff --git a/chrome/browser/renderer_host/resource_dispatcher_host.h b/chrome/browser/renderer_host/resource_dispatcher_host.h index cbd62c2..c9da811 100644 --- a/chrome/browser/renderer_host/resource_dispatcher_host.h +++ b/chrome/browser/renderer_host/resource_dispatcher_host.h @@ -2,515 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// This is the browser side of the resource dispatcher, it receives requests -// from the child process (i.e. [Renderer, Plugin, Worker]ProcessHost), and -// dispatches them to URLRequests. It then forwards the messages from the -// URLRequests back to the correct process for handling. -// -// See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading - #ifndef CHROME_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_H_ #define CHROME_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_H_ #pragma once -#include <map> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/gtest_prod_util.h" -#include "base/observer_list.h" -#include "base/scoped_ptr.h" -#include "base/timer.h" -#include "chrome/common/child_process_info.h" -#include "chrome/common/notification_type.h" -#include "chrome/browser/renderer_host/resource_queue.h" -#include "ipc/ipc_message.h" -#include "net/url_request/url_request.h" -#include "webkit/glue/resource_type.h" - -class CrossSiteResourceHandler; -class DownloadFileManager; -class DownloadRequestLimiter; -class LoginHandler; -class NotificationDetails; -class PluginService; -class ResourceDispatcherHostRequestInfo; -class ResourceHandler; -class ResourceMessageFilter; -class SafeBrowsingService; -class SaveFileManager; -class SSLClientAuthHandler; -class UserScriptListener; -class WebKitThread; -struct DownloadSaveInfo; -struct GlobalRequestID; -struct ViewHostMsg_Resource_Request; -struct ViewMsg_ClosePage_Params; - -namespace net { -class URLRequestContext; -} // namespace net - -namespace webkit_blob { -class DeletableFileReference; -} - -class ResourceDispatcherHost : public net::URLRequest::Delegate { - public: - class Observer { - public: - virtual ~Observer() {} - virtual void OnRequestStarted(ResourceDispatcherHost* resource_dispatcher, - net::URLRequest* request) = 0; - virtual void OnResponseCompleted( - ResourceDispatcherHost* resource_dispatcher, - net::URLRequest* request) = 0; - virtual void OnReceivedRedirect(ResourceDispatcherHost* resource_dispatcher, - net::URLRequest* request, - const GURL& new_url) = 0; - }; - - ResourceDispatcherHost(); - ~ResourceDispatcherHost(); - - void Initialize(); - - // Puts the resource dispatcher host in an inactive state (unable to begin - // new requests). Cancels all pending requests. - void Shutdown(); - - // Returns true if the message was a resource message that was processed. - // If it was, message_was_ok will be false iff the message was corrupt. - bool OnMessageReceived(const IPC::Message& message, - ResourceMessageFilter* filter, - bool* message_was_ok); - - // Initiates a download from the browser process (as opposed to a resource - // request from the renderer or another child process). - void BeginDownload(const GURL& url, - const GURL& referrer, - const DownloadSaveInfo& save_info, - bool prompt_for_save_location, - int process_unique_id, - int route_id, - net::URLRequestContext* request_context); - - // Initiates a save file from the browser process (as opposed to a resource - // request from the renderer or another child process). - void BeginSaveFile(const GURL& url, - const GURL& referrer, - int process_unique_id, - int route_id, - net::URLRequestContext* request_context); - - // Cancels the given request if it still exists. We ignore cancels from the - // renderer in the event of a download. - void CancelRequest(int process_unique_id, - int request_id, - bool from_renderer); - - // Follows a deferred redirect for the given request. - // new_first_party_for_cookies, if non-empty, is the new cookie policy URL - // for the redirected URL. If the cookie policy URL needs changing, pass - // true as has_new_first_party_for_cookies and the new cookie policy URL as - // new_first_party_for_cookies. Otherwise, pass false as - // has_new_first_party_for_cookies, and new_first_party_for_cookies will not - // be used. - void FollowDeferredRedirect(int process_unique_id, - int request_id, - bool has_new_first_party_for_cookies, - const GURL& new_first_party_for_cookies); - - // Starts a request that was deferred during ResourceHandler::OnWillStart(). - void StartDeferredRequest(int process_unique_id, int request_id); - - // Returns true if it's ok to send the data. If there are already too many - // data messages pending, it pauses the request and returns false. In this - // case the caller should not send the data. - bool WillSendData(int process_unique_id, int request_id); - - // Pauses or resumes network activity for a particular request. - void PauseRequest(int process_unique_id, int request_id, bool pause); - - // Returns the number of pending requests. This is designed for the unittests - int pending_requests() const { - return static_cast<int>(pending_requests_.size()); - } - - // Intended for unit-tests only. Returns the memory cost of all the - // outstanding requests (pending and blocked) for |process_unique_id|. - int GetOutstandingRequestsMemoryCost(int process_unique_id) const; - - // Intended for unit-tests only. Overrides the outstanding requests bound. - void set_max_outstanding_requests_cost_per_process(int limit) { - max_outstanding_requests_cost_per_process_ = limit; - } - - // The average private bytes increase of the browser for each new pending - // request. Experimentally obtained. - static const int kAvgBytesPerOutstandingRequest = 4400; - - DownloadFileManager* download_file_manager() const { - return download_file_manager_; - } - - DownloadRequestLimiter* download_request_limiter() const { - return download_request_limiter_.get(); - } - - SaveFileManager* save_file_manager() const { - return save_file_manager_; - } - - SafeBrowsingService* safe_browsing_service() const { - return safe_browsing_; - } - - WebKitThread* webkit_thread() const { - return webkit_thread_.get(); - } - - // Called when the onunload handler for a cross-site request has finished. - void OnClosePageACK(const ViewMsg_ClosePage_Params& params); - - // Force cancels any pending requests for the given process. - void CancelRequestsForProcess(int process_unique_id); - - // Force cancels any pending requests for the given route id. This method - // acts like CancelRequestsForProcess when route_id is -1. - void CancelRequestsForRoute(int process_unique_id, int route_id); - - // net::URLRequest::Delegate - virtual void OnReceivedRedirect(net::URLRequest* request, - const GURL& new_url, - bool* defer_redirect); - virtual void OnAuthRequired(net::URLRequest* request, - net::AuthChallengeInfo* auth_info); - virtual void OnCertificateRequested( - net::URLRequest* request, - net::SSLCertRequestInfo* cert_request_info); - virtual void OnSSLCertificateError(net::URLRequest* request, - int cert_error, - net::X509Certificate* cert); - virtual void OnGetCookies(net::URLRequest* request, - bool blocked_by_policy); - virtual void OnSetCookie(net::URLRequest* request, - const std::string& cookie_line, - const net::CookieOptions& options, - bool blocked_by_policy); - virtual void OnResponseStarted(net::URLRequest* request); - virtual void OnReadCompleted(net::URLRequest* request, int bytes_read); - void OnResponseCompleted(net::URLRequest* request); - - // Helper functions to get our extra data out of a request. The given request - // must have been one we created so that it has the proper extra data pointer. - static ResourceDispatcherHostRequestInfo* InfoForRequest( - net::URLRequest* request); - static const ResourceDispatcherHostRequestInfo* InfoForRequest( - const net::URLRequest* request); - - // Extracts the render view/process host's identifiers from the given request - // and places them in the given out params (both required). If there are no - // such IDs associated with the request (such as non-page-related requests), - // this function will return false and both out params will be -1. - static bool RenderViewForRequest(const net::URLRequest* request, - int* render_process_host_id, - int* render_view_host_id); - - // Adds an observer. The observer will be called on the IO thread. To - // observe resource events on the UI thread, subscribe to the - // NOTIFY_RESOURCE_* notifications of the notification service. - void AddObserver(Observer* obs); - - // Removes an observer. - void RemoveObserver(Observer* obs); - - // Retrieves a net::URLRequest. Must be called from the IO thread. - net::URLRequest* GetURLRequest(const GlobalRequestID& request_id) const; - - // Notifies our observers that a request has been cancelled. - void NotifyResponseCompleted(net::URLRequest* request, int process_unique_id); - - void RemovePendingRequest(int process_unique_id, int request_id); - - // Causes all new requests for the route identified by - // |process_unique_id| and |route_id| to be blocked (not being - // started) until ResumeBlockedRequestsForRoute or - // CancelBlockedRequestsForRoute is called. - void BlockRequestsForRoute(int process_unique_id, int route_id); - - // Resumes any blocked request for the specified route id. - void ResumeBlockedRequestsForRoute(int process_unique_id, int route_id); - - // Cancels any blocked request for the specified route id. - void CancelBlockedRequestsForRoute(int process_unique_id, int route_id); - - // Decrements the pending_data_count for the request and resumes - // the request if it was paused due to too many pending data - // messages sent. - void DataReceivedACK(int process_unique_id, int request_id); - - // Maintains a collection of temp files created in support of - // the download_to_file capability. Used to grant access to the - // child process and to defer deletion of the file until it's - // no longer needed. - void RegisterDownloadedTempFile( - int child_id, int request_id, - webkit_blob::DeletableFileReference* reference); - void UnregisterDownloadedTempFile(int child_id, int request_id); - - // Needed for the sync IPC message dispatcher macros. - bool Send(IPC::Message* message); - - // Controls if we launch or squash prefetch requests as they arrive - // from renderers. - static bool is_prefetch_enabled(); - static void set_is_prefetch_enabled(bool value); - - private: - FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, - TestBlockedRequestsProcessDies); - FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, - IncrementOutstandingRequestsMemoryCost); - FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, - CalculateApproximateMemoryCost); - FRIEND_TEST_ALL_PREFIXES(ApplyExtensionLocalizationFilterTest, WrongScheme); - FRIEND_TEST_ALL_PREFIXES(ApplyExtensionLocalizationFilterTest, GoodScheme); - FRIEND_TEST_ALL_PREFIXES(ApplyExtensionLocalizationFilterTest, - GoodSchemeWrongResourceType); - - class ShutdownTask; - - friend class ShutdownTask; - - // Associates the given info with the given request. The info will then be - // owned by the request. - void SetRequestInfo(net::URLRequest* request, - ResourceDispatcherHostRequestInfo* info); - - // A shutdown helper that runs on the IO thread. - void OnShutdown(); - - // Returns true if the request is paused. - bool PauseRequestIfNeeded(ResourceDispatcherHostRequestInfo* info); - - // Resumes the given request by calling OnResponseStarted or OnReadCompleted. - void ResumeRequest(const GlobalRequestID& request_id); - - // Internal function to start reading for the first time. - void StartReading(net::URLRequest* request); - - // Reads data from the response using our internal buffer as async IO. - // Returns true if data is available immediately, false otherwise. If the - // return value is false, we will receive a OnReadComplete() callback later. - bool Read(net::URLRequest* request, int* bytes_read); - - // Internal function to finish an async IO which has completed. Returns - // true if there is more data to read (e.g. we haven't read EOF yet and - // no errors have occurred). - bool CompleteRead(net::URLRequest*, int* bytes_read); - - // Internal function to finish handling the ResponseStarted message. Returns - // true on success. - bool CompleteResponseStarted(net::URLRequest* request); - - // Helper function for regular and download requests. - void BeginRequestInternal(net::URLRequest* request); - - // Helper function that cancels |request|. - void CancelRequestInternal(net::URLRequest* request, bool from_renderer); - - // Helper function that inserts |request| into the resource queue. - void InsertIntoResourceQueue( - net::URLRequest* request, - const ResourceDispatcherHostRequestInfo& request_info); - - // Updates the "cost" of outstanding requests for |process_unique_id|. - // The "cost" approximates how many bytes are consumed by all the in-memory - // data structures supporting this request (net::URLRequest object, - // HttpNetworkTransaction, etc...). - // The value of |cost| is added to the running total, and the resulting - // sum is returned. - int IncrementOutstandingRequestsMemoryCost(int cost, - int process_unique_id); - - // Estimate how much heap space |request| will consume to run. - static int CalculateApproximateMemoryCost(net::URLRequest* request); - - // The list of all requests that we have pending. This list is not really - // optimized, and assumes that we have relatively few requests pending at once - // since some operations require brute-force searching of the list. - // - // It may be enhanced in the future to provide some kind of prioritization - // mechanism. We should also consider a hashtable or binary tree if it turns - // out we have a lot of things here. - typedef std::map<GlobalRequestID, net::URLRequest*> PendingRequestList; - - // Deletes the pending request identified by the iterator passed in. - // This function will invalidate the iterator passed in. Callers should - // not rely on this iterator being valid on return. - void RemovePendingRequest(const PendingRequestList::iterator& iter); - - // Notify our observers that we started receiving a response for a request. - void NotifyResponseStarted(net::URLRequest* request, int process_unique_id); - - // Notify our observers that a request has been redirected. - void NotifyReceivedRedirect(net::URLRequest* request, - int process_unique_id, - const GURL& new_url); - - // Tries to handle the url with an external protocol. If the request is - // handled, the function returns true. False otherwise. - bool HandleExternalProtocol(int request_id, - int process_unique_id, - int route_id, - const GURL& url, - ResourceType::Type resource_type, - ResourceHandler* handler); - - // Checks all pending requests and updates the load states and upload - // progress if necessary. - void UpdateLoadStates(); - - // Checks the upload state and sends an update if one is necessary. - bool MaybeUpdateUploadProgress(ResourceDispatcherHostRequestInfo *info, - net::URLRequest *request); - - // Resumes or cancels (if |cancel_requests| is true) any blocked requests. - void ProcessBlockedRequestsForRoute(int process_unique_id, - int route_id, - bool cancel_requests); - - void OnRequestResource(const IPC::Message& msg, - int request_id, - const ViewHostMsg_Resource_Request& request_data); - void OnSyncLoad(int request_id, - const ViewHostMsg_Resource_Request& request_data, - IPC::Message* sync_result); - void BeginRequest(int request_id, - const ViewHostMsg_Resource_Request& request_data, - IPC::Message* sync_result, // only valid for sync - int route_id); // only valid for async - void OnDataReceivedACK(int request_id); - void OnDataDownloadedACK(int request_id); - void OnUploadProgressACK(int request_id); - void OnCancelRequest(int request_id); - void OnFollowRedirect(int request_id, - bool has_new_first_party_for_cookies, - const GURL& new_first_party_for_cookies); - void OnReleaseDownloadedFile(int request_id); - - ResourceHandler* CreateSafeBrowsingResourceHandler( - ResourceHandler* handler, int child_id, int route_id, - ResourceType::Type resource_type); - - // Creates ResourceDispatcherHostRequestInfo for a browser-initiated request - // (a download or a page save). |download| should be true if the request - // is a file download. - ResourceDispatcherHostRequestInfo* CreateRequestInfoForBrowserRequest( - ResourceHandler* handler, int child_id, int route_id, bool download); - - // Returns true if |request| is in |pending_requests_|. - bool IsValidRequest(net::URLRequest* request); - - // Sets replace_extension_localization_templates on all text/css requests that - // have "chrome-extension://" scheme. - static void ApplyExtensionLocalizationFilter( - const GURL& url, - const ResourceType::Type& resource_type, - ResourceDispatcherHostRequestInfo* request_info); - - // Determine request priority based on how critical this resource typically - // is to user-perceived page load performance. - static net::RequestPriority DetermineRequestPriority(ResourceType::Type type); - - // Sends the given notification on the UI thread. The RenderViewHost's - // controller is used as the source. - template <class T> - static void NotifyOnUI(NotificationType type, - int render_process_id, - int render_view_id, - T* detail); - - PendingRequestList pending_requests_; - - // Collection of temp files downloaded for child processes via - // the download_to_file mechanism. We avoid deleting them until - // the client no longer needs them. - typedef std::map<int, scoped_refptr<webkit_blob::DeletableFileReference> > - DeletableFilesMap; // key is request id - typedef std::map<int, DeletableFilesMap> - RegisteredTempFiles; // key is child process id - RegisteredTempFiles registered_temp_files_; - - // A timer that periodically calls UpdateLoadStates while pending_requests_ - // is not empty. - base::RepeatingTimer<ResourceDispatcherHost> update_load_states_timer_; - - // Handles the resource requests from the moment we want to start them. - ResourceQueue resource_queue_; - - // We own the download file writing thread and manager - scoped_refptr<DownloadFileManager> download_file_manager_; - - // Determines whether a download is allowed. - scoped_refptr<DownloadRequestLimiter> download_request_limiter_; - - // We own the save file manager. - scoped_refptr<SaveFileManager> save_file_manager_; - - scoped_refptr<UserScriptListener> user_script_listener_; - - scoped_refptr<SafeBrowsingService> safe_browsing_; - - // We own the WebKit thread and see to its destruction. - scoped_ptr<WebKitThread> webkit_thread_; - - // Request ID for browser initiated requests. request_ids generated by - // child processes are counted up from 0, while browser created requests - // start at -2 and go down from there. (We need to start at -2 because -1 is - // used as a special value all over the resource_dispatcher_host for - // uninitialized variables.) This way, we no longer have the unlikely (but - // observed in the real world!) event where we have two requests with the same - // request_id_. - int request_id_; - - // List of objects observing resource dispatching. - ObserverList<Observer> observer_list_; - - // For running tasks. - ScopedRunnableMethodFactory<ResourceDispatcherHost> method_runner_; - - // True if the resource dispatcher host has been shut down. - bool is_shutdown_; - - typedef std::vector<net::URLRequest*> BlockedRequestsList; - typedef std::pair<int, int> ProcessRouteIDs; - typedef std::map<ProcessRouteIDs, BlockedRequestsList*> BlockedRequestMap; - BlockedRequestMap blocked_requests_map_; - - // Maps the process_unique_ids to the approximate number of bytes - // being used to service its resource requests. No entry implies 0 cost. - typedef std::map<int, int> OutstandingRequestsMemoryCostMap; - OutstandingRequestsMemoryCostMap outstanding_requests_memory_cost_map_; - - // |max_outstanding_requests_cost_per_process_| is the upper bound on how - // many outstanding requests can be issued per child process host. - // The constraint is expressed in terms of bytes (where the cost of - // individual requests is given by CalculateApproximateMemoryCost). - // The total number of outstanding requests is roughly: - // (max_outstanding_requests_cost_per_process_ / - // kAvgBytesPerOutstandingRequest) - int max_outstanding_requests_cost_per_process_; - - // Used during IPC message dispatching so that the handlers can get a pointer - // to the source of the message. - ResourceMessageFilter* filter_; - - static bool is_prefetch_enabled_; - - DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHost); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/resource_dispatcher_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_H_ diff --git a/chrome/browser/renderer_host/resource_dispatcher_host_request_info.h b/chrome/browser/renderer_host/resource_dispatcher_host_request_info.h index 462e886..cff06b9 100644 --- a/chrome/browser/renderer_host/resource_dispatcher_host_request_info.h +++ b/chrome/browser/renderer_host/resource_dispatcher_host_request_info.h @@ -6,236 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_REQUEST_INFO_H_ #pragma once -#include <string> - -#include "base/basictypes.h" -#include "base/time.h" -#include "chrome/common/child_process_info.h" -#include "net/base/load_states.h" -#include "net/url_request/url_request.h" -#include "webkit/glue/resource_type.h" - -class CrossSiteResourceHandler; -class LoginHandler; -class ResourceDispatcherHost; -class ResourceHandler; -class SSLClientAuthHandler; - -namespace webkit_blob { -class BlobData; -} - -// Holds the data ResourceDispatcherHost associates with each request. -// Retrieve this data by calling ResourceDispatcherHost::InfoForRequest. -class ResourceDispatcherHostRequestInfo : public net::URLRequest::UserData { - public: - // This will take a reference to the handler. - ResourceDispatcherHostRequestInfo( - ResourceHandler* handler, - ChildProcessInfo::ProcessType process_type, - int child_id, - int route_id, - int request_id, - ResourceType::Type resource_type, - uint64 upload_size, - bool is_download, - bool allow_download, - bool has_user_gesture, - int host_renderer_id, - int host_render_view_id); - virtual ~ResourceDispatcherHostRequestInfo(); - - // Top-level ResourceHandler servicing this request. - ResourceHandler* resource_handler() { return resource_handler_.get(); } - - // CrossSiteResourceHandler for this request, if it is a cross-site request. - // (NULL otherwise.) This handler is part of the chain of ResourceHandlers - // pointed to by resource_handler, and is not owned by this class. - CrossSiteResourceHandler* cross_site_handler() { - return cross_site_handler_; - } - void set_cross_site_handler(CrossSiteResourceHandler* h) { - cross_site_handler_ = h; - } - - // Pointer to the login handler, or NULL if there is none for this request. - LoginHandler* login_handler() const { return login_handler_.get(); } - void set_login_handler(LoginHandler* lh); - - // Pointer to the SSL auth, or NULL if there is none for this request. - SSLClientAuthHandler* ssl_client_auth_handler() const { - return ssl_client_auth_handler_.get(); - } - void set_ssl_client_auth_handler(SSLClientAuthHandler* s); - - // Identifies the type of process (renderer, plugin, etc.) making the request. - ChildProcessInfo::ProcessType process_type() const { - return process_type_; - } - - // The child process unique ID of the requestor. This duplicates the value - // stored on the request by SetChildProcessUniqueIDForRequest in - // url_request_tracking. - int child_id() const { return child_id_; } - - // The IPC route identifier for this request (this identifies the RenderView - // or like-thing in the renderer that the request gets routed to). - int route_id() const { return route_id_; } - - // Unique identifier for this resource request. - int request_id() const { return request_id_; } - - // Number of messages we've sent to the renderer that we haven't gotten an - // ACK for. This allows us to avoid having too many messages in flight. - int pending_data_count() const { return pending_data_count_; } - void IncrementPendingDataCount() { pending_data_count_++; } - void DecrementPendingDataCount() { pending_data_count_--; } - - // Downloads are allowed only as a top level request. - bool allow_download() const { return allow_download_; } - - bool has_user_gesture() const { return has_user_gesture_; } - - // Whether this is a download. - bool is_download() const { return is_download_; } - void set_is_download(bool download) { is_download_ = download; } - - // The number of clients that have called pause on this request. - int pause_count() const { return pause_count_; } - void set_pause_count(int count) { pause_count_ = count; } - - // Identifies the type of resource, such as subframe, media, etc. - ResourceType::Type resource_type() const { return resource_type_; } - - // Whether we should apply a filter to this resource that replaces - // localization templates with the appropriate localized strings. This is set - // for CSS resources used by extensions. - bool replace_extension_localization_templates() const { - return replace_extension_localization_templates_; - } - void set_replace_extension_localization_templates() { - replace_extension_localization_templates_ = true; - } - - // Returns the last updated state of the load. This is updated periodically - // by the ResourceDispatcherHost and tracked here so we don't send out - // unnecessary state change notifications. - net::LoadState last_load_state() const { return last_load_state_; } - void set_last_load_state(net::LoadState s) { last_load_state_ = s; } - - // When there is upload data, this is the byte count of that data. When there - // is no upload, this will be 0. - uint64 upload_size() const { return upload_size_; } - void set_upload_size(uint64 upload_size) { upload_size_ = upload_size; } - - // When we're uploading data, this is the the byte offset into the uploaded - // data that we've uploaded that we've send an upload progress update about. - // The ResourceDispatcherHost will periodically update this value to track - // upload progress and make sure it doesn't sent out duplicate updates. - uint64 last_upload_position() const { return last_upload_position_; } - void set_last_upload_position(uint64 p) { last_upload_position_ = p; } - - // Indicates when the ResourceDispatcherHost last update the upload - // position. This is used to make sure we don't send too many updates. - base::TimeTicks last_upload_ticks() const { return last_upload_ticks_; } - void set_last_upload_ticks(base::TimeTicks t) { last_upload_ticks_ = t; } - - // Set when the ResourceDispatcherHost has sent out an upload progress, and - // cleared whtn the ACK is received. This is used to throttle updates so - // multiple updates aren't in flight at once. - bool waiting_for_upload_progress_ack() const { - return waiting_for_upload_progress_ack_; - } - void set_waiting_for_upload_progress_ack(bool waiting) { - waiting_for_upload_progress_ack_ = waiting; - } - - // The approximate in-memory size (bytes) that we credited this request - // as consuming in |outstanding_requests_memory_cost_map_|. - int memory_cost() const { return memory_cost_; } - void set_memory_cost(int cost) { memory_cost_ = cost; } - - int host_renderer_id() const { return host_renderer_id_; } - int host_render_view_id() const { return host_render_view_id_; } - - // We hold a reference to the requested blob data to ensure it doesn't - // get finally released prior to the net::URLRequestJob being started. - webkit_blob::BlobData* requested_blob_data() const { - return requested_blob_data_.get(); - } - void set_requested_blob_data(webkit_blob::BlobData* data); - - private: - friend class ResourceDispatcherHost; - - // Request is temporarily not handling network data. Should be used only - // by the ResourceDispatcherHost, not the event handlers (accessors are - // provided for consistency with the rest of the interface). - bool is_paused() const { return is_paused_; } - void set_is_paused(bool paused) { is_paused_ = paused; } - - // Whether we called OnResponseStarted for this request or not. Should be used - // only by the ResourceDispatcherHost, not the event handlers (accessors are - // provided for consistency with the rest of the interface). - bool called_on_response_started() const { - return called_on_response_started_; - } - void set_called_on_response_started(bool called) { - called_on_response_started_ = called; - } - - // Whether this request has started reading any bytes from the response - // yet. Will be true after the first (unpaused) call to Read. Should be used - // only by the ResourceDispatcherHost, not the event handlers (accessors are - // provided for consistency with the rest of the interface). - bool has_started_reading() const { return has_started_reading_; } - void set_has_started_reading(bool reading) { has_started_reading_ = reading; } - - // How many bytes have been read while this request has been paused. Should be - // used only by the ResourceDispatcherHost, not the event handlers (accessors - // are provided for consistency with the rest of the interface). - int paused_read_bytes() const { return paused_read_bytes_; } - void set_paused_read_bytes(int bytes) { paused_read_bytes_ = bytes; } - - scoped_refptr<ResourceHandler> resource_handler_; - CrossSiteResourceHandler* cross_site_handler_; // Non-owning, may be NULL. - scoped_refptr<LoginHandler> login_handler_; - scoped_refptr<SSLClientAuthHandler> ssl_client_auth_handler_; - ChildProcessInfo::ProcessType process_type_; - int child_id_; - int route_id_; - int request_id_; - int pending_data_count_; - bool is_download_; - bool allow_download_; - bool has_user_gesture_; - int pause_count_; - ResourceType::Type resource_type_; - bool replace_extension_localization_templates_; - net::LoadState last_load_state_; - uint64 upload_size_; - uint64 last_upload_position_; - base::TimeTicks last_upload_ticks_; - bool waiting_for_upload_progress_ack_; - int memory_cost_; - scoped_refptr<webkit_blob::BlobData> requested_blob_data_; - - // "Private" data accessible only to ResourceDispatcherHost (use the - // accessors above for consistency). - bool is_paused_; - bool called_on_response_started_; - bool has_started_reading_; - int paused_read_bytes_; - - // The following two members are specified if the request is initiated by - // a plugin like Gears. - - // Contains the id of the host renderer. - int host_renderer_id_; - // Contains the id of the host render view. - int host_render_view_id_; - - DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHostRequestInfo); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" #endif // CHROME_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_REQUEST_INFO_H_ diff --git a/chrome/browser/renderer_host/resource_handler.h b/chrome/browser/renderer_host/resource_handler.h index c231406..864ad49 100644 --- a/chrome/browser/renderer_host/resource_handler.h +++ b/chrome/browser/renderer_host/resource_handler.h @@ -2,95 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// This is the browser side of the resource dispatcher, it receives requests -// from the RenderProcessHosts, and dispatches them to URLRequests. It then -// fowards the messages from the URLRequests back to the correct process for -// handling. -// -// See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading - #ifndef CHROME_BROWSER_RENDERER_HOST_RESOURCE_HANDLER_H_ #define CHROME_BROWSER_RENDERER_HOST_RESOURCE_HANDLER_H_ #pragma once -#include <string> - -#include "chrome/browser/browser_thread.h" - -namespace net { -class IOBuffer; -class URLRequestStatus; -} // namespace net - -struct ResourceResponse; -class GURL; - -// The resource dispatcher host uses this interface to push load events to the -// renderer, allowing for differences in the types of IPC messages generated. -// See the implementations of this interface defined below. -class ResourceHandler - : public base::RefCountedThreadSafe< - ResourceHandler, BrowserThread::DeleteOnIOThread> { - public: - // Called as upload progress is made. - virtual bool OnUploadProgress(int request_id, - uint64 position, - uint64 size) = 0; - - // The request was redirected to a new URL. |*defer| has an initial value of - // false. Set |*defer| to true to defer the redirect. The redirect may be - // followed later on via ResourceDispatcherHost::FollowDeferredRedirect. - virtual bool OnRequestRedirected(int request_id, const GURL& url, - ResourceResponse* response, - bool* defer) = 0; - - // Response headers and meta data are available. - virtual bool OnResponseStarted(int request_id, - ResourceResponse* response) = 0; - - // Called before the net::URLRequest for |request_id| (whose url is |url|) is - // to be started. If the handler returns false, then the request is cancelled. - // Otherwise if the return value is true, the ResourceHandler can delay the - // request from starting by setting |*defer = true|. A deferred request will - // not have called net::URLRequest::Start(), and will not resume until someone - // calls ResourceDispatcherHost::StartDeferredRequest(). - virtual bool OnWillStart(int request_id, const GURL& url, bool* defer) = 0; - - // Data will be read for the response. Upon success, this method places the - // size and address of the buffer where the data is to be written in its - // out-params. This call will be followed by either OnReadCompleted or - // OnResponseCompleted, at which point the buffer may be recycled. - virtual bool OnWillRead(int request_id, - net::IOBuffer** buf, - int* buf_size, - int min_size) = 0; - - // Data (*bytes_read bytes) was written into the buffer provided by - // OnWillRead. A return value of false cancels the request, true continues - // reading data. - virtual bool OnReadCompleted(int request_id, int* bytes_read) = 0; - - // The response is complete. The final response status is given. - // Returns false if the handler is deferring the call to a later time. - virtual bool OnResponseCompleted(int request_id, - const net::URLRequestStatus& status, - const std::string& security_info) = 0; - - // Signals that the request is closed (i.e. finished successfully, cancelled). - // This is a signal that the associated net::URLRequest isn't valid anymore. - virtual void OnRequestClosed() = 0; - - // This notification is synthesized by the RedirectToFileResourceHandler - // to indicate progress of 'download_to_file' requests. OnReadCompleted - // calls are consumed by the RedirectToFileResourceHandler and replaced - // with OnDataDownloaded calls. - virtual void OnDataDownloaded(int request_id, int bytes_downloaded) {} - - protected: - friend class BrowserThread; - friend class DeleteTask<ResourceHandler>; - - virtual ~ResourceHandler() {} -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/resource_handler.h" #endif // CHROME_BROWSER_RENDERER_HOST_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/resource_message_filter.h b/chrome/browser/renderer_host/resource_message_filter.h index 8af9a3d..c33d644 100644 --- a/chrome/browser/renderer_host/resource_message_filter.h +++ b/chrome/browser/renderer_host/resource_message_filter.h @@ -5,77 +5,7 @@ #ifndef CHROME_BROWSER_RENDERER_HOST_RESOURCE_MESSAGE_FILTER_H_ #define CHROME_BROWSER_RENDERER_HOST_RESOURCE_MESSAGE_FILTER_H_ -#include "base/scoped_ptr.h" -#include "chrome/browser/browser_message_filter.h" -#include "chrome/common/child_process_info.h" - -class ChromeURLRequestContext; -class ResourceDispatcherHost; -struct ViewHostMsg_Resource_Request; - -namespace net { -class URLRequestContext; -} // namespace net - -// This class filters out incoming IPC messages for network requests and -// processes them on the IPC thread. As a result, network requests are not -// delayed by costly UI processing that may be occuring on the main thread of -// the browser. It also means that any hangs in starting a network request -// will not interfere with browser UI. -class ResourceMessageFilter : public BrowserMessageFilter { - public: - // Allows overriding the net::URLRequestContext used to service requests. - class URLRequestContextOverride - : public base::RefCountedThreadSafe<URLRequestContextOverride> { - public: - URLRequestContextOverride() {} - - virtual net::URLRequestContext* GetRequestContext( - const ViewHostMsg_Resource_Request& resource_request) = 0; - - protected: - friend class base::RefCountedThreadSafe<URLRequestContextOverride>; - virtual ~URLRequestContextOverride() {} - - DISALLOW_COPY_AND_ASSIGN(URLRequestContextOverride); - }; - - ResourceMessageFilter(int child_id, - ChildProcessInfo::ProcessType process_type, - ResourceDispatcherHost* resource_dispatcher_host); - - // BrowserMessageFilter implementation. - virtual void OnChannelClosing(); - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - - // Returns the net::URLRequestContext for the given request. - ChromeURLRequestContext* GetURLRequestContext( - const ViewHostMsg_Resource_Request& resource_request); - - void set_url_request_context_override(URLRequestContextOverride* u) { - url_request_context_override_ = u; - } - - int child_id() const { return child_id_; } - ChildProcessInfo::ProcessType process_type() const { return process_type_; } - - protected: - // Protected destructor so that we can be overriden in tests. - virtual ~ResourceMessageFilter(); - - private: - // The ID of the child process. - int child_id_; - - ChildProcessInfo::ProcessType process_type_; - - // Owned by BrowserProcess, which is guaranteed to outlive us. - ResourceDispatcherHost* resource_dispatcher_host_; - - scoped_refptr<URLRequestContextOverride> url_request_context_override_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(ResourceMessageFilter); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/resource_message_filter.h" #endif // CHROME_BROWSER_RENDERER_HOST_RESOURCE_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/resource_queue.h b/chrome/browser/renderer_host/resource_queue.h index e3e5e2f..2e65c2e 100644 --- a/chrome/browser/renderer_host/resource_queue.h +++ b/chrome/browser/renderer_host/resource_queue.h @@ -6,95 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_RESOURCE_QUEUE_H_ #pragma once -#include <map> -#include <set> - -#include "base/basictypes.h" - -namespace net { -class URLRequest; -} // namespace net - -class ResourceDispatcherHostRequestInfo; -struct GlobalRequestID; - -// Makes decisions about delaying or not each net::URLRequest in the queue. -// All methods are called on the IO thread. -class ResourceQueueDelegate { - public: - // Should return true if it wants the |request| to not be started at this - // point. To start the delayed request, ResourceQueue::StartDelayedRequest - // should be used. - virtual bool ShouldDelayRequest( - net::URLRequest* request, - const ResourceDispatcherHostRequestInfo& request_info, - const GlobalRequestID& request_id) = 0; - - // Called just before ResourceQueue shutdown. After that, the delegate - // should not use the ResourceQueue. - virtual void WillShutdownResourceQueue() = 0; - - protected: - virtual ~ResourceQueueDelegate(); -}; - -// Makes it easy to delay starting URL requests until specified conditions are -// met. -class ResourceQueue { - public: - typedef std::set<ResourceQueueDelegate*> DelegateSet; - - // UI THREAD ONLY ------------------------------------------------------------ - - // Construct the queue. You must initialize it using Initialize. - ResourceQueue(); - ~ResourceQueue(); - - // Initialize the queue with set of delegates it should ask for each incoming - // request. - void Initialize(const DelegateSet& delegates); - - // IO THREAD ONLY ------------------------------------------------------------ - - // Must be called before destroying the queue. No other methods can be called - // after that. - void Shutdown(); - - // Takes care to start the |request| after all delegates allow that. If no - // delegate demands delaying the request it will be started immediately. - void AddRequest(net::URLRequest* request, - const ResourceDispatcherHostRequestInfo& request_info); - - // Tells the queue that the net::URLRequest object associated with - // |request_id| is no longer valid. - void RemoveRequest(const GlobalRequestID& request_id); - - // A delegate should call StartDelayedRequest when it wants to allow the - // request to start. If it was the last delegate that demanded the request - // to be delayed, the request will be started. - void StartDelayedRequest(ResourceQueueDelegate* delegate, - const GlobalRequestID& request_id); - - private: - typedef std::map<GlobalRequestID, net::URLRequest*> RequestMap; - typedef std::map<GlobalRequestID, DelegateSet> InterestedDelegatesMap; - - // The registered delegates. Will not change after the queue has been - // initialized. - DelegateSet delegates_; - - // Stores net::URLRequest objects associated with each GlobalRequestID. This - // helps decoupling the queue from ResourceDispatcherHost. - RequestMap requests_; - - // Maps a GlobalRequestID to the set of delegates that want to prevent the - // associated request from starting yet. - InterestedDelegatesMap interested_delegates_; - - // True when we are shutting down. - bool shutdown_; - - DISALLOW_COPY_AND_ASSIGN(ResourceQueue); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/resource_queue.h" #endif // CHROME_BROWSER_RENDERER_HOST_RESOURCE_QUEUE_H_ diff --git a/chrome/browser/renderer_host/resource_request_details.h b/chrome/browser/renderer_host/resource_request_details.h index 2cfad35..5bd9b02 100644 --- a/chrome/browser/renderer_host/resource_request_details.h +++ b/chrome/browser/renderer_host/resource_request_details.h @@ -2,70 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// The ResourceRequestDetails object contains additional details about a -// resource request. It copies many of the publicly accessible member variables -// of net::URLRequest, but exists on the UI thread. - #ifndef CHROME_BROWSER_RENDERER_HOST_RESOURCE_REQUEST_DETAILS_H_ #define CHROME_BROWSER_RENDERER_HOST_RESOURCE_REQUEST_DETAILS_H_ #pragma once -#include <string> - -#include "googleurl/src/gurl.h" -#include "net/url_request/url_request_status.h" -#include "webkit/glue/resource_type.h" - -namespace net { -class URLRequest; -} // namespace net - -// Details about a resource request notification. -class ResourceRequestDetails { - public: - ResourceRequestDetails(const net::URLRequest* request, int cert_id); - - virtual ~ResourceRequestDetails(); - - const GURL& url() const { return url_; } - const GURL& original_url() const { return original_url_; } - const std::string& method() const { return method_; } - const std::string& referrer() const { return referrer_; } - bool has_upload() const { return has_upload_; } - int load_flags() const { return load_flags_; } - int origin_child_id() const { return origin_child_id_; } - const net::URLRequestStatus& status() const { return status_; } - int ssl_cert_id() const { return ssl_cert_id_; } - int ssl_cert_status() const { return ssl_cert_status_; } - ResourceType::Type resource_type() const { return resource_type_; } - - private: - GURL url_; - GURL original_url_; - std::string method_; - std::string referrer_; - bool has_upload_; - int load_flags_; - int origin_child_id_; - net::URLRequestStatus status_; - int ssl_cert_id_; - int ssl_cert_status_; - ResourceType::Type resource_type_; -}; - -// Details about a redirection of a resource request. -class ResourceRedirectDetails : public ResourceRequestDetails { - public: - ResourceRedirectDetails(const net::URLRequest* request, - int cert_id, - const GURL& new_url); - virtual ~ResourceRedirectDetails(); - - // The URL to which we are being redirected. - const GURL& new_url() const { return new_url_; } - - private: - GURL new_url_; -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/resource_request_details.h" #endif // CHROME_BROWSER_RENDERER_HOST_RESOURCE_REQUEST_DETAILS_H_ diff --git a/chrome/browser/renderer_host/site_instance.h b/chrome/browser/renderer_host/site_instance.h index edb377f..baf3071 100644 --- a/chrome/browser/renderer_host/site_instance.h +++ b/chrome/browser/renderer_host/site_instance.h @@ -6,192 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_SITE_INSTANCE_H_ #pragma once -#include "chrome/browser/renderer_host/render_process_host.h" -#include "chrome/common/notification_observer.h" -#include "chrome/common/notification_registrar.h" -#include "googleurl/src/gurl.h" - -class BrowsingInstance; - -/////////////////////////////////////////////////////////////////////////////// -// -// SiteInstance class -// -// A SiteInstance is a data structure that is associated with all pages in a -// given instance of a web site. Here, a web site is identified by its -// registered domain name and scheme. An instance includes all pages -// that are connected (i.e., either a user or a script navigated from one -// to the other). We represent instances using the BrowsingInstance class. -// -// In --process-per-tab, one SiteInstance is created for each tab (i.e., in the -// TabContents constructor), unless the tab is created by script (i.e., in -// TabContents::CreateNewView). This corresponds to one process per -// BrowsingInstance. -// -// In process-per-site-instance (the current default process model), -// SiteInstances are created (1) when the user manually creates a new tab -// (which also creates a new BrowsingInstance), and (2) when the user navigates -// across site boundaries (which uses the same BrowsingInstance). If the user -// navigates within a site, or opens links in new tabs within a site, the same -// SiteInstance is used. -// -// In --process-per-site, we consolidate all SiteInstances for a given site, -// throughout the entire profile. This ensures that only one process will be -// dedicated to each site. -// -// Each NavigationEntry for a TabContents points to the SiteInstance that -// rendered it. Each RenderViewHost also points to the SiteInstance that it is -// associated with. A SiteInstance keeps track of the number of these -// references and deletes itself when the count goes to zero. This means that -// a SiteInstance is only live as long as it is accessible, either from new -// tabs with no NavigationEntries or in NavigationEntries in the history. -// -/////////////////////////////////////////////////////////////////////////////// -class SiteInstance : public base::RefCounted<SiteInstance>, - public NotificationObserver { - public: - // Get the BrowsingInstance to which this SiteInstance belongs. - BrowsingInstance* browsing_instance() { return browsing_instance_; } - - // Sets the factory used to create new RenderProcessHosts. This will also be - // passed on to SiteInstances spawned by this one. - // - // The factory must outlive the SiteInstance; ownership is not transferred. It - // may be NULL, in which case the default BrowserRenderProcessHost will be - // created (this is the behavior if you don't call this function). - void set_render_process_host_factory(RenderProcessHostFactory* rph_factory) { - render_process_host_factory_ = rph_factory; - } - - // Update / Get the max page ID for this SiteInstance. - void UpdateMaxPageID(int32 page_id) { - if (page_id > max_page_id_) - max_page_id_ = page_id; - } - int32 max_page_id() const { return max_page_id_; } - - // Whether this SiteInstance has a running process associated with it. - bool HasProcess() const; - - // Returns the current process being used to render pages in this - // SiteInstance. If the process has crashed or otherwise gone away, then - // this method will create a new process and update our host ID accordingly. - RenderProcessHost* GetProcess(); - - // Set / Get the web site that this SiteInstance is rendering pages for. - // This includes the scheme and registered domain, but not the port. If the - // URL does not have a valid registered domain, then the full hostname is - // stored. - void SetSite(const GURL& url); - const GURL& site() const { return site_; } - bool has_site() const { return has_site_; } - - // Returns whether there is currently a related SiteInstance (registered with - // BrowsingInstance) for the site of the given url. If so, we should try to - // avoid dedicating an unused SiteInstance to it (e.g., in a new tab). - bool HasRelatedSiteInstance(const GURL& url); - - // Gets a SiteInstance for the given URL that shares the current - // BrowsingInstance, creating a new SiteInstance if necessary. This ensures - // that a BrowsingInstance only has one SiteInstance per site, so that pages - // in a BrowsingInstance have the ability to script each other. Callers - // should ensure that this SiteInstance becomes ref counted, by storing it in - // a scoped_refptr. (By having this method, we can hide the BrowsingInstance - // class from the rest of the codebase.) - // TODO(creis): This may be an argument to build a pass_refptr<T> class, as - // Darin suggests. - SiteInstance* GetRelatedSiteInstance(const GURL& url); - - // Factory method to create a new SiteInstance. This will create a new - // new BrowsingInstance, so it should only be used when creating a new tab - // from scratch (or similar circumstances). Callers should ensure that - // this SiteInstance becomes ref counted, by storing it in a scoped_refptr. - // - // The render process host factory may be NULL. See SiteInstance constructor. - // - // TODO(creis): This may be an argument to build a pass_refptr<T> class, as - // Darin suggests. - static SiteInstance* CreateSiteInstance(Profile* profile); - - // Factory method to get the appropriate SiteInstance for the given URL, in - // a new BrowsingInstance. Use this instead of CreateSiteInstance when you - // know the URL, since it allows special site grouping rules to be applied - // (for example, to group chrome-ui pages into the same instance). - static SiteInstance* CreateSiteInstanceForURL(Profile* profile, - const GURL& url); - - // Returns the site for the given URL, which includes only the scheme and - // registered domain. Returns an empty GURL if the URL has no host. - static GURL GetSiteForURL(Profile* profile, const GURL& url); - - // Return whether both URLs are part of the same web site, for the purpose of - // assigning them to processes accordingly. The decision is currently based - // on the registered domain of the URLs (google.com, bbc.co.uk), as well as - // the scheme (https, http). This ensures that two pages will be in - // the same process if they can communicate with other via JavaScript. - // (e.g., docs.google.com and mail.google.com have DOM access to each other - // if they both set their document.domain properties to google.com.) - static bool IsSameWebSite(Profile* profile, - const GURL& url1, const GURL& url2); - - // Returns the renderer type for this URL. - static RenderProcessHost::Type RendererTypeForURL(const GURL& url); - - protected: - friend class base::RefCounted<SiteInstance>; - friend class BrowsingInstance; - - // Virtual to allow tests to extend it. - virtual ~SiteInstance(); - - // Create a new SiteInstance. Protected to give access to BrowsingInstance - // and tests; most callers should use CreateSiteInstance or - // GetRelatedSiteInstance instead. - explicit SiteInstance(BrowsingInstance* browsing_instance); - - // Get the effective URL for the given actual URL. If the URL is part of an - // installed app, the effective URL is an extension URL with the ID of that - // extension as the host. This has the effect of grouping apps together in - // a common SiteInstance. - static GURL GetEffectiveURL(Profile* profile, const GURL& url); - - // Returns the type of renderer process this instance belongs in, for grouping - // purposes. - RenderProcessHost::Type GetRendererType(); - - private: - // NotificationObserver implementation. - virtual void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - NotificationRegistrar registrar_; - - // BrowsingInstance to which this SiteInstance belongs. - scoped_refptr<BrowsingInstance> browsing_instance_; - - // Factory for new RenderProcessHosts, not owned by this class. NULL indiactes - // that the default BrowserRenderProcessHost should be created. - const RenderProcessHostFactory* render_process_host_factory_; - - // Current RenderProcessHost that is rendering pages for this SiteInstance. - // This pointer will only change once the RenderProcessHost is destructed. It - // will still remain the same even if the process crashes, since in that - // scenario the RenderProcessHost remains the same. - RenderProcessHost* process_; - - // The current max_page_id in the SiteInstance's RenderProcessHost. If the - // rendering process dies, its replacement should start issuing page IDs that - // are larger than this value. - int32 max_page_id_; - - // The web site that this SiteInstance is rendering pages for. - GURL site_; - - // Whether SetSite has been called. - bool has_site_; - - DISALLOW_COPY_AND_ASSIGN(SiteInstance); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/site_instance.h" #endif // CHROME_BROWSER_RENDERER_HOST_SITE_INSTANCE_H_ diff --git a/chrome/browser/renderer_host/socket_stream_dispatcher_host.h b/chrome/browser/renderer_host/socket_stream_dispatcher_host.h index 23d18e0..63aa961 100644 --- a/chrome/browser/renderer_host/socket_stream_dispatcher_host.h +++ b/chrome/browser/renderer_host/socket_stream_dispatcher_host.h @@ -6,60 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_SOCKET_STREAM_DISPATCHER_HOST_H_ #pragma once -#include <vector> - -#include "base/id_map.h" -#include "chrome/browser/browser_message_filter.h" -#include "chrome/browser/renderer_host/resource_message_filter.h" -#include "net/socket_stream/socket_stream.h" - -class GURL; -class SocketStreamHost; - -// Dispatches ViewHostMsg_SocketStream_* messages sent from renderer. -// It also acts as SocketStream::Delegate so that it sends -// ViewMsg_SocketStream_* messages back to renderer. -class SocketStreamDispatcherHost : public BrowserMessageFilter, - public net::SocketStream::Delegate { - public: - SocketStreamDispatcherHost(); - virtual ~SocketStreamDispatcherHost(); - - // BrowserMessageFilter methods. - virtual bool OnMessageReceived(const IPC::Message& message, - bool* message_was_ok); - - // The object died, so cancel and detach all requests associated with it. - void CancelRequestsForProcess(int host_id); - - // SocketStream::Delegate methods. - virtual void OnConnected(net::SocketStream* socket, - int max_pending_send_allowed); - virtual void OnSentData(net::SocketStream* socket, int amount_sent); - virtual void OnReceivedData(net::SocketStream* socket, - const char* data, int len); - virtual void OnClose(net::SocketStream* socket); - - void set_url_request_context_override( - ResourceMessageFilter::URLRequestContextOverride* u) { - url_request_context_override_ = u; - } - - private: - // Message handlers called by OnMessageReceived. - void OnConnect(const GURL& url, int socket_id); - void OnSendData(int socket_id, const std::vector<char>& data); - void OnCloseReq(int socket_id); - - void DeleteSocketStreamHost(int socket_id); - - net::URLRequestContext* GetURLRequestContext(); - - IDMap<SocketStreamHost> hosts_; - scoped_refptr<ResourceMessageFilter::URLRequestContextOverride> - url_request_context_override_; - - DISALLOW_COPY_AND_ASSIGN(SocketStreamDispatcherHost); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/socket_stream_dispatcher_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_SOCKET_STREAM_DISPATCHER_HOST_H_ diff --git a/chrome/browser/renderer_host/socket_stream_host.h b/chrome/browser/renderer_host/socket_stream_host.h index 50afad2..f8ecab2 100644 --- a/chrome/browser/renderer_host/socket_stream_host.h +++ b/chrome/browser/renderer_host/socket_stream_host.h @@ -6,56 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_SOCKET_STREAM_HOST_H_ #pragma once -#include <vector> - -#include "base/ref_counted.h" -#include "net/socket_stream/socket_stream.h" - -class GURL; - -namespace net { -class SocketStreamJob; -class URLRequestContext; -} // namespace net - -// Host of SocketStreamHandle. -// Each SocketStreamHandle will have an unique socket_id assigned by -// SocketStreamHost constructor. If socket id is chrome_common_net::kNoSocketId, -// there is no SocketStreamHost. -// Each SocketStreamHost has SocketStream to manage bi-directional -// communication over socket stream. -// The lifetime of an instance of this class is completely controlled by the -// SocketStreamDispatcherHost. -class SocketStreamHost { - public: - SocketStreamHost(net::SocketStream::Delegate* delegate, int socket_id); - ~SocketStreamHost(); - - // Gets socket_id associated with |socket|. - static int SocketIdFromSocketStream(net::SocketStream* socket); - - int socket_id() const { return socket_id_; } - - // Starts to open connection to |url|. - void Connect(const GURL& url, net::URLRequestContext* request_context); - - // Sends |data| over the socket stream. - // socket stream must be open to send data. - // Returns true if the data is put in transmit buffer in socket stream. - // Returns false otherwise (transmit buffer exceeds limit, or socket - // stream is closed). - bool SendData(const std::vector<char>& data); - - // Closes the socket stream. - void Close(); - - private: - net::SocketStream::Delegate* delegate_; - int socket_id_; - - scoped_refptr<net::SocketStreamJob> socket_; - - DISALLOW_COPY_AND_ASSIGN(SocketStreamHost); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/socket_stream_host.h" #endif // CHROME_BROWSER_RENDERER_HOST_SOCKET_STREAM_HOST_H_ diff --git a/chrome/browser/renderer_host/sync_resource_handler.h b/chrome/browser/renderer_host/sync_resource_handler.h index d0e3d5c..0d89590 100644 --- a/chrome/browser/renderer_host/sync_resource_handler.h +++ b/chrome/browser/renderer_host/sync_resource_handler.h @@ -6,55 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_SYNC_RESOURCE_HANDLER_H_ #pragma once -#include <string> - -#include "chrome/browser/renderer_host/resource_handler.h" -#include "chrome/common/resource_response.h" - -class ResourceDispatcherHost; -class ResourceMessageFilter; - -namespace IPC { -class Message; -} - -namespace net { -class IOBuffer; -} - -// Used to complete a synchronous resource request in response to resource load -// events from the resource dispatcher host. -class SyncResourceHandler : public ResourceHandler { - public: - SyncResourceHandler(ResourceMessageFilter* filter, - const GURL& url, - IPC::Message* result_message, - ResourceDispatcherHost* resource_dispatcher_host); - - virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); - virtual bool OnRequestRedirected(int request_id, const GURL& new_url, - ResourceResponse* response, bool* defer); - virtual bool OnResponseStarted(int request_id, ResourceResponse* response); - virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); - virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, - int min_size); - virtual bool OnReadCompleted(int request_id, int* bytes_read); - virtual bool OnResponseCompleted(int request_id, - const net::URLRequestStatus& status, - const std::string& security_info); - virtual void OnRequestClosed(); - - private: - enum { kReadBufSize = 3840 }; - - ~SyncResourceHandler(); - - scoped_refptr<net::IOBuffer> read_buffer_; - - SyncLoadResult result_; - ResourceMessageFilter* filter_; - IPC::Message* result_message_; - ResourceDispatcherHost* rdh_; -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/sync_resource_handler.h" #endif // CHROME_BROWSER_RENDERER_HOST_SYNC_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/x509_user_cert_resource_handler.h b/chrome/browser/renderer_host/x509_user_cert_resource_handler.h index 1c20cce..72411b7 100644 --- a/chrome/browser/renderer_host/x509_user_cert_resource_handler.h +++ b/chrome/browser/renderer_host/x509_user_cert_resource_handler.h @@ -6,75 +6,7 @@ #define CHROME_BROWSER_RENDERER_HOST_X509_USER_CERT_RESOURCE_HANDLER_H_ #pragma once -#include <string> - -#include "base/scoped_ptr.h" -#include "chrome/browser/renderer_host/resource_handler.h" -#include "googleurl/src/gurl.h" - -namespace net { -class URLRequest; -class URLRequestStatus; -} // namespace net - -class ResourceDispatcherHost; -struct DownloadBuffer; - -// This class handles the "application/x-x509-user-cert" mime-type -// which is a certificate generated by a CA after a previous -// <keygen> form post. - -class X509UserCertResourceHandler : public ResourceHandler { - public: - X509UserCertResourceHandler(ResourceDispatcherHost* host, - net::URLRequest* request, - int render_process_host_id, int render_view_id); - - virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); - - // Not needed, as this event handler ought to be the final resource. - virtual bool OnRequestRedirected(int request_id, const GURL& url, - ResourceResponse* resp, bool* defer); - - // Check if this indeed an X509 cert. - virtual bool OnResponseStarted(int request_id, ResourceResponse* resp); - - // Pass-through implementation. - virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); - - // Create a new buffer to store received data. - virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, - int min_size); - - // A read was completed, maybe allocate a new buffer for further data. - virtual bool OnReadCompleted(int request_id, int* bytes_read); - - // Done downloading the certificate. - virtual bool OnResponseCompleted(int request_id, - const net::URLRequestStatus& urs, - const std::string& sec_info); - - virtual void OnRequestClosed(); - - private: - virtual ~X509UserCertResourceHandler(); - - void AssembleResource(); - - GURL url_; - ResourceDispatcherHost* host_; - net::URLRequest* request_; - size_t content_length_; - scoped_ptr<DownloadBuffer> buffer_; - scoped_refptr<net::IOBuffer> read_buffer_; - scoped_refptr<net::IOBuffer> resource_buffer_; // Downloaded certificate. - static const int kReadBufSize = 32768; - // The id of the |RenderProcessHost| which started the download. - int render_process_host_id_; - // The id of the |RenderView| which started the download. - int render_view_id_; - - DISALLOW_COPY_AND_ASSIGN(X509UserCertResourceHandler); -}; +// TODO(jam): remove this file when all files have been converted. +#include "content/browser/renderer_host/x509_user_cert_resource_handler.h" #endif // CHROME_BROWSER_RENDERER_HOST_X509_USER_CERT_RESOURCE_HANDLER_H_ diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index 565c687..6935973 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi @@ -1875,83 +1875,18 @@ 'browser/remoting/setup_flow_start_host_step.cc', 'browser/remoting/setup_flow_start_host_step.h', 'browser/remove_rows_table_model.h', - 'browser/renderer_host/accelerated_surface_container_mac.cc', - 'browser/renderer_host/accelerated_surface_container_mac.h', - 'browser/renderer_host/accelerated_surface_container_manager_mac.cc', - 'browser/renderer_host/accelerated_surface_container_manager_mac.h', - 'browser/renderer_host/async_resource_handler.cc', - 'browser/renderer_host/async_resource_handler.h', - 'browser/renderer_host/audio_renderer_host.cc', - 'browser/renderer_host/audio_renderer_host.h', - 'browser/renderer_host/audio_sync_reader.cc', - 'browser/renderer_host/audio_sync_reader.h', - 'browser/renderer_host/backing_store.cc', - 'browser/renderer_host/backing_store.h', - 'browser/renderer_host/backing_store_mac.h', - 'browser/renderer_host/backing_store_mac.mm', - 'browser/renderer_host/backing_store_manager.cc', - 'browser/renderer_host/backing_store_manager.h', - 'browser/renderer_host/backing_store_skia.cc', - 'browser/renderer_host/backing_store_skia.h', - 'browser/renderer_host/backing_store_win.cc', - 'browser/renderer_host/backing_store_win.h', - 'browser/renderer_host/backing_store_x.cc', - 'browser/renderer_host/backing_store_x.h', - 'browser/renderer_host/blob_message_filter.cc', - 'browser/renderer_host/blob_message_filter.h', 'browser/renderer_host/browser_render_process_host.cc', 'browser/renderer_host/browser_render_process_host.h', - 'browser/renderer_host/buffered_resource_handler.cc', - 'browser/renderer_host/buffered_resource_handler.h', - 'browser/renderer_host/cross_site_resource_handler.cc', - 'browser/renderer_host/cross_site_resource_handler.h', - 'browser/renderer_host/database_message_filter.cc', - 'browser/renderer_host/database_message_filter.h', 'browser/renderer_host/download_resource_handler.cc', 'browser/renderer_host/download_resource_handler.h', 'browser/renderer_host/download_throttling_resource_handler.cc', 'browser/renderer_host/download_throttling_resource_handler.h', - 'browser/renderer_host/file_utilities_message_filter.cc', - 'browser/renderer_host/file_utilities_message_filter.h', - 'browser/renderer_host/global_request_id.h', - 'browser/renderer_host/gpu_message_filter.cc', - 'browser/renderer_host/gpu_message_filter.h', 'browser/renderer_host/gtk_im_context_wrapper.cc', 'browser/renderer_host/gtk_im_context_wrapper.h', 'browser/renderer_host/gtk_key_bindings_handler.cc', 'browser/renderer_host/gtk_key_bindings_handler.h', 'browser/renderer_host/offline_resource_handler.cc', 'browser/renderer_host/offline_resource_handler.h', - 'browser/renderer_host/pepper_file_message_filter.cc', - 'browser/renderer_host/pepper_file_message_filter.h', - 'browser/renderer_host/pepper_message_filter.cc', - 'browser/renderer_host/pepper_message_filter.h', - 'browser/renderer_host/redirect_to_file_resource_handler.cc', - 'browser/renderer_host/redirect_to_file_resource_handler.h', - 'browser/renderer_host/render_message_filter.cc', - 'browser/renderer_host/render_message_filter.h', - 'browser/renderer_host/render_message_filter_gtk.cc', - 'browser/renderer_host/render_message_filter_mac.mm', - 'browser/renderer_host/render_message_filter_win.cc', - 'browser/renderer_host/render_process_host.cc', - 'browser/renderer_host/render_process_host.h', - 'browser/renderer_host/render_sandbox_host_linux.cc', - 'browser/renderer_host/render_sandbox_host_linux.h', - 'browser/renderer_host/render_view_host.cc', - 'browser/renderer_host/render_view_host.h', - 'browser/renderer_host/render_view_host_delegate.cc', - 'browser/renderer_host/render_view_host_delegate.h', - 'browser/renderer_host/render_view_host_factory.cc', - 'browser/renderer_host/render_view_host_factory.h', - 'browser/renderer_host/render_view_host_notification_task.h', - 'browser/renderer_host/render_widget_fullscreen_host.cc', - 'browser/renderer_host/render_widget_fullscreen_host.h', - 'browser/renderer_host/render_widget_helper.cc', - 'browser/renderer_host/render_widget_helper.h', - 'browser/renderer_host/render_widget_host.cc', - 'browser/renderer_host/render_widget_host.h', - 'browser/renderer_host/render_widget_host_view.cc', - 'browser/renderer_host/render_widget_host_view.h', 'browser/renderer_host/render_widget_host_view_gtk.cc', 'browser/renderer_host/render_widget_host_view_gtk.h', 'browser/renderer_host/render_widget_host_view_mac.h', @@ -1960,33 +1895,12 @@ 'browser/renderer_host/render_widget_host_view_views.h', 'browser/renderer_host/render_widget_host_view_win.cc', 'browser/renderer_host/render_widget_host_view_win.h', - 'browser/renderer_host/resource_dispatcher_host.cc', - 'browser/renderer_host/resource_dispatcher_host.h', - 'browser/renderer_host/resource_dispatcher_host_request_info.cc', - 'browser/renderer_host/resource_dispatcher_host_request_info.h', - 'browser/renderer_host/resource_handler.h', - 'browser/renderer_host/resource_message_filter.cc', - 'browser/renderer_host/resource_message_filter.h', - 'browser/renderer_host/resource_queue.cc', - 'browser/renderer_host/resource_queue.h', - 'browser/renderer_host/resource_request_details.cc', - 'browser/renderer_host/resource_request_details.h', 'browser/renderer_host/safe_browsing_resource_handler.cc', 'browser/renderer_host/safe_browsing_resource_handler.h', 'browser/renderer_host/save_file_resource_handler.cc', - 'browser/renderer_host/save_file_resource_handler.h', - 'browser/renderer_host/site_instance.cc', - 'browser/renderer_host/site_instance.h', - 'browser/renderer_host/socket_stream_dispatcher_host.cc', - 'browser/renderer_host/socket_stream_dispatcher_host.h', - 'browser/renderer_host/socket_stream_host.cc', - 'browser/renderer_host/socket_stream_host.h', - 'browser/renderer_host/sync_resource_handler.cc', - 'browser/renderer_host/sync_resource_handler.h', + 'browser/renderer_host/save_file_resource_handler.h', 'browser/renderer_host/web_cache_manager.cc', 'browser/renderer_host/web_cache_manager.h', - 'browser/renderer_host/x509_user_cert_resource_handler.cc', - 'browser/renderer_host/x509_user_cert_resource_handler.h', 'browser/renderer_preferences_util.cc', 'browser/renderer_preferences_util.h', 'browser/repost_form_warning_controller.cc', diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index 12c2654..5e3cdd4 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi @@ -83,8 +83,6 @@ 'browser/prefs/pref_service_mock_builder.h', 'browser/prefs/testing_pref_store.cc', 'browser/prefs/testing_pref_store.h', - 'browser/renderer_host/mock_render_process_host.cc', - 'browser/renderer_host/mock_render_process_host.h', 'browser/renderer_host/test/test_backing_store.cc', 'browser/renderer_host/test/test_backing_store.h', 'browser/renderer_host/test/test_render_view_host.cc', @@ -180,6 +178,8 @@ 'test/unit/chrome_test_suite.h', 'test/values_test_util.cc', 'test/values_test_util.h', + '../content/browser/renderer_host/mock_render_process_host.cc', + '../content/browser/renderer_host/mock_render_process_host.h', '../content/browser/tab_contents/test_tab_contents.cc', '../content/browser/tab_contents/test_tab_contents.h', ], @@ -569,7 +569,6 @@ 'browser/printing/printing_layout_uitest.cc', 'browser/process_singleton_linux_uitest.cc', 'browser/process_singleton_uitest.cc', - 'browser/renderer_host/resource_dispatcher_host_uitest.cc', 'browser/repost_form_warning_uitest.cc', 'browser/sanity_uitest.cc', 'browser/session_history_uitest.cc', @@ -602,6 +601,7 @@ 'test/ui/sunspider_uitest.cc', 'test/ui/v8_benchmark_uitest.cc', 'worker/worker_uitest.cc', + '../content/browser/renderer_host/resource_dispatcher_host_uitest.cc', ], 'conditions': [ ['target_arch!="arm"', { @@ -1448,13 +1448,9 @@ 'browser/process_singleton_mac_unittest.cc', 'browser/profiles/profile_manager_unittest.cc', 'browser/remoting/directory_add_request_unittest.cc', - 'browser/renderer_host/audio_renderer_host_unittest.cc', 'browser/renderer_host/gtk_im_context_wrapper_unittest.cc', 'browser/renderer_host/gtk_key_bindings_handler_unittest.cc', - 'browser/renderer_host/render_widget_host_unittest.cc', 'browser/renderer_host/render_widget_host_view_mac_unittest.mm', - 'browser/renderer_host/resource_dispatcher_host_unittest.cc', - 'browser/renderer_host/resource_queue_unittest.cc', 'browser/renderer_host/test/render_view_host_unittest.cc', 'browser/renderer_host/test/site_instance_unittest.cc', 'browser/renderer_host/web_cache_manager_unittest.cc', @@ -1845,6 +1841,10 @@ 'test/v8_unit_test.cc', 'test/v8_unit_test.h', 'tools/convert_dict/convert_dict_unittest.cc', + '../content/browser/renderer_host/audio_renderer_host_unittest.cc', + '../content/browser/renderer_host/render_widget_host_unittest.cc', + '../content/browser/renderer_host/resource_dispatcher_host_unittest.cc', + '../content/browser/renderer_host/resource_queue_unittest.cc', '../content/browser/tab_contents/navigation_controller_unittest.cc', '../content/browser/tab_contents/navigation_entry_unittest.cc', '../content/browser/tab_contents/render_view_host_manager_unittest.cc', diff --git a/chrome/browser/renderer_host/accelerated_surface_container_mac.cc b/content/browser/renderer_host/accelerated_surface_container_mac.cc index f379931..a661c92 100644 --- a/chrome/browser/renderer_host/accelerated_surface_container_mac.cc +++ b/content/browser/renderer_host/accelerated_surface_container_mac.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/accelerated_surface_container_mac.h" +#include "content/browser/renderer_host/accelerated_surface_container_mac.h" #include "app/surface/io_surface_support_mac.h" #include "base/logging.h" -#include "chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h" +#include "content/browser/renderer_host/accelerated_surface_container_manager_mac.h" #include "webkit/plugins/npapi/webplugin.h" AcceleratedSurfaceContainerMac::AcceleratedSurfaceContainerMac( diff --git a/content/browser/renderer_host/accelerated_surface_container_mac.h b/content/browser/renderer_host/accelerated_surface_container_mac.h new file mode 100644 index 0000000..2bffb32 --- /dev/null +++ b/content/browser/renderer_host/accelerated_surface_container_mac.h @@ -0,0 +1,152 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MAC_H_ +#define CONTENT_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MAC_H_ +#pragma once + +// The "GPU plugin" is currently implemented as a special kind of +// NPAPI plugin to provide high-performance on-screen 3D rendering for +// Pepper 3D. +// +// On Windows and X11 platforms the GPU plugin relies on cross-process +// parenting of windows, which is not supported via any public APIs in +// the Mac OS X window system. +// +// To achieve full hardware acceleration we use the new IOSurface APIs +// introduced in Mac OS X 10.6. The GPU plugin's process produces an +// IOSurface and renders into it using OpenGL. It uses the +// IOSurfaceGetID and IOSurfaceLookup APIs to pass a reference to this +// surface to the browser process for on-screen rendering. The GPU +// plugin essentially looks like a windowless plugin; the browser +// process gets all of the mouse events, because the plugin process +// does not have an on-screen window. +// +// This class encapsulates some of the management of these data +// structures, in conjunction with the AcceleratedSurfaceContainerManagerMac. + +#include <CoreFoundation/CoreFoundation.h> +#include <OpenGL/OpenGL.h> + +#include "app/surface/transport_dib.h" +#include "base/basictypes.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/scoped_ptr.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/rect.h" + +namespace webkit { +namespace npapi { +struct WebPluginGeometry; +} +} + +class AcceleratedSurfaceContainerManagerMac; + +class AcceleratedSurfaceContainerMac { + public: + AcceleratedSurfaceContainerMac( + AcceleratedSurfaceContainerManagerMac* manager, + bool opaque); + virtual ~AcceleratedSurfaceContainerMac(); + + // Sets the backing store and size of this accelerated surface container. + // There are two versions: the IOSurface version is used on systems where the + // IOSurface API is supported (Mac OS X 10.6 and later); the TransportDIB is + // used on Mac OS X 10.5 and earlier. + void SetSizeAndIOSurface(int32 width, + int32 height, + uint64 io_surface_identifier); + void SetSizeAndTransportDIB(int32 width, + int32 height, + TransportDIB::Handle transport_dib); + + // Tells the accelerated surface container that its geometry has changed, + // for example because of a scroll event. (Note that the container + // currently only pays attention to the clip width and height, since the + // view in which it is hosted is responsible for positioning it on the + // page.) + void SetGeometry(const webkit::npapi::WebPluginGeometry& geom); + + // Draws this accelerated surface's contents, texture mapped onto a quad in + // the given OpenGL context. TODO(kbr): figure out and define exactly how the + // coordinate system will work out. + void Draw(CGLContextObj context); + + // Causes the next Draw call to trigger a texture upload. Should be called any + // time the drawing context has changed. + void ForceTextureReload() { texture_needs_upload_ = true; } + + // Returns if the surface should be shown. + bool ShouldBeVisible() const; + + // Notifies the the container that its surface was painted to. + void set_was_painted_to(uint64 surface_id); + + // Notifies the container that its surface is invalid. + void set_surface_invalid() { was_painted_to_ = false; } + private: + // The manager of this accelerated surface container. + AcceleratedSurfaceContainerManagerMac* manager_; + + // Whether this accelerated surface's content is supposed to be opaque. + bool opaque_; + + // The IOSurfaceRef, if any, that has been handed from the GPU + // plugin process back to the browser process for drawing. + // This is held as a CFTypeRef because we can't refer to the + // IOSurfaceRef type when building on 10.5. + base::mac::ScopedCFTypeRef<CFTypeRef> surface_; + + // The id of |surface_|, or 0 if |surface_| is NULL. + uint64 surface_id_; + + // The width and height of the io surface. During resizing, this is different + // from |width_| and |height_|. + int32 surface_width_; + int32 surface_height_; + + // The TransportDIB which is used in pre-10.6 systems where the IOSurface + // API is not supported. This is a weak reference to the actual TransportDIB + // whic is owned by the GPU process. + scoped_ptr<TransportDIB> transport_dib_; + + // The width and height of the container. + int32 width_; + int32 height_; + + // The clip rectangle, relative to the (x_, y_) origin. + gfx::Rect clip_rect_; + + // The "live" OpenGL texture referring to this IOSurfaceRef. Note + // that per the CGLTexImageIOSurface2D API we do not need to + // explicitly update this texture's contents once created. All we + // need to do is ensure it is re-bound before attempting to draw + // with it. + GLuint texture_; + + // True if we need to upload the texture again during the next draw. + bool texture_needs_upload_; + + // This may refer to an old version of the texture if the container is + // resized, for example. + GLuint texture_pending_deletion_; + + // Stores if the plugin has a visible state. + bool visible_; + + // Stores if the plugin's IOSurface has been swapped before. Used to not show + // it before it hasn't been painted to at least once. + bool was_painted_to_; + + // Releases the IOSurface reference, if any, retained by this object. + void ReleaseIOSurface(); + + // Enqueue our texture for later deletion. + void EnqueueTextureForDeletion(); + + DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerMac); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MAC_H_ diff --git a/chrome/browser/renderer_host/accelerated_surface_container_manager_mac.cc b/content/browser/renderer_host/accelerated_surface_container_manager_mac.cc index ff1f052..9c14b14 100644 --- a/chrome/browser/renderer_host/accelerated_surface_container_manager_mac.cc +++ b/content/browser/renderer_host/accelerated_surface_container_manager_mac.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/accelerated_surface_container_manager_mac.h" +#include "content/browser/renderer_host/accelerated_surface_container_manager_mac.h" #include "base/logging.h" -#include "chrome/browser/renderer_host/accelerated_surface_container_mac.h" +#include "content/browser/renderer_host/accelerated_surface_container_mac.h" #include "webkit/plugins/npapi/webplugin.h" AcceleratedSurfaceContainerManagerMac::AcceleratedSurfaceContainerManagerMac() diff --git a/content/browser/renderer_host/accelerated_surface_container_manager_mac.h b/content/browser/renderer_host/accelerated_surface_container_manager_mac.h new file mode 100644 index 0000000..316ff58 --- /dev/null +++ b/content/browser/renderer_host/accelerated_surface_container_manager_mac.h @@ -0,0 +1,124 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MANAGER_MAC_H_ +#define CONTENT_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MANAGER_MAC_H_ +#pragma once + +#include <OpenGL/OpenGL.h> +#include <map> + +#include "app/surface/transport_dib.h" +#include "base/basictypes.h" +#include "base/synchronization/lock.h" +#include "ui/gfx/native_widget_types.h" + +namespace webkit { +namespace npapi { +struct WebPluginGeometry; +} +} + +class AcceleratedSurfaceContainerMac; + +// Helper class that manages the backing store and on-screen rendering +// of instances of the GPU plugin on the Mac. +class AcceleratedSurfaceContainerManagerMac { + public: + AcceleratedSurfaceContainerManagerMac(); + + // Allocates a new "fake" PluginWindowHandle, which is used as the + // key for the other operations. + gfx::PluginWindowHandle AllocateFakePluginWindowHandle(bool opaque, + bool root); + + // Destroys a fake PluginWindowHandle and associated storage. + void DestroyFakePluginWindowHandle(gfx::PluginWindowHandle id); + + // Indicates whether the given PluginWindowHandle is "root", which + // means that we are using accelerated compositing and that this one + // contains the compositor's output. + bool IsRootContainer(gfx::PluginWindowHandle id) const; + + // Returns the handle of the compositor surface, or kNullPluginWindow if no + // compositor surface is active. + gfx::PluginWindowHandle root_container_handle() const { + return root_container_handle_; + } + + // Informs the manager if gpu rendering is active. + void set_gpu_rendering_active(bool active); + + // Sets the size and backing store of the plugin instance. There are two + // versions: the IOSurface version is used on systems where the IOSurface + // API is supported (Mac OS X 10.6 and later); the TransportDIB is used on + // Mac OS X 10.5 and earlier. + void SetSizeAndIOSurface(gfx::PluginWindowHandle id, + int32 width, + int32 height, + uint64 io_surface_identifier); + void SetSizeAndTransportDIB(gfx::PluginWindowHandle id, + int32 width, + int32 height, + TransportDIB::Handle transport_dib); + + // Takes an update from WebKit about a plugin's position and size and moves + // the plugin accordingly. + void SetPluginContainerGeometry( + const webkit::npapi::WebPluginGeometry& move); + + // Draws the plugin container associated with the given id into the given + // OpenGL context, which must already be current. + void Draw(CGLContextObj context, gfx::PluginWindowHandle id); + + // Causes the next Draw call on each container to trigger a texture upload. + // Should be called any time the drawing context has changed. + void ForceTextureReload(); + + // Notifies a surface that it has been painted to. + void SetSurfaceWasPaintedTo(gfx::PluginWindowHandle id, uint64 surface_id); + + // Notifies the root container that its surface is invalid. + void SetRootSurfaceInvalid(); + + // Returns if a given surface should be shown. + bool SurfaceShouldBeVisible(gfx::PluginWindowHandle id) const; + private: + uint32 current_id_; + + // Maps a "fake" plugin window handle to the corresponding container. + AcceleratedSurfaceContainerMac* + MapIDToContainer(gfx::PluginWindowHandle id) const; + + // A map that associates plugin window handles with their containers. + typedef std::map<gfx::PluginWindowHandle, AcceleratedSurfaceContainerMac*> + PluginWindowToContainerMap; + PluginWindowToContainerMap plugin_window_to_container_map_; + + // The "root" container, which is only used to draw the output of + // the accelerated compositor if it is active. Currently, + // accelerated plugins (Core Animation and Pepper 3D) are drawn on + // top of the page's contents rather than transformed and composited + // with the rest of the page. At some point we would like them to be + // treated uniformly with other page elements; when this is done, + // the separate treatment of the root container can go away because + // there will only be one container active when the accelerated + // compositor is active. + AcceleratedSurfaceContainerMac* root_container_; + gfx::PluginWindowHandle root_container_handle_; + + // True if gpu rendering is active. The root container is created on demand + // and destroyed only when a renderer process exits. When the compositor was + // created, this is set to |false| while the compositor is not needed. + bool gpu_rendering_active_; + + // Both |plugin_window_to_container_map_| and the + // AcceleratedSurfaceContainerMac in it are not threadsafe, but accessed from + // multiple threads. All these accesses are guarded by this lock. + mutable base::Lock lock_; + + DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerManagerMac); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_GPU_PLUGIN_CONTAINER_MANAGER_MAC_H_ diff --git a/chrome/browser/renderer_host/async_resource_handler.cc b/content/browser/renderer_host/async_resource_handler.cc index 0a2bcbb..937f120 100644 --- a/chrome/browser/renderer_host/async_resource_handler.cc +++ b/content/browser/renderer_host/async_resource_handler.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/async_resource_handler.h" +#include "content/browser/renderer_host/async_resource_handler.h" #include <algorithm> #include <vector> @@ -13,12 +13,12 @@ #include "chrome/browser/debugger/devtools_netlog_observer.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/net/load_timing_observer.h" -#include "chrome/browser/renderer_host/global_request_id.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" -#include "chrome/browser/renderer_host/resource_message_filter.h" #include "chrome/common/render_messages.h" #include "chrome/common/resource_response.h" +#include "content/browser/renderer_host/global_request_id.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/resource_message_filter.h" #include "net/base/io_buffer.h" #include "net/base/load_flags.h" #include "net/base/net_log.h" diff --git a/content/browser/renderer_host/async_resource_handler.h b/content/browser/renderer_host/async_resource_handler.h new file mode 100644 index 0000000..8e61f8a --- /dev/null +++ b/content/browser/renderer_host/async_resource_handler.h @@ -0,0 +1,61 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_ASYNC_RESOURCE_HANDLER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_ASYNC_RESOURCE_HANDLER_H_ +#pragma once + +#include <string> + +#include "chrome/browser/renderer_host/resource_handler.h" + +class ResourceDispatcherHost; +class ResourceMessageFilter; +class SharedIOBuffer; + +// Used to complete an asynchronous resource request in response to resource +// load events from the resource dispatcher host. +class AsyncResourceHandler : public ResourceHandler { + public: + AsyncResourceHandler(ResourceMessageFilter* filter, + int routing_id, + const GURL& url, + ResourceDispatcherHost* resource_dispatcher_host); + + // ResourceHandler implementation: + virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); + virtual bool OnRequestRedirected(int request_id, const GURL& new_url, + ResourceResponse* response, bool* defer); + virtual bool OnResponseStarted(int request_id, ResourceResponse* response); + virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); + virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, + int min_size); + virtual bool OnReadCompleted(int request_id, int* bytes_read); + virtual bool OnResponseCompleted(int request_id, + const net::URLRequestStatus& status, + const std::string& security_info); + virtual void OnRequestClosed(); + virtual void OnDataDownloaded(int request_id, int bytes_downloaded); + + static void GlobalCleanup(); + + private: + virtual ~AsyncResourceHandler(); + + scoped_refptr<SharedIOBuffer> read_buffer_; + ResourceMessageFilter* filter_; + int routing_id_; + ResourceDispatcherHost* rdh_; + + // |next_buffer_size_| is the size of the buffer to be allocated on the next + // OnWillRead() call. We exponentially grow the size of the buffer allocated + // when our owner fills our buffers. On the first OnWillRead() call, we + // allocate a buffer of 32k and double it in OnReadCompleted() if the buffer + // was filled, up to a maximum size of 512k. + int next_buffer_size_; + + DISALLOW_COPY_AND_ASSIGN(AsyncResourceHandler); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_ASYNC_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/audio_renderer_host.cc b/content/browser/renderer_host/audio_renderer_host.cc index 4ab9a1a..4fac389 100644 --- a/chrome/browser/renderer_host/audio_renderer_host.cc +++ b/content/browser/renderer_host/audio_renderer_host.cc @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/audio_renderer_host.h" +#include "content/browser/renderer_host/audio_renderer_host.h" #include "base/metrics/histogram.h" #include "base/process.h" #include "base/shared_memory.h" -#include "chrome/browser/renderer_host/audio_sync_reader.h" #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" +#include "content/browser/renderer_host/audio_sync_reader.h" #include "ipc/ipc_logging.h" // The minimum number of samples in a hardware packet. diff --git a/content/browser/renderer_host/audio_renderer_host.h b/content/browser/renderer_host/audio_renderer_host.h new file mode 100644 index 0000000..128723c --- /dev/null +++ b/content/browser/renderer_host/audio_renderer_host.h @@ -0,0 +1,223 @@ +// 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. +// +// AudioRendererHost serves audio related requests from AudioRenderer which +// lives inside the render process and provide access to audio hardware. +// +// This class is owned by BrowserRenderProcessHost, and instantiated on UI +// thread, but all other operations and method calls happen on IO thread, so we +// need to be extra careful about the lifetime of this object. AudioManager is a +// singleton and created in IO thread, audio output streams are also created in +// the IO thread, so we need to destroy them also in IO thread. After this class +// is created, a task of OnInitialized() is posted on IO thread in which +// singleton of AudioManager is created and. +// +// Here's an example of a typical IPC dialog for audio: +// +// Renderer AudioRendererHost +// | | +// | CreateStream > | +// | < Created | +// | | +// | Play > | +// | < Playing | time +// | | +// | < RequestAudioPacket | +// | AudioPacketReady > | +// | ... | +// | < RequestAudioPacket | +// | AudioPacketReady > | +// | | +// | ... | +// | < RequestAudioPacket | +// | AudioPacketReady > | +// | ... | +// | Pause > | +// | < Paused | +// | ... | +// | Start > | +// | < Started | +// | ... | +// | Close > | +// v v + +// The above mode of operation uses relatively big buffers and has latencies +// of 50 ms or more. There is a second mode of operation which is low latency. +// For low latency audio, the picture above is modified by not having the +// RequestAudioPacket and the AudioPacketReady messages, instead a SyncSocket +// pair is used to signal buffer readiness without having to route messages +// using the IO thread. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_AUDIO_RENDERER_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_AUDIO_RENDERER_HOST_H_ +#pragma once + +#include <map> + +#include "base/gtest_prod_util.h" +#include "base/process.h" +#include "base/ref_counted.h" +#include "base/scoped_ptr.h" +#include "base/shared_memory.h" +#include "chrome/browser/browser_message_filter.h" +#include "chrome/browser/browser_thread.h" +#include "ipc/ipc_message.h" +#include "media/audio/audio_io.h" +#include "media/audio/audio_output_controller.h" +#include "media/audio/simple_sources.h" + +class AudioManager; +struct ViewHostMsg_Audio_CreateStream_Params; + +class AudioRendererHost : public BrowserMessageFilter, + public media::AudioOutputController::EventHandler { + public: + typedef std::pair<int32, int> AudioEntryId; + + struct AudioEntry { + AudioEntry(); + ~AudioEntry(); + + // The AudioOutputController that manages the audio stream. + scoped_refptr<media::AudioOutputController> controller; + + // Render view ID that requested the audio stream. + int32 render_view_id; + + // The audio stream ID in the render view. + int stream_id; + + // Shared memory for transmission of the audio data. + base::SharedMemory shared_memory; + + // The synchronous reader to be used by the controller. We have the + // ownership of the reader. + scoped_ptr<media::AudioOutputController::SyncReader> reader; + + bool pending_buffer_request; + + // Set to true after we called Close() for the controller. + bool pending_close; + }; + + typedef std::map<AudioEntryId, AudioEntry*> AudioEntryMap; + + // Called from UI thread from the owner of this object. + AudioRendererHost(); + + + // BrowserMessageFilter implementation. + virtual void OnChannelClosing(); + virtual void OnDestruct() const; + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + + ///////////////////////////////////////////////////////////////////////////// + // AudioOutputController::EventHandler implementations. + virtual void OnCreated(media::AudioOutputController* controller); + virtual void OnPlaying(media::AudioOutputController* controller); + virtual void OnPaused(media::AudioOutputController* controller); + virtual void OnError(media::AudioOutputController* controller, + int error_code); + virtual void OnMoreData(media::AudioOutputController* controller, + AudioBuffersState buffers_state); + + private: + friend class AudioRendererHostTest; + friend class BrowserThread; + friend class DeleteTask<AudioRendererHost>; + friend class MockAudioRendererHost; + FRIEND_TEST_ALL_PREFIXES(AudioRendererHostTest, CreateMockStream); + FRIEND_TEST_ALL_PREFIXES(AudioRendererHostTest, MockStreamDataConversation); + + virtual ~AudioRendererHost(); + + //////////////////////////////////////////////////////////////////////////// + // Methods called on IO thread. + // Returns true if the message is an audio related message and should be + // handled by this class. + bool IsAudioRendererHostMessage(const IPC::Message& message); + + // Audio related IPC message handlers. + // Creates an audio output stream with the specified format. If this call is + // successful this object would keep an internal entry of the stream for the + // required properties. + void OnCreateStream(const IPC::Message& msg, int stream_id, + const ViewHostMsg_Audio_CreateStream_Params& params, + bool low_latency); + + // Play the audio stream referenced by |stream_id|. + void OnPlayStream(const IPC::Message& msg, int stream_id); + + // Pause the audio stream referenced by |stream_id|. + void OnPauseStream(const IPC::Message& msg, int stream_id); + + // Discard all audio data in stream referenced by |stream_id|. + void OnFlushStream(const IPC::Message& msg, int stream_id); + + // Close the audio stream referenced by |stream_id|. + void OnCloseStream(const IPC::Message& msg, int stream_id); + + // Set the volume of the audio stream referenced by |stream_id|. + void OnSetVolume(const IPC::Message& msg, int stream_id, double volume); + + // Get the volume of the audio stream referenced by |stream_id|. + void OnGetVolume(const IPC::Message& msg, int stream_id); + + // Notify packet has been prepared for the audio stream. + void OnNotifyPacketReady(const IPC::Message& msg, int stream_id, + uint32 packet_size); + + // Complete the process of creating an audio stream. This will set up the + // shared memory or shared socket in low latency mode. + void DoCompleteCreation(media::AudioOutputController* controller); + + // Send a state change message to the renderer. + void DoSendPlayingMessage(media::AudioOutputController* controller); + void DoSendPausedMessage(media::AudioOutputController* controller); + + // Request more data from the renderer. This method is used only in normal + // latency mode. + void DoRequestMoreData(media::AudioOutputController* controller, + AudioBuffersState buffers_state); + + // Handle error coming from audio stream. + void DoHandleError(media::AudioOutputController* controller, int error_code); + + // Send an error message to the renderer. + void SendErrorMessage(int32 render_view_id, int32 stream_id); + + // Delete all audio entry and all audio streams + void DeleteEntries(); + + // Closes the stream. The stream is then deleted in DeleteEntry() after it + // is closed. + void CloseAndDeleteStream(AudioEntry* entry); + + // Called on the audio thread after the audio stream is closed. + void OnStreamClosed(AudioEntry* entry); + + // Delete an audio entry and close the related audio stream. + void DeleteEntry(AudioEntry* entry); + + // Delete audio entry and close the related audio stream due to an error, + // and error message is send to the renderer. + void DeleteEntryOnError(AudioEntry* entry); + + // A helper method to look up a AudioEntry with a tuple of render view + // id and stream id. Returns NULL if not found. + AudioEntry* LookupById(int render_view_id, int stream_id); + + // Search for a AudioEntry having the reference to |controller|. + // This method is used to look up an AudioEntry after a controller + // event is received. + AudioEntry* LookupByController(media::AudioOutputController* controller); + + // A map of id to audio sources. + AudioEntryMap audio_entries_; + + DISALLOW_COPY_AND_ASSIGN(AudioRendererHost); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_AUDIO_RENDERER_HOST_H_ diff --git a/chrome/browser/renderer_host/audio_renderer_host_unittest.cc b/content/browser/renderer_host/audio_renderer_host_unittest.cc index a71401f..4f6c3cd 100644 --- a/chrome/browser/renderer_host/audio_renderer_host_unittest.cc +++ b/content/browser/renderer_host/audio_renderer_host_unittest.cc @@ -8,9 +8,9 @@ #include "base/scoped_ptr.h" #include "base/sync_socket.h" #include "chrome/browser/browser_thread.h" -#include "chrome/browser/renderer_host/audio_renderer_host.h" #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" +#include "content/browser/renderer_host/audio_renderer_host.h" #include "ipc/ipc_message_utils.h" #include "media/audio/audio_manager.h" #include "media/audio/fake_audio_output_stream.h" diff --git a/chrome/browser/renderer_host/audio_sync_reader.cc b/content/browser/renderer_host/audio_sync_reader.cc index ce989e5..261bec0 100644 --- a/chrome/browser/renderer_host/audio_sync_reader.cc +++ b/content/browser/renderer_host/audio_sync_reader.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/audio_sync_reader.h" +#include "content/browser/renderer_host/audio_sync_reader.h" #include "base/process_util.h" #include "base/shared_memory.h" diff --git a/content/browser/renderer_host/audio_sync_reader.h b/content/browser/renderer_host/audio_sync_reader.h new file mode 100644 index 0000000..054bb52 --- /dev/null +++ b/content/browser/renderer_host/audio_sync_reader.h @@ -0,0 +1,56 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_AUDIO_SYNC_READER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_AUDIO_SYNC_READER_H_ +#pragma once + +#include "base/file_descriptor_posix.h" +#include "base/process.h" +#include "base/sync_socket.h" +#include "media/audio/audio_output_controller.h" + +namespace base { + +class SharedMemory; + +} + +// A AudioOutputController::SyncReader implementation using SyncSocket. This +// is used by AudioOutputController to provide a low latency data source for +// transmitting audio packets between the browser process and the renderer +// process. +class AudioSyncReader : public media::AudioOutputController::SyncReader { + public: + explicit AudioSyncReader(base::SharedMemory* shared_memory); + + virtual ~AudioSyncReader(); + + // media::AudioOutputController::SyncReader implementations. + virtual void UpdatePendingBytes(uint32 bytes); + virtual uint32 Read(void* data, uint32 size); + virtual void Close(); + + bool Init(); + bool PrepareForeignSocketHandle(base::ProcessHandle process_handle, +#if defined(OS_WIN) + base::SyncSocket::Handle* foreign_handle); +#else + base::FileDescriptor* foreign_handle); +#endif + + private: + base::SharedMemory* shared_memory_; + + // A pair of SyncSocket for transmitting audio data. + scoped_ptr<base::SyncSocket> socket_; + + // SyncSocket to be used by the renderer. The reference is released after + // PrepareForeignSocketHandle() is called and ran successfully. + scoped_ptr<base::SyncSocket> foreign_socket_; + + DISALLOW_COPY_AND_ASSIGN(AudioSyncReader); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_AUDIO_SYNC_READER_H_ diff --git a/chrome/browser/renderer_host/backing_store.cc b/content/browser/renderer_host/backing_store.cc index feebac3..2c6edfc 100644 --- a/chrome/browser/renderer_host/backing_store.cc +++ b/content/browser/renderer_host/backing_store.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/backing_store.h" +#include "content/browser/renderer_host/backing_store.h" BackingStore::BackingStore(RenderWidgetHost* widget, const gfx::Size& size) : render_widget_host_(widget), diff --git a/content/browser/renderer_host/backing_store.h b/content/browser/renderer_host/backing_store.h new file mode 100644 index 0000000..5043b3e --- /dev/null +++ b/content/browser/renderer_host/backing_store.h @@ -0,0 +1,75 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_H_ +#pragma once + +#include <vector> + +#include "app/surface/transport_dib.h" +#include "base/basictypes.h" +#include "ui/gfx/size.h" + +class RenderProcessHost; +class RenderWidgetHost; + +namespace gfx { +class Rect; +} + +namespace skia { +class PlatformCanvas; +} + +// Represents a backing store for the pixels in a RenderWidgetHost. +class BackingStore { + public: + virtual ~BackingStore(); + + RenderWidgetHost* render_widget_host() const { return render_widget_host_; } + const gfx::Size& size() { return size_; } + + // The number of bytes that this backing store consumes. The default + // implementation just assumes there's 32 bits per pixel over the current + // size of the screen. Implementations may override this if they have more + // information about the color depth. + virtual size_t MemorySize(); + + // Paints the bitmap from the renderer onto the backing store. bitmap_rect + // gives the location of bitmap, and copy_rects specifies the subregion(s) of + // the backingstore to be painted from the bitmap. + virtual void PaintToBackingStore( + RenderProcessHost* process, + TransportDIB::Id bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects) = 0; + + // Extracts the gives subset of the backing store and copies it to the given + // PlatformCanvas. The PlatformCanvas should not be initialized. This function + // will call initialize() with the correct size. The return value indicates + // success. + virtual bool CopyFromBackingStore(const gfx::Rect& rect, + skia::PlatformCanvas* output) = 0; + + // Scrolls the contents of clip_rect in the backing store by dx or dy (but dx + // and dy cannot both be non-zero). + virtual void ScrollBackingStore(int dx, int dy, + const gfx::Rect& clip_rect, + const gfx::Size& view_size) = 0; + protected: + // Can only be constructed via subclasses. + BackingStore(RenderWidgetHost* widget, const gfx::Size& size); + + private: + // The owner of this backing store. + RenderWidgetHost* render_widget_host_; + + // The size of the backing store. + gfx::Size size_; + + DISALLOW_COPY_AND_ASSIGN(BackingStore); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_H_ diff --git a/content/browser/renderer_host/backing_store_mac.h b/content/browser/renderer_host/backing_store_mac.h new file mode 100644 index 0000000..b9ac17f --- /dev/null +++ b/content/browser/renderer_host/backing_store_mac.h @@ -0,0 +1,56 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_MAC_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_MAC_H_ +#pragma once + +#include "base/basictypes.h" +#include "base/mac/scoped_cftyperef.h" +#include "content/browser/renderer_host/backing_store.h" + +class BackingStoreMac : public BackingStore { + public: + BackingStoreMac(RenderWidgetHost* widget, const gfx::Size& size); + virtual ~BackingStoreMac(); + + // A CGLayer that stores the contents of the backing store, cached in GPU + // memory if possible. + CGLayerRef cg_layer() { return cg_layer_; } + + // A CGBitmapContext that stores the contents of the backing store if the + // corresponding Cocoa view has not been inserted into an NSWindow yet. + CGContextRef cg_bitmap() { return cg_bitmap_; } + + // BackingStore implementation. + virtual void PaintToBackingStore( + RenderProcessHost* process, + TransportDIB::Id bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects); + virtual bool CopyFromBackingStore(const gfx::Rect& rect, + skia::PlatformCanvas* output); + virtual void ScrollBackingStore(int dx, int dy, + const gfx::Rect& clip_rect, + const gfx::Size& view_size); + + private: + // Creates a CGLayer associated with its owner view's window's graphics + // context, sized properly for the backing store. Returns NULL if the owner + // is not in a window with a CGContext. cg_layer_ is assigned this method's + // result. + CGLayerRef CreateCGLayer(); + + // Creates a CGBitmapContext sized properly for the backing store. The + // owner view need not be in a window. cg_bitmap_ is assigned this method's + // result. + CGContextRef CreateCGBitmapContext(); + + base::mac::ScopedCFTypeRef<CGContextRef> cg_bitmap_; + base::mac::ScopedCFTypeRef<CGLayerRef> cg_layer_; + + DISALLOW_COPY_AND_ASSIGN(BackingStoreMac); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_MAC_H_ diff --git a/chrome/browser/renderer_host/backing_store_mac.mm b/content/browser/renderer_host/backing_store_mac.mm index 0ba853e..424a7b8 100644 --- a/chrome/browser/renderer_host/backing_store_mac.mm +++ b/content/browser/renderer_host/backing_store_mac.mm @@ -4,16 +4,16 @@ #import <Cocoa/Cocoa.h> -#include "chrome/browser/renderer_host/backing_store_mac.h" +#include "content/browser/renderer_host/backing_store_mac.h" #include "app/surface/transport_dib.h" #include "base/logging.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/sys_info.h" -#include "chrome/browser/renderer_host/render_process_host.h" -#include "chrome/browser/renderer_host/render_widget_host.h" -#include "chrome/browser/renderer_host/render_widget_host_view.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_widget_host.h" +#include "content/browser/renderer_host/render_widget_host_view.h" #include "skia/ext/platform_canvas.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" diff --git a/chrome/browser/renderer_host/backing_store_manager.cc b/content/browser/renderer_host/backing_store_manager.cc index 080c020..bd50021 100644 --- a/chrome/browser/renderer_host/backing_store_manager.cc +++ b/content/browser/renderer_host/backing_store_manager.cc @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/backing_store_manager.h" +#include "content/browser/renderer_host/backing_store_manager.h" #include "base/sys_info.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" -#include "chrome/browser/renderer_host/backing_store.h" -#include "chrome/browser/renderer_host/render_widget_host.h" +#include "content/browser/renderer_host/backing_store.h" +#include "content/browser/renderer_host/render_widget_host.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/mru_cache.h" #include "chrome/common/notification_service.h" diff --git a/content/browser/renderer_host/backing_store_manager.h b/content/browser/renderer_host/backing_store_manager.h new file mode 100644 index 0000000..bc09fc7 --- /dev/null +++ b/content/browser/renderer_host/backing_store_manager.h @@ -0,0 +1,79 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_MANAGER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_MANAGER_H_ +#pragma once + +#include <vector> + +#include "app/surface/transport_dib.h" +#include "base/basictypes.h" +#include "base/process.h" +#include "ui/gfx/rect.h" +#include "ui/gfx/size.h" + +class BackingStore; +class RenderWidgetHost; + +// This class manages backing stores in the browsr. Every RenderWidgetHost is +// associated with a backing store which it requests from this class. The +// hosts don't maintain any references to the backing stores. These backing +// stores are maintained in a cache which can be trimmed as needed. +class BackingStoreManager { + public: + // Returns a backing store which matches the desired dimensions. + // + // backing_store_rect + // The desired backing store dimensions. + // Returns a pointer to the backing store on success, NULL on failure. + static BackingStore* GetBackingStore(RenderWidgetHost* host, + const gfx::Size& desired_size); + + // Makes a backing store which is fully ready for consumption, i.e. the + // bitmap from the renderer has been copied into the backing store. + // + // backing_store_size + // The desired backing store dimensions. + // bitmap_section + // The bitmap section from the renderer. + // bitmap_rect + // The rect to be painted into the backing store + // needs_full_paint + // Set if we need to send out a request to paint the view + // to the renderer. + static void PrepareBackingStore( + RenderWidgetHost* host, + const gfx::Size& backing_store_size, + TransportDIB::Id bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects, + bool* needs_full_paint); + + // Returns a matching backing store for the host. + // Returns NULL if we fail to find one. + static BackingStore* Lookup(RenderWidgetHost* host); + + // Removes the backing store for the host. + static void RemoveBackingStore(RenderWidgetHost* host); + + // Removes all backing stores. + static void RemoveAllBackingStores(); + + // Expires the given backing store. This emulates something getting evicted + // from the cache for the purpose of testing. Returns true if the host was + // removed, false if it wasn't found. + static bool ExpireBackingStoreForTest(RenderWidgetHost* host); + + // Current size in bytes of the backing store cache. + static size_t MemorySize(); + + private: + // Not intended for instantiation. + BackingStoreManager() {} + + DISALLOW_COPY_AND_ASSIGN(BackingStoreManager); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_MANAGER_H_ diff --git a/chrome/browser/renderer_host/backing_store_skia.cc b/content/browser/renderer_host/backing_store_skia.cc index 8d07a26..f756504 100644 --- a/chrome/browser/renderer_host/backing_store_skia.cc +++ b/content/browser/renderer_host/backing_store_skia.cc @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/backing_store_skia.h" +#include "content/browser/renderer_host/backing_store_skia.h" -#include "chrome/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_process_host.h" #include "skia/ext/platform_canvas.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/gfx/canvas.h" diff --git a/content/browser/renderer_host/backing_store_skia.h b/content/browser/renderer_host/backing_store_skia.h new file mode 100644 index 0000000..9f71fb0 --- /dev/null +++ b/content/browser/renderer_host/backing_store_skia.h @@ -0,0 +1,51 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_SKIA_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_SKIA_H_ +#pragma once + +#include "base/scoped_ptr.h" +#include "content/browser/renderer_host/backing_store.h" +#include "third_party/skia/include/core/SkBitmap.h" + +class SkCanvas; + +namespace gfx { +class Point; +class Canvas; +} + +// A backing store that uses skia. This is a temporary backing store used by +// RenderWidgetHostViewViews. In time, only GPU rendering will be used for +// RWHVV, and then this backing store will be removed. +class BackingStoreSkia : public BackingStore { + public: + BackingStoreSkia(RenderWidgetHost* widget, const gfx::Size& size); + virtual ~BackingStoreSkia(); + + void SkiaShowRect(const gfx::Point& point, gfx::Canvas* canvas); + + // BackingStore implementation. + virtual size_t MemorySize(); + virtual void PaintToBackingStore( + RenderProcessHost* process, + TransportDIB::Id bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects); + virtual bool CopyFromBackingStore(const gfx::Rect& rect, + skia::PlatformCanvas* output); + virtual void ScrollBackingStore(int dx, int dy, + const gfx::Rect& clip_rect, + const gfx::Size& view_size); + + private: + SkBitmap bitmap_; + + scoped_ptr<SkCanvas> canvas_; + + DISALLOW_COPY_AND_ASSIGN(BackingStoreSkia); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_SKIA_H_ diff --git a/chrome/browser/renderer_host/backing_store_win.cc b/content/browser/renderer_host/backing_store_win.cc index 4e68a0e..0023b51 100644 --- a/chrome/browser/renderer_host/backing_store_win.cc +++ b/content/browser/renderer_host/backing_store_win.cc @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/backing_store_win.h" +#include "content/browser/renderer_host/backing_store_win.h" #include "app/surface/transport_dib.h" #include "base/command_line.h" -#include "chrome/browser/renderer_host/render_process_host.h" -#include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/common/chrome_switches.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_widget_host.h" #include "skia/ext/platform_canvas.h" #include "ui/gfx/gdi_util.h" diff --git a/content/browser/renderer_host/backing_store_win.h b/content/browser/renderer_host/backing_store_win.h new file mode 100644 index 0000000..197de6bc --- /dev/null +++ b/content/browser/renderer_host/backing_store_win.h @@ -0,0 +1,52 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_WIN_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_WIN_H_ +#pragma once + +#include <windows.h> + +#include "base/basictypes.h" +#include "content/browser/renderer_host/backing_store.h" + +class BackingStoreWin : public BackingStore { + public: + BackingStoreWin(RenderWidgetHost* widget, const gfx::Size& size); + virtual ~BackingStoreWin(); + + HDC hdc() { return hdc_; } + + // Returns true if we should convert to the monitor profile when painting. + static bool ColorManagementEnabled(); + + // BackingStore implementation. + virtual size_t MemorySize(); + virtual void PaintToBackingStore(RenderProcessHost* process, + TransportDIB::Id bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects); + virtual bool CopyFromBackingStore(const gfx::Rect& rect, + skia::PlatformCanvas* output); + virtual void ScrollBackingStore(int dx, int dy, + const gfx::Rect& clip_rect, + const gfx::Size& view_size); + + private: + // The backing store dc. + HDC hdc_; + + // Handle to the backing store dib. + HANDLE backing_store_dib_; + + // Handle to the original bitmap in the dc. + HANDLE original_bitmap_; + + // Number of bits per pixel of the screen. + int color_depth_; + + DISALLOW_COPY_AND_ASSIGN(BackingStoreWin); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_WIN_H_ diff --git a/chrome/browser/renderer_host/backing_store_x.cc b/content/browser/renderer_host/backing_store_x.cc index 4272d40..5e1e33a 100644 --- a/chrome/browser/renderer_host/backing_store_x.cc +++ b/content/browser/renderer_host/backing_store_x.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/backing_store_x.h" +#include "content/browser/renderer_host/backing_store_x.h" #include <cairo-xlib.h> #include <gtk/gtk.h> @@ -23,7 +23,7 @@ #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/time.h" -#include "chrome/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_process_host.h" #include "skia/ext/platform_canvas.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/x/x11_util.h" diff --git a/content/browser/renderer_host/backing_store_x.h b/content/browser/renderer_host/backing_store_x.h new file mode 100644 index 0000000..f911b1f --- /dev/null +++ b/content/browser/renderer_host/backing_store_x.h @@ -0,0 +1,101 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_X_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_X_H_ +#pragma once + +#include "base/basictypes.h" +#include "build/build_config.h" +#include "content/browser/renderer_host/backing_store.h" +#include "ui/base/x/x11_util.h" + +namespace gfx { +class Point; +class Rect; +} // namespace gfx + +typedef struct _GdkDrawable GdkDrawable; +class SkBitmap; + +class BackingStoreX : public BackingStore { + public: + // Create a backing store on the X server. The visual is an Xlib Visual + // describing the format of the target window and the depth is the color + // depth of the X window which will be drawn into. + BackingStoreX(RenderWidgetHost* widget, + const gfx::Size& size, + void* visual, + int depth); + + // This is for unittesting only. An object constructed using this constructor + // will silently ignore all paints + BackingStoreX(RenderWidgetHost* widget, const gfx::Size& size); + + virtual ~BackingStoreX(); + + Display* display() const { return display_; } + XID root_window() const { return root_window_; } + + // Copy from the server-side backing store to the target window + // origin: the destination rectangle origin + // damage: the area to copy + // target: the X id of the target window + void XShowRect(const gfx::Point &origin, const gfx::Rect& damage, + XID target); + + // As above, but use Cairo instead of Xlib. + void CairoShowRect(const gfx::Rect& damage, GdkDrawable* drawable); + +#if defined(TOOLKIT_GTK) + // Paint the backing store into the target's |dest_rect|. + void PaintToRect(const gfx::Rect& dest_rect, GdkDrawable* target); +#endif + + // BackingStore implementation. + virtual size_t MemorySize(); + virtual void PaintToBackingStore( + RenderProcessHost* process, + TransportDIB::Id bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects); + virtual bool CopyFromBackingStore(const gfx::Rect& rect, + skia::PlatformCanvas* output); + virtual void ScrollBackingStore(int dx, int dy, + const gfx::Rect& clip_rect, + const gfx::Size& view_size); + + private: + // Paints the bitmap from the renderer onto the backing store without + // using Xrender to composite the pixmaps. + void PaintRectWithoutXrender(TransportDIB* bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects); + + // This is the connection to the X server where this backing store will be + // displayed. + Display* const display_; + // What flavor, if any, MIT-SHM (X shared memory) support we have. + const ui::SharedMemorySupport shared_memory_support_; + // If this is true, then we can use Xrender to composite our pixmaps. + const bool use_render_; + // If |use_render_| is false, this is the number of bits-per-pixel for |depth| + int pixmap_bpp_; + // if |use_render_| is false, we need the Visual to get the RGB masks. + void* const visual_; + // This is the depth of the target window. + const int visual_depth_; + // The parent window (probably a GtkDrawingArea) for this backing store. + const XID root_window_; + // This is a handle to the server side pixmap which is our backing store. + XID pixmap_; + // This is the RENDER picture pointing at |pixmap_|. + XID picture_; + // This is a default graphic context, used in XCopyArea + void* pixmap_gc_; + + DISALLOW_COPY_AND_ASSIGN(BackingStoreX); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BACKING_STORE_X_H_ diff --git a/chrome/browser/renderer_host/blob_message_filter.cc b/content/browser/renderer_host/blob_message_filter.cc index d31d5f7..433fe72 100644 --- a/chrome/browser/renderer_host/blob_message_filter.cc +++ b/content/browser/renderer_host/blob_message_filter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/blob_message_filter.h" +#include "content/browser/renderer_host/blob_message_filter.h" #include "chrome/browser/child_process_security_policy.h" #include "chrome/browser/chrome_blob_storage_context.h" diff --git a/content/browser/renderer_host/blob_message_filter.h b/content/browser/renderer_host/blob_message_filter.h new file mode 100644 index 0000000..aa1cdc6 --- /dev/null +++ b/content/browser/renderer_host/blob_message_filter.h @@ -0,0 +1,51 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_BLOB_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BLOB_MESSAGE_FILTER_H_ + +#include "base/hash_tables.h" +#include "chrome/browser/browser_message_filter.h" + +class ChromeBlobStorageContext; +class GURL; + +namespace IPC { +class Message; +} + +namespace webkit_blob { +class BlobData; +} + +class BlobMessageFilter : public BrowserMessageFilter { + public: + BlobMessageFilter(int process_id, + ChromeBlobStorageContext* blob_storage_context); + ~BlobMessageFilter(); + + // BrowserMessageFilter implementation. + virtual void OnChannelClosing(); + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + + private: + void OnRegisterBlobUrl(const GURL& url, + const scoped_refptr<webkit_blob::BlobData>& blob_data); + void OnRegisterBlobUrlFrom(const GURL& url, const GURL& src_url); + void OnUnregisterBlobUrl(const GURL& url); + + bool CheckPermission(webkit_blob::BlobData* blob_data) const; + + int process_id_; + scoped_refptr<ChromeBlobStorageContext> blob_storage_context_; + + // Keep track of blob URLs registered in this process. Need to unregister + // all of them when the renderer process dies. + base::hash_set<std::string> blob_urls_; + + DISALLOW_IMPLICIT_CONSTRUCTORS(BlobMessageFilter); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BLOB_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/buffered_resource_handler.cc b/content/browser/renderer_host/buffered_resource_handler.cc index 05aa75f..2e302f8 100644 --- a/chrome/browser/renderer_host/buffered_resource_handler.cc +++ b/content/browser/renderer_host/buffered_resource_handler.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/buffered_resource_handler.h" +#include "content/browser/renderer_host/buffered_resource_handler.h" #include <vector> @@ -11,12 +11,12 @@ #include "base/string_util.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/renderer_host/download_throttling_resource_handler.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" -#include "chrome/browser/renderer_host/x509_user_cert_resource_handler.h" #include "chrome/common/extensions/user_script.h" #include "chrome/common/resource_response.h" #include "chrome/common/url_constants.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/x509_user_cert_resource_handler.h" #include "net/base/io_buffer.h" #include "net/base/mime_sniffer.h" #include "net/base/mime_util.h" diff --git a/content/browser/renderer_host/buffered_resource_handler.h b/content/browser/renderer_host/buffered_resource_handler.h new file mode 100644 index 0000000..ab5393e --- /dev/null +++ b/content/browser/renderer_host/buffered_resource_handler.h @@ -0,0 +1,99 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_BUFFERED_RESOURCE_HANDLER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_BUFFERED_RESOURCE_HANDLER_H_ +#pragma once + +#include <string> + +#include "content/browser/renderer_host/resource_handler.h" + +class MessageLoop; +class ResourceDispatcherHost; + +namespace net { +class URLRequest; +} // namespace net + +// Used to buffer a request until enough data has been received. +class BufferedResourceHandler : public ResourceHandler { + public: + BufferedResourceHandler(ResourceHandler* handler, + ResourceDispatcherHost* host, + net::URLRequest* request); + + // ResourceHandler implementation: + virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); + virtual bool OnRequestRedirected(int request_id, const GURL& new_url, + ResourceResponse* response, bool* defer); + virtual bool OnResponseStarted(int request_id, ResourceResponse* response); + virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); + virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, + int min_size); + virtual bool OnReadCompleted(int request_id, int* bytes_read); + virtual bool OnResponseCompleted(int request_id, + const net::URLRequestStatus& status, + const std::string& security_info); + virtual void OnRequestClosed(); + + private: + virtual ~BufferedResourceHandler(); + + // Returns true if we should delay OnResponseStarted forwarding. + bool DelayResponse(); + + // Returns true if there will be a need to parse the DocType of the document + // to determine the right way to handle it. + bool ShouldBuffer(const GURL& url, const std::string& mime_type); + + // Returns true if there is enough information to process the DocType. + bool DidBufferEnough(int bytes_read); + + // Returns true if we have to keep buffering data. + bool KeepBuffering(int bytes_read); + + // Sends a pending OnResponseStarted notification. |in_complete| is true if + // this is invoked from |OnResponseCompleted|. + bool CompleteResponseStarted(int request_id, bool in_complete); + + // Returns true if we have to wait until the plugin list is generated. + bool ShouldWaitForPlugins(); + + // A test to determining whether the request should be forwarded to the + // download thread. If need_plugin_list was passed in and was set to true, + // that means that the check couldn't be fully done because the plugins aren't + // loaded. The function should be called again after the plugin list is + // loaded. + bool ShouldDownload(bool* need_plugin_list); + + // Informs the original ResourceHandler |real_handler_| that the response will + // be handled entirely by the new ResourceHandler |handler|. + // A reference to |handler| is acquired. + void UseAlternateResourceHandler(int request_id, ResourceHandler* handler); + + // Called on the file thread to load the list of plugins. + void LoadPlugins(); + + // Called on the IO thread once the list of plugins has been loaded. + void OnPluginsLoaded(); + + scoped_refptr<ResourceHandler> real_handler_; + scoped_refptr<ResourceResponse> response_; + ResourceDispatcherHost* host_; + net::URLRequest* request_; + scoped_refptr<net::IOBuffer> read_buffer_; + scoped_refptr<net::IOBuffer> my_buffer_; + int read_buffer_size_; + int bytes_read_; + bool sniff_content_; + bool should_buffer_; + bool wait_for_plugins_; + bool buffering_; + bool finished_; + + DISALLOW_COPY_AND_ASSIGN(BufferedResourceHandler); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_BUFFERED_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/cross_site_resource_handler.cc b/content/browser/renderer_host/cross_site_resource_handler.cc index d3236f6..ceb5554 100644 --- a/chrome/browser/renderer_host/cross_site_resource_handler.cc +++ b/content/browser/renderer_host/cross_site_resource_handler.cc @@ -4,15 +4,15 @@ #include <string> -#include "chrome/browser/renderer_host/cross_site_resource_handler.h" +#include "content/browser/renderer_host/cross_site_resource_handler.h" #include "base/logging.h" -#include "chrome/browser/renderer_host/global_request_id.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "chrome/browser/renderer_host/render_view_host_delegate.h" -#include "chrome/browser/renderer_host/render_view_host_notification_task.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/global_request_id.h" +#include "content/browser/renderer_host/render_view_host.h" +#include "content/browser/renderer_host/render_view_host_delegate.h" +#include "content/browser/renderer_host/render_view_host_notification_task.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" #include "net/base/io_buffer.h" CrossSiteResourceHandler::CrossSiteResourceHandler( diff --git a/content/browser/renderer_host/cross_site_resource_handler.h b/content/browser/renderer_host/cross_site_resource_handler.h new file mode 100644 index 0000000..9fee1b9 --- /dev/null +++ b/content/browser/renderer_host/cross_site_resource_handler.h @@ -0,0 +1,71 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_CROSS_SITE_RESOURCE_HANDLER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_CROSS_SITE_RESOURCE_HANDLER_H_ +#pragma once + +#include "content/browser/renderer_host/resource_handler.h" +#include "net/url_request/url_request_status.h" + +class ResourceDispatcherHost; +struct GlobalRequestID; + +// Ensures that cross-site responses are delayed until the onunload handler of +// the previous page is allowed to run. This handler wraps an +// AsyncEventHandler, and it sits inside SafeBrowsing and Buffered event +// handlers. This is important, so that it can intercept OnResponseStarted +// after we determine that a response is safe and not a download. +class CrossSiteResourceHandler : public ResourceHandler { + public: + CrossSiteResourceHandler(ResourceHandler* handler, + int render_process_host_id, + int render_view_id, + ResourceDispatcherHost* resource_dispatcher_host); + + // ResourceHandler implementation: + virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); + virtual bool OnRequestRedirected(int request_id, const GURL& new_url, + ResourceResponse* response, bool* defer); + virtual bool OnResponseStarted(int request_id, + ResourceResponse* response); + virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); + virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, + int min_size); + virtual bool OnReadCompleted(int request_id, int* bytes_read); + virtual bool OnResponseCompleted(int request_id, + const net::URLRequestStatus& status, + const std::string& security_info); + virtual void OnRequestClosed(); + + // We can now send the response to the new renderer, which will cause + // TabContents to swap in the new renderer and destroy the old one. + void ResumeResponse(); + + private: + virtual ~CrossSiteResourceHandler(); + + // Prepare to render the cross-site response in a new RenderViewHost, by + // telling the old RenderViewHost to run its onunload handler. + void StartCrossSiteTransition( + int request_id, + ResourceResponse* response, + const GlobalRequestID& global_id); + + scoped_refptr<ResourceHandler> next_handler_; + int render_process_host_id_; + int render_view_id_; + bool has_started_response_; + bool in_cross_site_transition_; + int request_id_; + bool completed_during_transition_; + net::URLRequestStatus completed_status_; + std::string completed_security_info_; + ResourceResponse* response_; + ResourceDispatcherHost* rdh_; + + DISALLOW_COPY_AND_ASSIGN(CrossSiteResourceHandler); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_CROSS_SITE_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/database_message_filter.cc b/content/browser/renderer_host/database_message_filter.cc index c3dc055..1e8cdb0 100644 --- a/chrome/browser/renderer_host/database_message_filter.cc +++ b/content/browser/renderer_host/database_message_filter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/database_message_filter.h" +#include "content/browser/renderer_host/database_message_filter.h" #include <string> diff --git a/content/browser/renderer_host/database_message_filter.h b/content/browser/renderer_host/database_message_filter.h new file mode 100644 index 0000000..7d432e8 --- /dev/null +++ b/content/browser/renderer_host/database_message_filter.h @@ -0,0 +1,103 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_DATABASE_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_DATABASE_MESSAGE_FILTER_H_ +#pragma once + +#include "base/hash_tables.h" +#include "base/string16.h" +#include "chrome/browser/browser_message_filter.h" +#include "chrome/common/content_settings.h" +#include "webkit/database/database_connections.h" +#include "webkit/database/database_tracker.h" + +class HostContentSettingsMap; + +class DatabaseMessageFilter + : public BrowserMessageFilter, + public webkit_database::DatabaseTracker::Observer { + public: + DatabaseMessageFilter( + webkit_database::DatabaseTracker* db_tracker, + HostContentSettingsMap *host_content_settings_map); + + // BrowserMessageFilter implementation. + virtual void OnChannelClosing(); + virtual void OverrideThreadForMessage(const IPC::Message& message, + BrowserThread::ID* thread); + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + + webkit_database::DatabaseTracker* database_tracker() const { + return db_tracker_.get(); + } + + private: + virtual ~DatabaseMessageFilter(); + + class PromptDelegate; + + void AddObserver(); + void RemoveObserver(); + + // VFS message handlers (file thread) + void OnDatabaseOpenFile(const string16& vfs_file_name, + int desired_flags, + IPC::Message* reply_msg); + void OnDatabaseDeleteFile(const string16& vfs_file_name, + const bool& sync_dir, + IPC::Message* reply_msg); + void OnDatabaseGetFileAttributes(const string16& vfs_file_name, + IPC::Message* reply_msg); + void OnDatabaseGetFileSize(const string16& vfs_file_name, + IPC::Message* reply_msg); + + // Database tracker message handlers (file thread) + void OnDatabaseOpened(const string16& origin_identifier, + const string16& database_name, + const string16& description, + int64 estimated_size); + void OnDatabaseModified(const string16& origin_identifier, + const string16& database_name); + void OnDatabaseClosed(const string16& origin_identifier, + const string16& database_name); + void OnAllowDatabase(const std::string& origin_url, + const string16& name, + const string16& display_name, + unsigned long estimated_size, + IPC::Message* reply_msg); + + // DatabaseTracker::Observer callbacks (file thread) + virtual void OnDatabaseSizeChanged(const string16& origin_identifier, + const string16& database_name, + int64 database_size, + int64 space_available); + virtual void OnDatabaseScheduledForDeletion(const string16& origin_identifier, + const string16& database_name); + + void DatabaseDeleteFile(const string16& vfs_file_name, + bool sync_dir, + IPC::Message* reply_msg, + int reschedule_count); + + // CookiePromptModalDialog response handler (io thread) + void AllowDatabaseResponse(IPC::Message* reply_msg, + ContentSetting content_setting); + + // The database tracker for the current profile. + scoped_refptr<webkit_database::DatabaseTracker> db_tracker_; + + // True if and only if this instance was added as an observer + // to DatabaseTracker. + bool observer_added_; + + // Keeps track of all DB connections opened by this renderer + webkit_database::DatabaseConnections database_connections_; + + // Used to look up permissions at database creation time. + scoped_refptr<HostContentSettingsMap> host_content_settings_map_; +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_DATABASE_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/file_utilities_message_filter.cc b/content/browser/renderer_host/file_utilities_message_filter.cc index f49c634..67377d6 100644 --- a/chrome/browser/renderer_host/file_utilities_message_filter.cc +++ b/content/browser/renderer_host/file_utilities_message_filter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/file_utilities_message_filter.h" +#include "content/browser/renderer_host/file_utilities_message_filter.h" #include "base/file_util.h" #include "chrome/browser/child_process_security_policy.h" diff --git a/content/browser/renderer_host/file_utilities_message_filter.h b/content/browser/renderer_host/file_utilities_message_filter.h new file mode 100644 index 0000000..92cd2f5 --- /dev/null +++ b/content/browser/renderer_host/file_utilities_message_filter.h @@ -0,0 +1,48 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_FILE_UTILITIES_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_FILE_UTILITIES_MESSAGE_FILTER_H_ + +#include "base/basictypes.h" +#include "base/file_path.h" +#include "chrome/browser/browser_message_filter.h" +#include "ipc/ipc_platform_file.h" + +namespace base { +struct PlatformFileInfo; +} + +namespace IPC { +class Message; +} + +class FileUtilitiesMessageFilter : public BrowserMessageFilter { + public: + explicit FileUtilitiesMessageFilter(int process_id); + + // BrowserMessageFilter implementation. + virtual void OverrideThreadForMessage(const IPC::Message& message, + BrowserThread::ID* thread); + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + private: + ~FileUtilitiesMessageFilter(); + + typedef void (*FileInfoWriteFunc)(IPC::Message* reply_msg, + const base::PlatformFileInfo& file_info); + + void OnGetFileSize(const FilePath& path, int64* result); + void OnGetFileModificationTime(const FilePath& path, base::Time* result); + void OnOpenFile(const FilePath& path, + int mode, + IPC::PlatformFileForTransit* result); + + // The ID of this process. + int process_id_; + + DISALLOW_IMPLICIT_CONSTRUCTORS(FileUtilitiesMessageFilter); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_FILE_UTILITIES_MESSAGE_FILTER_H_ diff --git a/content/browser/renderer_host/global_request_id.h b/content/browser/renderer_host/global_request_id.h new file mode 100644 index 0000000..031026f --- /dev/null +++ b/content/browser/renderer_host/global_request_id.h @@ -0,0 +1,32 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_GLOBAL_REQUEST_ID_H_ +#define CONTENT_BROWSER_RENDERER_HOST_GLOBAL_REQUEST_ID_H_ +#pragma once + +// Uniquely identifies a net::URLRequest. +struct GlobalRequestID { + GlobalRequestID() : child_id(-1), request_id(-1) { + } + + GlobalRequestID(int child_id, int request_id) + : child_id(child_id), + request_id(request_id) { + } + + // The unique ID of the child process (different from OS's PID). + int child_id; + + // The request ID (unique for the child). + int request_id; + + bool operator<(const GlobalRequestID& other) const { + if (child_id == other.child_id) + return request_id < other.request_id; + return child_id < other.child_id; + } +}; + +#endif // CHROME_BROWSER_RENDERER_HOST_GLOBAL_REQUEST_ID_H_ diff --git a/chrome/browser/renderer_host/gpu_message_filter.cc b/content/browser/renderer_host/gpu_message_filter.cc index bd16d26..157b96d 100644 --- a/chrome/browser/renderer_host/gpu_message_filter.cc +++ b/content/browser/renderer_host/gpu_message_filter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/gpu_message_filter.h" +#include "content/browser/renderer_host/gpu_message_filter.h" #include "base/callback.h" #include "chrome/browser/gpu_process_host_ui_shim.h" diff --git a/content/browser/renderer_host/gpu_message_filter.h b/content/browser/renderer_host/gpu_message_filter.h new file mode 100644 index 0000000..a81fa2a --- /dev/null +++ b/content/browser/renderer_host/gpu_message_filter.h @@ -0,0 +1,51 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_GPU_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_GPU_MESSAGE_FILTER_H_ +#pragma once + +#include "chrome/browser/browser_message_filter.h" + +struct GPUCreateCommandBufferConfig; +class GPUInfo; + +namespace IPC { +struct ChannelHandle; +} + +// A message filter for messages from the renderer to the GpuProcessHost +// in the browser. Such messages are typically destined for the GPU process, +// but need to be mediated by the browser. +class GpuMessageFilter : public BrowserMessageFilter, + public base::SupportsWeakPtr<GpuMessageFilter> { + public: + explicit GpuMessageFilter(int render_process_id); + + // BrowserMessageFilter methods: + virtual void OverrideThreadForMessage(const IPC::Message& message, + BrowserThread::ID* thread); + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + virtual void OnDestruct() const; + + private: + friend class BrowserThread; + friend class DeleteTask<GpuMessageFilter>; + virtual ~GpuMessageFilter(); + + // Message handlers called on the browser IO thread: + void OnEstablishGpuChannel(); + void OnSynchronizeGpu(IPC::Message* reply); + void OnCreateViewCommandBuffer( + int32 render_view_id, + const GPUCreateCommandBufferConfig& init_params, + IPC::Message* reply); + + int render_process_id_; + + DISALLOW_COPY_AND_ASSIGN(GpuMessageFilter); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_GPU_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/mock_render_process_host.cc b/content/browser/renderer_host/mock_render_process_host.cc index 1f1a2b3..e0a2fb0 100644 --- a/chrome/browser/renderer_host/mock_render_process_host.cc +++ b/content/browser/renderer_host/mock_render_process_host.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/mock_render_process_host.h" +#include "content/browser/renderer_host/mock_render_process_host.h" #include "chrome/browser/child_process_security_policy.h" diff --git a/content/browser/renderer_host/mock_render_process_host.h b/content/browser/renderer_host/mock_render_process_host.h new file mode 100644 index 0000000..abe0f82 --- /dev/null +++ b/content/browser/renderer_host/mock_render_process_host.h @@ -0,0 +1,102 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_MOCK_RENDER_PROCESS_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_MOCK_RENDER_PROCESS_HOST_H_ +#pragma once + +#include "base/basictypes.h" +#include "base/scoped_vector.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "ipc/ipc_test_sink.h" + +class MockRenderProcessHostFactory; +class TransportDIB; +class URLRequestContextGetter; + +// A mock render process host that has no corresponding renderer process. All +// IPC messages are sent into the message sink for inspection by tests. +class MockRenderProcessHost : public RenderProcessHost { + public: + explicit MockRenderProcessHost(Profile* profile); + virtual ~MockRenderProcessHost(); + + // Provides access to all IPC messages that would have been sent to the + // renderer via this RenderProcessHost. + IPC::TestSink& sink() { return sink_; } + + // Provides tests access to the max page ID currently used for this process. + int max_page_id() const { return max_page_id_; } + + // Provides test access to how many times a bad message has been received. + int bad_msg_count() const { return bad_msg_count_; } + + // RenderProcessHost implementation (public portion). + virtual bool Init(bool is_accessibility_enabled, bool is_extensions_process); + virtual int GetNextRoutingID(); + virtual void CancelResourceRequests(int render_widget_id); + virtual void CrossSiteClosePageACK(const ViewMsg_ClosePage_Params& params); + virtual bool WaitForUpdateMsg(int render_widget_id, + const base::TimeDelta& max_delay, + IPC::Message* msg); + virtual void ReceivedBadMessage(); + virtual void WidgetRestored(); + virtual void WidgetHidden(); + virtual void ViewCreated(); + virtual void AddWord(const string16& word); + virtual void SendVisitedLinkTable(base::SharedMemory* table_memory); + virtual void AddVisitedLinks( + const VisitedLinkCommon::Fingerprints& visited_links); + virtual void ResetVisitedLinks(); + virtual bool FastShutdownIfPossible(); + virtual bool SendWithTimeout(IPC::Message* msg, int timeout_ms); + virtual base::ProcessHandle GetHandle(); + + virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id); + + // IPC::Channel::Sender via RenderProcessHost. + virtual bool Send(IPC::Message* msg); + + // IPC::Channel::Listener via RenderProcessHost. + virtual bool OnMessageReceived(const IPC::Message& msg); + virtual void OnChannelConnected(int32 peer_pid); + + // Attaches the factory object so we can remove this object in its destructor + // and prevent MockRenderProcessHostFacotry from deleting it. + void SetFactory(const MockRenderProcessHostFactory* factory) { + factory_ = factory; + } + + private: + // Stores IPC messages that would have been sent to the renderer. + IPC::TestSink sink_; + TransportDIB* transport_dib_; + int bad_msg_count_; + const MockRenderProcessHostFactory* factory_; + + DISALLOW_COPY_AND_ASSIGN(MockRenderProcessHost); +}; + +class MockRenderProcessHostFactory : public RenderProcessHostFactory { + public: + MockRenderProcessHostFactory(); + virtual ~MockRenderProcessHostFactory(); + + virtual RenderProcessHost* CreateRenderProcessHost(Profile* profile) const; + + // Removes the given MockRenderProcessHost from the MockRenderProcessHost list + // without deleting it. When a test deletes a MockRenderProcessHost, we need + // to remove it from |processes_| to prevent it from being deleted twice. + void Remove(MockRenderProcessHost* host) const; + + private: + // A list of MockRenderProcessHosts created by this object. This list is used + // for deleting all MockRenderProcessHosts that have not deleted by a test in + // the destructor and prevent them from being leaked. + mutable ScopedVector<MockRenderProcessHost> processes_; + + DISALLOW_COPY_AND_ASSIGN(MockRenderProcessHostFactory); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_MOCK_RENDER_PROCESS_HOST_H_ diff --git a/chrome/browser/renderer_host/pepper_file_message_filter.cc b/content/browser/renderer_host/pepper_file_message_filter.cc index 5109e7b..9f7f9d9 100644 --- a/chrome/browser/renderer_host/pepper_file_message_filter.cc +++ b/content/browser/renderer_host/pepper_file_message_filter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/pepper_file_message_filter.h" +#include "content/browser/renderer_host/pepper_file_message_filter.h" #include "base/callback.h" #include "base/file_util.h" diff --git a/content/browser/renderer_host/pepper_file_message_filter.h b/content/browser/renderer_host/pepper_file_message_filter.h new file mode 100644 index 0000000..a06d9a4 --- /dev/null +++ b/content/browser/renderer_host/pepper_file_message_filter.h @@ -0,0 +1,72 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_PEPPER_FILE_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_PEPPER_FILE_MESSAGE_FILTER_H_ +#pragma once + +#include <string> +#include <vector> + +#include "base/file_path.h" +#include "base/process.h" +#include "base/ref_counted.h" +#include "base/task.h" +#include "build/build_config.h" +#include "chrome/browser/browser_message_filter.h" +#include "ipc/ipc_platform_file.h" +#include "webkit/plugins/ppapi/dir_contents.h" + +class Profile; + +// A message filter for Pepper-specific File I/O messages. +class PepperFileMessageFilter : public BrowserMessageFilter { + public: + PepperFileMessageFilter(int child_id, Profile* profile); + + // BrowserMessageFilter methods: + virtual void OverrideThreadForMessage(const IPC::Message& message, + BrowserThread::ID* thread); + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + virtual void OnDestruct() const; + + private: + friend class BrowserThread; + friend class DeleteTask<PepperFileMessageFilter>; + virtual ~PepperFileMessageFilter(); + + // Called on the FILE thread: + void OnPepperOpenFile(const FilePath& path, + int flags, + base::PlatformFileError* error, + IPC::PlatformFileForTransit* file); + void OnPepperRenameFile(const FilePath& path_from, + const FilePath& path_to, + base::PlatformFileError* error); + void OnPepperDeleteFileOrDir(const FilePath& path, + bool recursive, + base::PlatformFileError* error); + void OnPepperCreateDir(const FilePath& path, + base::PlatformFileError* error); + void OnPepperQueryFile(const FilePath& path, + base::PlatformFileInfo* info, + base::PlatformFileError* error); + void OnPepperGetDirContents(const FilePath& path, + webkit::ppapi::DirContents* contents, + base::PlatformFileError* error); + + FilePath MakePepperPath(const FilePath& base_path); + + // The channel associated with the renderer connection. This pointer is not + // owned by this class. + IPC::Channel* channel_; + + // The base path for the pepper data. + FilePath pepper_path_; + + DISALLOW_COPY_AND_ASSIGN(PepperFileMessageFilter); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_PEPPER_FILE_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/pepper_message_filter.cc b/content/browser/renderer_host/pepper_message_filter.cc index de0793d..6a77171 100644 --- a/chrome/browser/renderer_host/pepper_message_filter.cc +++ b/content/browser/renderer_host/pepper_message_filter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/pepper_message_filter.h" +#include "content/browser/renderer_host/pepper_message_filter.h" #include "base/basictypes.h" #include "base/process_util.h" diff --git a/content/browser/renderer_host/pepper_message_filter.h b/content/browser/renderer_host/pepper_message_filter.h new file mode 100644 index 0000000..31f920c --- /dev/null +++ b/content/browser/renderer_host/pepper_message_filter.h @@ -0,0 +1,70 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_PEPPER_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_PEPPER_MESSAGE_FILTER_H_ +#pragma once + +#include <string> + +#include "base/basictypes.h" +#include "base/process.h" +#include "chrome/browser/browser_message_filter.h" +#include "ipc/ipc_channel_proxy.h" +#include "ppapi/c/private/ppb_flash.h" + +class Profile; +class URLRequestContextGetter; + +namespace net { +class AddressList; +} + +class PepperMessageFilter : public BrowserMessageFilter { + public: + explicit PepperMessageFilter(Profile* profile); + virtual ~PepperMessageFilter(); + + private: + // BrowserMessageFilter methods. + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + +#if defined(ENABLE_FLAPPER_HACKS) + // Message handlers. + void OnConnectTcp(int routing_id, + int request_id, + const std::string& host, + uint16 port); + void OnConnectTcpAddress(int routing_id, + int request_id, + const PP_Flash_NetAddress& address); + + // |Send()| a |PepperMsg_ConnectTcpACK|, which reports an error. + bool SendConnectTcpACKError(int routing_id, + int request_id); + + // Used by |OnConnectTcp()| (below). + class LookupRequest; + friend class LookupRequest; + + // Continuation of |OnConnectTcp()|. + void ConnectTcpLookupFinished(int routing_id, + int request_id, + const net::AddressList& addresses); + void ConnectTcpOnWorkerThread(int routing_id, + int request_id, + net::AddressList addresses); + + // Continuation of |OnConnectTcpAddress()|. + void ConnectTcpAddressOnWorkerThread(int routing_id, + int request_id, + PP_Flash_NetAddress addr); +#endif // ENABLE_FLAPPER_HACKS + + Profile* profile_; + scoped_refptr<URLRequestContextGetter> request_context_; +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_PEPPER_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/redirect_to_file_resource_handler.cc b/content/browser/renderer_host/redirect_to_file_resource_handler.cc index 11d5934..bb18a4a 100644 --- a/chrome/browser/renderer_host/redirect_to_file_resource_handler.cc +++ b/content/browser/renderer_host/redirect_to_file_resource_handler.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/redirect_to_file_resource_handler.h" +#include "content/browser/renderer_host/redirect_to_file_resource_handler.h" #include "base/file_util.h" #include "base/file_util_proxy.h" #include "base/logging.h" #include "base/platform_file.h" #include "base/task.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/resource_response.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" #include "net/base/mime_sniffer.h" diff --git a/content/browser/renderer_host/redirect_to_file_resource_handler.h b/content/browser/renderer_host/redirect_to_file_resource_handler.h new file mode 100644 index 0000000..34fb082 --- /dev/null +++ b/content/browser/renderer_host/redirect_to_file_resource_handler.h @@ -0,0 +1,89 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_REDIRECT_TO_FILE_RESOURCE_HANDLER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_REDIRECT_TO_FILE_RESOURCE_HANDLER_H_ + +#include "base/file_path.h" +#include "base/platform_file.h" +#include "base/ref_counted.h" +#include "base/scoped_callback_factory.h" +#include "base/scoped_ptr.h" +#include "chrome/browser/renderer_host/resource_handler.h" +#include "net/base/completion_callback.h" + +class RefCountedPlatformFile; +class ResourceDispatcherHost; + +namespace net { +class FileStream; +class GrowableIOBuffer; +} + +namespace webkit_blob { +class DeletableFileReference; +} + +// Redirects network data to a file. This is intended to be layered in front +// of either the AsyncResourceHandler or the SyncResourceHandler. +class RedirectToFileResourceHandler : public ResourceHandler { + public: + RedirectToFileResourceHandler( + ResourceHandler* next_handler, + int process_id, + ResourceDispatcherHost* resource_dispatcher_host); + + // ResourceHandler implementation: + virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); + virtual bool OnRequestRedirected(int request_id, const GURL& new_url, + ResourceResponse* response, bool* defer); + virtual bool OnResponseStarted(int request_id, ResourceResponse* response); + virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); + virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, + int min_size); + virtual bool OnReadCompleted(int request_id, int* bytes_read); + virtual bool OnResponseCompleted(int request_id, + const net::URLRequestStatus& status, + const std::string& security_info); + virtual void OnRequestClosed(); + + private: + virtual ~RedirectToFileResourceHandler(); + void DidCreateTemporaryFile(base::PlatformFileError error_code, + base::PassPlatformFile file_handle, + FilePath file_path); + void DidWriteToFile(int result); + bool WriteMore(); + bool BufIsFull() const; + + base::ScopedCallbackFactory<RedirectToFileResourceHandler> callback_factory_; + + ResourceDispatcherHost* host_; + scoped_refptr<ResourceHandler> next_handler_; + int process_id_; + int request_id_; + + // We allocate a single, fixed-size IO buffer (buf_) used to read from the + // network (buf_write_pending_ is true while the system is copying data into + // buf_), and then write this buffer out to disk (write_callback_pending_ is + // true while writing to disk). Reading from the network is suspended while + // the buffer is full (BufIsFull returns true). The write_cursor_ member + // tracks the offset into buf_ that we are writing to disk. + + scoped_refptr<net::GrowableIOBuffer> buf_; + bool buf_write_pending_; + int write_cursor_; + + scoped_ptr<net::FileStream> file_stream_; + net::CompletionCallbackImpl<RedirectToFileResourceHandler> write_callback_; + bool write_callback_pending_; + + // We create a DeletableFileReference for the temp file created as + // a result of the download. + scoped_refptr<webkit_blob::DeletableFileReference> deletable_file_; + + DISALLOW_COPY_AND_ASSIGN(RedirectToFileResourceHandler); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_REDIRECT_TO_FILE_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/render_message_filter.cc b/content/browser/renderer_host/render_message_filter.cc index 0ca1002..388bddb 100644 --- a/chrome/browser/renderer_host/render_message_filter.cc +++ b/content/browser/renderer_host/render_message_filter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_message_filter.h" +#include "content/browser/renderer_host/render_message_filter.h" #include <map> @@ -39,9 +39,6 @@ #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/browser_render_process_host.h" -#include "chrome/browser/renderer_host/render_view_host_delegate.h" -#include "chrome/browser/renderer_host/render_view_host_notification_task.h" -#include "chrome/browser/renderer_host/render_widget_helper.h" #include "chrome/browser/spellchecker_platform_engine.h" #include "chrome/browser/task_manager/task_manager.h" #include "chrome/common/chrome_switches.h" @@ -51,6 +48,9 @@ #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" #include "chrome/common/url_constants.h" +#include "content/browser/renderer_host/render_view_host_delegate.h" +#include "content/browser/renderer_host/render_view_host_notification_task.h" +#include "content/browser/renderer_host/render_widget_helper.h" #include "ipc/ipc_channel_handle.h" #include "net/base/cookie_monster.h" #include "net/base/io_buffer.h" diff --git a/content/browser/renderer_host/render_message_filter.h b/content/browser/renderer_host/render_message_filter.h new file mode 100644 index 0000000..b821466 --- /dev/null +++ b/content/browser/renderer_host/render_message_filter.h @@ -0,0 +1,498 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_MESSAGE_FILTER_H_ +#pragma once + +#if defined(OS_WIN) +#include <windows.h> +#endif + +#include <string> +#include <vector> + +#include "app/surface/transport_dib.h" +#include "base/file_path.h" +#include "base/linked_ptr.h" +#include "base/string16.h" +#include "base/task.h" +#include "build/build_config.h" +#include "chrome/browser/browser_message_filter.h" +#include "chrome/browser/in_process_webkit/webkit_context.h" +#include "chrome/browser/net/resolve_proxy_msg_helper.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "chrome/common/content_settings.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebCache.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" +#include "ui/base/clipboard/clipboard.h" +#include "ui/gfx/native_widget_types.h" + +class ChromeURLRequestContext; +struct FontDescriptor; +class HostContentSettingsMap; +class HostZoomMap; +class NotificationsPrefsCache; +class Profile; +class RenderWidgetHelper; +class URLRequestContextGetter; +struct ViewHostMsg_CreateWindow_Params; +struct ViewHostMsg_CreateWorker_Params; + +namespace webkit { +namespace npapi { +struct WebPluginInfo; +} +} + +namespace base { +class SharedMemory; +} + +namespace net { +class CookieStore; +} + +namespace printing { +class PrinterQuery; +class PrintJobManager; +} + +struct ViewHostMsg_ScriptedPrint_Params; + +// This class filters out incoming IPC messages for the renderer process on the +// IPC thread. +class RenderMessageFilter : public BrowserMessageFilter, + public ResolveProxyMsgHelper::Delegate { + public: + // Create the filter. + RenderMessageFilter(int render_process_id, + PluginService* plugin_service, + Profile* profile, + RenderWidgetHelper* render_widget_helper); + + // BrowserMessageFilter methods: + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + virtual void OnDestruct() const; + + int render_process_id() const { return render_process_id_; } + ResourceDispatcherHost* resource_dispatcher_host() { + return resource_dispatcher_host_; + } + bool off_the_record() { return off_the_record_; } + + // Returns either the extension net::URLRequestContext or regular + // net::URLRequestContext depending on whether |url| is an extension URL. + // Only call on the IO thread. + ChromeURLRequestContext* GetRequestContextForURL(const GURL& url); + + private: + friend class BrowserThread; + friend class DeleteTask<RenderMessageFilter>; + + virtual ~RenderMessageFilter(); + + void OnMsgCreateWindow(const ViewHostMsg_CreateWindow_Params& params, + int* route_id, + int64* cloned_session_storage_namespace_id); + void OnMsgCreateWidget(int opener_id, + WebKit::WebPopupType popup_type, + int* route_id); + void OnMsgCreateFullscreenWidget(int opener_id, int* route_id); + void OnSetCookie(const IPC::Message& message, + const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie); + void OnGetCookies(const GURL& url, + const GURL& first_party_for_cookies, + IPC::Message* reply_msg); + void OnGetRawCookies(const GURL& url, + const GURL& first_party_for_cookies, + IPC::Message* reply_msg); + void OnDeleteCookie(const GURL& url, + const std::string& cookieName); + void OnCookiesEnabled(const GURL& url, + const GURL& first_party_for_cookies, + IPC::Message* reply_msg); + void OnPluginFileDialog(const IPC::Message& msg, + bool multiple_files, + const std::wstring& title, + const std::wstring& filter, + uint32 user_data); + +#if defined(OS_MACOSX) + void OnLoadFont(const FontDescriptor& font, + uint32* handle_size, + base::SharedMemoryHandle* handle); +#endif + +#if defined(OS_WIN) // This hack is Windows-specific. + // Cache fonts for the renderer. See RenderMessageFilter::OnPreCacheFont + // implementation for more details. + void OnPreCacheFont(LOGFONT font); +#endif + +#if !defined(OS_MACOSX) + // Not handled in the IO thread on Mac. + void OnGetScreenInfo(gfx::NativeViewId window, IPC::Message* reply); +#endif + void OnGetPlugins(bool refresh, IPC::Message* reply_msg); + void OnGetPluginsOnFileThread(bool refresh, IPC::Message* reply_msg); + void OnGetPluginInfo(int routing_id, + const GURL& url, + const GURL& policy_url, + const std::string& mime_type, + IPC::Message* reply_msg); + void OnGetPluginInfoOnFileThread(int render_view_id, + const GURL& url, + const GURL& policy_url, + const std::string& mime_type, + IPC::Message* reply_msg); + void OnGotPluginInfo(bool found, + const webkit::npapi::WebPluginInfo& info, + const std::string& actual_mime_type, + const GURL& policy_url, + IPC::Message* reply_msg); + void OnOpenChannelToPlugin(int routing_id, + const GURL& url, + const std::string& mime_type, + IPC::Message* reply_msg); + void OnOpenChannelToPepperPlugin(const FilePath& path, + IPC::Message* reply_msg); + void OnLaunchNaCl(const std::wstring& url, + int channel_descriptor, + IPC::Message* reply_msg); + void OnGenerateRoutingID(int* route_id); + void OnDownloadUrl(const IPC::Message& message, + const GURL& url, + const GURL& referrer); + void OnPlatformCheckSpelling(const string16& word, int tag, bool* correct); + void OnPlatformFillSuggestionList(const string16& word, + std::vector<string16>* suggestions); + void OnGetDocumentTag(IPC::Message* reply_msg); + void OnDocumentWithTagClosed(int tag); + void OnShowSpellingPanel(bool show); + void OnUpdateSpellingPanelWithMisspelledWord(const string16& word); + void OnDnsPrefetch(const std::vector<std::string>& hostnames); + void OnRendererHistograms(int sequence_number, + const std::vector<std::string>& histogram_info); +#if defined(USE_TCMALLOC) + void OnRendererTcmalloc(base::ProcessId pid, const std::string& output); +#endif + void OnReceiveContextMenuMsg(const IPC::Message& msg); + // Clipboard messages + void OnClipboardWriteObjectsAsync(const ui::Clipboard::ObjectMap& objects); + void OnClipboardWriteObjectsSync(const ui::Clipboard::ObjectMap& objects, + base::SharedMemoryHandle bitmap_handle); + + void OnClipboardIsFormatAvailable(ui::Clipboard::FormatType format, + ui::Clipboard::Buffer buffer, + IPC::Message* reply); + void OnClipboardReadText(ui::Clipboard::Buffer buffer, IPC::Message* reply); + void OnClipboardReadAsciiText(ui::Clipboard::Buffer buffer, + IPC::Message* reply); + void OnClipboardReadHTML(ui::Clipboard::Buffer buffer, IPC::Message* reply); +#if defined(OS_MACOSX) + void OnClipboardFindPboardWriteString(const string16& text); +#endif + void OnClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer, + IPC::Message* reply); + void OnClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type, + IPC::Message* reply); + void OnClipboardReadFilenames(ui::Clipboard::Buffer buffer, + IPC::Message* reply); + + void OnCheckNotificationPermission(const GURL& source_url, + int* permission_level); + +#if !defined(OS_MACOSX) + // Not handled in the IO thread on Mac. + void OnGetWindowRect(gfx::NativeViewId window, IPC::Message* reply); + void OnGetRootWindowRect(gfx::NativeViewId window, IPC::Message* reply); +#endif + + void OnRevealFolderInOS(const FilePath& path); + void OnGetCPBrowsingContext(uint32* context); + +#if defined(OS_WIN) + // Used to pass resulting EMF from renderer to browser in printing. + void OnDuplicateSection(base::SharedMemoryHandle renderer_handle, + base::SharedMemoryHandle* browser_handle); +#endif + +#if defined(OS_CHROMEOS) + // Used to ask the browser allocate a temporary file for the renderer + // to fill in resulting PDF in renderer. + void OnAllocateTempFileForPrinting(IPC::Message* reply_msg); + void OnTempFileForPrintingWritten(int sequence_number); +#endif + +#if defined(OS_POSIX) + // Used to ask the browser to allocate a block of shared memory for the + // renderer to send back data in, since shared memory can't be created + // in the renderer on POSIX due to the sandbox. + void OnAllocateSharedMemoryBuffer(uint32 buffer_size, + base::SharedMemoryHandle* handle); +#endif + + void OnResourceTypeStats(const WebKit::WebCache::ResourceTypeStats& stats); + static void OnResourceTypeStatsOnUIThread( + const WebKit::WebCache::ResourceTypeStats&, + base::ProcessId renderer_id); + + void OnV8HeapStats(int v8_memory_allocated, int v8_memory_used); + static void OnV8HeapStatsOnUIThread(int v8_memory_allocated, + int v8_memory_used, + base::ProcessId renderer_id); + + void OnDidZoomURL(const IPC::Message& message, + double zoom_level, + bool remember, + const GURL& url); + void UpdateHostZoomLevelsOnUIThread(double zoom_level, + bool remember, + const GURL& url, + int render_process_id, + int render_view_id); + + void OnResolveProxy(const GURL& url, IPC::Message* reply_msg); + + // ResolveProxyMsgHelper::Delegate implementation: + virtual void OnResolveProxyCompleted(IPC::Message* reply_msg, + int result, + const std::string& proxy_list); + + // A javascript code requested to print the current page. This is done in two + // steps and this is the first step. Get the print setting right here + // synchronously. It will hang the I/O completely. + void OnGetDefaultPrintSettings(IPC::Message* reply_msg); + void OnGetDefaultPrintSettingsReply( + scoped_refptr<printing::PrinterQuery> printer_query, + IPC::Message* reply_msg); + + // A javascript code requested to print the current page. The renderer host + // have to show to the user the print dialog and returns the selected print + // settings. + void OnScriptedPrint(const ViewHostMsg_ScriptedPrint_Params& params, + IPC::Message* reply_msg); + void OnScriptedPrintReply( + scoped_refptr<printing::PrinterQuery> printer_query, + int routing_id, + IPC::Message* reply_msg); + + // Browser side transport DIB allocation + void OnAllocTransportDIB(size_t size, + bool cache_in_browser, + TransportDIB::Handle* result); + void OnFreeTransportDIB(TransportDIB::Id dib_id); + + void OnOpenChannelToExtension(int routing_id, + const std::string& source_extension_id, + const std::string& target_extension_id, + const std::string& channel_name, int* port_id); + void OpenChannelToExtensionOnUIThread(int source_process_id, + int source_routing_id, + int receiver_port_id, + const std::string& source_extension_id, + const std::string& target_extension_id, + const std::string& channel_name); + void OnOpenChannelToTab(int routing_id, int tab_id, + const std::string& extension_id, + const std::string& channel_name, int* port_id); + void OpenChannelToTabOnUIThread(int source_process_id, int source_routing_id, + int receiver_port_id, + int tab_id, const std::string& extension_id, + const std::string& channel_name); + + void OnCloseCurrentConnections(); + void OnSetCacheMode(bool enabled); + void OnClearCache(bool preserve_ssl_host_info, IPC::Message* reply_msg); + void OnCacheableMetadataAvailable(const GURL& url, + double expected_response_time, + const std::vector<char>& data); + void OnEnableSpdy(bool enable); + void OnKeygen(uint32 key_size_index, const std::string& challenge_string, + const GURL& url, IPC::Message* reply_msg); + void OnKeygenOnWorkerThread( + int key_size_in_bits, + const std::string& challenge_string, + const GURL& url, + IPC::Message* reply_msg); + void OnGetExtensionMessageBundle(const std::string& extension_id, + IPC::Message* reply_msg); + void OnGetExtensionMessageBundleOnFileThread( + const FilePath& extension_path, + const std::string& extension_id, + const std::string& default_locale, + IPC::Message* reply_msg); + void OnAsyncOpenFile(const IPC::Message& msg, + const FilePath& path, + int flags, + int message_id); + void AsyncOpenFileOnFileThread(const FilePath& path, + int flags, + int message_id, + int routing_id); + +#if defined(USE_X11) + void DoOnGetScreenInfo(gfx::NativeViewId view, IPC::Message* reply_msg); + void DoOnGetWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg); + void DoOnGetRootWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg); + void DoOnClipboardIsFormatAvailable(ui::Clipboard::FormatType format, + ui::Clipboard::Buffer buffer, + IPC::Message* reply_msg); + void DoOnClipboardReadText(ui::Clipboard::Buffer buffer, + IPC::Message* reply_msg); + void DoOnClipboardReadAsciiText(ui::Clipboard::Buffer buffer, + IPC::Message* reply_msg); + void DoOnClipboardReadHTML(ui::Clipboard::Buffer buffer, + IPC::Message* reply_msg); + void DoOnClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer, + IPC::Message* reply_msg); + void DoOnClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type, + IPC::Message* reply_msg); + void DoOnClipboardReadFilenames(ui::Clipboard::Buffer buffer, + IPC::Message* reply_msg); + void DoOnAllocateTempFileForPrinting(IPC::Message* reply_msg); + void DoOnTempFileForPrintingWritten(int sequence_number); +#endif + + bool CheckBenchmarkingEnabled() const; + bool CheckPreparsedJsCachingEnabled() const; + + // We have our own clipboard because we want to access the clipboard on the + // IO thread instead of forwarding (possibly synchronous) messages to the UI + // thread. This instance of the clipboard should be accessed only on the IO + // thread. + static ui::Clipboard* GetClipboard(); + + // Cached resource request dispatcher host and plugin service, guaranteed to + // be non-null if Init succeeds. We do not own the objects, they are managed + // by the BrowserProcess, which has a wider scope than we do. + ResourceDispatcherHost* resource_dispatcher_host_; + PluginService* plugin_service_; + printing::PrintJobManager* print_job_manager_; + + // The Profile associated with our renderer process. This should only be + // accessed on the UI thread! + Profile* profile_; + + // The host content settings map. Stored separately from the profile so we can + // access it on other threads. + HostContentSettingsMap* content_settings_; + + // Helper class for handling PluginProcessHost_ResolveProxy messages (manages + // the requests to the proxy service). + ResolveProxyMsgHelper resolve_proxy_msg_helper_; + + // Contextual information to be used for requests created here. + scoped_refptr<URLRequestContextGetter> request_context_; + + // A request context that holds a cookie store for chrome-extension URLs. + scoped_refptr<URLRequestContextGetter> extensions_request_context_; + + scoped_refptr<RenderWidgetHelper> render_widget_helper_; + + // A cache of notifications preferences which is used to handle + // Desktop Notifications permission messages. + scoped_refptr<NotificationsPrefsCache> notification_prefs_; + + // Handles zoom-related messages. + scoped_refptr<HostZoomMap> host_zoom_map_; + + // Whether this process is used for off the record tabs. + bool off_the_record_; + + bool cloud_print_enabled_; + + base::TimeTicks last_plugin_refresh_time_; // Initialized to 0. + + scoped_refptr<WebKitContext> webkit_context_; + + int render_process_id_; + + DISALLOW_COPY_AND_ASSIGN(RenderMessageFilter); +}; + +// These classes implement completion callbacks for getting and setting +// cookies. +class SetCookieCompletion : public net::CompletionCallback { + public: + SetCookieCompletion(int render_process_id, + int render_view_id, + const GURL& url, + const std::string& cookie_line, + ChromeURLRequestContext* context); + virtual ~SetCookieCompletion(); + + virtual void RunWithParams(const Tuple1<int>& params); + + int render_process_id() const { + return render_process_id_; + } + + int render_view_id() const { + return render_view_id_; + } + + private: + int render_process_id_; + int render_view_id_; + GURL url_; + std::string cookie_line_; + scoped_refptr<ChromeURLRequestContext> context_; +}; + +class GetCookiesCompletion : public net::CompletionCallback { + public: + GetCookiesCompletion(int render_process_id, + int render_view_id, + const GURL& url, IPC::Message* reply_msg, + RenderMessageFilter* filter, + ChromeURLRequestContext* context, + bool raw_cookies); + virtual ~GetCookiesCompletion(); + + virtual void RunWithParams(const Tuple1<int>& params); + + int render_process_id() const { + return render_process_id_; + } + + int render_view_id() const { + return render_view_id_; + } + + void set_cookie_store(net::CookieStore* cookie_store); + + net::CookieStore* cookie_store() { + return cookie_store_.get(); + } + + private: + GURL url_; + IPC::Message* reply_msg_; + scoped_refptr<RenderMessageFilter> filter_; + scoped_refptr<ChromeURLRequestContext> context_; + int render_process_id_; + int render_view_id_; + bool raw_cookies_; + scoped_refptr<net::CookieStore> cookie_store_; +}; + +class CookiesEnabledCompletion : public net::CompletionCallback { + public: + CookiesEnabledCompletion(IPC::Message* reply_msg, + RenderMessageFilter* filter); + virtual ~CookiesEnabledCompletion(); + + virtual void RunWithParams(const Tuple1<int>& params); + + private: + IPC::Message* reply_msg_; + scoped_refptr<RenderMessageFilter> filter_; +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/render_message_filter_gtk.cc b/content/browser/renderer_host/render_message_filter_gtk.cc index d3e11e7..ce260c4 100644 --- a/chrome/browser/renderer_host/render_message_filter_gtk.cc +++ b/content/browser/renderer_host/render_message_filter_gtk.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_message_filter.h" +#include "content/browser/renderer_host/render_message_filter.h" #include <fcntl.h> #include <map> @@ -13,7 +13,6 @@ #include "chrome/browser/browser_thread.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/render_messages.h" -#include "grit/generated_resources.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" #include "third_party/WebKit/Source/WebKit/chromium/public/x11/WebScreenInfoFactory.h" #include "ui/base/clipboard/clipboard.h" @@ -223,6 +222,7 @@ void RenderMessageFilter::DoOnTempFileForPrintingWritten(int sequence_number) { // Erase the entry in the map. map->erase(it); } + #endif // defined(OS_CHROMEOS) void RenderMessageFilter::OnGetScreenInfo(gfx::NativeViewId view, diff --git a/chrome/browser/renderer_host/render_message_filter_mac.mm b/content/browser/renderer_host/render_message_filter_mac.mm index dd80f2e..a7d7c9f 100644 --- a/chrome/browser/renderer_host/render_message_filter_mac.mm +++ b/content/browser/renderer_host/render_message_filter_mac.mm @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_message_filter.h" +#include "content/browser/renderer_host/render_message_filter.h" #import <Cocoa/Cocoa.h> diff --git a/chrome/browser/renderer_host/render_message_filter_win.cc b/content/browser/renderer_host/render_message_filter_win.cc index ab4dafb..4f305fde 100644 --- a/chrome/browser/renderer_host/render_message_filter_win.cc +++ b/content/browser/renderer_host/render_message_filter_win.cc @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_message_filter.h" +#include "content/browser/renderer_host/render_message_filter.h" + #include "chrome/common/render_messages.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" #include "third_party/WebKit/Source/WebKit/chromium/public/win/WebScreenInfoFactory.h" diff --git a/chrome/browser/renderer_host/render_process_host.cc b/content/browser/renderer_host/render_process_host.cc index e319178..aed6d08 100644 --- a/chrome/browser/renderer_host/render_process_host.cc +++ b/content/browser/renderer_host/render_process_host.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_process_host.h" #include "base/rand_util.h" #include "base/sys_info.h" diff --git a/content/browser/renderer_host/render_process_host.h b/content/browser/renderer_host/render_process_host.h new file mode 100644 index 0000000..cc469fa --- /dev/null +++ b/content/browser/renderer_host/render_process_host.h @@ -0,0 +1,327 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ +#pragma once + +#include <set> + +#include "app/surface/transport_dib.h" +#include "base/id_map.h" +#include "base/process.h" +#include "base/process_util.h" +#include "base/scoped_ptr.h" +#include "base/time.h" +#include "chrome/common/visitedlink_common.h" +#include "ipc/ipc_sync_channel.h" + +class Profile; +class URLRequestContextGetter; +struct ViewMsg_ClosePage_Params; + +namespace base { +class SharedMemory; +} + +// Virtual interface that represents the browser side of the browser <-> +// renderer communication channel. There will generally be one +// RenderProcessHost per renderer process. +// +// The concrete implementation of this class for normal use is the +// BrowserRenderProcessHost. It may also be implemented by a testing interface +// for mocking purposes. +class RenderProcessHost : public IPC::Channel::Sender, + public IPC::Channel::Listener { + public: + typedef IDMap<RenderProcessHost>::iterator iterator; + + // We classify renderers according to their highest privilege, and try + // to group pages into renderers with similar privileges. + // Note: it may be possible for a renderer to have multiple privileges, + // in which case we call it an "extension" renderer. + enum Type { + TYPE_NORMAL, // Normal renderer, no extra privileges. + TYPE_WEBUI, // Renderer with WebUI privileges, like New Tab. + TYPE_EXTENSION, // Renderer with extension privileges. + }; + + // Details for RENDERER_PROCESS_CLOSED notifications. + struct RendererClosedDetails { + RendererClosedDetails(base::TerminationStatus status, + int exit_code, + bool was_extension_renderer) { + this->status = status; + this->exit_code = exit_code; + this->was_extension_renderer = was_extension_renderer; + } + base::TerminationStatus status; + int exit_code; + bool was_extension_renderer; + }; + + explicit RenderProcessHost(Profile* profile); + virtual ~RenderProcessHost(); + + // Returns the user profile associated with this renderer process. + Profile* profile() const { return profile_; } + + // Returns the unique ID for this child process. This can be used later in + // a call to FromID() to get back to this object (this is used to avoid + // sending non-threadsafe pointers to other threads). + // + // This ID will be unique for all child processes, including workers, plugins, + // etc. It is generated by ChildProcessInfo. + int id() const { return id_; } + + // Returns true iff channel_ has been set to non-NULL. Use this for checking + // if there is connection or not. + bool HasConnection() { return channel_.get() != NULL; } + + bool sudden_termination_allowed() const { + return sudden_termination_allowed_; + } + void set_sudden_termination_allowed(bool enabled) { + sudden_termination_allowed_ = enabled; + } + + // Used for refcounting, each holder of this object must Attach and Release + // just like it would for a COM object. This object should be allocated on + // the heap; when no listeners own it any more, it will delete itself. + void Attach(IPC::Channel::Listener* listener, int routing_id); + + // See Attach() + void Release(int listener_id); + + // Listeners should call this when they've sent a "Close" message and + // they're waiting for a "Close_ACK", so that if the renderer process + // goes away we'll know that it was intentional rather than a crash. + void ReportExpectingClose(int32 listener_id); + + // Allows iteration over this RenderProcessHost's RenderViewHost listeners. + // Use from UI thread only. + typedef IDMap<IPC::Channel::Listener>::const_iterator listeners_iterator; + + listeners_iterator ListenersIterator() { + return listeners_iterator(&listeners_); + } + + IPC::Channel::Listener* GetListenerByID(int routing_id) { + return listeners_.Lookup(routing_id); + } + + // Called to inform the render process host of a new "max page id" for a + // render view host. The render process host computes the largest page id + // across all render view hosts and uses the value when it needs to + // initialize a new renderer in place of the current one. + void UpdateMaxPageID(int32 page_id); + + void set_ignore_input_events(bool ignore_input_events) { + ignore_input_events_ = ignore_input_events; + } + bool ignore_input_events() { + return ignore_input_events_; + } + + // Returns how long the child has been idle. The definition of idle + // depends on when a derived class calls mark_child_process_activity_time(). + // This is a rough indicator and its resolution should not be better than + // 10 milliseconds. + base::TimeDelta get_child_process_idle_time() const { + return base::TimeTicks::Now() - child_process_activity_time_; + } + + // Call this function when it is evident that the child process is actively + // performing some operation, for example if we just received an IPC message. + void mark_child_process_activity_time() { + child_process_activity_time_ = base::TimeTicks::Now(); + } + + // Try to shutdown the associated render process as fast as possible, but + // only if |count| matches the number of render widgets that this process + // controls. + bool FastShutdownForPageCount(size_t count); + + bool fast_shutdown_started() { + return fast_shutdown_started_; + } + + // Virtual interface --------------------------------------------------------- + + // Initialize the new renderer process, returning true on success. This must + // be called once before the object can be used, but can be called after + // that with no effect. Therefore, if the caller isn't sure about whether + // the process has been created, it should just call Init(). + virtual bool Init( + bool is_accessibility_enabled, bool is_extensions_process) = 0; + + // Gets the next available routing id. + virtual int GetNextRoutingID() = 0; + + // Called on the UI thread to cancel any outstanding resource requests for + // the specified render widget. + virtual void CancelResourceRequests(int render_widget_id) = 0; + + // Called on the UI thread to simulate a ClosePage_ACK message to the + // ResourceDispatcherHost. Necessary for a cross-site request, in the case + // that the original RenderViewHost is not live and thus cannot run an + // onunload handler. + virtual void CrossSiteClosePageACK( + const ViewMsg_ClosePage_Params& params) = 0; + + // Called on the UI thread to wait for the next UpdateRect message for the + // specified render widget. Returns true if successful, and the msg out- + // param will contain a copy of the received UpdateRect message. + virtual bool WaitForUpdateMsg(int render_widget_id, + const base::TimeDelta& max_delay, + IPC::Message* msg) = 0; + + // Called when a received message cannot be decoded. + virtual void ReceivedBadMessage() = 0; + + // Track the count of visible widgets. Called by listeners to register and + // unregister visibility. + virtual void WidgetRestored() = 0; + virtual void WidgetHidden() = 0; + + // Called when RenderView is created by a listener. + virtual void ViewCreated() = 0; + + // Informs the renderer about a new visited link table. + virtual void SendVisitedLinkTable(base::SharedMemory* table_memory) = 0; + + // Notify the renderer that a link was visited. + virtual void AddVisitedLinks( + const VisitedLinkCommon::Fingerprints& links) = 0; + + // Clear internal visited links buffer and ask the renderer to update link + // coloring state for all of its links. + virtual void ResetVisitedLinks() = 0; + + // Try to shutdown the associated renderer process as fast as possible. + // If this renderer has any RenderViews with unload handlers, then this + // function does nothing. The current implementation uses TerminateProcess. + // Returns True if it was able to do fast shutdown. + virtual bool FastShutdownIfPossible() = 0; + + // Synchronously sends the message, waiting for the specified timeout. The + // implementor takes ownership of the given Message regardless of whether or + // not this method succeeds. Returns true on success. + virtual bool SendWithTimeout(IPC::Message* msg, int timeout_ms) = 0; + + // Returns the process object associated with the child process. In certain + // tests or single-process mode, this will actually represent the current + // process. + // + // NOTE: this is not necessarily valid immediately after calling Init, as + // Init starts the process asynchronously. It's guaranteed to be valid after + // the first IPC arrives. + virtual base::ProcessHandle GetHandle() = 0; + + // Transport DIB functions --------------------------------------------------- + + // Return the TransportDIB for the given id. On Linux, this can involve + // mapping shared memory. On Mac, the shared memory is created in the browser + // process and the cached metadata is returned. On Windows, this involves + // duplicating the handle from the remote process. The RenderProcessHost + // still owns the returned DIB. + virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) = 0; + + // Static management functions ----------------------------------------------- + + // Flag to run the renderer in process. This is primarily + // for debugging purposes. When running "in process", the + // browser maintains a single RenderProcessHost which communicates + // to a RenderProcess which is instantiated in the same process + // with the Browser. All IPC between the Browser and the + // Renderer is the same, it's just not crossing a process boundary. + static bool run_renderer_in_process() { + return run_renderer_in_process_; + } + static void set_run_renderer_in_process(bool value) { + run_renderer_in_process_ = value; + } + + // Allows iteration over all the RenderProcessHosts in the browser. Note + // that each host may not be active, and therefore may have NULL channels. + static iterator AllHostsIterator(); + + // Returns the RenderProcessHost given its ID. Returns NULL if the ID does + // not correspond to a live RenderProcessHost. + static RenderProcessHost* FromID(int render_process_id); + + // Returns true if the caller should attempt to use an existing + // RenderProcessHost rather than creating a new one. + static bool ShouldTryToUseExistingProcessHost(); + + // Get an existing RenderProcessHost associated with the given profile, if + // possible. The renderer process is chosen randomly from suitable renderers + // that share the same profile and type. + // Returns NULL if no suitable renderer process is available, in which case + // the caller is free to create a new renderer. + static RenderProcessHost* GetExistingProcessHost(Profile* profile, Type type); + + // Overrides the default heuristic for limiting the max renderer process + // count. This is useful for unit testing process limit behaviors. + // A value of zero means to use the default heuristic. + static void SetMaxRendererProcessCount(size_t count); + + protected: + // A proxy for our IPC::Channel that lives on the IO thread (see + // browser_process.h) + scoped_ptr<IPC::SyncChannel> channel_; + + // The registered listeners. When this list is empty or all NULL, we should + // delete ourselves + IDMap<IPC::Channel::Listener> listeners_; + + // The maximum page ID we've ever seen from the renderer process. + int32 max_page_id_; + + // True if fast shutdown has been performed on this RPH. + bool fast_shutdown_started_; + + // True if we've posted a DeleteTask and will be deleted soon. + bool deleting_soon_; + + private: + // The globally-unique identifier for this RPH. + int id_; + + Profile* profile_; + + // set of listeners that expect the renderer process to close + std::set<int> listeners_expecting_close_; + + // True if the process can be shut down suddenly. If this is true, then we're + // sure that all the RenderViews in the process can be shutdown suddenly. If + // it's false, then specific RenderViews might still be allowed to be shutdown + // suddenly by checking their SuddenTerminationAllowed() flag. This can occur + // if one tab has an unload event listener but another tab in the same process + // doesn't. + bool sudden_termination_allowed_; + + // Set to true if we shouldn't send input events. We actually do the + // filtering for this at the render widget level. + bool ignore_input_events_; + + // See getter above. + static bool run_renderer_in_process_; + + // Records the last time we regarded the child process active. + base::TimeTicks child_process_activity_time_; + + DISALLOW_COPY_AND_ASSIGN(RenderProcessHost); +}; + +// Factory object for RenderProcessHosts. Using this factory allows tests to +// swap out a different one to use a TestRenderProcessHost. +class RenderProcessHostFactory { + public: + virtual ~RenderProcessHostFactory() {} + virtual RenderProcessHost* CreateRenderProcessHost( + Profile* profile) const = 0; +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ diff --git a/chrome/browser/renderer_host/render_sandbox_host_linux.cc b/content/browser/renderer_host/render_sandbox_host_linux.cc index 7408031..8d05790 100644 --- a/chrome/browser/renderer_host/render_sandbox_host_linux.cc +++ b/content/browser/renderer_host/render_sandbox_host_linux.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_sandbox_host_linux.h" +#include "content/browser/renderer_host/render_sandbox_host_linux.h" #include <fcntl.h> #include <fontconfig/fontconfig.h> diff --git a/content/browser/renderer_host/render_sandbox_host_linux.h b/content/browser/renderer_host/render_sandbox_host_linux.h new file mode 100644 index 0000000..8a4d0aa11 --- /dev/null +++ b/content/browser/renderer_host/render_sandbox_host_linux.h @@ -0,0 +1,52 @@ +// 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. + +// http://code.google.com/p/chromium/wiki/LinuxSandboxIPC + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_SANDBOX_HOST_LINUX_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_SANDBOX_HOST_LINUX_H_ +#pragma once + +#include <string> + +#include "base/logging.h" + +template <typename T> struct DefaultSingletonTraits; + +// This is a singleton object which handles sandbox requests from the +// renderers. +class RenderSandboxHostLinux { + public: + // Returns the singleton instance. + static RenderSandboxHostLinux* GetInstance(); + + // Get the file descriptor which renderers should be given in order to signal + // crashes to the browser. + int GetRendererSocket() const { + DCHECK(initialized_); + return renderer_socket_; + } + pid_t pid() const { + DCHECK(initialized_); + return pid_; + } + void Init(const std::string& sandbox_path); + + private: + friend struct DefaultSingletonTraits<RenderSandboxHostLinux>; + // This object must be constructed on the main thread. + RenderSandboxHostLinux(); + ~RenderSandboxHostLinux(); + + // Whether Init() has been called yet. + bool initialized_; + + int renderer_socket_; + int childs_lifeline_fd_; + pid_t pid_; + + DISALLOW_COPY_AND_ASSIGN(RenderSandboxHostLinux); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_SANDBOX_HOST_LINUX_H_ diff --git a/chrome/browser/renderer_host/render_view_host.cc b/content/browser/renderer_host/render_view_host.cc index 9c96e6f..58d3768 100644 --- a/chrome/browser/renderer_host/render_view_host.cc +++ b/content/browser/renderer_host/render_view_host.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_view_host.h" +#include "content/browser/renderer_host/render_view_host.h" #include <string> #include <utility> @@ -24,10 +24,6 @@ #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/net/predictor_api.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/renderer_host/render_process_host.h" -#include "chrome/browser/renderer_host/render_view_host_delegate.h" -#include "chrome/browser/renderer_host/render_widget_host.h" -#include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/common/bindings_policy.h" #include "chrome/common/chrome_constants.h" @@ -44,6 +40,10 @@ #include "chrome/common/translate_errors.h" #include "chrome/common/url_constants.h" #include "chrome/common/web_apps.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_view_host_delegate.h" +#include "content/browser/renderer_host/render_widget_host.h" +#include "content/browser/renderer_host/render_widget_host_view.h" #include "net/base/net_util.h" #include "printing/native_metafile.h" #include "third_party/skia/include/core/SkBitmap.h" diff --git a/content/browser/renderer_host/render_view_host.h b/content/browser/renderer_host/render_view_host.h new file mode 100644 index 0000000..cc3bfac --- /dev/null +++ b/content/browser/renderer_host/render_view_host.h @@ -0,0 +1,741 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_H_ +#pragma once + +#include <string> +#include <vector> + +#include "base/process_util.h" +#include "base/scoped_ptr.h" +#include "chrome/browser/ui/find_bar/find_bar_controller.h" +#include "chrome/common/content_settings_types.h" +#include "chrome/common/page_zoom.h" +#include "chrome/common/render_view_commands.h" +#include "chrome/common/translate_errors.h" +#include "chrome/common/view_types.h" +#include "chrome/common/window_container_type.h" +#include "content/browser/renderer_host/render_widget_host.h" +#include "net/base/load_states.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebConsoleMessage.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextDirection.h" +#include "webkit/glue/webaccessibility.h" +#include "webkit/glue/window_open_disposition.h" + +class ChildProcessSecurityPolicy; +class FilePath; +class GURL; +class ListValue; +class RenderViewHostDelegate; +class SessionStorageNamespace; +class SiteInstance; +class SkBitmap; +class ViewMsg_Navigate; +struct ContentSettings; +struct ContextMenuParams; +struct MediaPlayerAction; +struct ThumbnailScore; +struct ViewHostMsg_AccessibilityNotification_Params; +struct ViewHostMsg_CreateWindow_Params; +struct ViewHostMsg_DomMessage_Params; +struct ViewHostMsg_ShowPopup_Params; +struct ViewMsg_Navigate_Params; +struct WebApplicationInfo; +struct WebDropData; +struct WebPreferences; +struct UserMetricsAction; + +namespace gfx { +class Point; +} // namespace gfx + +namespace webkit_glue { +struct CustomContextMenuContext; +struct WebAccessibility; +} // namespace webkit_glue + +namespace WebKit { +struct WebMediaPlayerAction; +} // namespace WebKit + +class URLRequestContextGetter; + +// +// RenderViewHost +// +// A RenderViewHost is responsible for creating and talking to a RenderView +// object in a child process. It exposes a high level API to users, for things +// like loading pages, adjusting the display and other browser functionality, +// which it translates into IPC messages sent over the IPC channel with the +// RenderView. It responds to all IPC messages sent by that RenderView and +// cracks them, calling a delegate object back with higher level types where +// possible. +// +// The intent of this class is to provide a view-agnostic communication +// conduit with a renderer. This is so we can build HTML views not only as +// TabContents (see TabContents for an example) but also as views, etc. +// +// The exact API of this object needs to be more thoroughly designed. Right +// now it mimics what TabContents exposed, which is a fairly large API and may +// contain things that are not relevant to a common subset of views. See also +// the comment in render_view_host_delegate.h about the size and scope of the +// delegate API. +// +// Right now, the concept of page navigation (both top level and frame) exists +// in the TabContents still, so if you instantiate one of these elsewhere, you +// will not be able to traverse pages back and forward. We need to determine +// if we want to bring that and other functionality down into this object so +// it can be shared by others. +// +class RenderViewHost : public RenderWidgetHost { + public: + // Returns the RenderViewHost given its ID and the ID of its render process. + // Returns NULL if the IDs do not correspond to a live RenderViewHost. + static RenderViewHost* FromID(int render_process_id, int render_view_id); + + // routing_id could be a valid route id, or it could be MSG_ROUTING_NONE, in + // which case RenderWidgetHost will create a new one. + // + // The session storage namespace parameter allows multiple render views and + // tab contentses to share the same session storage (part of the WebStorage + // spec) space. This is useful when restoring tabs, but most callers should + // pass in NULL which will cause a new SessionStorageNamespace to be created. + RenderViewHost(SiteInstance* instance, + RenderViewHostDelegate* delegate, + int routing_id, + SessionStorageNamespace* session_storage_namespace); + virtual ~RenderViewHost(); + + SiteInstance* site_instance() const { return instance_; } + RenderViewHostDelegate* delegate() const { return delegate_; } + void set_delegate(RenderViewHostDelegate* d) { delegate_ = d; } + + // Set up the RenderView child process. Virtual because it is overridden by + // TestRenderViewHost. If the |frame_name| parameter is non-empty, it is used + // as the name of the new top-level frame. + virtual bool CreateRenderView(const string16& frame_name); + + // Returns true if the RenderView is active and has not crashed. Virtual + // because it is overridden by TestRenderViewHost. + virtual bool IsRenderViewLive() const; + + base::TerminationStatus render_view_termination_status() const { + return render_view_termination_status_; + } + + // Send the renderer process the current preferences supplied by the + // RenderViewHostDelegate. + void SyncRendererPrefs(); + + // Sends the given navigation message. Use this rather than sending it + // yourself since this does the internal bookkeeping described below. This + // function takes ownership of the provided message pointer. + // + // If a cross-site request is in progress, we may be suspended while waiting + // for the onbeforeunload handler, so this function might buffer the message + // rather than sending it. + void Navigate(const ViewMsg_Navigate_Params& message); + + // Load the specified URL, this is a shortcut for Navigate(). + void NavigateToURL(const GURL& url); + + // Returns whether navigation messages are currently suspended for this + // RenderViewHost. Only true during a cross-site navigation, while waiting + // for the onbeforeunload handler. + bool are_navigations_suspended() const { return navigations_suspended_; } + + // Suspends (or unsuspends) any navigation messages from being sent from this + // RenderViewHost. This is called when a pending RenderViewHost is created + // for a cross-site navigation, because we must suspend any navigations until + // we hear back from the old renderer's onbeforeunload handler. Note that it + // is important that only one navigation event happen after calling this + // method with |suspend| equal to true. If |suspend| is false and there is + // a suspended_nav_message_, this will send the message. This function + // should only be called to toggle the state; callers should check + // are_navigations_suspended() first. + void SetNavigationsSuspended(bool suspend); + + // Causes the renderer to invoke the onbeforeunload event handler. The + // result will be returned via ViewMsg_ShouldClose. See also ClosePage which + // will fire the PageUnload event. + // + // Set bool for_cross_site_transition when this close is just for the current + // RenderView in the case of a cross-site transition. False means we're + // closing the entire tab. + void FirePageBeforeUnload(bool for_cross_site_transition); + + // Causes the renderer to close the current page, including running its + // onunload event handler. A ClosePage_ACK message will be sent to the + // ResourceDispatcherHost when it is finished. + // + // Please see ViewMsg_ClosePage in resource_messages_internal.h for a + // description of the parameters. + void ClosePage(bool for_cross_site_transition, + int new_render_process_host_id, + int new_request_id); + + // Close the page ignoring whether it has unload events registers. + // This is called after the beforeunload and unload events have fired + // and the user has agreed to continue with closing the page. + void ClosePageIgnoringUnloadEvents(); + + // Sets whether this RenderViewHost has an outstanding cross-site request, + // for which another renderer will need to run an onunload event handler. + // This is called before the first navigation event for this RenderViewHost, + // and again after the corresponding OnCrossSiteResponse. + void SetHasPendingCrossSiteRequest(bool has_pending_request, int request_id); + + // Returns the request_id for the pending cross-site request. + // This is just needed in case the unload of the current page + // hangs, in which case we need to swap to the pending RenderViewHost. + int GetPendingRequestId(); + + struct CommandState { + bool is_enabled; + RenderViewCommandCheckedState checked_state; + }; + CommandState GetStateForCommand(RenderViewCommand command) const; + + // Stops the current load. + void Stop(); + + // Reloads the current frame. + void ReloadFrame(); + + // Asks the renderer to "render" printed pages and initiate printing on our + // behalf. + bool PrintPages(); + + // Asks the renderer to render pages for print preview. + bool PrintPreview(); + + // Notify renderer of success/failure of print job. + void PrintingDone(int document_cookie, bool success); + + // Start looking for a string within the content of the page, with the + // specified options. + void StartFinding(int request_id, + const string16& search_string, + bool forward, + bool match_case, + bool find_next); + + // Cancel a pending find operation. + void StopFinding(FindBarController::SelectionAction selection_action); + + // Increment, decrement, or reset the zoom level of a page. + void Zoom(PageZoom::Function function); + + // Change the zoom level of a page to a specific value. + void SetZoomLevel(double zoom_level); + + // Change the encoding of the page. + void SetPageEncoding(const std::string& encoding); + + // Reset any override encoding on the page and change back to default. + void ResetPageEncodingToDefault(); + + // Change the alternate error page URL. An empty GURL disables the use of + // alternate error pages. + void SetAlternateErrorPageURL(const GURL& url); + + // D&d drop target messages that get sent to WebKit. + void DragTargetDragEnter(const WebDropData& drop_data, + const gfx::Point& client_pt, + const gfx::Point& screen_pt, + WebKit::WebDragOperationsMask operations_allowed); + void DragTargetDragOver(const gfx::Point& client_pt, + const gfx::Point& screen_pt, + WebKit::WebDragOperationsMask operations_allowed); + void DragTargetDragLeave(); + void DragTargetDrop(const gfx::Point& client_pt, + const gfx::Point& screen_pt); + + // Tell the RenderView to reserve a range of page ids of the given size. + void ReservePageIDRange(int size); + + // Runs some javascript within the context of a frame in the page. + void ExecuteJavascriptInWebFrame(const string16& frame_xpath, + const string16& jscript); + + // Runs some javascript within the context of a frame in the page. The result + // is sent back via the notification EXECUTE_JAVASCRIPT_RESULT. + int ExecuteJavascriptInWebFrameNotifyResult(const string16& frame_xpath, + const string16& jscript); + + // Insert some css into a frame in the page. |id| is optional, and specifies + // the element id given when inserting/replacing the style element. + void InsertCSSInWebFrame(const std::wstring& frame_xpath, + const std::string& css, + const std::string& id); + + // Logs a message to the console of a frame in the page. + void AddMessageToConsole(const string16& frame_xpath, + const string16& message, + const WebKit::WebConsoleMessage::Level&); + + // Edit operations. + void Undo(); + void Redo(); + void Cut(); + void Copy(); + void CopyToFindPboard(); + void Paste(); + void ToggleSpellCheck(); + void Delete(); + void SelectAll(); + void ToggleSpellPanel(bool is_currently_visible); + + // Downloads an image notifying the FavIcon delegate appropriately. The + // returned integer uniquely identifies the download for the lifetime of the + // browser. + int DownloadFavIcon(const GURL& url, int image_size); + + // Requests application info for the specified page. This is an asynchronous + // request. The delegate is notified by way of OnDidGetApplicationInfo when + // the data is available. + void GetApplicationInfo(int32 page_id); + + // Captures a thumbnail representation of the page. + void CaptureThumbnail(); + + // Captures a snapshot of the page. + void CaptureSnapshot(); + + // Notifies the RenderView that the JavaScript message that was shown was + // closed by the user. + void JavaScriptMessageBoxClosed(IPC::Message* reply_msg, + bool success, + const std::wstring& prompt); + + // Notifies the RenderView that the modal html dialog has been closed. + void ModalHTMLDialogClosed(IPC::Message* reply_msg, + const std::string& json_retval); + + // Send an action to the media player element located at |location|. + void MediaPlayerActionAt(const gfx::Point& location, + const WebKit::WebMediaPlayerAction& action); + + // Notifies the renderer that the context menu has closed. + void ContextMenuClosed( + const webkit_glue::CustomContextMenuContext& custom_context); + + // Prints the node that's under the context menu. + void PrintNodeUnderContextMenu(); + + // Triggers printing of the preview PDF. + void PrintForPrintPreview(); + + // Copies the image at the specified point. + void CopyImageAt(int x, int y); + + // Notifies the renderer that a a drag operation that it started has ended, + // either in a drop or by being cancelled. + void DragSourceEndedAt( + int client_x, int client_y, int screen_x, int screen_y, + WebKit::WebDragOperation operation); + + // Notifies the renderer that a drag and drop operation is in progress, with + // droppable items positioned over the renderer's view. + void DragSourceMovedTo( + int client_x, int client_y, int screen_x, int screen_y); + + // Notifies the renderer that we're done with the drag and drop operation. + // This allows the renderer to reset some state. + void DragSourceSystemDragEnded(); + + // Tell the render view to enable a set of javascript bindings. The argument + // should be a combination of values from BindingsPolicy. + void AllowBindings(int binding_flags); + + // Returns a bitwise OR of bindings types that have been enabled for this + // RenderView. See BindingsPolicy for details. + int enabled_bindings() const { return enabled_bindings_; } + + // See variable comment. + bool is_extension_process() const { return is_extension_process_; } + void set_is_extension_process(bool is_extension_process) { + is_extension_process_ = is_extension_process; + } + + // Sets a property with the given name and value on the Web UI binding object. + // Must call AllowWebUIBindings() on this renderer first. + void SetWebUIProperty(const std::string& name, const std::string& value); + + // Tells the renderer view to focus the first (last if reverse is true) node. + void SetInitialFocus(bool reverse); + + // Clears the node that is currently focused (if any). + void ClearFocusedNode(); + + // Tells the renderer view to scroll to the focused node. + void ScrollFocusedEditableNodeIntoView(); + + // Update render view specific (WebKit) preferences. + void UpdateWebPreferences(const WebPreferences& prefs); + + // Request the Renderer to ask the default plugin to start installation of + // missing plugin. Called by PluginInstallerInfoBarDelegate. + void InstallMissingPlugin(); + + // Load all blocked plugins in the RenderView. + void LoadBlockedPlugins(); + + // Get all script and frame urls from all frames in the current document. + // Called when a malware interstitial page is shown. + void GetMalwareDOMDetails(); + + // Get all savable resource links from current webpage, include main + // frame and sub-frame. + void GetAllSavableResourceLinksForCurrentPage(const GURL& page_url); + + // Get html data by serializing all frames of current page with lists + // which contain all resource links that have local copy. + // The parameter links contain original URLs of all saved links. + // The parameter local_paths contain corresponding local file paths of + // all saved links, which matched with vector:links one by one. + // The parameter local_directory_name is relative path of directory which + // contain all saved auxiliary files included all sub frames and resouces. + void GetSerializedHtmlDataForCurrentPageWithLocalLinks( + const std::vector<GURL>& links, + const std::vector<FilePath>& local_paths, + const FilePath& local_directory_name); + + // Notifies the Listener that one or more files have been chosen by the user + // from an Open File dialog for the form. + void FilesSelectedInChooser(const std::vector<FilePath>& files); + + // Notifies the RenderViewHost that its load state changed. + void LoadStateChanged(const GURL& url, net::LoadState load_state, + uint64 upload_position, uint64 upload_size); + + bool SuddenTerminationAllowed() const; + void set_sudden_termination_allowed(bool enabled) { + sudden_termination_allowed_ = enabled; + } + + // Forward a message from external host to chrome renderer. + void ForwardMessageFromExternalHost(const std::string& message, + const std::string& origin, + const std::string& target); + + // Message the renderer that we should be counted as a new document and not + // as a popup. + void DisassociateFromPopupCount(); + + // Tells the renderer whether it should allow window.close. This is initially + // set to false when creating a renderer-initiated window via window.open. + void AllowScriptToClose(bool visible); + + // Notifies the Renderer that a move or resize of its containing window has + // started (this is used to hide the autocomplete popups if any). + void WindowMoveOrResizeStarted(); + + // RenderWidgetHost public overrides. + virtual void Shutdown(); + virtual bool IsRenderView() const; + virtual bool OnMessageReceived(const IPC::Message& msg); + virtual void GotFocus(); + virtual void LostCapture(); + virtual void ForwardMouseEvent(const WebKit::WebMouseEvent& mouse_event); + virtual void OnMouseActivate(); + virtual void ForwardKeyboardEvent(const NativeWebKeyboardEvent& key_event); + virtual void ForwardEditCommand(const std::string& name, + const std::string& value); + virtual void ForwardEditCommandsForNextKeyEvent( + const EditCommands& edit_commands); + + // Creates a new RenderView with the given route id. + void CreateNewWindow(int route_id, + const ViewHostMsg_CreateWindow_Params& params); + + // Creates a new RenderWidget with the given route id. |popup_type| indicates + // if this widget is a popup and what kind of popup it is (select, autofill). + void CreateNewWidget(int route_id, WebKit::WebPopupType popup_type); + + // Creates a full screen RenderWidget. + void CreateNewFullscreenWidget(int route_id); + + // Sends the response to an extension api call. + void SendExtensionResponse(int request_id, bool success, + const std::string& response, + const std::string& error); + + // Sends a response to an extension api call that it was blocked for lack of + // permission. + void BlockExtensionRequest(int request_id); + + // Tells the renderer which browser window it is being attached to. + void UpdateBrowserWindowId(int window_id); + + // Tells the render view that a custom context action has been selected. + void PerformCustomContextMenuAction( + const webkit_glue::CustomContextMenuContext& custom_context, + unsigned action); + + // Informs renderer of updated content settings. + void SendContentSettings(const GURL& url, + const ContentSettings& settings); + + // Tells the renderer to notify us when the page contents preferred size + // changed. |flags| is a combination of + // |ViewHostMsg_EnablePreferredSizeChangedMode_Flags| values, which is defined + // in render_messages.h. + void EnablePreferredSizeChangedMode(int flags); + +#if defined(OS_MACOSX) + // Select popup menu related methods (for external popup menus). + void DidSelectPopupMenuItem(int selected_index); + void DidCancelPopupMenu(); +#endif + + // SearchBox notifications. + void SearchBoxChange(const string16& value, + bool verbatim, + int selection_start, + int selection_end); + void SearchBoxSubmit(const string16& value, + bool verbatim); + void SearchBoxCancel(); + void SearchBoxResize(const gfx::Rect& search_box_bounds); + void DetermineIfPageSupportsInstant(const string16& value, + bool verbatim, + int selection_start, + int selection_end); + + // Send a notification to the V8 JavaScript engine to change its parameters + // while performing stress testing. |cmd| is one of the values defined by + // |ViewHostMsg_JavaScriptStressTestControl_Commands|, which is defined + // in render_messages.h. + void JavaScriptStressTestControl(int cmd, int param); + +#if defined(UNIT_TEST) + // These functions shouldn't be necessary outside of testing. + + void set_save_accessibility_tree_for_testing(bool save) { + save_accessibility_tree_for_testing_ = save; + } + + const webkit_glue::WebAccessibility& accessibility_tree() { + return accessibility_tree_; + } + + bool is_waiting_for_unload_ack() { return is_waiting_for_unload_ack_; } +#endif + + // Checks that the given renderer can request |url|, if not it sets it to an + // empty url. + static void FilterURL(ChildProcessSecurityPolicy* policy, + int renderer_id, + GURL* url); + + protected: + // RenderWidgetHost protected overrides. + virtual bool PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, + bool* is_keyboard_shortcut); + virtual void UnhandledKeyboardEvent(const NativeWebKeyboardEvent& event); + virtual void OnUserGesture(); + virtual void NotifyRendererUnresponsive(); + virtual void NotifyRendererResponsive(); + virtual void OnMsgFocusedNodeChanged(bool is_editable_node); + virtual void OnMsgFocus(); + virtual void OnMsgBlur(); + + // IPC message handlers. + void OnMsgShowView(int route_id, + WindowOpenDisposition disposition, + const gfx::Rect& initial_pos, + bool user_gesture); + void OnMsgShowWidget(int route_id, const gfx::Rect& initial_pos); + void OnMsgShowFullscreenWidget(int route_id); + void OnMsgRunModal(IPC::Message* reply_msg); + void OnMsgRenderViewReady(); + void OnMsgRenderViewGone(int status, int error_code); + void OnMsgNavigate(const IPC::Message& msg); + void OnMsgUpdateState(int32 page_id, + const std::string& state); + void OnMsgUpdateTitle(int32 page_id, const std::wstring& title); + void OnMsgUpdateEncoding(const std::string& encoding); + void OnMsgUpdateTargetURL(int32 page_id, const GURL& url); + void OnMsgThumbnail(const GURL& url, + const ThumbnailScore& score, + const SkBitmap& bitmap); + void OnMsgScreenshot(const SkBitmap& bitmap); + void OnMsgClose(); + void OnMsgRequestMove(const gfx::Rect& pos); + void OnMsgDidStartLoading(); + void OnMsgDidStopLoading(); + void OnMsgDidChangeLoadProgress(double load_progress); + void OnMsgDocumentAvailableInMainFrame(); + void OnMsgDocumentOnLoadCompletedInMainFrame(int32 page_id); + void OnExecuteCodeFinished(int request_id, bool success); + void OnMsgUpdateFavIconURL(int32 page_id, const GURL& icon_url); + void OnMsgDidDownloadFavIcon(int id, + const GURL& image_url, + bool errored, + const SkBitmap& image_data); + void OnMsgContextMenu(const ContextMenuParams& params); + void OnMsgOpenURL(const GURL& url, const GURL& referrer, + WindowOpenDisposition disposition); + void OnMsgDidContentsPreferredSizeChange(const gfx::Size& new_size); + void OnMsgDomOperationResponse(const std::string& json_string, + int automation_id); + void OnMsgWebUISend(const GURL& source_url, + const std::string& message, + const std::string& content); + void OnMsgForwardMessageToExternalHost(const std::string& message, + const std::string& origin, + const std::string& target); + void OnMsgSetTooltipText(const std::wstring& tooltip_text, + WebKit::WebTextDirection text_direction_hint); + void OnMsgSelectionChanged(const std::string& text); + void OnMsgPasteFromSelectionClipboard(); + void OnMsgRunJavaScriptMessage(const std::wstring& message, + const std::wstring& default_prompt, + const GURL& frame_url, + const int flags, + IPC::Message* reply_msg); + void OnMsgRunBeforeUnloadConfirm(const GURL& frame_url, + const std::wstring& message, + IPC::Message* reply_msg); + void OnMsgShowModalHTMLDialog(const GURL& url, int width, int height, + const std::string& json_arguments, + IPC::Message* reply_msg); + void OnMsgStartDragging(const WebDropData& drop_data, + WebKit::WebDragOperationsMask operations_allowed, + const SkBitmap& image, + const gfx::Point& image_offset); + void OnUpdateDragCursor(WebKit::WebDragOperation drag_operation); + void OnTakeFocus(bool reverse); + void OnAddMessageToConsole(const std::wstring& message, + int32 line_no, + const std::wstring& source_id); + void OnUpdateInspectorSetting(const std::string& key, + const std::string& value); + void OnForwardToDevToolsAgent(const IPC::Message& message); + void OnForwardToDevToolsClient(const IPC::Message& message); + void OnActivateDevToolsWindow(); + void OnCloseDevToolsWindow(); + void OnRequestDockDevToolsWindow(); + void OnRequestUndockDevToolsWindow(); + void OnDevToolsRuntimePropertyChanged(const std::string& name, + const std::string& value); + void OnMsgShouldCloseACK(bool proceed); + + void OnExtensionRequest(const ViewHostMsg_DomMessage_Params& params); + void OnExtensionPostMessage(int port_id, const std::string& message); + void OnAccessibilityNotifications( + const std::vector<ViewHostMsg_AccessibilityNotification_Params>& params); + void OnCSSInserted(); + void OnContentBlocked(ContentSettingsType type, + const std::string& resource_identifier); + void OnAppCacheAccessed(const GURL& manifest_url, bool blocked_by_policy); + void OnWebDatabaseAccessed(const GURL& url, + const string16& name, + const string16& display_name, + unsigned long estimated_size, + bool blocked_by_policy); + void OnUpdateZoomLimits(int minimum_percent, + int maximum_percent, + bool remember); + void OnScriptEvalResponse(int id, const ListValue& result); + void OnCommandStateChanged(int command, + bool is_enabled, + int checked_state); + +#if defined(OS_MACOSX) + void OnMsgShowPopup(const ViewHostMsg_ShowPopup_Params& params); +#endif + + private: + friend class TestRenderViewHost; + + // The SiteInstance associated with this RenderViewHost. All pages drawn + // in this RenderViewHost are part of this SiteInstance. Should not change + // over time. + scoped_refptr<SiteInstance> instance_; + + // Our delegate, which wants to know about changes in the RenderView. + RenderViewHostDelegate* delegate_; + + // true if we are currently waiting for a response for drag context + // information. + bool waiting_for_drag_context_response_; + + // A bitwise OR of bindings types that have been enabled for this RenderView. + // See BindingsPolicy for details. + int enabled_bindings_; + + // The request_id for the pending cross-site request. Set to -1 if + // there is a pending request, but we have not yet started the unload + // for the current page. Set to the request_id value of the pending + // request once we have gotten the some data for the pending page + // and thus started the unload process. + int pending_request_id_; + + // Whether we should buffer outgoing Navigate messages rather than sending + // them. This will be true when a RenderViewHost is created for a cross-site + // request, until we hear back from the onbeforeunload handler of the old + // RenderViewHost. + bool navigations_suspended_; + + // We only buffer a suspended navigation message while we a pending RVH for a + // TabContents. There will only ever be one suspended navigation, because + // TabContents will destroy the pending RVH and create a new one if a second + // navigation occurs. + scoped_ptr<ViewMsg_Navigate> suspended_nav_message_; + + // If we were asked to RunModal, then this will hold the reply_msg that we + // must return to the renderer to unblock it. + IPC::Message* run_modal_reply_msg_; + + // Set to true when there is a pending ViewMsg_ShouldClose message. This + // ensures we don't spam the renderer with multiple beforeunload requests. + // When either this value or is_waiting_for_unload_ack_ is true, the value of + // unload_ack_is_for_cross_site_transition_ indicates whether this is for a + // cross-site transition or a tab close attempt. + bool is_waiting_for_beforeunload_ack_; + + // Set to true when there is a pending ViewMsg_Close message. Also see + // is_waiting_for_beforeunload_ack_, unload_ack_is_for_cross_site_transition_. + bool is_waiting_for_unload_ack_; + + // Valid only when is_waiting_for_beforeunload_ack_ or + // is_waiting_for_unload_ack_ is true. This tells us if the unload request + // is for closing the entire tab ( = false), or only this RenderViewHost in + // the case of a cross-site transition ( = true). + bool unload_ack_is_for_cross_site_transition_; + + bool are_javascript_messages_suppressed_; + + // True if the render view can be shut down suddenly. + bool sudden_termination_allowed_; + + // The session storage namespace to be used by the associated render view. + scoped_refptr<SessionStorageNamespace> session_storage_namespace_; + + // Whether this render view will get extension api bindings. This controls + // what process type we use. + bool is_extension_process_; + + // Whether the accessibility tree should be saved, for unit testing. + bool save_accessibility_tree_for_testing_; + + // The most recently received accessibility tree - for unit testing only. + webkit_glue::WebAccessibility accessibility_tree_; + + // The termination status of the last render view that terminated. + base::TerminationStatus render_view_termination_status_; + + // The enabled/disabled states of various commands. + std::map<RenderViewCommand, CommandState> command_states_; + + DISALLOW_COPY_AND_ASSIGN(RenderViewHost); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_H_ diff --git a/chrome/browser/renderer_host/render_view_host_delegate.cc b/content/browser/renderer_host/render_view_host_delegate.cc index 1c6f2e6..f169205 100644 --- a/chrome/browser/renderer_host/render_view_host_delegate.cc +++ b/content/browser/renderer_host/render_view_host_delegate.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_view_host_delegate.h" +#include "content/browser/renderer_host/render_view_host_delegate.h" #include "base/singleton.h" #include "chrome/common/render_messages.h" diff --git a/content/browser/renderer_host/render_view_host_delegate.h b/content/browser/renderer_host/render_view_host_delegate.h new file mode 100644 index 0000000..e4c5f46 --- /dev/null +++ b/content/browser/renderer_host/render_view_host_delegate.h @@ -0,0 +1,584 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_DELEGATE_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_DELEGATE_H_ +#pragma once + +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "base/process_util.h" +#include "base/ref_counted.h" +#include "base/string16.h" +#include "chrome/common/content_settings_types.h" +#include "chrome/common/dom_storage_common.h" +#include "chrome/common/translate_errors.h" +#include "chrome/common/view_types.h" +#include "chrome/common/window_container_type.h" +#include "ipc/ipc_channel.h" +#include "net/base/load_states.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" +#include "webkit/glue/window_open_disposition.h" + + +class AutomationResourceRoutingDelegate; +class BackgroundContents; +struct BookmarkNodeData; +class BookmarkNode; +struct ContextMenuParams; +class FilePath; +class GURL; +class ListValue; +struct NativeWebKeyboardEvent; +class NavigationEntry; +class Profile; +struct RendererPreferences; +class RenderProcessHost; +class RenderViewHost; +class ResourceRedirectDetails; +class ResourceRequestDetails; +class SkBitmap; +class SSLClientAuthHandler; +class SSLAddCertHandler; +class TabContents; +struct ThumbnailScore; +struct ViewHostMsg_CreateWindow_Params; +struct ViewHostMsg_DomMessage_Params; +struct ViewHostMsg_FrameNavigate_Params; +struct WebApplicationInfo; +struct WebDropData; +struct WebMenuItem; +class WebKeyboardEvent; +struct WebPreferences; + +namespace base { +class WaitableEvent; +} + +namespace gfx { +class Point; +class Rect; +class Size; +} + +namespace IPC { +class Message; +} + +namespace net { +class CookieList; +class CookieOptions; +} + +namespace webkit_glue { +struct FormData; +class FormField; +struct PasswordForm; +} + +// +// RenderViewHostDelegate +// +// An interface implemented by an object interested in knowing about the state +// of the RenderViewHost. +// +// This interface currently encompasses every type of message that was +// previously being sent by TabContents itself. Some of these notifications +// may not be relevant to all users of RenderViewHost and we should consider +// exposing a more generic Send function on RenderViewHost and a response +// listener here to serve that need. +// +class RenderViewHostDelegate : public IPC::Channel::Listener { + public: + // View ---------------------------------------------------------------------- + // Functions that can be routed directly to a view-specific class. + + class View { + public: + // The page is trying to open a new page (e.g. a popup window). The window + // should be created associated with the given route, but it should not be + // shown yet. That should happen in response to ShowCreatedWindow. + // |params.window_container_type| describes the type of RenderViewHost + // container that is requested -- in particular, the window.open call may + // have specified 'background' and 'persistent' in the feature string. + // + // The passed |params.frame_name| parameter is the name parameter that was + // passed to window.open(), and will be empty if none was passed. + // + // Note: this is not called "CreateWindow" because that will clash with + // the Windows function which is actually a #define. + // + // NOTE: this takes ownership of @modal_dialog_event + virtual void CreateNewWindow( + int route_id, + const ViewHostMsg_CreateWindow_Params& params) = 0; + + // The page is trying to open a new widget (e.g. a select popup). The + // widget should be created associated with the given route, but it should + // not be shown yet. That should happen in response to ShowCreatedWidget. + // |popup_type| indicates if the widget is a popup and what kind of popup it + // is (select, autofill...). + virtual void CreateNewWidget(int route_id, + WebKit::WebPopupType popup_type) = 0; + + // Creates a full screen RenderWidget. Similar to above. + virtual void CreateNewFullscreenWidget(int route_id) = 0; + + // Show a previously created page with the specified disposition and bounds. + // The window is identified by the route_id passed to CreateNewWindow. + // + // Note: this is not called "ShowWindow" because that will clash with + // the Windows function which is actually a #define. + virtual void ShowCreatedWindow(int route_id, + WindowOpenDisposition disposition, + const gfx::Rect& initial_pos, + bool user_gesture) = 0; + + // Show the newly created widget with the specified bounds. + // The widget is identified by the route_id passed to CreateNewWidget. + virtual void ShowCreatedWidget(int route_id, + const gfx::Rect& initial_pos) = 0; + + // Show the newly created full screen widget. Similar to above. + virtual void ShowCreatedFullscreenWidget(int route_id) = 0; + + // A context menu should be shown, to be built using the context information + // provided in the supplied params. + virtual void ShowContextMenu(const ContextMenuParams& params) = 0; + + // Shows a popup menu with the specified items. + // This method should call RenderViewHost::DidSelectPopupMenuItemAt() or + // RenderViewHost::DidCancelPopupMenu() ased on the user action. + virtual void ShowPopupMenu(const gfx::Rect& bounds, + int item_height, + double item_font_size, + int selected_item, + const std::vector<WebMenuItem>& items, + bool right_aligned) = 0; + + // The user started dragging content of the specified type within the + // RenderView. Contextual information about the dragged content is supplied + // by WebDropData. + virtual void StartDragging(const WebDropData& drop_data, + WebKit::WebDragOperationsMask allowed_ops, + const SkBitmap& image, + const gfx::Point& image_offset) = 0; + + // The page wants to update the mouse cursor during a drag & drop operation. + // |operation| describes the current operation (none, move, copy, link.) + virtual void UpdateDragCursor(WebKit::WebDragOperation operation) = 0; + + // Notification that view for this delegate got the focus. + virtual void GotFocus() = 0; + + // Callback to inform the browser that the page is returning the focus to + // the browser's chrome. If reverse is true, it means the focus was + // retrieved by doing a Shift-Tab. + virtual void TakeFocus(bool reverse) = 0; + + // Notification that the view has lost capture. + virtual void LostCapture() = 0; + + // The page wants the hosting window to activate/deactivate itself (it + // called the JavaScript window.focus()/blur() method). + virtual void Activate() = 0; + virtual void Deactivate() = 0; + + // Callback to give the browser a chance to handle the specified keyboard + // event before sending it to the renderer. + // Returns true if the |event| was handled. Otherwise, if the |event| would + // be handled in HandleKeyboardEvent() method as a normal keyboard shortcut, + // |*is_keyboard_shortcut| should be set to true. + virtual bool PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, + bool* is_keyboard_shortcut) = 0; + + // Callback to inform the browser that the renderer did not process the + // specified events. This gives an opportunity to the browser to process the + // event (used for keyboard shortcuts). + virtual void HandleKeyboardEvent(const NativeWebKeyboardEvent& event) = 0; + + // Notifications about mouse events in this view. This is useful for + // implementing global 'on hover' features external to the view. + virtual void HandleMouseMove() = 0; + virtual void HandleMouseDown() = 0; + virtual void HandleMouseLeave() = 0; + virtual void HandleMouseUp() = 0; + virtual void HandleMouseActivate() = 0; + + // The contents' preferred size changed. + virtual void UpdatePreferredSize(const gfx::Size& pref_size) = 0; + + protected: + virtual ~View() {} + }; + + // RendererManagerment ------------------------------------------------------- + // Functions for managing switching of Renderers. For TabContents, this is + // implemented by the RenderViewHostManager + + class RendererManagement { + public: + // Notification whether we should close the page, after an explicit call to + // AttemptToClosePage. This is called before a cross-site request or before + // a tab/window is closed (as indicated by the first parameter) to allow the + // appropriate renderer to approve or deny the request. |proceed| indicates + // whether the user chose to proceed. + virtual void ShouldClosePage(bool for_cross_site_transition, + bool proceed) = 0; + + // Called by ResourceDispatcherHost when a response for a pending cross-site + // request is received. The ResourceDispatcherHost will pause the response + // until the onunload handler of the previous renderer is run. + virtual void OnCrossSiteResponse(int new_render_process_host_id, + int new_request_id) = 0; + + // Called the ResourceDispatcherHost's associate CrossSiteRequestHandler + // when a cross-site navigation has been canceled. + virtual void OnCrossSiteNavigationCanceled() = 0; + + protected: + virtual ~RendererManagement() {} + }; + + // ContentSettings------------------------------------------------------------ + // Interface for content settings related events. + + class ContentSettings { + public: + // Called when content in the current page was blocked due to the user's + // content settings. + virtual void OnContentBlocked(ContentSettingsType type, + const std::string& resource_identifier) = 0; + + // Called when cookies for the given URL were read either from within the + // current page or while loading it. |blocked_by_policy| should be true, if + // reading cookies was blocked due to the user's content settings. In that + // case, this function should invoke OnContentBlocked. + virtual void OnCookiesRead( + const GURL& url, + const net::CookieList& cookie_list, + bool blocked_by_policy) = 0; + + // Called when a specific cookie in the current page was changed. + // |blocked_by_policy| should be true, if the cookie was blocked due to the + // user's content settings. In that case, this function should invoke + // OnContentBlocked. + virtual void OnCookieChanged(const GURL& url, + const std::string& cookie_line, + const net::CookieOptions& options, + bool blocked_by_policy) = 0; + + // Called when a specific indexed db factory in the current page was + // accessed. If access was blocked due to the user's content settings, + // |blocked_by_policy| should be true, and this function should invoke + // OnContentBlocked. + virtual void OnIndexedDBAccessed(const GURL& url, + const string16& description, + bool blocked_by_policy) = 0; + + // Called when a specific local storage area in the current page was + // accessed. If access was blocked due to the user's content settings, + // |blocked_by_policy| should be true, and this function should invoke + // OnContentBlocked. + virtual void OnLocalStorageAccessed(const GURL& url, + DOMStorageType storage_type, + bool blocked_by_policy) = 0; + + // Called when a specific Web database in the current page was accessed. If + // access was blocked due to the user's content settings, + // |blocked_by_policy| should eb true, and this function should invoke + // OnContentBlocked. + virtual void OnWebDatabaseAccessed(const GURL& url, + const string16& name, + const string16& display_name, + unsigned long estimated_size, + bool blocked_by_policy) = 0; + + // Called when a specific appcache in the current page was accessed. If + // access was blocked due to the user's content settings, + // |blocked_by_policy| should eb true, and this function should invoke + // OnContentBlocked. + virtual void OnAppCacheAccessed(const GURL& manifest_url, + bool blocked_by_policy) = 0; + + // Called when geolocation permission was set in a frame on the current + // page. + virtual void OnGeolocationPermissionSet(const GURL& requesting_frame, + bool allowed) = 0; + + protected: + virtual ~ContentSettings() {} + }; + + // BookmarkDrag -------------------------------------------------------------- + // Interface for forwarding bookmark drag and drop to extenstions. + + class BookmarkDrag { + public: + virtual void OnDragEnter(const BookmarkNodeData& data) = 0; + virtual void OnDragOver(const BookmarkNodeData& data) = 0; + virtual void OnDragLeave(const BookmarkNodeData& data) = 0; + virtual void OnDrop(const BookmarkNodeData& data) = 0; + + protected: + virtual ~BookmarkDrag() {} + }; + + // SSL ----------------------------------------------------------------------- + // Interface for UI and other RenderViewHost-specific interactions with SSL. + + class SSL { + public: + // Displays a dialog to select client certificates from |request_info|, + // returning them to |handler|. + virtual void ShowClientCertificateRequestDialog( + scoped_refptr<SSLClientAuthHandler> handler) = 0; + + // Called when |handler| encounters an error in verifying a + // received client certificate. Note that, because CAs often will + // not send us intermediate certificates, the verification we can + // do is minimal: we verify the certificate is parseable, that we + // have the corresponding private key, and that the certificate + // has not expired. + virtual void OnVerifyClientCertificateError( + scoped_refptr<SSLAddCertHandler> handler, int error_code) = 0; + + // Called when |handler| requests the user's confirmation in adding a + // client certificate. + virtual void AskToAddClientCertificate( + scoped_refptr<SSLAddCertHandler> handler) = 0; + + // Called when |handler| successfully adds a client certificate. + virtual void OnAddClientCertificateSuccess( + scoped_refptr<SSLAddCertHandler> handler) = 0; + + // Called when |handler| encounters an error adding a client certificate. + virtual void OnAddClientCertificateError( + scoped_refptr<SSLAddCertHandler> handler, int error_code) = 0; + + // Called when |handler| has completed, so the delegate may release any + // state accumulated. + virtual void OnAddClientCertificateFinished( + scoped_refptr<SSLAddCertHandler> handler) = 0; + + protected: + virtual ~SSL() {} + }; + + // --------------------------------------------------------------------------- + + // Returns the current delegate associated with a feature. May return NULL if + // there is no corresponding delegate. + virtual View* GetViewDelegate(); + virtual RendererManagement* GetRendererManagementDelegate(); + virtual ContentSettings* GetContentSettingsDelegate(); + + virtual BookmarkDrag* GetBookmarkDragDelegate(); + virtual SSL* GetSSLDelegate(); + + // Return the delegate for registering RenderViewHosts for automation resource + // routing. + virtual AutomationResourceRoutingDelegate* + GetAutomationResourceRoutingDelegate(); + + // IPC::Channel::Listener implementation. + // This is used to give the delegate a chance to filter IPC messages. + virtual bool OnMessageReceived(const IPC::Message& message); + + // Gets the URL that is currently being displayed, if there is one. + virtual const GURL& GetURL() const; + + // Return this object cast to a TabContents, if it is one. If the object is + // not a TabContents, returns NULL. DEPRECATED: Be sure to include brettw and + // jam as reviewers before you use this method. + virtual TabContents* GetAsTabContents(); + + // Return this object cast to a BackgroundContents, if it is one. If the + // object is not a BackgroundContents, returns NULL. + virtual BackgroundContents* GetAsBackgroundContents(); + + // Return id number of browser window which this object is attached to. If no + // browser window is attached to, just return -1. + virtual int GetBrowserWindowID() const = 0; + + // Return type of RenderView which is attached with this object. + virtual ViewType::Type GetRenderViewType() const = 0; + + // The RenderView is being constructed (message sent to the renderer process + // to construct a RenderView). Now is a good time to send other setup events + // to the RenderView. This precedes any other commands to the RenderView. + virtual void RenderViewCreated(RenderViewHost* render_view_host) {} + + // The RenderView has been constructed. + virtual void RenderViewReady(RenderViewHost* render_view_host) {} + + // The RenderView died somehow (crashed or was killed by the user). + virtual void RenderViewGone(RenderViewHost* render_view_host, + base::TerminationStatus status, + int error_code) {} + + // The RenderView is going to be deleted. This is called when each + // RenderView is going to be destroyed + virtual void RenderViewDeleted(RenderViewHost* render_view_host) {} + + // The RenderView was navigated to a different page. + virtual void DidNavigate(RenderViewHost* render_view_host, + const ViewHostMsg_FrameNavigate_Params& params) {} + + // The state for the page changed and should be updated. + virtual void UpdateState(RenderViewHost* render_view_host, + int32 page_id, + const std::string& state) {} + + // The page's title was changed and should be updated. + virtual void UpdateTitle(RenderViewHost* render_view_host, + int32 page_id, + const std::wstring& title) {} + + // The page's encoding was changed and should be updated. + virtual void UpdateEncoding(RenderViewHost* render_view_host, + const std::string& encoding) {} + + // The destination URL has changed should be updated + virtual void UpdateTargetURL(int32 page_id, const GURL& url) {} + + // The thumbnail representation of the page changed and should be updated. + virtual void UpdateThumbnail(const GURL& url, + const SkBitmap& bitmap, + const ThumbnailScore& score) {} + + // Inspector setting was changed and should be persisted. + virtual void UpdateInspectorSetting(const std::string& key, + const std::string& value) = 0; + + virtual void ClearInspectorSettings() = 0; + + // The page is trying to close the RenderView's representation in the client. + virtual void Close(RenderViewHost* render_view_host) {} + + // The page is trying to move the RenderView's representation in the client. + virtual void RequestMove(const gfx::Rect& new_bounds) {} + + // The RenderView began loading a new page. This corresponds to WebKit's + // notion of the throbber starting. + virtual void DidStartLoading() {} + + // The RenderView stopped loading a page. This corresponds to WebKit's + // notion of the throbber stopping. + virtual void DidStopLoading() {} + + // The RenderView made progress loading a page's top frame. + // |progress| is a value between 0 (nothing loaded) to 1.0 (top frame + // entirely loaded). + virtual void DidChangeLoadProgress(double progress) {} + + // The RenderView's main frame document element is ready. This happens when + // the document has finished parsing. + virtual void DocumentAvailableInMainFrame(RenderViewHost* render_view_host) {} + + // The onload handler in the RenderView's main frame has completed. + virtual void DocumentOnLoadCompletedInMainFrame( + RenderViewHost* render_view_host, + int32 page_id) {} + + // The page wants to open a URL with the specified disposition. + virtual void RequestOpenURL(const GURL& url, + const GURL& referrer, + WindowOpenDisposition disposition) {} + + // A DOM automation operation completed. The result of the operation is + // expressed in a json string. + virtual void DomOperationResponse(const std::string& json_string, + int automation_id) {} + + // A message was sent from HTML-based UI. + // By default we ignore such messages. + virtual void ProcessWebUIMessage( + const ViewHostMsg_DomMessage_Params& params) {} + + // A message for external host. By default we ignore such messages. + // |receiver| can be a receiving script and |message| is any + // arbitrary string that makes sense to the receiver. + virtual void ProcessExternalHostMessage(const std::string& message, + const std::string& origin, + const std::string& target) {} + + // A javascript message, confirmation or prompt should be shown. + virtual void RunJavaScriptMessage(const std::wstring& message, + const std::wstring& default_prompt, + const GURL& frame_url, + const int flags, + IPC::Message* reply_msg, + bool* did_suppress_message) {} + + virtual void RunBeforeUnloadConfirm(const std::wstring& message, + IPC::Message* reply_msg) {} + + virtual void ShowModalHTMLDialog(const GURL& url, int width, int height, + const std::string& json_arguments, + IPC::Message* reply_msg) {} + + // |url| is assigned to a server that can provide alternate error pages. If + // the returned URL is empty, the default error page built into WebKit will + // be used. + virtual GURL GetAlternateErrorPageURL() const; + + // Return a dummy RendererPreferences object that will be used by the renderer + // associated with the owning RenderViewHost. + virtual RendererPreferences GetRendererPrefs(Profile* profile) const = 0; + + // Returns a WebPreferences object that will be used by the renderer + // associated with the owning render view host. + virtual WebPreferences GetWebkitPrefs(); + + // Notification the user has made a gesture while focus was on the + // page. This is used to avoid uninitiated user downloads (aka carpet + // bombing), see DownloadRequestLimiter for details. + virtual void OnUserGesture() {} + + // Notification from the renderer host that blocked UI event occurred. + // This happens when there are tab-modal dialogs. In this case, the + // notification is needed to let us draw attention to the dialog (i.e. + // refocus on the modal dialog, flash title etc). + virtual void OnIgnoredUIEvent() {} + + // Notification that the renderer has become unresponsive. The + // delegate can use this notification to show a warning to the user. + virtual void RendererUnresponsive(RenderViewHost* render_view_host, + bool is_during_unload) {} + + // Notification that a previously unresponsive renderer has become + // responsive again. The delegate can use this notification to end the + // warning shown to the user. + virtual void RendererResponsive(RenderViewHost* render_view_host) {} + + // Notification that the RenderViewHost's load state changed. + virtual void LoadStateChanged(const GURL& url, net::LoadState load_state, + uint64 upload_position, uint64 upload_size) {} + + // Returns true if this view is used to host an external tab container. + virtual bool IsExternalTabContainer() const; + + // The RenderView has inserted one css file into page. + virtual void DidInsertCSS() {} + + // A different node in the page got focused. + virtual void FocusedNodeChanged(bool is_editable_node) {} + + // Updates the minimum and maximum zoom percentages. + virtual void UpdateZoomLimits(int minimum_percent, + int maximum_percent, + bool remember) {} + + // Notification that a worker process has crashed. + void WorkerCrashed() {} + + protected: + virtual ~RenderViewHostDelegate() {} +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_DELEGATE_H_ diff --git a/chrome/browser/renderer_host/render_view_host_factory.cc b/content/browser/renderer_host/render_view_host_factory.cc index 070fdec..6fc01cf 100644 --- a/chrome/browser/renderer_host/render_view_host_factory.cc +++ b/content/browser/renderer_host/render_view_host_factory.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_view_host_factory.h" +#include "content/browser/renderer_host/render_view_host_factory.h" #include "base/logging.h" -#include "chrome/browser/renderer_host/render_view_host.h" +#include "content/browser/renderer_host/render_view_host.h" // static RenderViewHostFactory* RenderViewHostFactory::factory_ = NULL; diff --git a/content/browser/renderer_host/render_view_host_factory.h b/content/browser/renderer_host/render_view_host_factory.h new file mode 100644 index 0000000..5d0f58d --- /dev/null +++ b/content/browser/renderer_host/render_view_host_factory.h @@ -0,0 +1,68 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_ +#pragma once + +#include "base/basictypes.h" + +class RenderViewHost; +class RenderViewHostDelegate; +class SessionStorageNamespace; +class SiteInstance; + +namespace base { +class WaitableEvent; +} // namespace base + +// A factory for creating RenderViewHosts. There is a global factory function +// that can be installed for the purposes of testing to provide a specialized +// RenderViewHost class. +class RenderViewHostFactory { + public: + // Creates a RenderViewHost using the currently registered factory, or the + // default one if no factory is registered. Ownership of the returned + // pointer will be passed to the caller. + static RenderViewHost* Create(SiteInstance* instance, + RenderViewHostDelegate* delegate, + int routing_id, + SessionStorageNamespace* session_storage); + + // Returns true if there is currently a globally-registered factory. + static bool has_factory() { + return !!factory_; + } + + protected: + RenderViewHostFactory() {} + virtual ~RenderViewHostFactory() {} + + // You can derive from this class and specify an implementation for this + // function to create a different kind of RenderViewHost for testing. + virtual RenderViewHost* CreateRenderViewHost( + SiteInstance* instance, + RenderViewHostDelegate* delegate, + int routing_id, + SessionStorageNamespace* session_storage_namespace) = 0; + + // Registers your factory to be called when new RenderViewHosts are created. + // We have only one global factory, so there must be no factory registered + // before the call. This class does NOT take ownership of the pointer. + static void RegisterFactory(RenderViewHostFactory* factory); + + // Unregister the previously registered factory. With no factory registered, + // the default RenderViewHosts will be created. + static void UnregisterFactory(); + + private: + // The current globally registered factory. This is NULL when we should + // create the default RenderViewHosts. + static RenderViewHostFactory* factory_; + + DISALLOW_COPY_AND_ASSIGN(RenderViewHostFactory); +}; + + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_ diff --git a/content/browser/renderer_host/render_view_host_notification_task.h b/content/browser/renderer_host/render_view_host_notification_task.h new file mode 100644 index 0000000..f9051c4 --- /dev/null +++ b/content/browser/renderer_host/render_view_host_notification_task.h @@ -0,0 +1,337 @@ +// 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 defines utility functions for sending notifications (calling +// methods that return void and do not have out params) to the RenderViewHost +// or one of its delegate interfaces. The notifications are dispatched +// asynchronously, and only if the specified RenderViewHost still exists. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_NOTIFICATION_TASK_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_NOTIFICATION_TASK_H_ +#pragma once + +#include "base/callback.h" +#include "base/task.h" +#include "chrome/browser/browser_thread.h" +#include "content/browser/renderer_host/render_view_host.h" +#include "content/browser/renderer_host/render_view_host_delegate.h" + +// ---------------------------------------------------------------------------- + +namespace internal { + +// The simplest Mapper, used when proxying calls to a RenderViewHost. +class RenderViewHostIdentityMapper { + public: + typedef RenderViewHost MappedType; + static MappedType* Map(RenderViewHost* rvh) { return rvh; } +}; + +template <typename Method, typename Params, + typename Mapper = RenderViewHostIdentityMapper> +class RenderViewHostNotificationTask : public Task { + public: + RenderViewHostNotificationTask(int render_process_id, + int render_view_id, + Method method, + const Params& params) + : render_process_id_(render_process_id), + render_view_id_(render_view_id), + unbound_method_(method, params) { + } + + virtual void Run() { + RenderViewHost* rvh = RenderViewHost::FromID(render_process_id_, + render_view_id_); + typename Mapper::MappedType* obj = Mapper::Map(rvh); + if (obj) + unbound_method_.Run(obj); + } + + private: + int render_process_id_; + int render_view_id_; + UnboundMethod<typename Mapper::MappedType, Method, Params> unbound_method_; + + DISALLOW_COPY_AND_ASSIGN(RenderViewHostNotificationTask); +}; + +// For proxying calls to RenderViewHost + +template <typename Method, typename Params> +inline void CallRenderViewHostHelper(int render_process_id, int render_view_id, + Method method, const Params& params) { + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + new RenderViewHostNotificationTask<Method, Params>(render_process_id, + render_view_id, + method, + params)); +} + +// For proxying calls to RenderViewHostDelegate::ContentSettings + +class RenderViewHostToContentSettingsDelegate { + public: + typedef RenderViewHostDelegate::ContentSettings MappedType; + static MappedType* Map(RenderViewHost* rvh) { + return rvh ? rvh->delegate()->GetContentSettingsDelegate() : NULL; + } +}; + +template <typename Method, typename Params> +inline void CallRenderViewHostContentSettingsDelegateHelper( + int render_process_id, + int render_view_id, + Method method, + const Params& params) { + + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + new RenderViewHostNotificationTask< + Method, Params, RenderViewHostToContentSettingsDelegate>( + render_process_id, + render_view_id, + method, + params)); +} + +// For proxying calls to RenderViewHostDelegate::RendererManagement + +class RenderViewHostToRendererManagementDelegate { + public: + typedef RenderViewHostDelegate::RendererManagement MappedType; + static MappedType* Map(RenderViewHost* rvh) { + return rvh ? rvh->delegate()->GetRendererManagementDelegate() : NULL; + } +}; + +template <typename Method, typename Params> +inline void CallRenderViewHostRendererManagementDelegateHelper( + int render_process_id, + int render_view_id, + Method method, + const Params& params) { + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + new RenderViewHostNotificationTask< + Method, Params, RenderViewHostToRendererManagementDelegate>( + render_process_id, + render_view_id, + method, + params)); +} + +// For proxying calls to RenderViewHostDelegate::SSL + +class RenderViewHostToSSLDelegate { + public: + typedef RenderViewHostDelegate::SSL MappedType; + static MappedType* Map(RenderViewHost* rvh) { + return rvh ? rvh->delegate()->GetSSLDelegate() : NULL; + } +}; + +template <typename Method, typename Params> +inline void CallRenderViewHostSSLDelegateHelper( + int render_process_id, + int render_view_id, + Method method, + const Params& params) { + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + new RenderViewHostNotificationTask< + Method, Params, RenderViewHostToSSLDelegate>( + render_process_id, + render_view_id, + method, + params)); +} + +} // namespace internal + +// ---------------------------------------------------------------------------- +// Proxy calls to the specified RenderViewHost. + +template <typename Method> +inline void CallRenderViewHost(int render_process_id, + int render_view_id, + Method method) { + internal::CallRenderViewHostHelper(render_process_id, + render_view_id, + method, + MakeTuple()); +} + +template <typename Method, typename A> +inline void CallRenderViewHost(int render_process_id, + int render_view_id, + Method method, + const A& a) { + internal::CallRenderViewHostHelper(render_process_id, + render_view_id, + method, + MakeTuple(a)); +} + +template <typename Method, typename A, typename B> +inline void CallRenderViewHost(int render_process_id, + int render_view_id, + Method method, + const A& a, + const B& b) { + internal::CallRenderViewHostHelper(render_process_id, + render_view_id, + method, + MakeTuple(a, b)); +} + +// ---------------------------------------------------------------------------- +// Proxy calls to the specified RenderViewHost's ContentSettings delegate. + +template <typename Method> +inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, + int render_view_id, + Method method) { + internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, + render_view_id, + method, + MakeTuple()); +} + +template <typename Method, typename A> +inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a) { + internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, + render_view_id, + method, + MakeTuple(a)); + } + +template <typename Method, typename A, typename B> +inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a, + const B& b) { + internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, + render_view_id, + method, + MakeTuple(a, b)); +} + +template <typename Method, typename A, typename B, typename C> +inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a, + const B& b, + const C& c) { + internal::CallRenderViewHostContentSettingsDelegateHelper(render_process_id, + render_view_id, + method, + MakeTuple(a, b, c)); +} + +template <typename Method, typename A, typename B, typename C, typename D> +inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a, + const B& b, + const C& c, + const D& d) { + internal::CallRenderViewHostContentSettingsDelegateHelper( + render_process_id, + render_view_id, + method, + MakeTuple(a, b, c, d)); +} + +template <typename Method, + typename A, typename B, typename C, typename D, typename E> +inline void CallRenderViewHostContentSettingsDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a, + const B& b, + const C& c, + const D& d, + const E& e) { + internal::CallRenderViewHostContentSettingsDelegateHelper( + render_process_id, render_view_id, method, MakeTuple(a, b, c, d, e)); +} + +// ---------------------------------------------------------------------------- +// Proxy calls to the specified RenderViewHost's RendererManagement delegate. + +template <typename Method> +inline void CallRenderViewHostRendererManagementDelegate(int render_process_id, + int render_view_id, + Method method) { + internal::CallRenderViewHostRendererManagementDelegateHelper( + render_process_id, + render_view_id, + method, + MakeTuple()); +} + +template <typename Method, typename A> +inline void CallRenderViewHostRendererManagementDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a) { + internal::CallRenderViewHostRendererManagementDelegateHelper( + render_process_id, + render_view_id, + method, + MakeTuple(a)); +} + +template <typename Method, typename A, typename B> +inline void CallRenderViewHostRendererManagementDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a, + const B& b) { + internal::CallRenderViewHostRendererManagementDelegateHelper( + render_process_id, + render_view_id, + method, + MakeTuple(a, b)); +} + +// ---------------------------------------------------------------------------- +// Proxy calls to the specified RenderViewHost's SSL delegate. + +template <typename Method, typename A> +inline void CallRenderViewHostSSLDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a) { + internal::CallRenderViewHostSSLDelegateHelper( + render_process_id, + render_view_id, + method, + MakeTuple(a)); +} + +template <typename Method, typename A, typename B> +inline void CallRenderViewHostSSLDelegate(int render_process_id, + int render_view_id, + Method method, + const A& a, + const B& b) { + internal::CallRenderViewHostSSLDelegateHelper( + render_process_id, + render_view_id, + method, + MakeTuple(a, b)); +} + +// ---------------------------------------------------------------------------- + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_NOTIFICATION_TASK_H_ diff --git a/chrome/browser/renderer_host/render_widget_fullscreen_host.cc b/content/browser/renderer_host/render_widget_fullscreen_host.cc index c3ee786..4fbd140 100644 --- a/chrome/browser/renderer_host/render_widget_fullscreen_host.cc +++ b/content/browser/renderer_host/render_widget_fullscreen_host.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_widget_fullscreen_host.h" +#include "content/browser/renderer_host/render_widget_fullscreen_host.h" RenderWidgetFullscreenHost::RenderWidgetFullscreenHost( RenderProcessHost* process, int routing_id) diff --git a/content/browser/renderer_host/render_widget_fullscreen_host.h b/content/browser/renderer_host/render_widget_fullscreen_host.h new file mode 100644 index 0000000..fce2200 --- /dev/null +++ b/content/browser/renderer_host/render_widget_fullscreen_host.h @@ -0,0 +1,15 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_FULLSCREEN_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_FULLSCREEN_HOST_H_ + +#include "content/browser/renderer_host/render_widget_host.h" + +class RenderWidgetFullscreenHost : public RenderWidgetHost { + public: + RenderWidgetFullscreenHost(RenderProcessHost* process, int routing_id); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_FULLSCREEN_HOST_H_ diff --git a/chrome/browser/renderer_host/render_widget_helper.cc b/content/browser/renderer_host/render_widget_helper.cc index 3d808df..c3bb7de 100644 --- a/chrome/browser/renderer_host/render_widget_helper.cc +++ b/content/browser/renderer_host/render_widget_helper.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_widget_helper.h" +#include "content/browser/renderer_host/render_widget_helper.h" #include "base/eintr_wrapper.h" #include "base/threading/thread.h" #include "chrome/browser/browser_thread.h" -#include "chrome/browser/renderer_host/render_process_host.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/render_messages_params.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_view_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" // A Task used with InvokeLater that we hold a pointer to in pending_paints_. // Instances are deleted by MessageLoop after it calls their Run method. diff --git a/content/browser/renderer_host/render_widget_helper.h b/content/browser/renderer_host/render_widget_helper.h new file mode 100644 index 0000000..0dd25d7 --- /dev/null +++ b/content/browser/renderer_host/render_widget_helper.h @@ -0,0 +1,216 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HELPER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HELPER_H_ +#pragma once + +#include <map> + +#include "app/surface/transport_dib.h" +#include "base/atomic_sequence_num.h" +#include "base/hash_tables.h" +#include "base/process.h" +#include "base/ref_counted.h" +#include "base/synchronization/lock.h" +#include "base/synchronization/waitable_event.h" +#include "chrome/common/window_container_type.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" + +namespace IPC { +class Message; +} + +namespace base { +class TimeDelta; +} + +class ResourceDispatcherHost; +struct ViewHostMsg_CreateWindow_Params; +struct ViewMsg_ClosePage_Params; + + +// Instantiated per RenderProcessHost to provide various optimizations on +// behalf of a RenderWidgetHost. This class bridges between the IO thread +// where the RenderProcessHost's MessageFilter lives and the UI thread where +// the RenderWidgetHost lives. +// +// +// OPTIMIZED RESIZE +// +// RenderWidgetHelper is used to implement optimized resize. When the +// RenderWidgetHost is resized, it sends a Resize message to its RenderWidget +// counterpart in the renderer process. The RenderWidget generates a +// UpdateRect message in response to the Resize message, and it sets the +// IS_RESIZE_ACK flag in the UpdateRect message to true. +// +// Back in the browser process, when the RenderProcessHost's MessageFilter +// sees a UpdateRect message, it directs it to the RenderWidgetHelper by +// calling the DidReceiveUpdateMsg method. That method stores the data for +// the UpdateRect message in a map, where it can be directly accessed by the +// RenderWidgetHost on the UI thread during a call to RenderWidgetHost's +// GetBackingStore method. +// +// When the RenderWidgetHost's GetBackingStore method is called, it first +// checks to see if it is waiting for a resize ack. If it is, then it calls +// the RenderWidgetHelper's WaitForUpdateMsg to check if there is already a +// resulting UpdateRect message (or to wait a short amount of time for one to +// arrive). The main goal of this mechanism is to short-cut the usual way in +// which IPC messages are proxied over to the UI thread via InvokeLater. +// This approach is necessary since window resize is followed up immediately +// by a request to repaint the window. +// +// +// OPTIMIZED TAB SWITCHING +// +// When a RenderWidgetHost is in a background tab, it is flagged as hidden. +// This causes the corresponding RenderWidget to stop sending UpdateRect +// messages. The RenderWidgetHost also discards its backingstore when it is +// hidden, which helps free up memory. As a result, when a RenderWidgetHost +// is restored, it can be momentarily without a backingstore. (Restoring a +// RenderWidgetHost results in a WasRestored message being sent to the +// RenderWidget, which triggers a full UpdateRect message.) This can lead to +// an observed rendering glitch as the TabContents will just have to fill +// white overtop the RenderWidgetHost until the RenderWidgetHost receives a +// UpdateRect message to refresh its backingstore. +// +// To avoid this 'white flash', the RenderWidgetHost again makes use of the +// RenderWidgetHelper's WaitForUpdateMsg method. When the RenderWidgetHost's +// GetBackingStore method is called, it will call WaitForUpdateMsg if it has +// no backingstore. +// +// TRANSPORT DIB CREATION +// +// On some platforms (currently the Mac) the renderer cannot create transport +// DIBs because of sandbox limitations. Thus, it has to make synchronous IPCs +// to the browser for them. Since these requests are synchronous, they cannot +// terminate on the UI thread. Thus, in this case, this object performs the +// allocation and maintains the set of allocated transport DIBs which the +// renderers can refer to. +// +class RenderWidgetHelper + : public base::RefCountedThreadSafe<RenderWidgetHelper> { + public: + RenderWidgetHelper(); + + void Init(int render_process_id, + ResourceDispatcherHost* resource_dispatcher_host); + + // Gets the next available routing id. This is thread safe. + int GetNextRoutingID(); + + + // UI THREAD ONLY ----------------------------------------------------------- + + // These three functions provide the backend implementation of the + // corresponding functions in RenderProcessHost. See those declarations + // for documentation. + void CancelResourceRequests(int render_widget_id); + void CrossSiteClosePageACK(const ViewMsg_ClosePage_Params& params); + bool WaitForUpdateMsg(int render_widget_id, + const base::TimeDelta& max_delay, + IPC::Message* msg); + +#if defined(OS_MACOSX) + // Given the id of a transport DIB, return a mapping to it or NULL on error. + TransportDIB* MapTransportDIB(TransportDIB::Id dib_id); +#endif + + + // IO THREAD ONLY ----------------------------------------------------------- + + // Called on the IO thread when a UpdateRect message is received. + void DidReceiveUpdateMsg(const IPC::Message& msg); + + void CreateNewWindow(const ViewHostMsg_CreateWindow_Params& params, + base::ProcessHandle render_process, + int* route_id); + void CreateNewWidget(int opener_id, + WebKit::WebPopupType popup_type, + int* route_id); + void CreateNewFullscreenWidget(int opener_id, int* route_id); + +#if defined(OS_MACOSX) + // Called on the IO thread to handle the allocation of a TransportDIB. If + // |cache_in_browser| is |true|, then a copy of the shmem is kept by the + // browser, and it is the caller's repsonsibility to call + // FreeTransportDIB(). In all cases, the caller is responsible for deleting + // the resulting TransportDIB. + void AllocTransportDIB(size_t size, + bool cache_in_browser, + TransportDIB::Handle* result); + + // Called on the IO thread to handle the freeing of a transport DIB + void FreeTransportDIB(TransportDIB::Id dib_id); +#endif + + private: + // A class used to proxy a paint message. PaintMsgProxy objects are created + // on the IO thread and destroyed on the UI thread. + class UpdateMsgProxy; + friend class UpdateMsgProxy; + friend class base::RefCountedThreadSafe<RenderWidgetHelper>; + + // Map from render_widget_id to live PaintMsgProxy instance. + typedef base::hash_map<int, UpdateMsgProxy*> UpdateMsgProxyMap; + + ~RenderWidgetHelper(); + + // Called on the UI thread to discard a paint message. + void OnDiscardUpdateMsg(UpdateMsgProxy* proxy); + + // Called on the UI thread to dispatch a paint message if necessary. + void OnDispatchUpdateMsg(UpdateMsgProxy* proxy); + + // Called on the UI thread to finish creating a window. + void OnCreateWindowOnUI(const ViewHostMsg_CreateWindow_Params& params, + int route_id); + + // Called on the IO thread after a window was created on the UI thread. + void OnCreateWindowOnIO(int route_id); + + // Called on the UI thread to finish creating a widget. + void OnCreateWidgetOnUI(int opener_id, + int route_id, + WebKit::WebPopupType popup_type); + + // Called on the UI thread to create a fullscreen widget. + void OnCreateFullscreenWidgetOnUI(int opener_id, int route_id); + + // Called on the IO thread to cancel resource requests for the render widget. + void OnCancelResourceRequests(int render_widget_id); + + // Called on the IO thread to resume a cross-site response. + void OnCrossSiteClosePageACK(const ViewMsg_ClosePage_Params& params); + +#if defined(OS_MACOSX) + // Called on destruction to release all allocated transport DIBs + void ClearAllocatedDIBs(); + + // On OSX we keep file descriptors to all the allocated DIBs around until + // the renderer frees them. + base::Lock allocated_dibs_lock_; + std::map<TransportDIB::Id, int> allocated_dibs_; +#endif + + // A map of live paint messages. Must hold pending_paints_lock_ to access. + // The UpdateMsgProxy objects are not owned by this map. (See UpdateMsgProxy + // for details about how the lifetime of instances are managed.) + UpdateMsgProxyMap pending_paints_; + base::Lock pending_paints_lock_; + + int render_process_id_; + + // Event used to implement WaitForUpdateMsg. + base::WaitableEvent event_; + + // The next routing id to use. + base::AtomicSequenceNumber next_routing_id_; + + ResourceDispatcherHost* resource_dispatcher_host_; + + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHelper); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HELPER_H_ diff --git a/chrome/browser/renderer_host/render_widget_host.cc b/content/browser/renderer_host/render_widget_host.cc index 13e5da7..5fbd2df 100644 --- a/chrome/browser/renderer_host/render_widget_host.cc +++ b/content/browser/renderer_host/render_widget_host.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_widget_host.h" +#include "content/browser/renderer_host/render_widget_host.h" #include "base/auto_reset.h" #include "base/command_line.h" @@ -10,17 +10,17 @@ #include "base/metrics/histogram.h" #include "chrome/browser/accessibility/browser_accessibility_state.h" #include "chrome/browser/metrics/user_metrics.h" -#include "chrome/browser/renderer_host/backing_store.h" -#include "chrome/browser/renderer_host/backing_store_manager.h" -#include "chrome/browser/renderer_host/render_process_host.h" -#include "chrome/browser/renderer_host/render_widget_helper.h" -#include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/result_codes.h" #include "chrome/common/native_web_keyboard_event.h" #include "chrome/common/notification_service.h" #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" +#include "content/browser/renderer_host/backing_store.h" +#include "content/browser/renderer_host/backing_store_manager.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "content/browser/renderer_host/render_widget_helper.h" +#include "content/browser/renderer_host/render_widget_host_view.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebCompositionUnderline.h" #include "ui/base/keycodes/keyboard_codes.h" #include "webkit/glue/webcursor.h" diff --git a/content/browser/renderer_host/render_widget_host.h b/content/browser/renderer_host/render_widget_host.h new file mode 100644 index 0000000..d3598dd --- /dev/null +++ b/content/browser/renderer_host/render_widget_host.h @@ -0,0 +1,677 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_H_ +#pragma once + +#include <deque> +#include <string> +#include <vector> + +#include "app/surface/transport_dib.h" +#include "base/gtest_prod_util.h" +#include "base/process_util.h" +#include "base/scoped_ptr.h" +#include "base/string16.h" +#include "base/timer.h" +#include "chrome/common/edit_command.h" +#include "chrome/common/native_web_keyboard_event.h" +#include "chrome/common/property_bag.h" +#include "ipc/ipc_channel.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextDirection.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextInputType.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/rect.h" +#include "ui/gfx/size.h" + +namespace gfx { +class Rect; +} + +namespace WebKit { +class WebInputEvent; +class WebMouseEvent; +struct WebCompositionUnderline; +struct WebScreenInfo; +} + +class BackingStore; +class PaintObserver; +class RenderProcessHost; +class RenderWidgetHostView; +class TransportDIB; +class WebCursor; +struct ViewHostMsg_UpdateRect_Params; + +// This class manages the browser side of a browser<->renderer HWND connection. +// The HWND lives in the browser process, and windows events are sent over +// IPC to the corresponding object in the renderer. The renderer paints into +// shared memory, which we transfer to a backing store and blit to the screen +// when Windows sends us a WM_PAINT message. +// +// How Shutdown Works +// +// There are two situations in which this object, a RenderWidgetHost, can be +// instantiated: +// +// 1. By a TabContents as the communication conduit for a rendered web page. +// The TabContents instantiates a derived class: RenderViewHost. +// 2. By a TabContents as the communication conduit for a select widget. The +// TabContents instantiates the RenderWidgetHost directly. +// +// For every TabContents there are several objects in play that need to be +// properly destroyed or cleaned up when certain events occur. +// +// - TabContents - the TabContents itself, and its associated HWND. +// - RenderViewHost - representing the communication conduit with the child +// process. +// - RenderWidgetHostView - the view of the web page content, message handler, +// and plugin root. +// +// Normally, the TabContents contains a child RenderWidgetHostView that renders +// the contents of the loaded page. It has a WS_CLIPCHILDREN style so that it +// does no painting of its own. +// +// The lifetime of the RenderWidgetHostView is tied to the render process. If +// the render process dies, the RenderWidgetHostView goes away and all +// references to it must become NULL. If the TabContents finds itself without a +// RenderWidgetHostView, it paints Sad Tab instead. +// +// RenderViewHost (a RenderWidgetHost subclass) is the conduit used to +// communicate with the RenderView and is owned by the TabContents. If the +// render process crashes, the RenderViewHost remains and restarts the render +// process if needed to continue navigation. +// +// The TabContents is itself owned by the NavigationController in which it +// resides. +// +// Some examples of how shutdown works: +// +// When a tab is closed (either by the user, the web page calling window.close, +// etc) the TabStrip destroys the associated NavigationController, which calls +// Destroy on each TabContents it owns. +// +// For a TabContents, its Destroy method tells the RenderViewHost to +// shut down the render process and die. +// +// When the render process is destroyed it destroys the View: the +// RenderWidgetHostView, which destroys its HWND and deletes that object. +// +// For select popups, the situation is a little different. The RenderWidgetHost +// associated with the select popup owns the view and itself (is responsible +// for destroying itself when the view is closed). The TabContents's only +// responsibility is to select popups is to create them when it is told to. When +// the View is destroyed via an IPC message (for when WebCore destroys the +// popup, e.g. if the user selects one of the options), or because +// WM_CANCELMODE is received by the view, the View schedules the destruction of +// the render process. However in this case since there's no TabContents +// container, when the render process is destroyed, the RenderWidgetHost just +// deletes itself, which is safe because no one else should have any references +// to it (the TabContents does not). +// +// It should be noted that the RenderViewHost, not the RenderWidgetHost, +// handles IPC messages relating to the render process going away, since the +// way a RenderViewHost (TabContents) handles the process dying is different to +// the way a select popup does. As such the RenderWidgetHostView handles these +// messages for select popups. This placement is more out of convenience than +// anything else. When the view is live, these messages are forwarded to it by +// the RenderWidgetHost's IPC message map. +// +class RenderWidgetHost : public IPC::Channel::Listener, + public IPC::Channel::Sender { + public: + // Used as the details object for a + // RENDER_WIDGET_HOST_DID_RECEIVE_PAINT_AT_SIZE_ACK notification. + struct PaintAtSizeAckDetails { + // The tag that was passed to the PaintAtSize() call that triggered this + // ack. + int tag; + gfx::Size size; + }; + + // routing_id can be MSG_ROUTING_NONE, in which case the next available + // routing id is taken from the RenderProcessHost. + RenderWidgetHost(RenderProcessHost* process, int routing_id); + virtual ~RenderWidgetHost(); + + // Gets/Sets the View of this RenderWidgetHost. Can be NULL, e.g. if the + // RenderWidget is being destroyed or the render process crashed. You should + // never cache this pointer since it can become NULL if the renderer crashes, + // instead you should always ask for it using the accessor. + void set_view(RenderWidgetHostView* view) { view_ = view; } + RenderWidgetHostView* view() const { return view_; } + + RenderProcessHost* process() const { return process_; } + int routing_id() const { return routing_id_; } + bool renderer_accessible() { return renderer_accessible_; } + + // Returns the property bag for this widget, where callers can add extra data + // they may wish to associate with it. Returns a pointer rather than a + // reference since the PropertyAccessors expect this. + const PropertyBag* property_bag() const { return &property_bag_; } + PropertyBag* property_bag() { return &property_bag_; } + + // Called when a renderer object already been created for this host, and we + // just need to be attached to it. Used for window.open, <select> dropdown + // menus, and other times when the renderer initiates creating an object. + void Init(); + + // Tells the renderer to die and then calls Destroy(). + virtual void Shutdown(); + + // Manual RTTI FTW. We are not hosting a web page. + virtual bool IsRenderView() const; + + // IPC::Channel::Listener + virtual bool OnMessageReceived(const IPC::Message& msg); + + // Sends a message to the corresponding object in the renderer. + virtual bool Send(IPC::Message* msg); + + // Called to notify the RenderWidget that it has been hidden or restored from + // having been hidden. + void WasHidden(); + void WasRestored(); + + // Called to notify the RenderWidget that it has been resized. + void WasResized(); + + // Called to notify the RenderWidget that its associated native window got + // focused. + virtual void GotFocus(); + + // Tells the renderer it got/lost focus. + void Focus(); + void Blur(); + virtual void LostCapture(); + + // Tells us whether the page is rendered directly via the GPU process. + bool is_accelerated_compositing_active() { + return is_accelerated_compositing_active_; + } + + // Notifies the RenderWidgetHost that the View was destroyed. + void ViewDestroyed(); + + // Indicates if the page has finished loading. + void SetIsLoading(bool is_loading); + + // This tells the renderer to paint into a bitmap and return it, + // regardless of whether the tab is hidden or not. It resizes the + // web widget to match the |page_size| and then returns the bitmap + // scaled so it matches the |desired_size|, so that the scaling + // happens on the rendering thread. When the bitmap is ready, the + // renderer sends a PaintAtSizeACK to this host, and a + // RENDER_WIDGET_HOST_DID_RECEIVE_PAINT_AT_SIZE_ACK notification is issued. + // Note that this bypasses most of the update logic that is normally invoked, + // and doesn't put the results into the backing store. + void PaintAtSize(TransportDIB::Handle dib_handle, + int tag, + const gfx::Size& page_size, + const gfx::Size& desired_size); + + // Get access to the widget's backing store. If a resize is in progress, + // then the current size of the backing store may be less than the size of + // the widget's view. If you pass |force_create| as true, then the backing + // store will be created if it doesn't exist. Otherwise, NULL will be returned + // if the backing store doesn't already exist. It will also return NULL if the + // backing store could not be created. + BackingStore* GetBackingStore(bool force_create); + + // Allocate a new backing store of the given size. Returns NULL on failure + // (for example, if we don't currently have a RenderWidgetHostView.) + BackingStore* AllocBackingStore(const gfx::Size& size); + + // When a backing store does asynchronous painting, it will call this function + // when it is done with the DIB. We will then forward a message to the + // renderer to send another paint. + void DonePaintingToBackingStore(); + + // GPU accelerated version of GetBackingStore function. This will + // trigger a re-composite to the view. If a resize is pending, it will + // block briefly waiting for an ack from the renderer. + void ScheduleComposite(); + + // Starts a hang monitor timeout. If there's already a hang monitor timeout + // the new one will only fire if it has a shorter delay than the time + // left on the existing timeouts. + void StartHangMonitorTimeout(base::TimeDelta delay); + + // Restart the active hang monitor timeout. Clears all existing timeouts and + // starts with a new one. This can be because the renderer has become + // active, the tab is being hidden, or the user has chosen to wait some more + // to give the tab a chance to become active and we don't want to display a + // warning too soon. + void RestartHangMonitorTimeout(); + + // Stops all existing hang monitor timeouts and assumes the renderer is + // responsive. + void StopHangMonitorTimeout(); + + // Called when the system theme changes. At this time all existing native + // theme handles are invalid and the renderer must obtain new ones and + // repaint. + void SystemThemeChanged(); + + // Forwards the given message to the renderer. These are called by the view + // when it has received a message. + virtual void ForwardMouseEvent(const WebKit::WebMouseEvent& mouse_event); + // Called when a mouse click activates the renderer. + virtual void OnMouseActivate(); + void ForwardWheelEvent(const WebKit::WebMouseWheelEvent& wheel_event); + virtual void ForwardKeyboardEvent(const NativeWebKeyboardEvent& key_event); + virtual void ForwardEditCommand(const std::string& name, + const std::string& value); + virtual void ForwardEditCommandsForNextKeyEvent( + const EditCommands& edit_commands); +#if defined(TOUCH_UI) + virtual void ForwardTouchEvent(const WebKit::WebTouchEvent& touch_event); +#endif + + + // Update the text direction of the focused input element and notify it to a + // renderer process. + // These functions have two usage scenarios: changing the text direction + // from a menu (as Safari does), and; changing the text direction when a user + // presses a set of keys (as IE and Firefox do). + // 1. Change the text direction from a menu. + // In this scenario, we receive a menu event only once and we should update + // the text direction immediately when a user chooses a menu item. So, we + // should call both functions at once as listed in the following snippet. + // void RenderViewHost::SetTextDirection(WebTextDirection direction) { + // UpdateTextDirection(direction); + // NotifyTextDirection(); + // } + // 2. Change the text direction when pressing a set of keys. + // Because of auto-repeat, we may receive the same key-press event many + // times while we presses the keys and it is nonsense to send the same IPC + // message every time when we receive a key-press event. + // To suppress the number of IPC messages, we just update the text direction + // when receiving a key-press event and send an IPC message when we release + // the keys as listed in the following snippet. + // if (key_event.type == WebKeyboardEvent::KEY_DOWN) { + // if (key_event.windows_key_code == 'A' && + // key_event.modifiers == WebKeyboardEvent::CTRL_KEY) { + // UpdateTextDirection(dir); + // } else { + // CancelUpdateTextDirection(); + // } + // } else if (key_event.type == WebKeyboardEvent::KEY_UP) { + // NotifyTextDirection(); + // } + // Once we cancel updating the text direction, we have to ignore all + // succeeding UpdateTextDirection() requests until calling + // NotifyTextDirection(). (We may receive keydown events even after we + // canceled updating the text direction because of auto-repeat.) + // Note: we cannot undo this change for compatibility with Firefox and IE. + void UpdateTextDirection(WebKit::WebTextDirection direction); + void CancelUpdateTextDirection(); + void NotifyTextDirection(); + + // Notifies the renderer whether or not the input method attached to this + // process is activated. + // When the input method is activated, a renderer process sends IPC messages + // to notify the status of its composition node. (This message is mainly used + // for notifying the position of the input cursor so that the browser can + // display input method windows under the cursor.) + void SetInputMethodActive(bool activate); + + // Update the composition node of the renderer (or WebKit). + // WebKit has a special node (a composition node) for input method to change + // its text without affecting any other DOM nodes. When the input method + // (attached to the browser) updates its text, the browser sends IPC messages + // to update the composition node of the renderer. + // (Read the comments of each function for its detail.) + + // Sets the text of the composition node. + // This function can also update the cursor position and mark the specified + // range in the composition node. + // A browser should call this function: + // * when it receives a WM_IME_COMPOSITION message with a GCS_COMPSTR flag + // (on Windows); + // * when it receives a "preedit_changed" signal of GtkIMContext (on Linux); + // * when markedText of NSTextInput is called (on Mac). + void ImeSetComposition( + const string16& text, + const std::vector<WebKit::WebCompositionUnderline>& underlines, + int selection_start, + int selection_end); + + // Finishes an ongoing composition with the specified text. + // A browser should call this function: + // * when it receives a WM_IME_COMPOSITION message with a GCS_RESULTSTR flag + // (on Windows); + // * when it receives a "commit" signal of GtkIMContext (on Linux); + // * when insertText of NSTextInput is called (on Mac). + void ImeConfirmComposition(const string16& text); + + // Finishes an ongoing composition with the composition text set by last + // SetComposition() call. + void ImeConfirmComposition(); + + // Cancels an ongoing composition. + void ImeCancelComposition(); + + // Makes an IPC call to toggle the spelling panel. + void ToggleSpellPanel(bool is_currently_visible); + + // Makes an IPC call to tell webkit to replace the currently selected word + // or a word around the cursor. + void Replace(const string16& word); + + // Makes an IPC call to tell webkit to advance to the next misspelling. + void AdvanceToNextMisspelling(); + + // Enable renderer accessibility. This should only be called when a + // screenreader is detected. + void EnableRendererAccessibility(); + + // Relays a request from assistive technology to set focus to the + // node with this accessibility object id. + void SetAccessibilityFocus(int acc_obj_id); + + // Relays a request from assistive technology to perform the default action + // on a node with this accessibility object id. + void AccessibilityDoDefaultAction(int acc_obj_id); + + // Acknowledges a ViewHostMsg_AccessibilityNotifications message. + void AccessibilityNotificationsAck(); + + // Sets the active state (i.e., control tints). + virtual void SetActive(bool active); + + void set_ignore_input_events(bool ignore_input_events) { + ignore_input_events_ = ignore_input_events; + } + bool ignore_input_events() const { + return ignore_input_events_; + } + + // Activate deferred plugin handles. + void ActivateDeferredPluginHandles(); + + const gfx::Point& last_scroll_offset() const { return last_scroll_offset_; } + + protected: + // Internal implementation of the public Forward*Event() methods. + void ForwardInputEvent(const WebKit::WebInputEvent& input_event, + int event_size, bool is_keyboard_shortcut); + + // Called when we receive a notification indicating that the renderer + // process has gone. This will reset our state so that our state will be + // consistent if a new renderer is created. + void RendererExited(base::TerminationStatus status, int exit_code); + + // Retrieves an id the renderer can use to refer to its view. + // This is used for various IPC messages, including plugins. + gfx::NativeViewId GetNativeViewId(); + + // Called to handled a keyboard event before sending it to the renderer. + // This is overridden by RenderView to send upwards to its delegate. + // Returns true if the event was handled, and then the keyboard event will + // not be sent to the renderer anymore. Otherwise, if the |event| would + // be handled in HandleKeyboardEvent() method as a normal keyboard shortcut, + // |*is_keyboard_shortcut| should be set to true. + virtual bool PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, + bool* is_keyboard_shortcut); + + // Called when a keyboard event was not processed by the renderer. This is + // overridden by RenderView to send upwards to its delegate. + virtual void UnhandledKeyboardEvent(const NativeWebKeyboardEvent& event) {} + + // Notification that the user has made some kind of input that could + // perform an action. The render view host overrides this to forward the + // information to its delegate (see corresponding function in + // RenderViewHostDelegate). The gestures that count are 1) any mouse down + // event and 2) enter or space key presses. + virtual void OnUserGesture() {} + + // Callbacks for notification when the renderer becomes unresponsive to user + // input events, and subsequently responsive again. RenderViewHost overrides + // these to tell its delegate to show the user a warning. + virtual void NotifyRendererUnresponsive() {} + virtual void NotifyRendererResponsive() {} + + protected: + // true if a renderer has once been valid. We use this flag to display a sad + // tab only when we lose our renderer and not if a paint occurs during + // initialization. + bool renderer_initialized_; + + private: + FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, Resize); + FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, ResizeThenCrash); + FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, HiddenPaint); + FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostTest, PaintAtSize); + + // Tell this object to destroy itself. + void Destroy(); + + // Checks whether the renderer is hung and calls NotifyRendererUnresponsive + // if it is. + void CheckRendererIsUnresponsive(); + + // Called if we know the renderer is responsive. When we currently think the + // renderer is unresponsive, this will clear that state and call + // NotifyRendererResponsive. + void RendererIsResponsive(); + + // IPC message handlers + void OnMsgRenderViewReady(); + void OnMsgRenderViewGone(int status, int error_code); + void OnMsgClose(); + void OnMsgRequestMove(const gfx::Rect& pos); + void OnMsgPaintAtSizeAck(int tag, const gfx::Size& size); + void OnMsgUpdateRect(const ViewHostMsg_UpdateRect_Params& params); + void OnMsgInputEventAck(const IPC::Message& message); + virtual void OnMsgFocus(); + virtual void OnMsgBlur(); + + void OnMsgSetCursor(const WebCursor& cursor); + void OnMsgImeUpdateTextInputState(WebKit::WebTextInputType type, + const gfx::Rect& caret_rect); + void OnMsgImeCancelComposition(); + + void OnMsgDidActivateAcceleratedCompositing(bool activated); + +#if defined(OS_MACOSX) + void OnMsgGetScreenInfo(gfx::NativeViewId view, + WebKit::WebScreenInfo* results); + void OnMsgGetWindowRect(gfx::NativeViewId window_id, gfx::Rect* results); + void OnMsgGetRootWindowRect(gfx::NativeViewId window_id, gfx::Rect* results); + void OnMsgPluginFocusChanged(bool focused, int plugin_id); + void OnMsgStartPluginIme(); + void OnAllocateFakePluginWindowHandle(bool opaque, + bool root, + gfx::PluginWindowHandle* id); + void OnDestroyFakePluginWindowHandle(gfx::PluginWindowHandle id); + void OnAcceleratedSurfaceSetIOSurface(gfx::PluginWindowHandle window, + int32 width, + int32 height, + uint64 mach_port); + void OnAcceleratedSurfaceSetTransportDIB(gfx::PluginWindowHandle window, + int32 width, + int32 height, + TransportDIB::Handle transport_dib); + void OnAcceleratedSurfaceBuffersSwapped(gfx::PluginWindowHandle window, + uint64 surface_id); +#elif defined(OS_POSIX) + void OnMsgCreatePluginContainer(gfx::PluginWindowHandle id); + void OnMsgDestroyPluginContainer(gfx::PluginWindowHandle id); +#endif + + // Paints the given bitmap to the current backing store at the given location. + void PaintBackingStoreRect(TransportDIB::Id bitmap, + const gfx::Rect& bitmap_rect, + const std::vector<gfx::Rect>& copy_rects, + const gfx::Size& view_size); + + // Scrolls the given |clip_rect| in the backing by the given dx/dy amount. The + // |dib| and its corresponding location |bitmap_rect| in the backing store + // is the newly painted pixels by the renderer. + void ScrollBackingStoreRect(int dx, int dy, const gfx::Rect& clip_rect, + const gfx::Size& view_size); + + // Called by OnMsgInputEventAck() to process a keyboard event ack message. + void ProcessKeyboardEventAck(int type, bool processed); + + // Called by OnMsgInputEventAck() to process a wheel event ack message. + // This could result in a task being posted to allow additional wheel + // input messages to be coalesced. + void ProcessWheelAck(); + + // True if renderer accessibility is enabled. This should only be set when a + // screenreader is detected as it can potentially slow down Chrome. + bool renderer_accessible_; + + // The View associated with the RenderViewHost. The lifetime of this object + // is associated with the lifetime of the Render process. If the Renderer + // crashes, its View is destroyed and this pointer becomes NULL, even though + // render_view_host_ lives on to load another URL (creating a new View while + // doing so). + RenderWidgetHostView* view_; + + // Created during construction but initialized during Init*(). Therefore, it + // is guaranteed never to be NULL, but its channel may be NULL if the + // renderer crashed, so you must always check that. + RenderProcessHost* process_; + + // Stores random bits of data for others to associate with this object. + PropertyBag property_bag_; + + // The ID of the corresponding object in the Renderer Instance. + int routing_id_; + + // Indicates whether a page is loading or not. + bool is_loading_; + + // Indicates whether a page is hidden or not. + bool is_hidden_; + + // True when a page is rendered directly via the GPU process. + bool is_accelerated_compositing_active_; + + // Set if we are waiting for a repaint ack for the view. + bool repaint_ack_pending_; + + // True when waiting for RESIZE_ACK. + bool resize_ack_pending_; + + // The current size of the RenderWidget. + gfx::Size current_size_; + + // The current reserved area of the RenderWidget where contents should not be + // rendered to draw the resize corner, sidebar mini tabs etc. + gfx::Rect current_reserved_rect_; + + // The size we last sent as requested size to the renderer. |current_size_| + // is only updated once the resize message has been ack'd. This on the other + // hand is updated when the resize message is sent. This is very similar to + // |resize_ack_pending_|, but the latter is not set if the new size has width + // or height zero, which is why we need this too. + gfx::Size in_flight_size_; + + // The reserved area we last sent to the renderer. |current_reserved_rect_| + // is only updated once the resize message has been ack'd. This on the other + // hand is updated when the resize message is sent. + gfx::Rect in_flight_reserved_rect_; + + // True if a mouse move event was sent to the render view and we are waiting + // for a corresponding ViewHostMsg_HandleInputEvent_ACK message. + bool mouse_move_pending_; + + // The next mouse move event to send (only non-null while mouse_move_pending_ + // is true). + scoped_ptr<WebKit::WebMouseEvent> next_mouse_move_; + + // (Similar to |mouse_move_pending_|.) True if a mouse wheel event was sent + // and we are waiting for a corresponding ack. + bool mouse_wheel_pending_; + + typedef std::deque<WebKit::WebMouseWheelEvent> WheelEventQueue; + + // (Similar to |next_mouse_move_|.) The next mouse wheel events to send. + // Unlike mouse moves, mouse wheel events received while one is pending are + // coalesced (by accumulating deltas) if they match the previous event in + // modifiers. On the Mac, in particular, mouse wheel events are received at a + // high rate; not waiting for the ack results in jankiness, and using the same + // mechanism as for mouse moves (just dropping old events when multiple ones + // would be queued) results in very slow scrolling. + WheelEventQueue coalesced_mouse_wheel_events_; + + // The time when an input event was sent to the RenderWidget. + base::TimeTicks input_event_start_time_; + + // If true, then we should repaint when restoring even if we have a + // backingstore. This flag is set to true if we receive a paint message + // while is_hidden_ to true. Even though we tell the render widget to hide + // itself, a paint message could already be in flight at that point. + bool needs_repainting_on_restore_; + + // This is true if the renderer is currently unresponsive. + bool is_unresponsive_; + + // The following value indicates a time in the future when we would consider + // the renderer hung if it does not generate an appropriate response message. + base::Time time_when_considered_hung_; + + // This timer runs to check if time_when_considered_hung_ has past. + base::OneShotTimer<RenderWidgetHost> hung_renderer_timer_; + + // Flag to detect recursive calls to GetBackingStore(). + bool in_get_backing_store_; + + // Set when we call DidPaintRect/DidScrollRect on the view. + bool view_being_painted_; + + // Used for UMA histogram logging to measure the time for a repaint view + // operation to finish. + base::TimeTicks repaint_start_time_; + + // Queue of keyboard events that we need to track. + typedef std::deque<NativeWebKeyboardEvent> KeyQueue; + + // A queue of keyboard events. We can't trust data from the renderer so we + // stuff key events into a queue and pop them out on ACK, feeding our copy + // back to whatever unhandled handler instead of the returned version. + KeyQueue key_queue_; + + // Set to true if we shouldn't send input events from the render widget. + bool ignore_input_events_; + + // Set when we update the text direction of the selected input element. + bool text_direction_updated_; + WebKit::WebTextDirection text_direction_; + + // Set when we cancel updating the text direction. + // This flag also ignores succeeding update requests until we call + // NotifyTextDirection(). + bool text_direction_canceled_; + + // Indicates if the next sequence of Char events should be suppressed or not. + // System may translate a RawKeyDown event into zero or more Char events, + // usually we send them to the renderer directly in sequence. However, If a + // RawKeyDown event was not handled by the renderer but was handled by + // our UnhandledKeyboardEvent() method, e.g. as an accelerator key, then we + // shall not send the following sequence of Char events, which was generated + // by this RawKeyDown event, to the renderer. Otherwise the renderer may + // handle the Char events and cause unexpected behavior. + // For example, pressing alt-2 may let the browser switch to the second tab, + // but the Char event generated by alt-2 may also activate a HTML element + // if its accesskey happens to be "2", then the user may get confused when + // switching back to the original tab, because the content may already be + // changed. + bool suppress_next_char_events_; + + std::vector<gfx::PluginWindowHandle> deferred_plugin_handles_; + + // The last scroll offset of the render widget. + gfx::Point last_scroll_offset_; + + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHost); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_H_ diff --git a/chrome/browser/renderer_host/render_widget_host_unittest.cc b/content/browser/renderer_host/render_widget_host_unittest.cc index 546854e..546854e 100644 --- a/chrome/browser/renderer_host/render_widget_host_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_unittest.cc diff --git a/chrome/browser/renderer_host/render_widget_host_view.cc b/content/browser/renderer_host/render_widget_host_view.cc index 6413f3a..a3b4d8c 100644 --- a/chrome/browser/renderer_host/render_widget_host_view.cc +++ b/content/browser/renderer_host/render_widget_host_view.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/render_widget_host_view.h" +#include "content/browser/renderer_host/render_widget_host_view.h" RenderWidgetHostView::~RenderWidgetHostView() {} diff --git a/content/browser/renderer_host/render_widget_host_view.h b/content/browser/renderer_host/render_widget_host_view.h new file mode 100644 index 0000000..a3f7031 --- /dev/null +++ b/content/browser/renderer_host/render_widget_host_view.h @@ -0,0 +1,326 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_H_ +#pragma once + +#if defined(OS_MACOSX) +#include <OpenGL/OpenGL.h> +#endif + +#include <string> +#include <vector> + +#include "app/surface/transport_dib.h" +#include "base/process_util.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkColor.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextInputType.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/rect.h" + +namespace gfx { +class Rect; +class Size; +} +namespace IPC { +class Message; +} + +class BackingStore; +class RenderProcessHost; +class RenderWidgetHost; +class WebCursor; +struct NativeWebKeyboardEvent; +struct ViewHostMsg_AccessibilityNotification_Params; + +namespace webkit_glue { +struct WebAccessibility; +} + +namespace webkit { +namespace npapi { +struct WebPluginGeometry; +} +} + +// RenderWidgetHostView is an interface implemented by an object that acts as +// the "View" portion of a RenderWidgetHost. The RenderWidgetHost and its +// associated RenderProcessHost own the "Model" in this case which is the +// child renderer process. The View is responsible for receiving events from +// the surrounding environment and passing them to the RenderWidgetHost, and +// for actually displaying the content of the RenderWidgetHost when it +// changes. +class RenderWidgetHostView { + public: + virtual ~RenderWidgetHostView(); + + // Platform-specific creator. Use this to construct new RenderWidgetHostViews + // rather than using RenderWidgetHostViewWin & friends. + // + // This function must NOT size it, because the RenderView in the renderer + // wounldn't have been created yet. The widget would set its "waiting for + // resize ack" flag, and the ack would never come becasue no RenderView + // received it. + // + // The RenderWidgetHost must already be created (because we can't know if it's + // going to be a regular RenderWidgetHost or a RenderViewHost (a subclass). + static RenderWidgetHostView* CreateViewForWidget(RenderWidgetHost* widget); + + // Retrieves the RenderWidgetHostView corresponding to the specified + // |native_view|, or NULL if there is no such instance. + static RenderWidgetHostView* GetRenderWidgetHostViewFromNativeView( + gfx::NativeView native_view); + + // Perform all the initialization steps necessary for this object to represent + // a popup (such as a <select> dropdown), then shows the popup at |pos|. + virtual void InitAsPopup(RenderWidgetHostView* parent_host_view, + const gfx::Rect& pos) = 0; + + // Perform all the initialization steps necessary for this object to represent + // a full screen window. + virtual void InitAsFullscreen() = 0; + + // Returns the associated RenderWidgetHost. + virtual RenderWidgetHost* GetRenderWidgetHost() const = 0; + + // Notifies the View that it has become visible. + virtual void DidBecomeSelected() = 0; + + // Notifies the View that it has been hidden. + virtual void WasHidden() = 0; + + // Tells the View to size itself to the specified size. + virtual void SetSize(const gfx::Size& size) = 0; + + // Retrieves the native view used to contain plugins and identify the + // renderer in IPC messages. + virtual gfx::NativeView GetNativeView() = 0; + + // Moves all plugin windows as described in the given list. + virtual void MovePluginWindows( + const std::vector<webkit::npapi::WebPluginGeometry>& moves) = 0; + + // Actually set/take focus to/from the associated View component. + virtual void Focus() = 0; + virtual void Blur() = 0; + + // Returns true if the View currently has the focus. + virtual bool HasFocus() = 0; + + // Shows/hides the view. These must always be called together in pairs. + // It is not legal to call Hide() multiple times in a row. + virtual void Show() = 0; + virtual void Hide() = 0; + + // Whether the view is showing. + virtual bool IsShowing() = 0; + + // Retrieve the bounds of the View, in screen coordinates. + virtual gfx::Rect GetViewBounds() const = 0; + + // Sets the cursor to the one associated with the specified cursor_type + virtual void UpdateCursor(const WebCursor& cursor) = 0; + + // Indicates whether the page has finished loading. + virtual void SetIsLoading(bool is_loading) = 0; + + // Updates the state of the input method attached to the view. + virtual void ImeUpdateTextInputState(WebKit::WebTextInputType type, + const gfx::Rect& caret_rect) = 0; + + // Cancel the ongoing composition of the input method attached to the view. + virtual void ImeCancelComposition() = 0; + + // Informs the view that a portion of the widget's backing store was scrolled + // and/or painted. The view should ensure this gets copied to the screen. + // + // If the scroll_rect is non-empty, then a portion of the widget's backing + // store was scrolled by dx pixels horizontally and dy pixels vertically. + // The exposed rect from the scroll operation is included in copy_rects. + // + // There are subtle performance implications here. The RenderWidget gets sent + // a paint ack after this returns, so if the view only ever invalidates in + // response to this, then on Windows, where WM_PAINT has lower priority than + // events which can cause renderer resizes/paint rect updates, e.g. + // drag-resizing can starve painting; this function thus provides the view its + // main chance to ensure it stays painted and not just invalidated. On the + // other hand, if this always blindly paints, then if we're already in the + // midst of a paint on the callstack, we can double-paint unnecessarily. + // (Worse, we might recursively call RenderWidgetHost::GetBackingStore().) + // Thus implementers should generally paint as much of |rect| as possible + // synchronously with as little overpainting as possible. + virtual void DidUpdateBackingStore( + const gfx::Rect& scroll_rect, int scroll_dx, int scroll_dy, + const std::vector<gfx::Rect>& copy_rects) = 0; + + // Notifies the View that the renderer has ceased to exist. + virtual void RenderViewGone(base::TerminationStatus status, + int error_code) = 0; + + // Notifies the View that the renderer will be delete soon. + virtual void WillDestroyRenderWidget(RenderWidgetHost* rwh) = 0; + + // Tells the View to destroy itself. + virtual void Destroy() = 0; + + // Tells the View that the tooltip text for the current mouse position over + // the page has changed. + virtual void SetTooltipText(const std::wstring& tooltip_text) = 0; + + // Notifies the View that the renderer text selection has changed. + virtual void SelectionChanged(const std::string& text) {} + + // Tells the View whether the context menu is showing. This is used on Linux + // to suppress updates to webkit focus for the duration of the show. + virtual void ShowingContextMenu(bool showing) {} + + // Allocate a backing store for this view + virtual BackingStore* AllocBackingStore(const gfx::Size& size) = 0; + +#if defined(OS_MACOSX) + // Tells the view whether or not to accept first responder status. If |flag| + // is true, the view does not accept first responder status and instead + // manually becomes first responder when it receives a mouse down event. If + // |flag| is false, the view participates in the key-view chain as normal. + virtual void SetTakesFocusOnlyOnMouseDown(bool flag) = 0; + + // Retrieve the bounds of the view, in cocoa view coordinates. + // If the UI scale factor is 2, |GetViewBounds()| will return a size of e.g. + // (400, 300) in pixels, while this method will return (200, 150). + // Even though this returns an gfx::Rect, the result is NOT IN PIXELS. + virtual gfx::Rect GetViewCocoaBounds() const = 0; + + // Get the view's window's position on the screen. + virtual gfx::Rect GetRootWindowRect() = 0; + + // Set the view's active state (i.e., tint state of controls). + virtual void SetActive(bool active) = 0; + + // Notifies the view that its enclosing window has changed visibility + // (minimized/unminimized, app hidden/unhidden, etc). + // TODO(stuartmorgan): This is a temporary plugin-specific workaround for + // <http://crbug.com/34266>. Once that is fixed, this (and the corresponding + // message and renderer-side handling) can be removed in favor of using + // WasHidden/DidBecomeSelected. + virtual void SetWindowVisibility(bool visible) = 0; + + // Informs the view that its containing window's frame changed. + virtual void WindowFrameChanged() = 0; + + // Informs the view that a plugin gained or lost focus. + virtual void PluginFocusChanged(bool focused, int plugin_id) = 0; + + // Start plugin IME. + virtual void StartPluginIme() = 0; + + // Does any event handling necessary for plugin IME; should be called after + // the plugin has already had a chance to process the event. If plugin IME is + // not enabled, this is a no-op, so it is always safe to call. + // Returns true if the event was handled by IME. + virtual bool PostProcessEventForPluginIme( + const NativeWebKeyboardEvent& event) = 0; + + // Methods associated with GPU-accelerated plug-in instances. + virtual gfx::PluginWindowHandle AllocateFakePluginWindowHandle( + bool opaque, bool root) = 0; + virtual void DestroyFakePluginWindowHandle( + gfx::PluginWindowHandle window) = 0; + virtual void AcceleratedSurfaceSetIOSurface( + gfx::PluginWindowHandle window, + int32 width, + int32 height, + uint64 io_surface_identifier) = 0; + virtual void AcceleratedSurfaceSetTransportDIB( + gfx::PluginWindowHandle window, + int32 width, + int32 height, + TransportDIB::Handle transport_dib) = 0; + // |window| and |surface_id| indicate which accelerated surface's + // buffers swapped. |renderer_id|, |route_id| and + // |swap_buffers_count| are used to formulate a reply to the GPU + // process to prevent it from getting too far ahead. They may all be + // zero, in which case no flow control is enforced; this case is + // currently used for accelerated plugins. + virtual void AcceleratedSurfaceBuffersSwapped( + gfx::PluginWindowHandle window, + uint64 surface_id, + int renderer_id, + int32 route_id, + uint64 swap_buffers_count) = 0; + virtual void GpuRenderingStateDidChange() = 0; +#endif + +#if defined(TOOLKIT_USES_GTK) + virtual void CreatePluginContainer(gfx::PluginWindowHandle id) = 0; + virtual void DestroyPluginContainer(gfx::PluginWindowHandle id) = 0; + virtual void AcceleratedCompositingActivated(bool activated) = 0; +#endif + +#if defined(OS_WIN) + virtual void WillWmDestroy() = 0; + virtual void ShowCompositorHostWindow(bool show) = 0; +#endif + + virtual gfx::PluginWindowHandle AcquireCompositingSurface() = 0; + virtual void ReleaseCompositingSurface(gfx::PluginWindowHandle surface) = 0; + + // Toggles visual muting of the render view area. This is on when a + // constrained window is showing, for example. |color| is the shade of + // the overlay that covers the render view. If |animate| is true, the overlay + // gradually fades in; otherwise it takes effect immediately. To remove the + // fade effect, pass a NULL value for |color|. In this case, |animate| is + // ignored. + virtual void SetVisuallyDeemphasized(const SkColor* color, bool animate) = 0; + + void set_popup_type(WebKit::WebPopupType popup_type) { + popup_type_ = popup_type; + } + WebKit::WebPopupType popup_type() const { return popup_type_; } + + // Subclasses should override this method to do what is appropriate to set + // the custom background for their platform. + virtual void SetBackground(const SkBitmap& background); + const SkBitmap& background() const { return background_; } + + // Returns true if the native view, |native_view|, is contained within in the + // widget associated with this RenderWidgetHostView. + virtual bool ContainsNativeView(gfx::NativeView native_view) const = 0; + + virtual void UpdateAccessibilityTree( + const webkit_glue::WebAccessibility& tree) { } + virtual void OnAccessibilityNotifications( + const std::vector<ViewHostMsg_AccessibilityNotification_Params>& params) { + } + + gfx::Rect reserved_contents_rect() const { + return reserved_rect_; + } + void set_reserved_contents_rect(const gfx::Rect& reserved_rect) { + reserved_rect_ = reserved_rect; + } + + protected: + // Interface class only, do not construct. + RenderWidgetHostView() : popup_type_(WebKit::WebPopupTypeNone) {} + + // Whether this view is a popup and what kind of popup it is (select, + // autofill...). + WebKit::WebPopupType popup_type_; + + // A custom background to paint behind the web content. This will be tiled + // horizontally. Can be null, in which case we fall back to painting white. + SkBitmap background_; + + // The current reserved area in view coordinates where contents should not be + // rendered to draw the resize corner, sidebar mini tabs etc. + gfx::Rect reserved_rect_; + + private: + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostView); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_H_ diff --git a/chrome/browser/renderer_host/resource_dispatcher_host.cc b/content/browser/renderer_host/resource_dispatcher_host.cc index a93dcb8..94f5c5e 100644 --- a/chrome/browser/renderer_host/resource_dispatcher_host.cc +++ b/content/browser/renderer_host/resource_dispatcher_host.cc @@ -4,7 +4,7 @@ // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" #include <set> #include <vector> @@ -35,22 +35,9 @@ #include "chrome/browser/prerender/prerender_manager.h" #include "chrome/browser/prerender/prerender_resource_handler.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/renderer_host/async_resource_handler.h" -#include "chrome/browser/renderer_host/buffered_resource_handler.h" -#include "chrome/browser/renderer_host/cross_site_resource_handler.h" #include "chrome/browser/renderer_host/download_resource_handler.h" -#include "chrome/browser/renderer_host/global_request_id.h" -#include "chrome/browser/renderer_host/redirect_to_file_resource_handler.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "chrome/browser/renderer_host/render_view_host_delegate.h" -#include "chrome/browser/renderer_host/render_view_host_notification_task.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" -#include "chrome/browser/renderer_host/resource_message_filter.h" -#include "chrome/browser/renderer_host/resource_queue.h" -#include "chrome/browser/renderer_host/resource_request_details.h" #include "chrome/browser/renderer_host/safe_browsing_resource_handler.h" #include "chrome/browser/renderer_host/save_file_resource_handler.h" -#include "chrome/browser/renderer_host/sync_resource_handler.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/browser/ssl/ssl_client_auth_handler.h" #include "chrome/browser/ssl/ssl_manager.h" @@ -61,6 +48,19 @@ #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" #include "chrome/common/url_constants.h" +#include "content/browser/renderer_host/async_resource_handler.h" +#include "content/browser/renderer_host/buffered_resource_handler.h" +#include "content/browser/renderer_host/cross_site_resource_handler.h" +#include "content/browser/renderer_host/global_request_id.h" +#include "content/browser/renderer_host/redirect_to_file_resource_handler.h" +#include "content/browser/renderer_host/render_view_host.h" +#include "content/browser/renderer_host/render_view_host_delegate.h" +#include "content/browser/renderer_host/render_view_host_notification_task.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/resource_message_filter.h" +#include "content/browser/renderer_host/resource_queue.h" +#include "content/browser/renderer_host/resource_request_details.h" +#include "content/browser/renderer_host/sync_resource_handler.h" #include "net/base/auth.h" #include "net/base/cert_status_flags.h" #include "net/base/cookie_monster.h" diff --git a/content/browser/renderer_host/resource_dispatcher_host.h b/content/browser/renderer_host/resource_dispatcher_host.h new file mode 100644 index 0000000..fb78dcc --- /dev/null +++ b/content/browser/renderer_host/resource_dispatcher_host.h @@ -0,0 +1,516 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This is the browser side of the resource dispatcher, it receives requests +// from the child process (i.e. [Renderer, Plugin, Worker]ProcessHost), and +// dispatches them to URLRequests. It then forwards the messages from the +// URLRequests back to the correct process for handling. +// +// See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_H_ +#pragma once + +#include <map> +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "base/gtest_prod_util.h" +#include "base/observer_list.h" +#include "base/scoped_ptr.h" +#include "base/timer.h" +#include "chrome/common/child_process_info.h" +#include "chrome/common/notification_type.h" +#include "content/browser/renderer_host/resource_queue.h" +#include "ipc/ipc_message.h" +#include "net/url_request/url_request.h" +#include "webkit/glue/resource_type.h" + +class CrossSiteResourceHandler; +class DownloadFileManager; +class DownloadRequestLimiter; +class LoginHandler; +class NotificationDetails; +class PluginService; +class ResourceDispatcherHostRequestInfo; +class ResourceHandler; +class ResourceMessageFilter; +class SafeBrowsingService; +class SaveFileManager; +class SSLClientAuthHandler; +class UserScriptListener; +class WebKitThread; +struct DownloadSaveInfo; +struct GlobalRequestID; +struct ViewHostMsg_Resource_Request; +struct ViewMsg_ClosePage_Params; + +namespace net { +class URLRequestContext; +} // namespace net + +namespace webkit_blob { +class DeletableFileReference; +} + +class ResourceDispatcherHost : public net::URLRequest::Delegate { + public: + class Observer { + public: + virtual ~Observer() {} + virtual void OnRequestStarted(ResourceDispatcherHost* resource_dispatcher, + net::URLRequest* request) = 0; + virtual void OnResponseCompleted( + ResourceDispatcherHost* resource_dispatcher, + net::URLRequest* request) = 0; + virtual void OnReceivedRedirect(ResourceDispatcherHost* resource_dispatcher, + net::URLRequest* request, + const GURL& new_url) = 0; + }; + + ResourceDispatcherHost(); + ~ResourceDispatcherHost(); + + void Initialize(); + + // Puts the resource dispatcher host in an inactive state (unable to begin + // new requests). Cancels all pending requests. + void Shutdown(); + + // Returns true if the message was a resource message that was processed. + // If it was, message_was_ok will be false iff the message was corrupt. + bool OnMessageReceived(const IPC::Message& message, + ResourceMessageFilter* filter, + bool* message_was_ok); + + // Initiates a download from the browser process (as opposed to a resource + // request from the renderer or another child process). + void BeginDownload(const GURL& url, + const GURL& referrer, + const DownloadSaveInfo& save_info, + bool prompt_for_save_location, + int process_unique_id, + int route_id, + net::URLRequestContext* request_context); + + // Initiates a save file from the browser process (as opposed to a resource + // request from the renderer or another child process). + void BeginSaveFile(const GURL& url, + const GURL& referrer, + int process_unique_id, + int route_id, + net::URLRequestContext* request_context); + + // Cancels the given request if it still exists. We ignore cancels from the + // renderer in the event of a download. + void CancelRequest(int process_unique_id, + int request_id, + bool from_renderer); + + // Follows a deferred redirect for the given request. + // new_first_party_for_cookies, if non-empty, is the new cookie policy URL + // for the redirected URL. If the cookie policy URL needs changing, pass + // true as has_new_first_party_for_cookies and the new cookie policy URL as + // new_first_party_for_cookies. Otherwise, pass false as + // has_new_first_party_for_cookies, and new_first_party_for_cookies will not + // be used. + void FollowDeferredRedirect(int process_unique_id, + int request_id, + bool has_new_first_party_for_cookies, + const GURL& new_first_party_for_cookies); + + // Starts a request that was deferred during ResourceHandler::OnWillStart(). + void StartDeferredRequest(int process_unique_id, int request_id); + + // Returns true if it's ok to send the data. If there are already too many + // data messages pending, it pauses the request and returns false. In this + // case the caller should not send the data. + bool WillSendData(int process_unique_id, int request_id); + + // Pauses or resumes network activity for a particular request. + void PauseRequest(int process_unique_id, int request_id, bool pause); + + // Returns the number of pending requests. This is designed for the unittests + int pending_requests() const { + return static_cast<int>(pending_requests_.size()); + } + + // Intended for unit-tests only. Returns the memory cost of all the + // outstanding requests (pending and blocked) for |process_unique_id|. + int GetOutstandingRequestsMemoryCost(int process_unique_id) const; + + // Intended for unit-tests only. Overrides the outstanding requests bound. + void set_max_outstanding_requests_cost_per_process(int limit) { + max_outstanding_requests_cost_per_process_ = limit; + } + + // The average private bytes increase of the browser for each new pending + // request. Experimentally obtained. + static const int kAvgBytesPerOutstandingRequest = 4400; + + DownloadFileManager* download_file_manager() const { + return download_file_manager_; + } + + DownloadRequestLimiter* download_request_limiter() const { + return download_request_limiter_.get(); + } + + SaveFileManager* save_file_manager() const { + return save_file_manager_; + } + + SafeBrowsingService* safe_browsing_service() const { + return safe_browsing_; + } + + WebKitThread* webkit_thread() const { + return webkit_thread_.get(); + } + + // Called when the onunload handler for a cross-site request has finished. + void OnClosePageACK(const ViewMsg_ClosePage_Params& params); + + // Force cancels any pending requests for the given process. + void CancelRequestsForProcess(int process_unique_id); + + // Force cancels any pending requests for the given route id. This method + // acts like CancelRequestsForProcess when route_id is -1. + void CancelRequestsForRoute(int process_unique_id, int route_id); + + // net::URLRequest::Delegate + virtual void OnReceivedRedirect(net::URLRequest* request, + const GURL& new_url, + bool* defer_redirect); + virtual void OnAuthRequired(net::URLRequest* request, + net::AuthChallengeInfo* auth_info); + virtual void OnCertificateRequested( + net::URLRequest* request, + net::SSLCertRequestInfo* cert_request_info); + virtual void OnSSLCertificateError(net::URLRequest* request, + int cert_error, + net::X509Certificate* cert); + virtual void OnGetCookies(net::URLRequest* request, + bool blocked_by_policy); + virtual void OnSetCookie(net::URLRequest* request, + const std::string& cookie_line, + const net::CookieOptions& options, + bool blocked_by_policy); + virtual void OnResponseStarted(net::URLRequest* request); + virtual void OnReadCompleted(net::URLRequest* request, int bytes_read); + void OnResponseCompleted(net::URLRequest* request); + + // Helper functions to get our extra data out of a request. The given request + // must have been one we created so that it has the proper extra data pointer. + static ResourceDispatcherHostRequestInfo* InfoForRequest( + net::URLRequest* request); + static const ResourceDispatcherHostRequestInfo* InfoForRequest( + const net::URLRequest* request); + + // Extracts the render view/process host's identifiers from the given request + // and places them in the given out params (both required). If there are no + // such IDs associated with the request (such as non-page-related requests), + // this function will return false and both out params will be -1. + static bool RenderViewForRequest(const net::URLRequest* request, + int* render_process_host_id, + int* render_view_host_id); + + // Adds an observer. The observer will be called on the IO thread. To + // observe resource events on the UI thread, subscribe to the + // NOTIFY_RESOURCE_* notifications of the notification service. + void AddObserver(Observer* obs); + + // Removes an observer. + void RemoveObserver(Observer* obs); + + // Retrieves a net::URLRequest. Must be called from the IO thread. + net::URLRequest* GetURLRequest(const GlobalRequestID& request_id) const; + + // Notifies our observers that a request has been cancelled. + void NotifyResponseCompleted(net::URLRequest* request, int process_unique_id); + + void RemovePendingRequest(int process_unique_id, int request_id); + + // Causes all new requests for the route identified by + // |process_unique_id| and |route_id| to be blocked (not being + // started) until ResumeBlockedRequestsForRoute or + // CancelBlockedRequestsForRoute is called. + void BlockRequestsForRoute(int process_unique_id, int route_id); + + // Resumes any blocked request for the specified route id. + void ResumeBlockedRequestsForRoute(int process_unique_id, int route_id); + + // Cancels any blocked request for the specified route id. + void CancelBlockedRequestsForRoute(int process_unique_id, int route_id); + + // Decrements the pending_data_count for the request and resumes + // the request if it was paused due to too many pending data + // messages sent. + void DataReceivedACK(int process_unique_id, int request_id); + + // Maintains a collection of temp files created in support of + // the download_to_file capability. Used to grant access to the + // child process and to defer deletion of the file until it's + // no longer needed. + void RegisterDownloadedTempFile( + int child_id, int request_id, + webkit_blob::DeletableFileReference* reference); + void UnregisterDownloadedTempFile(int child_id, int request_id); + + // Needed for the sync IPC message dispatcher macros. + bool Send(IPC::Message* message); + + // Controls if we launch or squash prefetch requests as they arrive + // from renderers. + static bool is_prefetch_enabled(); + static void set_is_prefetch_enabled(bool value); + + private: + FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, + TestBlockedRequestsProcessDies); + FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, + IncrementOutstandingRequestsMemoryCost); + FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest, + CalculateApproximateMemoryCost); + FRIEND_TEST_ALL_PREFIXES(ApplyExtensionLocalizationFilterTest, WrongScheme); + FRIEND_TEST_ALL_PREFIXES(ApplyExtensionLocalizationFilterTest, GoodScheme); + FRIEND_TEST_ALL_PREFIXES(ApplyExtensionLocalizationFilterTest, + GoodSchemeWrongResourceType); + + class ShutdownTask; + + friend class ShutdownTask; + + // Associates the given info with the given request. The info will then be + // owned by the request. + void SetRequestInfo(net::URLRequest* request, + ResourceDispatcherHostRequestInfo* info); + + // A shutdown helper that runs on the IO thread. + void OnShutdown(); + + // Returns true if the request is paused. + bool PauseRequestIfNeeded(ResourceDispatcherHostRequestInfo* info); + + // Resumes the given request by calling OnResponseStarted or OnReadCompleted. + void ResumeRequest(const GlobalRequestID& request_id); + + // Internal function to start reading for the first time. + void StartReading(net::URLRequest* request); + + // Reads data from the response using our internal buffer as async IO. + // Returns true if data is available immediately, false otherwise. If the + // return value is false, we will receive a OnReadComplete() callback later. + bool Read(net::URLRequest* request, int* bytes_read); + + // Internal function to finish an async IO which has completed. Returns + // true if there is more data to read (e.g. we haven't read EOF yet and + // no errors have occurred). + bool CompleteRead(net::URLRequest*, int* bytes_read); + + // Internal function to finish handling the ResponseStarted message. Returns + // true on success. + bool CompleteResponseStarted(net::URLRequest* request); + + // Helper function for regular and download requests. + void BeginRequestInternal(net::URLRequest* request); + + // Helper function that cancels |request|. + void CancelRequestInternal(net::URLRequest* request, bool from_renderer); + + // Helper function that inserts |request| into the resource queue. + void InsertIntoResourceQueue( + net::URLRequest* request, + const ResourceDispatcherHostRequestInfo& request_info); + + // Updates the "cost" of outstanding requests for |process_unique_id|. + // The "cost" approximates how many bytes are consumed by all the in-memory + // data structures supporting this request (net::URLRequest object, + // HttpNetworkTransaction, etc...). + // The value of |cost| is added to the running total, and the resulting + // sum is returned. + int IncrementOutstandingRequestsMemoryCost(int cost, + int process_unique_id); + + // Estimate how much heap space |request| will consume to run. + static int CalculateApproximateMemoryCost(net::URLRequest* request); + + // The list of all requests that we have pending. This list is not really + // optimized, and assumes that we have relatively few requests pending at once + // since some operations require brute-force searching of the list. + // + // It may be enhanced in the future to provide some kind of prioritization + // mechanism. We should also consider a hashtable or binary tree if it turns + // out we have a lot of things here. + typedef std::map<GlobalRequestID, net::URLRequest*> PendingRequestList; + + // Deletes the pending request identified by the iterator passed in. + // This function will invalidate the iterator passed in. Callers should + // not rely on this iterator being valid on return. + void RemovePendingRequest(const PendingRequestList::iterator& iter); + + // Notify our observers that we started receiving a response for a request. + void NotifyResponseStarted(net::URLRequest* request, int process_unique_id); + + // Notify our observers that a request has been redirected. + void NotifyReceivedRedirect(net::URLRequest* request, + int process_unique_id, + const GURL& new_url); + + // Tries to handle the url with an external protocol. If the request is + // handled, the function returns true. False otherwise. + bool HandleExternalProtocol(int request_id, + int process_unique_id, + int route_id, + const GURL& url, + ResourceType::Type resource_type, + ResourceHandler* handler); + + // Checks all pending requests and updates the load states and upload + // progress if necessary. + void UpdateLoadStates(); + + // Checks the upload state and sends an update if one is necessary. + bool MaybeUpdateUploadProgress(ResourceDispatcherHostRequestInfo *info, + net::URLRequest *request); + + // Resumes or cancels (if |cancel_requests| is true) any blocked requests. + void ProcessBlockedRequestsForRoute(int process_unique_id, + int route_id, + bool cancel_requests); + + void OnRequestResource(const IPC::Message& msg, + int request_id, + const ViewHostMsg_Resource_Request& request_data); + void OnSyncLoad(int request_id, + const ViewHostMsg_Resource_Request& request_data, + IPC::Message* sync_result); + void BeginRequest(int request_id, + const ViewHostMsg_Resource_Request& request_data, + IPC::Message* sync_result, // only valid for sync + int route_id); // only valid for async + void OnDataReceivedACK(int request_id); + void OnDataDownloadedACK(int request_id); + void OnUploadProgressACK(int request_id); + void OnCancelRequest(int request_id); + void OnFollowRedirect(int request_id, + bool has_new_first_party_for_cookies, + const GURL& new_first_party_for_cookies); + void OnReleaseDownloadedFile(int request_id); + + ResourceHandler* CreateSafeBrowsingResourceHandler( + ResourceHandler* handler, int child_id, int route_id, + ResourceType::Type resource_type); + + // Creates ResourceDispatcherHostRequestInfo for a browser-initiated request + // (a download or a page save). |download| should be true if the request + // is a file download. + ResourceDispatcherHostRequestInfo* CreateRequestInfoForBrowserRequest( + ResourceHandler* handler, int child_id, int route_id, bool download); + + // Returns true if |request| is in |pending_requests_|. + bool IsValidRequest(net::URLRequest* request); + + // Sets replace_extension_localization_templates on all text/css requests that + // have "chrome-extension://" scheme. + static void ApplyExtensionLocalizationFilter( + const GURL& url, + const ResourceType::Type& resource_type, + ResourceDispatcherHostRequestInfo* request_info); + + // Determine request priority based on how critical this resource typically + // is to user-perceived page load performance. + static net::RequestPriority DetermineRequestPriority(ResourceType::Type type); + + // Sends the given notification on the UI thread. The RenderViewHost's + // controller is used as the source. + template <class T> + static void NotifyOnUI(NotificationType type, + int render_process_id, + int render_view_id, + T* detail); + + PendingRequestList pending_requests_; + + // Collection of temp files downloaded for child processes via + // the download_to_file mechanism. We avoid deleting them until + // the client no longer needs them. + typedef std::map<int, scoped_refptr<webkit_blob::DeletableFileReference> > + DeletableFilesMap; // key is request id + typedef std::map<int, DeletableFilesMap> + RegisteredTempFiles; // key is child process id + RegisteredTempFiles registered_temp_files_; + + // A timer that periodically calls UpdateLoadStates while pending_requests_ + // is not empty. + base::RepeatingTimer<ResourceDispatcherHost> update_load_states_timer_; + + // Handles the resource requests from the moment we want to start them. + ResourceQueue resource_queue_; + + // We own the download file writing thread and manager + scoped_refptr<DownloadFileManager> download_file_manager_; + + // Determines whether a download is allowed. + scoped_refptr<DownloadRequestLimiter> download_request_limiter_; + + // We own the save file manager. + scoped_refptr<SaveFileManager> save_file_manager_; + + scoped_refptr<UserScriptListener> user_script_listener_; + + scoped_refptr<SafeBrowsingService> safe_browsing_; + + // We own the WebKit thread and see to its destruction. + scoped_ptr<WebKitThread> webkit_thread_; + + // Request ID for browser initiated requests. request_ids generated by + // child processes are counted up from 0, while browser created requests + // start at -2 and go down from there. (We need to start at -2 because -1 is + // used as a special value all over the resource_dispatcher_host for + // uninitialized variables.) This way, we no longer have the unlikely (but + // observed in the real world!) event where we have two requests with the same + // request_id_. + int request_id_; + + // List of objects observing resource dispatching. + ObserverList<Observer> observer_list_; + + // For running tasks. + ScopedRunnableMethodFactory<ResourceDispatcherHost> method_runner_; + + // True if the resource dispatcher host has been shut down. + bool is_shutdown_; + + typedef std::vector<net::URLRequest*> BlockedRequestsList; + typedef std::pair<int, int> ProcessRouteIDs; + typedef std::map<ProcessRouteIDs, BlockedRequestsList*> BlockedRequestMap; + BlockedRequestMap blocked_requests_map_; + + // Maps the process_unique_ids to the approximate number of bytes + // being used to service its resource requests. No entry implies 0 cost. + typedef std::map<int, int> OutstandingRequestsMemoryCostMap; + OutstandingRequestsMemoryCostMap outstanding_requests_memory_cost_map_; + + // |max_outstanding_requests_cost_per_process_| is the upper bound on how + // many outstanding requests can be issued per child process host. + // The constraint is expressed in terms of bytes (where the cost of + // individual requests is given by CalculateApproximateMemoryCost). + // The total number of outstanding requests is roughly: + // (max_outstanding_requests_cost_per_process_ / + // kAvgBytesPerOutstandingRequest) + int max_outstanding_requests_cost_per_process_; + + // Used during IPC message dispatching so that the handlers can get a pointer + // to the source of the message. + ResourceMessageFilter* filter_; + + static bool is_prefetch_enabled_; + + DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHost); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_H_ diff --git a/chrome/browser/renderer_host/resource_dispatcher_host_request_info.cc b/content/browser/renderer_host/resource_dispatcher_host_request_info.cc index d324c2a..695889e 100644 --- a/chrome/browser/renderer_host/resource_dispatcher_host_request_info.cc +++ b/content/browser/renderer_host/resource_dispatcher_host_request_info.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" -#include "chrome/browser/renderer_host/resource_handler.h" #include "chrome/browser/ssl/ssl_client_auth_handler.h" #include "chrome/browser/ui/login/login_prompt.h" +#include "content/browser/renderer_host/resource_handler.h" #include "webkit/blob/blob_data.h" ResourceDispatcherHostRequestInfo::ResourceDispatcherHostRequestInfo( diff --git a/content/browser/renderer_host/resource_dispatcher_host_request_info.h b/content/browser/renderer_host/resource_dispatcher_host_request_info.h new file mode 100644 index 0000000..c05c4f9 --- /dev/null +++ b/content/browser/renderer_host/resource_dispatcher_host_request_info.h @@ -0,0 +1,241 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_REQUEST_INFO_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_REQUEST_INFO_H_ +#pragma once + +#include <string> + +#include "base/basictypes.h" +#include "base/time.h" +#include "chrome/common/child_process_info.h" +#include "net/base/load_states.h" +#include "net/url_request/url_request.h" +#include "webkit/glue/resource_type.h" + +class CrossSiteResourceHandler; +class LoginHandler; +class ResourceDispatcherHost; +class ResourceHandler; +class SSLClientAuthHandler; + +namespace webkit_blob { +class BlobData; +} + +// Holds the data ResourceDispatcherHost associates with each request. +// Retrieve this data by calling ResourceDispatcherHost::InfoForRequest. +class ResourceDispatcherHostRequestInfo : public net::URLRequest::UserData { + public: + // This will take a reference to the handler. + ResourceDispatcherHostRequestInfo( + ResourceHandler* handler, + ChildProcessInfo::ProcessType process_type, + int child_id, + int route_id, + int request_id, + ResourceType::Type resource_type, + uint64 upload_size, + bool is_download, + bool allow_download, + bool has_user_gesture, + int host_renderer_id, + int host_render_view_id); + virtual ~ResourceDispatcherHostRequestInfo(); + + // Top-level ResourceHandler servicing this request. + ResourceHandler* resource_handler() { return resource_handler_.get(); } + + // CrossSiteResourceHandler for this request, if it is a cross-site request. + // (NULL otherwise.) This handler is part of the chain of ResourceHandlers + // pointed to by resource_handler, and is not owned by this class. + CrossSiteResourceHandler* cross_site_handler() { + return cross_site_handler_; + } + void set_cross_site_handler(CrossSiteResourceHandler* h) { + cross_site_handler_ = h; + } + + // Pointer to the login handler, or NULL if there is none for this request. + LoginHandler* login_handler() const { return login_handler_.get(); } + void set_login_handler(LoginHandler* lh); + + // Pointer to the SSL auth, or NULL if there is none for this request. + SSLClientAuthHandler* ssl_client_auth_handler() const { + return ssl_client_auth_handler_.get(); + } + void set_ssl_client_auth_handler(SSLClientAuthHandler* s); + + // Identifies the type of process (renderer, plugin, etc.) making the request. + ChildProcessInfo::ProcessType process_type() const { + return process_type_; + } + + // The child process unique ID of the requestor. This duplicates the value + // stored on the request by SetChildProcessUniqueIDForRequest in + // url_request_tracking. + int child_id() const { return child_id_; } + + // The IPC route identifier for this request (this identifies the RenderView + // or like-thing in the renderer that the request gets routed to). + int route_id() const { return route_id_; } + + // Unique identifier for this resource request. + int request_id() const { return request_id_; } + + // Number of messages we've sent to the renderer that we haven't gotten an + // ACK for. This allows us to avoid having too many messages in flight. + int pending_data_count() const { return pending_data_count_; } + void IncrementPendingDataCount() { pending_data_count_++; } + void DecrementPendingDataCount() { pending_data_count_--; } + + // Downloads are allowed only as a top level request. + bool allow_download() const { return allow_download_; } + + bool has_user_gesture() const { return has_user_gesture_; } + + // Whether this is a download. + bool is_download() const { return is_download_; } + void set_is_download(bool download) { is_download_ = download; } + + // The number of clients that have called pause on this request. + int pause_count() const { return pause_count_; } + void set_pause_count(int count) { pause_count_ = count; } + + // Identifies the type of resource, such as subframe, media, etc. + ResourceType::Type resource_type() const { return resource_type_; } + + // Whether we should apply a filter to this resource that replaces + // localization templates with the appropriate localized strings. This is set + // for CSS resources used by extensions. + bool replace_extension_localization_templates() const { + return replace_extension_localization_templates_; + } + void set_replace_extension_localization_templates() { + replace_extension_localization_templates_ = true; + } + + // Returns the last updated state of the load. This is updated periodically + // by the ResourceDispatcherHost and tracked here so we don't send out + // unnecessary state change notifications. + net::LoadState last_load_state() const { return last_load_state_; } + void set_last_load_state(net::LoadState s) { last_load_state_ = s; } + + // When there is upload data, this is the byte count of that data. When there + // is no upload, this will be 0. + uint64 upload_size() const { return upload_size_; } + void set_upload_size(uint64 upload_size) { upload_size_ = upload_size; } + + // When we're uploading data, this is the the byte offset into the uploaded + // data that we've uploaded that we've send an upload progress update about. + // The ResourceDispatcherHost will periodically update this value to track + // upload progress and make sure it doesn't sent out duplicate updates. + uint64 last_upload_position() const { return last_upload_position_; } + void set_last_upload_position(uint64 p) { last_upload_position_ = p; } + + // Indicates when the ResourceDispatcherHost last update the upload + // position. This is used to make sure we don't send too many updates. + base::TimeTicks last_upload_ticks() const { return last_upload_ticks_; } + void set_last_upload_ticks(base::TimeTicks t) { last_upload_ticks_ = t; } + + // Set when the ResourceDispatcherHost has sent out an upload progress, and + // cleared whtn the ACK is received. This is used to throttle updates so + // multiple updates aren't in flight at once. + bool waiting_for_upload_progress_ack() const { + return waiting_for_upload_progress_ack_; + } + void set_waiting_for_upload_progress_ack(bool waiting) { + waiting_for_upload_progress_ack_ = waiting; + } + + // The approximate in-memory size (bytes) that we credited this request + // as consuming in |outstanding_requests_memory_cost_map_|. + int memory_cost() const { return memory_cost_; } + void set_memory_cost(int cost) { memory_cost_ = cost; } + + int host_renderer_id() const { return host_renderer_id_; } + int host_render_view_id() const { return host_render_view_id_; } + + // We hold a reference to the requested blob data to ensure it doesn't + // get finally released prior to the net::URLRequestJob being started. + webkit_blob::BlobData* requested_blob_data() const { + return requested_blob_data_.get(); + } + void set_requested_blob_data(webkit_blob::BlobData* data); + + private: + friend class ResourceDispatcherHost; + + // Request is temporarily not handling network data. Should be used only + // by the ResourceDispatcherHost, not the event handlers (accessors are + // provided for consistency with the rest of the interface). + bool is_paused() const { return is_paused_; } + void set_is_paused(bool paused) { is_paused_ = paused; } + + // Whether we called OnResponseStarted for this request or not. Should be used + // only by the ResourceDispatcherHost, not the event handlers (accessors are + // provided for consistency with the rest of the interface). + bool called_on_response_started() const { + return called_on_response_started_; + } + void set_called_on_response_started(bool called) { + called_on_response_started_ = called; + } + + // Whether this request has started reading any bytes from the response + // yet. Will be true after the first (unpaused) call to Read. Should be used + // only by the ResourceDispatcherHost, not the event handlers (accessors are + // provided for consistency with the rest of the interface). + bool has_started_reading() const { return has_started_reading_; } + void set_has_started_reading(bool reading) { has_started_reading_ = reading; } + + // How many bytes have been read while this request has been paused. Should be + // used only by the ResourceDispatcherHost, not the event handlers (accessors + // are provided for consistency with the rest of the interface). + int paused_read_bytes() const { return paused_read_bytes_; } + void set_paused_read_bytes(int bytes) { paused_read_bytes_ = bytes; } + + scoped_refptr<ResourceHandler> resource_handler_; + CrossSiteResourceHandler* cross_site_handler_; // Non-owning, may be NULL. + scoped_refptr<LoginHandler> login_handler_; + scoped_refptr<SSLClientAuthHandler> ssl_client_auth_handler_; + ChildProcessInfo::ProcessType process_type_; + int child_id_; + int route_id_; + int request_id_; + int pending_data_count_; + bool is_download_; + bool allow_download_; + bool has_user_gesture_; + int pause_count_; + ResourceType::Type resource_type_; + bool replace_extension_localization_templates_; + net::LoadState last_load_state_; + uint64 upload_size_; + uint64 last_upload_position_; + base::TimeTicks last_upload_ticks_; + bool waiting_for_upload_progress_ack_; + int memory_cost_; + scoped_refptr<webkit_blob::BlobData> requested_blob_data_; + + // "Private" data accessible only to ResourceDispatcherHost (use the + // accessors above for consistency). + bool is_paused_; + bool called_on_response_started_; + bool has_started_reading_; + int paused_read_bytes_; + + // The following two members are specified if the request is initiated by + // a plugin like Gears. + + // Contains the id of the host renderer. + int host_renderer_id_; + // Contains the id of the host render view. + int host_render_view_id_; + + DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHostRequestInfo); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RESOURCE_DISPATCHER_HOST_REQUEST_INFO_H_ diff --git a/chrome/browser/renderer_host/resource_dispatcher_host_uitest.cc b/content/browser/renderer_host/resource_dispatcher_host_uitest.cc index 5271595..5271595 100644 --- a/chrome/browser/renderer_host/resource_dispatcher_host_uitest.cc +++ b/content/browser/renderer_host/resource_dispatcher_host_uitest.cc diff --git a/chrome/browser/renderer_host/resource_dispatcher_host_unittest.cc b/content/browser/renderer_host/resource_dispatcher_host_unittest.cc index d996f31..e68c3b9 100644 --- a/chrome/browser/renderer_host/resource_dispatcher_host_unittest.cc +++ b/content/browser/renderer_host/resource_dispatcher_host_unittest.cc @@ -9,14 +9,14 @@ #include "base/process_util.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/child_process_security_policy.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" -#include "chrome/browser/renderer_host/resource_handler.h" -#include "chrome/browser/renderer_host/resource_message_filter.h" #include "chrome/common/chrome_plugin_lib.h" #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" #include "chrome/common/resource_response.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/resource_handler.h" +#include "content/browser/renderer_host/resource_message_filter.h" #include "net/base/net_errors.h" #include "net/base/upload_data.h" #include "net/http/http_util.h" diff --git a/content/browser/renderer_host/resource_handler.h b/content/browser/renderer_host/resource_handler.h new file mode 100644 index 0000000..c4de36e --- /dev/null +++ b/content/browser/renderer_host/resource_handler.h @@ -0,0 +1,96 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This is the browser side of the resource dispatcher, it receives requests +// from the RenderProcessHosts, and dispatches them to URLRequests. It then +// fowards the messages from the URLRequests back to the correct process for +// handling. +// +// See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RESOURCE_HANDLER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RESOURCE_HANDLER_H_ +#pragma once + +#include <string> + +#include "chrome/browser/browser_thread.h" + +namespace net { +class IOBuffer; +class URLRequestStatus; +} // namespace net + +struct ResourceResponse; +class GURL; + +// The resource dispatcher host uses this interface to push load events to the +// renderer, allowing for differences in the types of IPC messages generated. +// See the implementations of this interface defined below. +class ResourceHandler + : public base::RefCountedThreadSafe< + ResourceHandler, BrowserThread::DeleteOnIOThread> { + public: + // Called as upload progress is made. + virtual bool OnUploadProgress(int request_id, + uint64 position, + uint64 size) = 0; + + // The request was redirected to a new URL. |*defer| has an initial value of + // false. Set |*defer| to true to defer the redirect. The redirect may be + // followed later on via ResourceDispatcherHost::FollowDeferredRedirect. + virtual bool OnRequestRedirected(int request_id, const GURL& url, + ResourceResponse* response, + bool* defer) = 0; + + // Response headers and meta data are available. + virtual bool OnResponseStarted(int request_id, + ResourceResponse* response) = 0; + + // Called before the net::URLRequest for |request_id| (whose url is |url|) is + // to be started. If the handler returns false, then the request is cancelled. + // Otherwise if the return value is true, the ResourceHandler can delay the + // request from starting by setting |*defer = true|. A deferred request will + // not have called net::URLRequest::Start(), and will not resume until someone + // calls ResourceDispatcherHost::StartDeferredRequest(). + virtual bool OnWillStart(int request_id, const GURL& url, bool* defer) = 0; + + // Data will be read for the response. Upon success, this method places the + // size and address of the buffer where the data is to be written in its + // out-params. This call will be followed by either OnReadCompleted or + // OnResponseCompleted, at which point the buffer may be recycled. + virtual bool OnWillRead(int request_id, + net::IOBuffer** buf, + int* buf_size, + int min_size) = 0; + + // Data (*bytes_read bytes) was written into the buffer provided by + // OnWillRead. A return value of false cancels the request, true continues + // reading data. + virtual bool OnReadCompleted(int request_id, int* bytes_read) = 0; + + // The response is complete. The final response status is given. + // Returns false if the handler is deferring the call to a later time. + virtual bool OnResponseCompleted(int request_id, + const net::URLRequestStatus& status, + const std::string& security_info) = 0; + + // Signals that the request is closed (i.e. finished successfully, cancelled). + // This is a signal that the associated net::URLRequest isn't valid anymore. + virtual void OnRequestClosed() = 0; + + // This notification is synthesized by the RedirectToFileResourceHandler + // to indicate progress of 'download_to_file' requests. OnReadCompleted + // calls are consumed by the RedirectToFileResourceHandler and replaced + // with OnDataDownloaded calls. + virtual void OnDataDownloaded(int request_id, int bytes_downloaded) {} + + protected: + friend class BrowserThread; + friend class DeleteTask<ResourceHandler>; + + virtual ~ResourceHandler() {} +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/resource_message_filter.cc b/content/browser/renderer_host/resource_message_filter.cc index 5a27f65..7b3229b 100644 --- a/chrome/browser/renderer_host/resource_message_filter.cc +++ b/content/browser/renderer_host/resource_message_filter.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/resource_message_filter.h" +#include "content/browser/renderer_host/resource_message_filter.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/render_messages.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" ResourceMessageFilter::ResourceMessageFilter( int child_id, diff --git a/content/browser/renderer_host/resource_message_filter.h b/content/browser/renderer_host/resource_message_filter.h new file mode 100644 index 0000000..7e8fb93 --- /dev/null +++ b/content/browser/renderer_host/resource_message_filter.h @@ -0,0 +1,81 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RESOURCE_MESSAGE_FILTER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RESOURCE_MESSAGE_FILTER_H_ + +#include "base/scoped_ptr.h" +#include "chrome/browser/browser_message_filter.h" +#include "chrome/common/child_process_info.h" + +class ChromeURLRequestContext; +class ResourceDispatcherHost; +struct ViewHostMsg_Resource_Request; + +namespace net { +class URLRequestContext; +} // namespace net + +// This class filters out incoming IPC messages for network requests and +// processes them on the IPC thread. As a result, network requests are not +// delayed by costly UI processing that may be occuring on the main thread of +// the browser. It also means that any hangs in starting a network request +// will not interfere with browser UI. +class ResourceMessageFilter : public BrowserMessageFilter { + public: + // Allows overriding the net::URLRequestContext used to service requests. + class URLRequestContextOverride + : public base::RefCountedThreadSafe<URLRequestContextOverride> { + public: + URLRequestContextOverride() {} + + virtual net::URLRequestContext* GetRequestContext( + const ViewHostMsg_Resource_Request& resource_request) = 0; + + protected: + friend class base::RefCountedThreadSafe<URLRequestContextOverride>; + virtual ~URLRequestContextOverride() {} + + DISALLOW_COPY_AND_ASSIGN(URLRequestContextOverride); + }; + + ResourceMessageFilter(int child_id, + ChildProcessInfo::ProcessType process_type, + ResourceDispatcherHost* resource_dispatcher_host); + + // BrowserMessageFilter implementation. + virtual void OnChannelClosing(); + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + + // Returns the net::URLRequestContext for the given request. + ChromeURLRequestContext* GetURLRequestContext( + const ViewHostMsg_Resource_Request& resource_request); + + void set_url_request_context_override(URLRequestContextOverride* u) { + url_request_context_override_ = u; + } + + int child_id() const { return child_id_; } + ChildProcessInfo::ProcessType process_type() const { return process_type_; } + + protected: + // Protected destructor so that we can be overriden in tests. + virtual ~ResourceMessageFilter(); + + private: + // The ID of the child process. + int child_id_; + + ChildProcessInfo::ProcessType process_type_; + + // Owned by BrowserProcess, which is guaranteed to outlive us. + ResourceDispatcherHost* resource_dispatcher_host_; + + scoped_refptr<URLRequestContextOverride> url_request_context_override_; + + DISALLOW_IMPLICIT_CONSTRUCTORS(ResourceMessageFilter); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RESOURCE_MESSAGE_FILTER_H_ diff --git a/chrome/browser/renderer_host/resource_queue.cc b/content/browser/renderer_host/resource_queue.cc index 3b667bf..ef58791 100644 --- a/chrome/browser/renderer_host/resource_queue.cc +++ b/content/browser/renderer_host/resource_queue.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/resource_queue.h" +#include "content/browser/renderer_host/resource_queue.h" #include "base/stl_util-inl.h" #include "chrome/browser/browser_thread.h" -#include "chrome/browser/renderer_host/global_request_id.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/global_request_id.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" ResourceQueueDelegate::~ResourceQueueDelegate() { } diff --git a/content/browser/renderer_host/resource_queue.h b/content/browser/renderer_host/resource_queue.h new file mode 100644 index 0000000..4bf45d9 --- /dev/null +++ b/content/browser/renderer_host/resource_queue.h @@ -0,0 +1,100 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_RESOURCE_QUEUE_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RESOURCE_QUEUE_H_ +#pragma once + +#include <map> +#include <set> + +#include "base/basictypes.h" + +namespace net { +class URLRequest; +} // namespace net + +class ResourceDispatcherHostRequestInfo; +struct GlobalRequestID; + +// Makes decisions about delaying or not each net::URLRequest in the queue. +// All methods are called on the IO thread. +class ResourceQueueDelegate { + public: + // Should return true if it wants the |request| to not be started at this + // point. To start the delayed request, ResourceQueue::StartDelayedRequest + // should be used. + virtual bool ShouldDelayRequest( + net::URLRequest* request, + const ResourceDispatcherHostRequestInfo& request_info, + const GlobalRequestID& request_id) = 0; + + // Called just before ResourceQueue shutdown. After that, the delegate + // should not use the ResourceQueue. + virtual void WillShutdownResourceQueue() = 0; + + protected: + virtual ~ResourceQueueDelegate(); +}; + +// Makes it easy to delay starting URL requests until specified conditions are +// met. +class ResourceQueue { + public: + typedef std::set<ResourceQueueDelegate*> DelegateSet; + + // UI THREAD ONLY ------------------------------------------------------------ + + // Construct the queue. You must initialize it using Initialize. + ResourceQueue(); + ~ResourceQueue(); + + // Initialize the queue with set of delegates it should ask for each incoming + // request. + void Initialize(const DelegateSet& delegates); + + // IO THREAD ONLY ------------------------------------------------------------ + + // Must be called before destroying the queue. No other methods can be called + // after that. + void Shutdown(); + + // Takes care to start the |request| after all delegates allow that. If no + // delegate demands delaying the request it will be started immediately. + void AddRequest(net::URLRequest* request, + const ResourceDispatcherHostRequestInfo& request_info); + + // Tells the queue that the net::URLRequest object associated with + // |request_id| is no longer valid. + void RemoveRequest(const GlobalRequestID& request_id); + + // A delegate should call StartDelayedRequest when it wants to allow the + // request to start. If it was the last delegate that demanded the request + // to be delayed, the request will be started. + void StartDelayedRequest(ResourceQueueDelegate* delegate, + const GlobalRequestID& request_id); + + private: + typedef std::map<GlobalRequestID, net::URLRequest*> RequestMap; + typedef std::map<GlobalRequestID, DelegateSet> InterestedDelegatesMap; + + // The registered delegates. Will not change after the queue has been + // initialized. + DelegateSet delegates_; + + // Stores net::URLRequest objects associated with each GlobalRequestID. This + // helps decoupling the queue from ResourceDispatcherHost. + RequestMap requests_; + + // Maps a GlobalRequestID to the set of delegates that want to prevent the + // associated request from starting yet. + InterestedDelegatesMap interested_delegates_; + + // True when we are shutting down. + bool shutdown_; + + DISALLOW_COPY_AND_ASSIGN(ResourceQueue); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RESOURCE_QUEUE_H_ diff --git a/chrome/browser/renderer_host/resource_queue_unittest.cc b/content/browser/renderer_host/resource_queue_unittest.cc index 39d831a..7041bed 100644 --- a/chrome/browser/renderer_host/resource_queue_unittest.cc +++ b/content/browser/renderer_host/resource_queue_unittest.cc @@ -5,10 +5,10 @@ #include "base/message_loop.h" #include "base/scoped_ptr.h" #include "chrome/browser/browser_thread.h" -#include "chrome/browser/renderer_host/global_request_id.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" -#include "chrome/browser/renderer_host/resource_handler.h" -#include "chrome/browser/renderer_host/resource_queue.h" +#include "content/browser/renderer_host/global_request_id.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/resource_handler.h" +#include "content/browser/renderer_host/resource_queue.h" #include "googleurl/src/gurl.h" #include "net/url_request/url_request.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chrome/browser/renderer_host/resource_request_details.cc b/content/browser/renderer_host/resource_request_details.cc index 2a6636c..5570181 100644 --- a/chrome/browser/renderer_host/resource_request_details.cc +++ b/content/browser/renderer_host/resource_request_details.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/resource_request_details.h" +#include "content/browser/renderer_host/resource_request_details.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" #include "chrome/browser/worker_host/worker_service.h" ResourceRequestDetails::ResourceRequestDetails(const net::URLRequest* request, diff --git a/content/browser/renderer_host/resource_request_details.h b/content/browser/renderer_host/resource_request_details.h new file mode 100644 index 0000000..06c915f --- /dev/null +++ b/content/browser/renderer_host/resource_request_details.h @@ -0,0 +1,71 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// The ResourceRequestDetails object contains additional details about a +// resource request. It copies many of the publicly accessible member variables +// of net::URLRequest, but exists on the UI thread. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RESOURCE_REQUEST_DETAILS_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RESOURCE_REQUEST_DETAILS_H_ +#pragma once + +#include <string> + +#include "googleurl/src/gurl.h" +#include "net/url_request/url_request_status.h" +#include "webkit/glue/resource_type.h" + +namespace net { +class URLRequest; +} // namespace net + +// Details about a resource request notification. +class ResourceRequestDetails { + public: + ResourceRequestDetails(const net::URLRequest* request, int cert_id); + + virtual ~ResourceRequestDetails(); + + const GURL& url() const { return url_; } + const GURL& original_url() const { return original_url_; } + const std::string& method() const { return method_; } + const std::string& referrer() const { return referrer_; } + bool has_upload() const { return has_upload_; } + int load_flags() const { return load_flags_; } + int origin_child_id() const { return origin_child_id_; } + const net::URLRequestStatus& status() const { return status_; } + int ssl_cert_id() const { return ssl_cert_id_; } + int ssl_cert_status() const { return ssl_cert_status_; } + ResourceType::Type resource_type() const { return resource_type_; } + + private: + GURL url_; + GURL original_url_; + std::string method_; + std::string referrer_; + bool has_upload_; + int load_flags_; + int origin_child_id_; + net::URLRequestStatus status_; + int ssl_cert_id_; + int ssl_cert_status_; + ResourceType::Type resource_type_; +}; + +// Details about a redirection of a resource request. +class ResourceRedirectDetails : public ResourceRequestDetails { + public: + ResourceRedirectDetails(const net::URLRequest* request, + int cert_id, + const GURL& new_url); + virtual ~ResourceRedirectDetails(); + + // The URL to which we are being redirected. + const GURL& new_url() const { return new_url_; } + + private: + GURL new_url_; +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_RESOURCE_REQUEST_DETAILS_H_ diff --git a/chrome/browser/renderer_host/socket_stream_dispatcher_host.cc b/content/browser/renderer_host/socket_stream_dispatcher_host.cc index 95db4d8..4b88ff0 100644 --- a/chrome/browser/renderer_host/socket_stream_dispatcher_host.cc +++ b/content/browser/renderer_host/socket_stream_dispatcher_host.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/socket_stream_dispatcher_host.h" +#include "content/browser/renderer_host/socket_stream_dispatcher_host.h" #include "base/logging.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/renderer_host/socket_stream_host.h" #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" #include "chrome/common/net/socket_stream.h" #include "chrome/common/net/url_request_context_getter.h" +#include "content/browser/renderer_host/socket_stream_host.h" #include "net/websockets/websocket_job.h" #include "net/websockets/websocket_throttle.h" diff --git a/content/browser/renderer_host/socket_stream_dispatcher_host.h b/content/browser/renderer_host/socket_stream_dispatcher_host.h new file mode 100644 index 0000000..0089e0c --- /dev/null +++ b/content/browser/renderer_host/socket_stream_dispatcher_host.h @@ -0,0 +1,65 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_SOCKET_STREAM_DISPATCHER_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_SOCKET_STREAM_DISPATCHER_HOST_H_ +#pragma once + +#include <vector> + +#include "base/id_map.h" +#include "chrome/browser/browser_message_filter.h" +#include "content/browser/renderer_host/resource_message_filter.h" +#include "net/socket_stream/socket_stream.h" + +class GURL; +class SocketStreamHost; + +// Dispatches ViewHostMsg_SocketStream_* messages sent from renderer. +// It also acts as SocketStream::Delegate so that it sends +// ViewMsg_SocketStream_* messages back to renderer. +class SocketStreamDispatcherHost : public BrowserMessageFilter, + public net::SocketStream::Delegate { + public: + SocketStreamDispatcherHost(); + virtual ~SocketStreamDispatcherHost(); + + // BrowserMessageFilter methods. + virtual bool OnMessageReceived(const IPC::Message& message, + bool* message_was_ok); + + // The object died, so cancel and detach all requests associated with it. + void CancelRequestsForProcess(int host_id); + + // SocketStream::Delegate methods. + virtual void OnConnected(net::SocketStream* socket, + int max_pending_send_allowed); + virtual void OnSentData(net::SocketStream* socket, int amount_sent); + virtual void OnReceivedData(net::SocketStream* socket, + const char* data, int len); + virtual void OnClose(net::SocketStream* socket); + + void set_url_request_context_override( + ResourceMessageFilter::URLRequestContextOverride* u) { + url_request_context_override_ = u; + } + + private: + // Message handlers called by OnMessageReceived. + void OnConnect(const GURL& url, int socket_id); + void OnSendData(int socket_id, const std::vector<char>& data); + void OnCloseReq(int socket_id); + + void DeleteSocketStreamHost(int socket_id); + + net::URLRequestContext* GetURLRequestContext(); + + IDMap<SocketStreamHost> hosts_; + scoped_refptr<ResourceMessageFilter::URLRequestContextOverride> + url_request_context_override_; + + DISALLOW_COPY_AND_ASSIGN(SocketStreamDispatcherHost); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_SOCKET_STREAM_DISPATCHER_HOST_H_ diff --git a/chrome/browser/renderer_host/socket_stream_host.cc b/content/browser/renderer_host/socket_stream_host.cc index a38975f..e98f7db 100644 --- a/chrome/browser/renderer_host/socket_stream_host.cc +++ b/content/browser/renderer_host/socket_stream_host.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/socket_stream_host.h" +#include "content/browser/renderer_host/socket_stream_host.h" #include "base/logging.h" #include "chrome/common/net/socket_stream.h" diff --git a/content/browser/renderer_host/socket_stream_host.h b/content/browser/renderer_host/socket_stream_host.h new file mode 100644 index 0000000..249b35c --- /dev/null +++ b/content/browser/renderer_host/socket_stream_host.h @@ -0,0 +1,61 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_SOCKET_STREAM_HOST_H_ +#define CONTENT_BROWSER_RENDERER_HOST_SOCKET_STREAM_HOST_H_ +#pragma once + +#include <vector> + +#include "base/ref_counted.h" +#include "net/socket_stream/socket_stream.h" + +class GURL; + +namespace net { +class SocketStreamJob; +class URLRequestContext; +} // namespace net + +// Host of SocketStreamHandle. +// Each SocketStreamHandle will have an unique socket_id assigned by +// SocketStreamHost constructor. If socket id is chrome_common_net::kNoSocketId, +// there is no SocketStreamHost. +// Each SocketStreamHost has SocketStream to manage bi-directional +// communication over socket stream. +// The lifetime of an instance of this class is completely controlled by the +// SocketStreamDispatcherHost. +class SocketStreamHost { + public: + SocketStreamHost(net::SocketStream::Delegate* delegate, int socket_id); + ~SocketStreamHost(); + + // Gets socket_id associated with |socket|. + static int SocketIdFromSocketStream(net::SocketStream* socket); + + int socket_id() const { return socket_id_; } + + // Starts to open connection to |url|. + void Connect(const GURL& url, net::URLRequestContext* request_context); + + // Sends |data| over the socket stream. + // socket stream must be open to send data. + // Returns true if the data is put in transmit buffer in socket stream. + // Returns false otherwise (transmit buffer exceeds limit, or socket + // stream is closed). + bool SendData(const std::vector<char>& data); + + // Closes the socket stream. + void Close(); + + private: + net::SocketStream::Delegate* delegate_; + int socket_id_; + + scoped_refptr<net::SocketStreamJob> socket_; + + DISALLOW_COPY_AND_ASSIGN(SocketStreamHost); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_SOCKET_STREAM_HOST_H_ diff --git a/chrome/browser/renderer_host/sync_resource_handler.cc b/content/browser/renderer_host/sync_resource_handler.cc index 5ae3333..1b9a8f6 100644 --- a/chrome/browser/renderer_host/sync_resource_handler.cc +++ b/content/browser/renderer_host/sync_resource_handler.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/sync_resource_handler.h" +#include "content/browser/renderer_host/sync_resource_handler.h" #include "base/logging.h" #include "chrome/browser/debugger/devtools_netlog_observer.h" #include "chrome/browser/net/load_timing_observer.h" -#include "chrome/browser/renderer_host/global_request_id.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/browser/renderer_host/resource_message_filter.h" #include "chrome/common/render_messages.h" +#include "content/browser/renderer_host/global_request_id.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_message_filter.h" #include "net/base/io_buffer.h" #include "net/http/http_response_headers.h" diff --git a/content/browser/renderer_host/sync_resource_handler.h b/content/browser/renderer_host/sync_resource_handler.h new file mode 100644 index 0000000..95e8bfe --- /dev/null +++ b/content/browser/renderer_host/sync_resource_handler.h @@ -0,0 +1,60 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_SYNC_RESOURCE_HANDLER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_SYNC_RESOURCE_HANDLER_H_ +#pragma once + +#include <string> + +#include "content/browser/renderer_host/resource_handler.h" +#include "chrome/common/resource_response.h" + +class ResourceDispatcherHost; +class ResourceMessageFilter; + +namespace IPC { +class Message; +} + +namespace net { +class IOBuffer; +} + +// Used to complete a synchronous resource request in response to resource load +// events from the resource dispatcher host. +class SyncResourceHandler : public ResourceHandler { + public: + SyncResourceHandler(ResourceMessageFilter* filter, + const GURL& url, + IPC::Message* result_message, + ResourceDispatcherHost* resource_dispatcher_host); + + virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); + virtual bool OnRequestRedirected(int request_id, const GURL& new_url, + ResourceResponse* response, bool* defer); + virtual bool OnResponseStarted(int request_id, ResourceResponse* response); + virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); + virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, + int min_size); + virtual bool OnReadCompleted(int request_id, int* bytes_read); + virtual bool OnResponseCompleted(int request_id, + const net::URLRequestStatus& status, + const std::string& security_info); + virtual void OnRequestClosed(); + + private: + enum { kReadBufSize = 3840 }; + + ~SyncResourceHandler(); + + scoped_refptr<net::IOBuffer> read_buffer_; + + SyncLoadResult result_; + ResourceMessageFilter* filter_; + IPC::Message* result_message_; + ResourceDispatcherHost* rdh_; +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_SYNC_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/x509_user_cert_resource_handler.cc b/content/browser/renderer_host/x509_user_cert_resource_handler.cc index c4703c1..7393e73 100644 --- a/chrome/browser/renderer_host/x509_user_cert_resource_handler.cc +++ b/content/browser/renderer_host/x509_user_cert_resource_handler.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/x509_user_cert_resource_handler.h" +#include "content/browser/renderer_host/x509_user_cert_resource_handler.h" #include "base/string_util.h" #include "chrome/browser/download/download_types.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host.h" -#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h" #include "chrome/browser/ssl/ssl_add_cert_handler.h" #include "chrome/common/resource_response.h" #include "chrome/common/url_constants.h" +#include "content/browser/renderer_host/resource_dispatcher_host.h" +#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h" #include "net/base/io_buffer.h" #include "net/base/mime_sniffer.h" #include "net/base/mime_util.h" diff --git a/content/browser/renderer_host/x509_user_cert_resource_handler.h b/content/browser/renderer_host/x509_user_cert_resource_handler.h new file mode 100644 index 0000000..0d2df61 --- /dev/null +++ b/content/browser/renderer_host/x509_user_cert_resource_handler.h @@ -0,0 +1,80 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_X509_USER_CERT_RESOURCE_HANDLER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_X509_USER_CERT_RESOURCE_HANDLER_H_ +#pragma once + +#include <string> + +#include "base/scoped_ptr.h" +#include "content/browser/renderer_host/resource_handler.h" +#include "googleurl/src/gurl.h" + +namespace net { +class URLRequest; +class URLRequestStatus; +} // namespace net + +class ResourceDispatcherHost; +struct DownloadBuffer; + +// This class handles the "application/x-x509-user-cert" mime-type +// which is a certificate generated by a CA after a previous +// <keygen> form post. + +class X509UserCertResourceHandler : public ResourceHandler { + public: + X509UserCertResourceHandler(ResourceDispatcherHost* host, + net::URLRequest* request, + int render_process_host_id, int render_view_id); + + virtual bool OnUploadProgress(int request_id, uint64 position, uint64 size); + + // Not needed, as this event handler ought to be the final resource. + virtual bool OnRequestRedirected(int request_id, const GURL& url, + ResourceResponse* resp, bool* defer); + + // Check if this indeed an X509 cert. + virtual bool OnResponseStarted(int request_id, ResourceResponse* resp); + + // Pass-through implementation. + virtual bool OnWillStart(int request_id, const GURL& url, bool* defer); + + // Create a new buffer to store received data. + virtual bool OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, + int min_size); + + // A read was completed, maybe allocate a new buffer for further data. + virtual bool OnReadCompleted(int request_id, int* bytes_read); + + // Done downloading the certificate. + virtual bool OnResponseCompleted(int request_id, + const net::URLRequestStatus& urs, + const std::string& sec_info); + + virtual void OnRequestClosed(); + + private: + virtual ~X509UserCertResourceHandler(); + + void AssembleResource(); + + GURL url_; + ResourceDispatcherHost* host_; + net::URLRequest* request_; + size_t content_length_; + scoped_ptr<DownloadBuffer> buffer_; + scoped_refptr<net::IOBuffer> read_buffer_; + scoped_refptr<net::IOBuffer> resource_buffer_; // Downloaded certificate. + static const int kReadBufSize = 32768; + // The id of the |RenderProcessHost| which started the download. + int render_process_host_id_; + // The id of the |RenderView| which started the download. + int render_view_id_; + + DISALLOW_COPY_AND_ASSIGN(X509UserCertResourceHandler); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_X509_USER_CERT_RESOURCE_HANDLER_H_ diff --git a/chrome/browser/renderer_host/site_instance.cc b/content/browser/site_instance.cc index ef722b2..642a6b7 100644 --- a/chrome/browser/renderer_host/site_instance.cc +++ b/content/browser/site_instance.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/renderer_host/site_instance.h" +#include "content/browser/site_instance.h" #include "chrome/browser/browsing_instance.h" #include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/renderer_host/browser_render_process_host.h" #include "chrome/browser/webui/web_ui_factory.h" +#include "chrome/browser/renderer_host/browser_render_process_host.h" #include "chrome/common/notification_service.h" #include "chrome/common/url_constants.h" #include "net/base/registry_controlled_domain.h" diff --git a/content/browser/site_instance.h b/content/browser/site_instance.h new file mode 100644 index 0000000..058cc54 --- /dev/null +++ b/content/browser/site_instance.h @@ -0,0 +1,197 @@ +// 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 CONTENT_BROWSER_RENDERER_HOST_SITE_INSTANCE_H_ +#define CONTENT_BROWSER_RENDERER_HOST_SITE_INSTANCE_H_ +#pragma once + +#include "chrome/common/notification_observer.h" +#include "chrome/common/notification_registrar.h" +#include "content/browser/renderer_host/render_process_host.h" +#include "googleurl/src/gurl.h" + +class BrowsingInstance; + +/////////////////////////////////////////////////////////////////////////////// +// +// SiteInstance class +// +// A SiteInstance is a data structure that is associated with all pages in a +// given instance of a web site. Here, a web site is identified by its +// registered domain name and scheme. An instance includes all pages +// that are connected (i.e., either a user or a script navigated from one +// to the other). We represent instances using the BrowsingInstance class. +// +// In --process-per-tab, one SiteInstance is created for each tab (i.e., in the +// TabContents constructor), unless the tab is created by script (i.e., in +// TabContents::CreateNewView). This corresponds to one process per +// BrowsingInstance. +// +// In process-per-site-instance (the current default process model), +// SiteInstances are created (1) when the user manually creates a new tab +// (which also creates a new BrowsingInstance), and (2) when the user navigates +// across site boundaries (which uses the same BrowsingInstance). If the user +// navigates within a site, or opens links in new tabs within a site, the same +// SiteInstance is used. +// +// In --process-per-site, we consolidate all SiteInstances for a given site, +// throughout the entire profile. This ensures that only one process will be +// dedicated to each site. +// +// Each NavigationEntry for a TabContents points to the SiteInstance that +// rendered it. Each RenderViewHost also points to the SiteInstance that it is +// associated with. A SiteInstance keeps track of the number of these +// references and deletes itself when the count goes to zero. This means that +// a SiteInstance is only live as long as it is accessible, either from new +// tabs with no NavigationEntries or in NavigationEntries in the history. +// +/////////////////////////////////////////////////////////////////////////////// +class SiteInstance : public base::RefCounted<SiteInstance>, + public NotificationObserver { + public: + // Get the BrowsingInstance to which this SiteInstance belongs. + BrowsingInstance* browsing_instance() { return browsing_instance_; } + + // Sets the factory used to create new RenderProcessHosts. This will also be + // passed on to SiteInstances spawned by this one. + // + // The factory must outlive the SiteInstance; ownership is not transferred. It + // may be NULL, in which case the default BrowserRenderProcessHost will be + // created (this is the behavior if you don't call this function). + void set_render_process_host_factory(RenderProcessHostFactory* rph_factory) { + render_process_host_factory_ = rph_factory; + } + + // Update / Get the max page ID for this SiteInstance. + void UpdateMaxPageID(int32 page_id) { + if (page_id > max_page_id_) + max_page_id_ = page_id; + } + int32 max_page_id() const { return max_page_id_; } + + // Whether this SiteInstance has a running process associated with it. + bool HasProcess() const; + + // Returns the current process being used to render pages in this + // SiteInstance. If the process has crashed or otherwise gone away, then + // this method will create a new process and update our host ID accordingly. + RenderProcessHost* GetProcess(); + + // Set / Get the web site that this SiteInstance is rendering pages for. + // This includes the scheme and registered domain, but not the port. If the + // URL does not have a valid registered domain, then the full hostname is + // stored. + void SetSite(const GURL& url); + const GURL& site() const { return site_; } + bool has_site() const { return has_site_; } + + // Returns whether there is currently a related SiteInstance (registered with + // BrowsingInstance) for the site of the given url. If so, we should try to + // avoid dedicating an unused SiteInstance to it (e.g., in a new tab). + bool HasRelatedSiteInstance(const GURL& url); + + // Gets a SiteInstance for the given URL that shares the current + // BrowsingInstance, creating a new SiteInstance if necessary. This ensures + // that a BrowsingInstance only has one SiteInstance per site, so that pages + // in a BrowsingInstance have the ability to script each other. Callers + // should ensure that this SiteInstance becomes ref counted, by storing it in + // a scoped_refptr. (By having this method, we can hide the BrowsingInstance + // class from the rest of the codebase.) + // TODO(creis): This may be an argument to build a pass_refptr<T> class, as + // Darin suggests. + SiteInstance* GetRelatedSiteInstance(const GURL& url); + + // Factory method to create a new SiteInstance. This will create a new + // new BrowsingInstance, so it should only be used when creating a new tab + // from scratch (or similar circumstances). Callers should ensure that + // this SiteInstance becomes ref counted, by storing it in a scoped_refptr. + // + // The render process host factory may be NULL. See SiteInstance constructor. + // + // TODO(creis): This may be an argument to build a pass_refptr<T> class, as + // Darin suggests. + static SiteInstance* CreateSiteInstance(Profile* profile); + + // Factory method to get the appropriate SiteInstance for the given URL, in + // a new BrowsingInstance. Use this instead of CreateSiteInstance when you + // know the URL, since it allows special site grouping rules to be applied + // (for example, to group chrome-ui pages into the same instance). + static SiteInstance* CreateSiteInstanceForURL(Profile* profile, + const GURL& url); + + // Returns the site for the given URL, which includes only the scheme and + // registered domain. Returns an empty GURL if the URL has no host. + static GURL GetSiteForURL(Profile* profile, const GURL& url); + + // Return whether both URLs are part of the same web site, for the purpose of + // assigning them to processes accordingly. The decision is currently based + // on the registered domain of the URLs (google.com, bbc.co.uk), as well as + // the scheme (https, http). This ensures that two pages will be in + // the same process if they can communicate with other via JavaScript. + // (e.g., docs.google.com and mail.google.com have DOM access to each other + // if they both set their document.domain properties to google.com.) + static bool IsSameWebSite(Profile* profile, + const GURL& url1, const GURL& url2); + + // Returns the renderer type for this URL. + static RenderProcessHost::Type RendererTypeForURL(const GURL& url); + + protected: + friend class base::RefCounted<SiteInstance>; + friend class BrowsingInstance; + + // Virtual to allow tests to extend it. + virtual ~SiteInstance(); + + // Create a new SiteInstance. Protected to give access to BrowsingInstance + // and tests; most callers should use CreateSiteInstance or + // GetRelatedSiteInstance instead. + explicit SiteInstance(BrowsingInstance* browsing_instance); + + // Get the effective URL for the given actual URL. If the URL is part of an + // installed app, the effective URL is an extension URL with the ID of that + // extension as the host. This has the effect of grouping apps together in + // a common SiteInstance. + static GURL GetEffectiveURL(Profile* profile, const GURL& url); + + // Returns the type of renderer process this instance belongs in, for grouping + // purposes. + RenderProcessHost::Type GetRendererType(); + + private: + // NotificationObserver implementation. + virtual void Observe(NotificationType type, + const NotificationSource& source, + const NotificationDetails& details); + + NotificationRegistrar registrar_; + + // BrowsingInstance to which this SiteInstance belongs. + scoped_refptr<BrowsingInstance> browsing_instance_; + + // Factory for new RenderProcessHosts, not owned by this class. NULL indiactes + // that the default BrowserRenderProcessHost should be created. + const RenderProcessHostFactory* render_process_host_factory_; + + // Current RenderProcessHost that is rendering pages for this SiteInstance. + // This pointer will only change once the RenderProcessHost is destructed. It + // will still remain the same even if the process crashes, since in that + // scenario the RenderProcessHost remains the same. + RenderProcessHost* process_; + + // The current max_page_id in the SiteInstance's RenderProcessHost. If the + // rendering process dies, its replacement should start issuing page IDs that + // are larger than this value. + int32 max_page_id_; + + // The web site that this SiteInstance is rendering pages for. + GURL site_; + + // Whether SetSite has been called. + bool has_site_; + + DISALLOW_COPY_AND_ASSIGN(SiteInstance); +}; + +#endif // CONTENT_BROWSER_RENDERER_HOST_SITE_INSTANCE_H_ diff --git a/content/content_browser.gypi b/content/content_browser.gypi index 8abb4ab..82085d1 100644 --- a/content/content_browser.gypi +++ b/content/content_browser.gypi @@ -12,6 +12,7 @@ #'content_common', '../app/app.gyp:app_resources', '../skia/skia.gyp:skia', + # TabContents uses zoom constants and functions from WebKit::WebView. '../third_party/WebKit/Source/WebKit/chromium/WebKit.gyp:webkit', '../ui/ui.gyp:ui_base', ], @@ -19,6 +20,92 @@ '..', ], 'sources': [ + 'browser/renderer_host/accelerated_surface_container_mac.cc', + 'browser/renderer_host/accelerated_surface_container_mac.h', + 'browser/renderer_host/accelerated_surface_container_manager_mac.cc', + 'browser/renderer_host/accelerated_surface_container_manager_mac.h', + 'browser/renderer_host/async_resource_handler.cc', + 'browser/renderer_host/async_resource_handler.h', + 'browser/renderer_host/audio_renderer_host.cc', + 'browser/renderer_host/audio_renderer_host.h', + 'browser/renderer_host/audio_sync_reader.cc', + 'browser/renderer_host/audio_sync_reader.h', + 'browser/renderer_host/backing_store.cc', + 'browser/renderer_host/backing_store.h', + 'browser/renderer_host/backing_store_mac.h', + 'browser/renderer_host/backing_store_mac.mm', + 'browser/renderer_host/backing_store_manager.cc', + 'browser/renderer_host/backing_store_manager.h', + 'browser/renderer_host/backing_store_skia.cc', + 'browser/renderer_host/backing_store_skia.h', + 'browser/renderer_host/backing_store_win.cc', + 'browser/renderer_host/backing_store_win.h', + 'browser/renderer_host/backing_store_x.cc', + 'browser/renderer_host/backing_store_x.h', + 'browser/renderer_host/blob_message_filter.cc', + 'browser/renderer_host/blob_message_filter.h', + 'browser/renderer_host/buffered_resource_handler.cc', + 'browser/renderer_host/buffered_resource_handler.h', + 'browser/renderer_host/cross_site_resource_handler.cc', + 'browser/renderer_host/cross_site_resource_handler.h', + 'browser/renderer_host/database_message_filter.cc', + 'browser/renderer_host/database_message_filter.h', + 'browser/renderer_host/file_utilities_message_filter.cc', + 'browser/renderer_host/file_utilities_message_filter.h', + 'browser/renderer_host/global_request_id.h', + 'browser/renderer_host/gpu_message_filter.cc', + 'browser/renderer_host/gpu_message_filter.h', + 'browser/renderer_host/pepper_file_message_filter.cc', + 'browser/renderer_host/pepper_file_message_filter.h', + 'browser/renderer_host/pepper_message_filter.cc', + 'browser/renderer_host/pepper_message_filter.h', + 'browser/renderer_host/redirect_to_file_resource_handler.cc', + 'browser/renderer_host/redirect_to_file_resource_handler.h', + 'browser/renderer_host/render_message_filter.cc', + 'browser/renderer_host/render_message_filter.h', + 'browser/renderer_host/render_message_filter_gtk.cc', + 'browser/renderer_host/render_message_filter_mac.mm', + 'browser/renderer_host/render_message_filter_win.cc', + 'browser/renderer_host/render_process_host.cc', + 'browser/renderer_host/render_process_host.h', + 'browser/renderer_host/render_sandbox_host_linux.cc', + 'browser/renderer_host/render_sandbox_host_linux.h', + 'browser/renderer_host/render_view_host.cc', + 'browser/renderer_host/render_view_host.h', + 'browser/renderer_host/render_view_host_delegate.cc', + 'browser/renderer_host/render_view_host_delegate.h', + 'browser/renderer_host/render_view_host_factory.cc', + 'browser/renderer_host/render_view_host_factory.h', + 'browser/renderer_host/render_view_host_notification_task.h', + 'browser/renderer_host/render_widget_fullscreen_host.cc', + 'browser/renderer_host/render_widget_fullscreen_host.h', + 'browser/renderer_host/render_widget_helper.cc', + 'browser/renderer_host/render_widget_helper.h', + 'browser/renderer_host/render_widget_host.cc', + 'browser/renderer_host/render_widget_host.h', + 'browser/renderer_host/render_widget_host_view.cc', + 'browser/renderer_host/render_widget_host_view.h', + 'browser/renderer_host/resource_dispatcher_host.cc', + 'browser/renderer_host/resource_dispatcher_host.h', + 'browser/renderer_host/resource_dispatcher_host_request_info.cc', + 'browser/renderer_host/resource_dispatcher_host_request_info.h', + 'browser/renderer_host/resource_handler.h', + 'browser/renderer_host/resource_message_filter.cc', + 'browser/renderer_host/resource_message_filter.h', + 'browser/renderer_host/resource_queue.cc', + 'browser/renderer_host/resource_queue.h', + 'browser/renderer_host/resource_request_details.cc', + 'browser/renderer_host/resource_request_details.h', + 'browser/renderer_host/socket_stream_dispatcher_host.cc', + 'browser/renderer_host/socket_stream_dispatcher_host.h', + 'browser/renderer_host/socket_stream_host.cc', + 'browser/renderer_host/socket_stream_host.h', + 'browser/renderer_host/sync_resource_handler.cc', + 'browser/renderer_host/sync_resource_handler.h', + 'browser/renderer_host/x509_user_cert_resource_handler.cc', + 'browser/renderer_host/x509_user_cert_resource_handler.h', + 'browser/site_instance.cc', + 'browser/site_instance.h', 'browser/tab_contents/background_contents.cc', 'browser/tab_contents/background_contents.h', 'browser/tab_contents/constrained_window.h', |