1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CONTENT_RENDERER_RENDER_VIEW_IMPL_H_
6 #define CONTENT_RENDERER_RENDER_VIEW_IMPL_H_
14 #include "base/basictypes.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/id_map.h"
17 #include "base/memory/linked_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/process/process.h"
21 #include "base/strings/string16.h"
22 #include "base/timer/timer.h"
23 #include "build/build_config.h"
24 #include "cc/input/top_controls_state.h"
25 #include "cc/resources/shared_bitmap.h"
26 #include "content/common/content_export.h"
27 #include "content/common/drag_event_source_info.h"
28 #include "content/common/edit_command.h"
29 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
30 #include "content/common/navigation_gesture.h"
31 #include "content/common/view_message_enums.h"
32 #include "content/public/common/page_zoom.h"
33 #include "content/public/common/referrer.h"
34 #include "content/public/common/renderer_preferences.h"
35 #include "content/public/common/stop_find_action.h"
36 #include "content/public/common/top_controls_state.h"
37 #include "content/public/common/web_preferences.h"
38 #include "content/public/renderer/render_view.h"
39 #include "content/renderer/mouse_lock_dispatcher.h"
40 #include "content/renderer/render_frame_impl.h"
41 #include "content/renderer/render_widget.h"
42 #include "content/renderer/stats_collection_observer.h"
43 #include "ipc/ipc_platform_file.h"
44 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
45 #include "third_party/WebKit/public/web/WebAXObject.h"
46 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
47 #include "third_party/WebKit/public/web/WebDataSource.h"
48 #include "third_party/WebKit/public/web/WebElement.h"
49 #include "third_party/WebKit/public/web/WebHistoryItem.h"
50 #include "third_party/WebKit/public/web/WebIconURL.h"
51 #include "third_party/WebKit/public/web/WebInputEvent.h"
52 #include "third_party/WebKit/public/web/WebNavigationType.h"
53 #include "third_party/WebKit/public/web/WebNode.h"
54 #include "third_party/WebKit/public/web/WebPageSerializerClient.h"
55 #include "third_party/WebKit/public/web/WebPageVisibilityState.h"
56 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
57 #include "third_party/WebKit/public/web/WebViewClient.h"
58 #include "ui/base/window_open_disposition.h"
59 #include "ui/surface/transport_dib.h"
61 #if defined(OS_ANDROID)
62 #include "content/renderer/android/content_detector.h"
63 #include "content/renderer/android/renderer_date_time_picker.h"
64 #include "third_party/WebKit/public/web/WebContentDetectionResult.h"
67 #if defined(COMPILER_MSVC)
68 // RenderViewImpl is a diamond-shaped hierarchy, with WebWidgetClient at the
69 // root. VS warns when we inherit the WebWidgetClient method implementations
70 // from RenderWidget. It's safe to ignore that warning.
71 #pragma warning(disable: 4250)
74 class PepperDeviceTest;
76 struct PP_NetAddress_Private;
77 struct FrameMsg_Navigate_Params;
78 struct ViewMsg_PostMessage_Params;
79 struct ViewMsg_StopFinding_Params;
86 class WebApplicationCacheHost;
87 class WebApplicationCacheHostClient;
88 class WebDOMMessageEvent;
90 class WebDateTimeChooserCompletion;
92 class WebGestureEvent;
95 class WebPeerConnection00Handler;
96 class WebPeerConnection00HandlerClient;
98 class WebPeerConnectionHandler;
99 class WebPeerConnectionHandlerClient;
100 class WebSocketStreamHandle;
101 class WebSpeechRecognizer;
102 class WebStorageNamespace;
105 struct WebActiveWheelFlingParameters;
106 struct WebDateTimeChooserParams;
107 struct WebFileChooserParams;
108 struct WebFindOptions;
109 struct WebMediaPlayerAction;
110 struct WebPluginAction;
112 struct WebWindowFeatures;
114 #if defined(OS_ANDROID)
115 class WebHitTestResult;
120 struct SelectedFileInfo;
124 class BrowserPluginManager;
127 class ExternalPopupMenu;
129 class HistoryController;
131 class ImageResourceFetcher;
132 class MouseLockDispatcher;
133 class NavigationState;
134 class PepperPluginInstanceImpl;
135 class RenderViewImplTest;
136 class RenderViewObserver;
137 class RenderViewTest;
138 class RendererDateTimePicker;
139 class RendererWebColorChooserImpl;
140 class SpeechRecognitionDispatcher;
141 class WebPluginDelegateProxy;
144 struct FileChooserParams;
145 struct RenderViewImplParams;
147 #if defined(OS_ANDROID)
148 class WebMediaPlayerProxyAndroid;
152 // RenderView is an object that manages a WebView object, and provides a
153 // communication interface with an embedding application process
155 class CONTENT_EXPORT RenderViewImpl
156 : public RenderWidget,
157 NON_EXPORTED_BASE(public blink::WebViewClient),
158 NON_EXPORTED_BASE(public blink::WebPageSerializerClient),
160 public base::SupportsWeakPtr<RenderViewImpl> {
162 // Creates a new RenderView. |opener_id| is the routing ID of the RenderView
163 // responsible for creating this RenderView. Note that if the original opener
164 // has been closed, |window_was_created_with_opener| will be true and
165 // |opener_id| will be MSG_ROUTING_NONE. When |swapped_out| is true, the
166 // |proxy_routing_id| is specified, so a RenderFrameProxy can be created for
167 // this RenderView's main RenderFrame.
168 static RenderViewImpl* Create(int32 opener_id,
169 bool window_was_created_with_opener,
170 const RendererPreferences& renderer_prefs,
171 const WebPreferences& webkit_prefs,
173 int32 main_frame_routing_id,
175 int64 session_storage_namespace_id,
176 const base::string16& frame_name,
177 bool is_renderer_created,
179 int32 proxy_routing_id,
183 const blink::WebScreenInfo& screen_info);
185 // Used by content_layouttest_support to hook into the creation of
187 static void InstallCreateHook(
188 RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*));
190 // Returns the RenderViewImpl containing the given WebView.
191 static RenderViewImpl* FromWebView(blink::WebView* webview);
193 // Returns the RenderViewImpl for the given routing ID.
194 static RenderViewImpl* FromRoutingID(int routing_id);
196 static size_t GetRenderViewCount();
198 // May return NULL when the view is closing.
199 blink::WebView* webview() const;
201 int history_list_offset() const { return history_list_offset_; }
203 const WebPreferences& webkit_preferences() const {
204 return webkit_preferences_;
207 const RendererPreferences& renderer_preferences() const {
208 return renderer_preferences_;
211 void set_send_content_state_immediately(bool value) {
212 send_content_state_immediately_ = value;
215 RenderFrameImpl* main_render_frame() { return main_render_frame_.get(); }
217 MouseLockDispatcher* mouse_lock_dispatcher() {
218 return mouse_lock_dispatcher_;
221 HistoryController* history_controller() {
222 return history_controller_.get();
225 // Lazily initialize this view's BrowserPluginManager and return it.
226 BrowserPluginManager* GetBrowserPluginManager();
228 // Functions to add and remove observers for this object.
229 void AddObserver(RenderViewObserver* observer);
230 void RemoveObserver(RenderViewObserver* observer);
232 // Returns the StatsCollectionObserver associated with this view, or NULL
233 // if one wasn't created;
234 StatsCollectionObserver* GetStatsCollectionObserver() {
235 return stats_collection_observer_.get();
238 // Adds the given file chooser request to the file_chooser_completion_ queue
239 // (see that var for more) and requests the chooser be displayed if there are
240 // no other waiting items in the queue.
242 // Returns true if the chooser was successfully scheduled. False means we
243 // didn't schedule anything.
244 bool ScheduleFileChooser(const FileChooserParams& params,
245 blink::WebFileChooserCompletion* completion);
247 #if defined(OS_ANDROID)
248 void DismissDateTimeDialog();
250 #if defined(OS_MACOSX) || defined(OS_ANDROID)
251 void DidHideExternalPopupMenu();
254 bool is_loading() const { return frames_in_progress_ != 0; }
256 void FrameDidStartLoading(blink::WebFrame* frame);
257 void FrameDidStopLoading(blink::WebFrame* frame);
259 // Plugin-related functions --------------------------------------------------
261 #if defined(ENABLE_PLUGINS)
262 // Get/set the plugin which will be used as to handle document find requests.
263 void set_plugin_find_handler(PepperPluginInstanceImpl* plugin) {
264 plugin_find_handler_ = plugin;
266 PepperPluginInstanceImpl* plugin_find_handler() {
267 return plugin_find_handler_;
270 PepperPluginInstanceImpl* focused_pepper_plugin() {
271 return focused_pepper_plugin_;
273 PepperPluginInstanceImpl* pepper_last_mouse_event_target() {
274 return pepper_last_mouse_event_target_;
276 void set_pepper_last_mouse_event_target(PepperPluginInstanceImpl* plugin) {
277 pepper_last_mouse_event_target_ = plugin;
280 #if defined(OS_MACOSX) || defined(OS_WIN)
281 // Informs the render view that the given plugin has gained or lost focus.
282 void PluginFocusChanged(bool focused, int plugin_id);
285 #if defined(OS_MACOSX)
286 // Starts plugin IME.
287 void StartPluginIme();
290 // Indicates that the given instance has been created.
291 void PepperInstanceCreated(PepperPluginInstanceImpl* instance);
293 // Indicates that the given instance is being destroyed. This is called from
294 // the destructor, so it's important that the instance is not dereferenced
296 void PepperInstanceDeleted(PepperPluginInstanceImpl* instance);
298 // Notification that the given plugin is focused or unfocused.
299 void PepperFocusChanged(PepperPluginInstanceImpl* instance, bool focused);
301 void RegisterPluginDelegate(WebPluginDelegateProxy* delegate);
302 void UnregisterPluginDelegate(WebPluginDelegateProxy* delegate);
303 #endif // ENABLE_PLUGINS
305 void TransferActiveWheelFlingAnimation(
306 const blink::WebActiveWheelFlingParameters& params);
308 // Returns true if the focused element is editable text from the perspective
309 // of IME support (also used for on-screen keyboard). Works correctly inside
310 // supported PPAPI plug-ins.
311 bool HasIMETextFocus();
313 // Callback for use with GetWindowSnapshot.
314 typedef base::Callback<void(
315 const gfx::Size&, const std::vector<unsigned char>&)>
316 WindowSnapshotCallback;
318 void GetWindowSnapshot(const WindowSnapshotCallback& callback);
320 // Dispatches the current navigation state to the browser. Called on a
321 // periodic timer so we don't send too many messages.
322 void SyncNavigationState();
324 // Returns the length of the session history of this RenderView. Note that
325 // this only coincides with the actual length of the session history if this
326 // RenderView is the currently active RenderView of a WebContents.
327 unsigned GetLocalSessionHistoryLengthForTesting() const;
329 // Invokes OnSetFocus and marks the widget as active depending on the value
330 // of |enable|. This is used for layout tests that need to control the focus
331 // synchronously from the renderer.
332 void SetFocusAndActivateForTesting(bool enable);
334 // Change the device scale factor and force the compositor to resize.
335 void SetDeviceScaleFactorForTesting(float factor);
337 // Change the device ICC color profile while running a layout test.
338 void SetDeviceColorProfileForTesting(const std::vector<char>& color_profile);
340 // Used to force the size of a window when running layout tests.
341 void ForceResizeForTesting(const gfx::Size& new_size);
343 void UseSynchronousResizeModeForTesting(bool enable);
345 // Control autoresize mode.
346 void EnableAutoResizeForTesting(const gfx::Size& min_size,
347 const gfx::Size& max_size);
348 void DisableAutoResizeForTesting(const gfx::Size& new_size);
350 // IPC::Listener implementation ----------------------------------------------
352 virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
354 // blink::WebWidgetClient implementation ------------------------------------
356 // Most methods are handled by RenderWidget.
357 virtual void didCommitAndDrawCompositorFrame();
358 virtual void didFocus();
359 virtual void didBlur();
360 virtual void show(blink::WebNavigationPolicy policy);
361 virtual void runModal();
362 virtual bool enterFullScreen();
363 virtual void exitFullScreen();
364 virtual bool requestPointerLock();
365 virtual void requestPointerUnlock();
366 virtual bool isPointerLocked();
367 virtual void didHandleGestureEvent(const blink::WebGestureEvent& event,
368 bool event_cancelled) OVERRIDE;
369 virtual void initializeLayerTreeView() OVERRIDE;
371 // blink::WebViewClient implementation --------------------------------------
373 virtual blink::WebView* createView(blink::WebLocalFrame* creator,
374 const blink::WebURLRequest& request,
375 const blink::WebWindowFeatures& features,
376 const blink::WebString& frame_name,
377 blink::WebNavigationPolicy policy,
378 bool suppress_opener);
379 virtual blink::WebWidget* createPopupMenu(blink::WebPopupType popup_type);
380 virtual blink::WebExternalPopupMenu* createExternalPopupMenu(
381 const blink::WebPopupMenuInfo& popup_menu_info,
382 blink::WebExternalPopupMenuClient* popup_menu_client);
383 virtual blink::WebStorageNamespace* createSessionStorageNamespace();
384 virtual void printPage(blink::WebLocalFrame* frame);
385 virtual bool enumerateChosenDirectory(
386 const blink::WebString& path,
387 blink::WebFileChooserCompletion* chooser_completion);
388 virtual void didCancelCompositionOnSelectionChange();
389 virtual bool handleCurrentKeyboardEvent();
390 virtual bool runFileChooser(
391 const blink::WebFileChooserParams& params,
392 blink::WebFileChooserCompletion* chooser_completion);
393 virtual void showValidationMessage(const blink::WebRect& anchor_in_root_view,
394 const blink::WebString& main_text,
395 const blink::WebString& sub_text,
396 blink::WebTextDirection hint) OVERRIDE;
397 virtual void hideValidationMessage() OVERRIDE;
398 virtual void moveValidationMessage(
399 const blink::WebRect& anchor_in_root_view) OVERRIDE;
400 virtual void setStatusText(const blink::WebString& text);
401 virtual void setMouseOverURL(const blink::WebURL& url);
402 virtual void setKeyboardFocusURL(const blink::WebURL& url);
403 virtual void startDragging(blink::WebLocalFrame* frame,
404 const blink::WebDragData& data,
405 blink::WebDragOperationsMask mask,
406 const blink::WebImage& image,
407 const blink::WebPoint& imageOffset);
408 virtual bool acceptsLoadDrops();
409 virtual void focusNext();
410 virtual void focusPrevious();
411 virtual void focusedNodeChanged(const blink::WebNode& node);
412 virtual void didUpdateLayout();
413 #if defined(OS_ANDROID)
414 virtual bool didTapMultipleTargets(
415 const blink::WebGestureEvent& event,
416 const blink::WebVector<blink::WebRect>& target_rects);
418 virtual blink::WebString acceptLanguages();
419 virtual void navigateBackForwardSoon(int offset);
420 virtual int historyBackListCount();
421 virtual int historyForwardListCount();
422 virtual void postAccessibilityEvent(
423 const blink::WebAXObject& obj, blink::WebAXEvent event);
424 virtual void didUpdateInspectorSetting(const blink::WebString& key,
425 const blink::WebString& value);
426 virtual blink::WebSpeechRecognizer* speechRecognizer();
427 virtual void zoomLimitsChanged(double minimum_level, double maximum_level);
428 virtual void zoomLevelChanged();
429 virtual double zoomLevelToZoomFactor(double zoom_level) const;
430 virtual double zoomFactorToZoomLevel(double factor) const;
431 virtual void registerProtocolHandler(const blink::WebString& scheme,
432 const blink::WebURL& base_url,
433 const blink::WebURL& url,
434 const blink::WebString& title);
435 virtual void unregisterProtocolHandler(const blink::WebString& scheme,
436 const blink::WebURL& base_url,
437 const blink::WebURL& url);
438 virtual blink::WebPageVisibilityState visibilityState() const;
439 virtual blink::WebPushClient* webPushClient();
440 virtual void draggableRegionsChanged();
442 #if defined(OS_ANDROID)
443 virtual void scheduleContentIntent(const blink::WebURL& intent);
444 virtual void cancelScheduledContentIntents();
445 virtual blink::WebContentDetectionResult detectContentAround(
446 const blink::WebHitTestResult& touch_hit);
448 // Only used on Android since all other platforms implement
449 // date and time input fields using MULTIPLE_FIELDS_UI
450 virtual bool openDateTimeChooser(const blink::WebDateTimeChooserParams&,
451 blink::WebDateTimeChooserCompletion*);
452 virtual void didScrollWithKeyboard(const blink::WebSize& delta);
455 // blink::WebPageSerializerClient implementation ----------------------------
457 virtual void didSerializeDataForFrame(
458 const blink::WebURL& frame_url,
459 const blink::WebCString& data,
460 PageSerializationStatus status) OVERRIDE;
462 // RenderView implementation -------------------------------------------------
464 virtual bool Send(IPC::Message* message) OVERRIDE;
465 virtual RenderFrame* GetMainRenderFrame() OVERRIDE;
466 virtual int GetRoutingID() const OVERRIDE;
467 virtual gfx::Size GetSize() const OVERRIDE;
468 virtual WebPreferences& GetWebkitPreferences() OVERRIDE;
469 virtual void SetWebkitPreferences(const WebPreferences& preferences) OVERRIDE;
470 virtual blink::WebView* GetWebView() OVERRIDE;
471 virtual blink::WebElement GetFocusedElement() const OVERRIDE;
472 virtual bool IsEditableNode(const blink::WebNode& node) const OVERRIDE;
473 virtual bool NodeContainsPoint(const blink::WebNode& node,
474 const gfx::Point& point) const OVERRIDE;
475 virtual bool ShouldDisplayScrollbars(int width, int height) const OVERRIDE;
476 virtual int GetEnabledBindings() const OVERRIDE;
477 virtual bool GetContentStateImmediately() const OVERRIDE;
478 virtual blink::WebPageVisibilityState GetVisibilityState() const OVERRIDE;
479 virtual void DidStartLoading() OVERRIDE;
480 virtual void DidStopLoading() OVERRIDE;
481 virtual void Repaint(const gfx::Size& size) OVERRIDE;
482 virtual void SetEditCommandForNextKeyEvent(const std::string& name,
483 const std::string& value) OVERRIDE;
484 virtual void ClearEditCommands() OVERRIDE;
485 virtual SSLStatus GetSSLStatusOfFrame(blink::WebFrame* frame) const OVERRIDE;
486 virtual const std::string& GetAcceptLanguages() const OVERRIDE;
487 #if defined(OS_ANDROID)
488 virtual void UpdateTopControlsState(TopControlsState constraints,
489 TopControlsState current,
490 bool animate) OVERRIDE;
492 bool uses_temporary_zoom_level() const { return uses_temporary_zoom_level_; }
494 // Please do not add your stuff randomly to the end here. If there is an
495 // appropriate section, add it there. If not, there are some random functions
496 // nearer to the top you can add it to.
498 // Cannot use std::set unfortunately since linked_ptr<> does not support
500 typedef std::vector<linked_ptr<ImageResourceFetcher> >
501 ImageResourceFetcherList;
504 // RenderWidget overrides:
505 virtual void OnClose() OVERRIDE;
506 virtual void Close() OVERRIDE;
507 virtual void OnResize(const ViewMsg_Resize_Params& params) OVERRIDE;
508 virtual void DidInitiatePaint() OVERRIDE;
509 virtual void DidFlushPaint() OVERRIDE;
510 virtual gfx::Vector2d GetScrollOffset() OVERRIDE;
511 virtual void DidHandleKeyEvent() OVERRIDE;
512 virtual bool WillHandleMouseEvent(
513 const blink::WebMouseEvent& event) OVERRIDE;
514 virtual bool WillHandleGestureEvent(
515 const blink::WebGestureEvent& event) OVERRIDE;
516 virtual void DidHandleMouseEvent(const blink::WebMouseEvent& event) OVERRIDE;
517 virtual void DidHandleTouchEvent(const blink::WebTouchEvent& event) OVERRIDE;
518 virtual bool HasTouchEventHandlersAt(const gfx::Point& point) const OVERRIDE;
519 virtual void OnSetFocus(bool enable) OVERRIDE;
520 virtual void OnWasHidden() OVERRIDE;
521 virtual void OnWasShown(bool needs_repainting,
522 const ui::LatencyInfo& latency_info) OVERRIDE;
523 virtual GURL GetURLForGraphicsContext3D() OVERRIDE;
524 virtual void OnImeSetComposition(
525 const base::string16& text,
526 const std::vector<blink::WebCompositionUnderline>& underlines,
528 int selection_end) OVERRIDE;
529 virtual void OnImeConfirmComposition(const base::string16& text,
530 const gfx::Range& replacement_range,
531 bool keep_selection) OVERRIDE;
532 virtual void SetDeviceScaleFactor(float device_scale_factor) OVERRIDE;
533 virtual bool SetDeviceColorProfile(
534 const std::vector<char>& color_profile) OVERRIDE;
535 virtual void OnOrientationChange() OVERRIDE;
536 virtual ui::TextInputType GetTextInputType() OVERRIDE;
537 virtual void GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) OVERRIDE;
538 #if defined(OS_MACOSX) || defined(USE_AURA)
539 virtual void GetCompositionCharacterBounds(
540 std::vector<gfx::Rect>* character_bounds) OVERRIDE;
541 virtual void GetCompositionRange(gfx::Range* range) OVERRIDE;
543 virtual bool CanComposeInline() OVERRIDE;
544 virtual void DidCommitCompositorFrame() OVERRIDE;
545 virtual void InstrumentWillBeginFrame(int frame_id) OVERRIDE;
546 virtual void InstrumentDidBeginFrame() OVERRIDE;
547 virtual void InstrumentDidCancelFrame() OVERRIDE;
548 virtual void InstrumentWillComposite() OVERRIDE;
551 explicit RenderViewImpl(RenderViewImplParams* params);
553 void Initialize(RenderViewImplParams* params);
554 virtual void SetScreenMetricsEmulationParameters(
555 float device_scale_factor,
556 const gfx::Point& root_layer_offset,
557 float root_layer_scale) OVERRIDE;
559 // Do not delete directly. This class is reference counted.
560 virtual ~RenderViewImpl();
564 friend class ExternalPopupMenuTest;
565 friend class PepperDeviceTest;
566 friend class RenderViewImplTest;
567 friend class RenderViewTest;
568 friend class RendererAccessibilityTest;
570 // TODO(nasko): Temporarily friend RenderFrameImpl, so we don't duplicate
571 // utility functions needed in both classes, while we move frame specific
572 // code away from this class.
573 friend class RenderFrameImpl;
575 FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuDisplayNoneTest, SelectItem);
576 FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuRemoveTest, RemoveOnChange);
577 FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuTest, NormalCase);
578 FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuTest, ShowPopupThenNavigate);
579 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, DecideNavigationPolicyForWebUI);
580 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
581 DidFailProvisionalLoadWithErrorForError);
582 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
583 DidFailProvisionalLoadWithErrorForCancellation);
584 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
585 DontIgnoreBackAfterNavEntryLimit);
586 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, ImeComposition);
587 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, InsertCharacters);
588 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, JSBlockSentAfterPageLoad);
589 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, LastCommittedUpdateState);
590 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnHandleKeyboardEvent);
591 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnImeTypeChanged);
592 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnNavStateChanged);
593 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnSetTextDirection);
594 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnUpdateWebPreferences);
595 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
596 SetEditableSelectionAndComposition);
597 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, StaleNavigationsIgnored);
598 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, UpdateTargetURLWithInvalidURL);
599 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
600 GetCompositionCharacterBoundsTest);
601 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnNavigationHttpPost);
602 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
603 DecideNavigationPolicyHandlesAllTopLevel);
604 #if defined(OS_MACOSX)
605 FRIEND_TEST_ALL_PREFIXES(RenderViewTest, MacTestCmdUp);
607 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, SetHistoryLengthAndPrune);
608 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, ZoomLimit);
609 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, NavigateFrame);
610 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, BasicRenderFrame);
611 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, TextInputTypeWithPepper);
612 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
613 MessageOrderInDidChangeSelection);
614 FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, SendCandidateWindowEvents);
615 FRIEND_TEST_ALL_PREFIXES(SuppressErrorPageTest, Suppresses);
616 FRIEND_TEST_ALL_PREFIXES(SuppressErrorPageTest, DoesNotSuppress);
618 typedef std::map<GURL, double> HostZoomLevels;
626 // Old WebFrameClient implementations ----------------------------------------
628 // RenderViewImpl used to be a WebFrameClient, but now RenderFrameImpl is the
629 // WebFrameClient. However, many implementations of WebFrameClient methods
630 // still live here and are called from RenderFrameImpl. These implementations
631 // are to be moved to RenderFrameImpl <http://crbug.com/361761>.
633 void didCreateDataSource(blink::WebLocalFrame* frame,
634 blink::WebDataSource* datasource);
635 void didClearWindowObject(blink::WebLocalFrame* frame);
636 void didChangeIcon(blink::WebLocalFrame*, blink::WebIconURL::Type);
637 void didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame);
638 void didChangeScrollOffset(blink::WebLocalFrame* frame);
640 static bool IsReload(const FrameMsg_Navigate_Params& params);
642 static Referrer GetReferrerFromRequest(
643 blink::WebFrame* frame,
644 const blink::WebURLRequest& request);
646 static WindowOpenDisposition NavigationPolicyToDisposition(
647 blink::WebNavigationPolicy policy);
649 void UpdateSessionHistory(blink::WebFrame* frame);
650 void SendUpdateState(HistoryEntry* entry);
652 // Sends a message and runs a nested message loop.
653 bool SendAndRunNestedMessageLoop(IPC::SyncMessage* message);
655 // IPC message handlers ------------------------------------------------------
657 // The documentation for these functions should be in
658 // content/common/*_messages.h for the message that the function is handling.
659 void OnExecuteEditCommand(const std::string& name, const std::string& value);
660 void OnMoveCaret(const gfx::Point& point);
661 void OnScrollFocusedEditableNodeIntoRect(const gfx::Rect& rect);
662 void OnSetEditCommandsForNextKeyEvent(const EditCommands& edit_commands);
663 void OnAllowBindings(int enabled_bindings_flags);
664 void OnAllowScriptToClose(bool script_can_close);
665 void OnCancelDownload(int32 download_id);
666 void OnClearFocusedElement();
668 void OnShowContextMenu(ui::MenuSourceType source_type,
669 const gfx::Point& location);
670 void OnCopyImageAt(int x, int y);
671 void OnSaveImageAt(int x, int y);
672 void OnDeterminePageLanguage();
673 void OnDisableScrollbarsForSmallWindows(
674 const gfx::Size& disable_scrollbars_size_limit);
675 void OnDragSourceEnded(const gfx::Point& client_point,
676 const gfx::Point& screen_point,
677 blink::WebDragOperation drag_operation);
678 void OnDragSourceSystemDragEnded();
679 void OnDragTargetDrop(const gfx::Point& client_pt,
680 const gfx::Point& screen_pt,
682 void OnDragTargetDragEnter(const DropData& drop_data,
683 const gfx::Point& client_pt,
684 const gfx::Point& screen_pt,
685 blink::WebDragOperationsMask operations_allowed,
687 void OnDragTargetDragLeave();
688 void OnDragTargetDragOver(const gfx::Point& client_pt,
689 const gfx::Point& screen_pt,
690 blink::WebDragOperationsMask operations_allowed,
692 void OnEnablePreferredSizeChangedMode();
693 void OnEnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size);
694 void OnDisableAutoResize(const gfx::Size& new_size);
695 void OnEnumerateDirectoryResponse(int id,
696 const std::vector<base::FilePath>& paths);
697 void OnFileChooserResponse(
698 const std::vector<ui::SelectedFileInfo>& files);
699 void OnFind(int request_id,
700 const base::string16&,
701 const blink::WebFindOptions&);
702 void OnGetAllSavableResourceLinksForCurrentPage(const GURL& page_url);
703 void OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
704 const std::vector<GURL>& links,
705 const std::vector<base::FilePath>& local_paths,
706 const base::FilePath& local_directory_name);
707 void OnMediaPlayerActionAt(const gfx::Point& location,
708 const blink::WebMediaPlayerAction& action);
709 void OnPluginActionAt(const gfx::Point& location,
710 const blink::WebPluginAction& action);
711 void OnMoveOrResizeStarted();
712 void OnPostMessageEvent(const ViewMsg_PostMessage_Params& params);
713 void OnReleaseDisambiguationPopupBitmap(const cc::SharedBitmapId& id);
714 void OnResetPageEncodingToDefault();
715 void OnSetActive(bool active);
716 void OnSetBackgroundOpaque(bool opaque);
717 void OnExitFullscreen();
718 void OnSetHistoryLengthAndPrune(int history_length, int32 minimum_page_id);
719 void OnSetInitialFocus(bool reverse);
720 void OnSetPageEncoding(const std::string& encoding_name);
721 void OnSetRendererPrefs(const RendererPreferences& renderer_prefs);
722 void OnSetWebUIProperty(const std::string& name, const std::string& value);
723 void OnSetZoomLevelForLoadingURL(const GURL& url, double zoom_level);
724 void OnSetZoomLevelForView(bool uses_temporary_zoom_level, double level);
726 void OnStopFinding(StopFindAction action);
727 void OnSuppressDialogsUntilSwapOut();
728 void OnThemeChanged();
729 void OnUpdateTargetURLAck();
730 void OnUpdateWebPreferences(const WebPreferences& prefs);
731 void OnZoom(PageZoom zoom);
732 void OnEnableViewSourceMode();
733 void OnDisownOpener();
734 void OnWindowSnapshotCompleted(const int snapshot_id,
735 const gfx::Size& size, const std::vector<unsigned char>& png);
736 void OnForceRedraw(int request_id);
737 void OnSelectWordAroundCaret();
738 #if defined(OS_ANDROID)
739 void OnActivateNearestFindResult(int request_id, float x, float y);
740 void OnFindMatchRects(int current_version);
741 void OnSelectPopupMenuItems(bool canceled,
742 const std::vector<int>& selected_indices);
743 void OnUndoScrollFocusedEditableNodeIntoRect();
744 void OnUpdateTopControlsState(bool enable_hiding,
747 void OnExtractSmartClipData(const gfx::Rect& rect);
748 #elif defined(OS_MACOSX)
749 void OnGetRenderedText();
750 void OnPluginImeCompositionCompleted(const base::string16& text,
752 void OnSelectPopupMenuItem(int selected_index);
753 void OnSetInLiveResize(bool in_live_resize);
754 void OnSetWindowVisibility(bool visible);
755 void OnWindowFrameChanged(const gfx::Rect& window_frame,
756 const gfx::Rect& view_frame);
759 // Adding a new message handler? Please add it in alphabetical order above
760 // and put it in the same position in the .cc file.
762 // Misc private functions ----------------------------------------------------
763 // Check whether the preferred size has changed.
764 void CheckPreferredSize();
766 // This callback is triggered when DownloadFavicon completes, either
767 // succesfully or with a failure. See DownloadFavicon for more
769 void DidDownloadFavicon(ImageResourceFetcher* fetcher,
770 const SkBitmap& image);
772 // Requests to download a favicon image. When done, the RenderView is notified
773 // by way of DidDownloadFavicon. Returns true if the request was successfully
774 // started, false otherwise. id is used to uniquely identify the request and
775 // passed back to the DidDownloadFavicon method. If the image has multiple
776 // frames, the frame whose size is image_size is returned. If the image
777 // doesn't have a frame at the specified size, the first is returned.
778 bool DownloadFavicon(int id, const GURL& image_url, int image_size);
780 // Called to get the WebPlugin to handle find requests in the document.
781 // Returns NULL if there is no such WebPlugin.
782 blink::WebPlugin* GetWebPluginForFind();
784 // Returns true if the |params| navigation is to an entry that has been
785 // cropped due to a recent navigation the browser did not know about.
786 bool IsBackForwardToStaleEntry(const FrameMsg_Navigate_Params& params,
789 // Make the given |frame| show an empty, unscriptable page.
790 // TODO(creis): Move this to RenderFrame.
791 void NavigateToSwappedOutURL(blink::WebFrame* frame);
793 // If we initiated a navigation, this function will populate |document_state|
794 // with the navigation information saved in OnNavigate().
795 void PopulateDocumentStateFromPending(DocumentState* document_state);
797 // Returns a new NavigationState populated with the navigation information
798 // saved in OnNavigate().
799 NavigationState* CreateNavigationStateFromPending();
801 // Processes the command-line flags --enable-viewport,
802 // --enable-fixed-layout[=w,h] and --enable-pinch.
803 void ProcessViewLayoutFlags(const base::CommandLine& command_line);
805 #if defined(OS_ANDROID)
806 // Launch an Android content intent with the given URL.
807 void LaunchAndroidContentIntent(const GURL& intent_url, size_t request_id);
810 // Sends a reply to the current find operation handling if it was a
811 // synchronous find request.
812 void SendFindReply(int request_id,
815 const blink::WebRect& selection_rect,
816 bool final_status_update);
818 // Starts nav_state_sync_timer_ if it isn't already running.
819 void StartNavStateSyncTimerIfNecessary();
821 #if defined(OS_POSIX) && !defined(OS_MACOSX)
822 void UpdateFontRenderingFromRendererPrefs();
824 void UpdateFontRenderingFromRendererPrefs() {}
827 // Update the target url and tell the browser that the target URL has changed.
828 // If |url| is empty, show |fallback_url|.
829 void UpdateTargetURL(const GURL& url, const GURL& fallback_url);
831 // Tells the browser what the new list of favicons for the webpage is.
832 void SendUpdateFaviconURL(const std::vector<FaviconURL>& urls);
834 // Invoked from DidStopLoading(). Sends the current list of loaded favicons to
836 void DidStopLoadingIcons();
838 // Coordinate conversion -----------------------------------------------------
840 gfx::RectF ClientRectToPhysicalWindowRect(const gfx::RectF& rect) const;
842 // RenderFrameImpl accessible state ------------------------------------------
843 // The following section is the set of methods that RenderFrameImpl needs
844 // to access RenderViewImpl state. The set of state variables are page-level
845 // specific, so they don't belong in RenderFrameImpl and should remain in
847 ObserverList<RenderViewObserver>& observers() {
851 // TODO(nasko): Remove this method when we move to frame proxy objects, since
852 // the concept of swapped out will be eliminated.
853 void set_is_swapped_out(bool swapped_out) {
854 is_swapped_out_ = swapped_out;
857 NavigationGesture navigation_gesture() {
858 return navigation_gesture_;
860 void set_navigation_gesture(NavigationGesture gesture) {
861 navigation_gesture_ = gesture;
864 // ---------------------------------------------------------------------------
865 // ADDING NEW FUNCTIONS? Please keep private functions alphabetized and put
866 // it in the same order in the .cc file as it was in the header.
867 // ---------------------------------------------------------------------------
869 // Settings ------------------------------------------------------------------
871 WebPreferences webkit_preferences_;
872 RendererPreferences renderer_preferences_;
874 HostZoomLevels host_zoom_levels_;
876 // Whether content state (such as form state, scroll position and page
877 // contents) should be sent to the browser immediately. This is normally
878 // false, but set to true by some tests.
879 bool send_content_state_immediately_;
881 // Bitwise-ORed set of extra bindings that have been enabled. See
882 // BindingsPolicy for details.
883 int enabled_bindings_;
885 // If true, we send IPC messages when |preferred_size_| changes.
886 bool send_preferred_size_changes_;
888 // If non-empty, and |send_preferred_size_changes_| is true, disable drawing
889 // scroll bars on windows smaller than this size. Used for windows that the
890 // browser resizes to the size of the content, such as browser action popups.
891 // If a render view is set to the minimum size of its content, webkit may add
892 // scroll bars. This makes sense for fixed sized windows, but it does not
893 // make sense when the size of the view was chosen to fit the content.
894 // This setting ensures that no scroll bars are drawn. The size limit exists
895 // because if the view grows beyond a size known to the browser, scroll bars
897 gfx::Size disable_scrollbars_size_limit_;
899 // Loading state -------------------------------------------------------------
901 // The gesture that initiated the current navigation.
902 // TODO(nasko): Move to RenderFrame, as this is per-frame state.
903 NavigationGesture navigation_gesture_;
906 bool opened_by_user_gesture_;
908 // Whether this RenderView was created by a frame that was suppressing its
909 // opener. If so, we may want to load pages in a separate process. See
910 // decidePolicyForNavigation for details.
911 bool opener_suppressed_;
913 // Whether we must stop creating nested message loops for modal dialogs until
914 // OnSwapOut is called. This is necessary because modal dialogs have a
915 // PageGroupLoadDeferrer on the stack that interferes with swapping out.
916 bool suppress_dialogs_until_swap_out_;
918 // Holds state pertaining to a navigation that we initiated. This is held by
919 // the WebDataSource::ExtraData attribute. We use pending_navigation_state_
920 // as a temporary holder for the state until the WebDataSource corresponding
921 // to the new navigation is created. See DidCreateDataSource.
922 // TODO(nasko): Move to RenderFrame, as this is per-frame state.
923 scoped_ptr<FrameMsg_Navigate_Params> pending_navigation_params_;
925 // Timer used to delay the updating of nav state (see SyncNavigationState).
926 base::OneShotTimer<RenderViewImpl> nav_state_sync_timer_;
928 // Page IDs ------------------------------------------------------------------
929 // See documentation in RenderView.
932 // Indicates the ID of the last page that we sent a FrameNavigate to the
933 // browser for. This is used to determine if the most recent transition
934 // generated a history entry (less than page_id_), or not (equal to or
935 // greater than). Note that this will be greater than page_id_ if the user
937 int32 last_page_id_sent_to_browser_;
939 // The next available page ID to use for this RenderView. These IDs are
940 // specific to a given RenderView and the frames within it.
943 // The offset of the current item in the history list.
944 int history_list_offset_;
946 // The RenderView's current impression of the history length. This includes
947 // any items that have committed in this process, but because of cross-process
948 // navigations, the history may have some entries that were committed in other
949 // processes. We won't know about them until the next navigation in this
951 int history_list_length_;
953 // Counter to track how many frames have sent start notifications but not stop
954 // notifications. TODO(avi): Remove this once DidStartLoading/DidStopLoading
956 int frames_in_progress_;
958 // The list of page IDs for each history item this RenderView knows about.
959 // Some entries may be -1 if they were rendered by other processes or were
960 // restored from a previous session. This lets us detect attempts to
961 // navigate to stale entries that have been cropped from our history.
962 std::vector<int32> history_page_ids_;
964 // UI state ------------------------------------------------------------------
966 // The state of our target_url transmissions. When we receive a request to
967 // send a URL to the browser, we set this to TARGET_INFLIGHT until an ACK
968 // comes back - if a new request comes in before the ACK, we store the new
969 // URL in pending_target_url_ and set the status to TARGET_PENDING. If an
970 // ACK comes back and we are in TARGET_PENDING, we send the stored URL and
971 // revert to TARGET_INFLIGHT.
973 // We don't need a queue of URLs to send, as only the latest is useful.
976 TARGET_INFLIGHT, // We have a request in-flight, waiting for an ACK
977 TARGET_PENDING // INFLIGHT + we have a URL waiting to be sent
978 } target_url_status_;
980 // The URL we show the user in the status bar. We use this to determine if we
981 // want to send a new one (we do not need to send duplicates). It will be
982 // equal to either |mouse_over_url_| or |focus_url_|, depending on which was
986 // The URL the user's mouse is hovering over.
987 GURL mouse_over_url_;
989 // The URL that has keyboard focus.
992 // The next target URL we want to send to the browser.
993 GURL pending_target_url_;
995 // Indicates whether this view overrides url-based zoom settings.
996 bool uses_temporary_zoom_level_;
998 #if defined(OS_ANDROID)
999 // Cache the old top controls state constraints. Used when updating
1000 // current value only without altering the constraints.
1001 cc::TopControlsState top_controls_constraints_;
1004 // View ----------------------------------------------------------------------
1006 // Cache the preferred size of the page in order to prevent sending the IPC
1007 // when layout() recomputes but doesn't actually change sizes.
1008 gfx::Size preferred_size_;
1010 // Used to delay determining the preferred size (to avoid intermediate
1011 // states for the sizes).
1012 base::OneShotTimer<RenderViewImpl> check_preferred_size_timer_;
1014 // Bookkeeping to suppress redundant scroll and focus requests for an already
1015 // scrolled and focused editable node.
1016 bool has_scrolled_focused_editable_node_into_rect_;
1017 gfx::Rect rect_for_scrolled_focused_editable_node_;
1019 bool has_scrolled_main_frame_;
1021 // Helper objects ------------------------------------------------------------
1023 scoped_ptr<RenderFrameImpl> main_render_frame_;
1025 // The next group of objects all implement RenderViewObserver, so are deleted
1026 // along with the RenderView automatically. This is why we just store
1029 // The speech recognition dispatcher attached to this view, lazily
1031 SpeechRecognitionDispatcher* speech_recognition_dispatcher_;
1033 // BrowserPluginManager attached to this view; lazily initialized.
1034 scoped_refptr<BrowserPluginManager> browser_plugin_manager_;
1036 DevToolsAgent* devtools_agent_;
1038 // Mouse Lock dispatcher attached to this view.
1039 MouseLockDispatcher* mouse_lock_dispatcher_;
1041 scoped_ptr<HistoryController> history_controller_;
1043 #if defined(OS_ANDROID)
1044 // Android Specific ---------------------------------------------------------
1046 // Expected id of the next content intent launched. Used to prevent scheduled
1047 // intents to be launched if aborted.
1048 size_t expected_content_intent_id_;
1050 // List of click-based content detectors.
1051 typedef std::vector< linked_ptr<ContentDetector> > ContentDetectorList;
1052 ContentDetectorList content_detectors_;
1054 // A date/time picker object for date and time related input elements.
1055 scoped_ptr<RendererDateTimePicker> date_time_picker_client_;
1058 // Plugins -------------------------------------------------------------------
1060 // All the currently active plugin delegates for this RenderView; kept so
1061 // that we can enumerate them to send updates about things like window
1062 // location or tab focus and visibily. These are non-owning references.
1063 std::set<WebPluginDelegateProxy*> plugin_delegates_;
1066 // The ID of the focused NPAPI plug-in.
1067 int focused_plugin_id_;
1070 #if defined(ENABLE_PLUGINS)
1071 PepperPluginInstanceImpl* plugin_find_handler_;
1073 typedef std::set<PepperPluginInstanceImpl*> PepperPluginSet;
1074 PepperPluginSet active_pepper_instances_;
1076 // TODO(jam): these belong on RenderFrame, once the browser knows which frame
1077 // is focused and sends the IPCs which use these to the correct frame. Until
1078 // then, we must store these on RenderView as that's the one place that knows
1079 // about all the RenderFrames for a page.
1081 // Whether or not the focus is on a PPAPI plugin
1082 PepperPluginInstanceImpl* focused_pepper_plugin_;
1084 // The plugin instance that received the last mouse event. It is set to NULL
1085 // if the last mouse event went to elements other than Pepper plugins.
1086 // |pepper_last_mouse_event_target_| is not owned by this class. We depend on
1087 // the RenderFrameImpl to NULL it out when it destructs.
1088 PepperPluginInstanceImpl* pepper_last_mouse_event_target_;
1091 // Misc ----------------------------------------------------------------------
1093 // The current and pending file chooser completion objects. If the queue is
1094 // nonempty, the first item represents the currently running file chooser
1095 // callback, and the remaining elements are the other file chooser completion
1096 // still waiting to be run (in order).
1097 struct PendingFileChooser;
1098 std::deque< linked_ptr<PendingFileChooser> > file_chooser_completions_;
1100 // The current directory enumeration callback
1101 std::map<int, blink::WebFileChooserCompletion*> enumeration_completions_;
1102 int enumeration_completion_id_;
1104 // The SessionStorage namespace that we're assigned to has an ID, and that ID
1105 // is passed to us upon creation. WebKit asks for this ID upon first use and
1106 // uses it whenever asking the browser process to allocate new storage areas.
1107 int64 session_storage_namespace_id_;
1109 // Stores edit commands associated to the next key event.
1110 // Shall be cleared as soon as the next key event is processed.
1111 EditCommands edit_commands_;
1113 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1114 // The external popup for the currently showing select popup.
1115 scoped_ptr<ExternalPopupMenu> external_popup_menu_;
1118 // All the registered observers. We expect this list to be small, so vector
1120 ObserverList<RenderViewObserver> observers_;
1122 // Wraps the |webwidget_| as a MouseLockDispatcher::LockTarget interface.
1123 scoped_ptr<MouseLockDispatcher::LockTarget> webwidget_mouse_lock_target_;
1125 // State associated with the GetWindowSnapshot function.
1126 int next_snapshot_id_;
1127 typedef std::map<int, WindowSnapshotCallback> PendingSnapshotMap;
1128 PendingSnapshotMap pending_snapshots_;
1130 // This field stores drag/drop related info for the event that is currently
1131 // being handled. If the current event results in starting a drag/drop
1132 // session, this info is sent to the browser along with other drag/drop info.
1133 DragEventSourceInfo possible_drag_event_info_;
1135 // NOTE: stats_collection_observer_ should be the last members because their
1136 // constructors call the AddObservers method of RenderViewImpl.
1137 scoped_ptr<StatsCollectionObserver> stats_collection_observer_;
1139 typedef std::map<cc::SharedBitmapId, cc::SharedBitmap*> BitmapMap;
1140 BitmapMap disambiguation_bitmaps_;
1142 // ---------------------------------------------------------------------------
1143 // ADDING NEW DATA? Please see if it fits appropriately in one of the above
1144 // sections rather than throwing it randomly at the end. If you're adding a
1145 // bunch of stuff, you should probably create a helper class and put your
1146 // data and methods on that to avoid bloating RenderView more. You can
1147 // use the Observer interface to filter IPC messages and receive frame change
1149 // ---------------------------------------------------------------------------
1151 DISALLOW_COPY_AND_ASSIGN(RenderViewImpl);
1154 } // namespace content
1156 #endif // CONTENT_RENDERER_RENDER_VIEW_IMPL_H_