blob: 0f322a3507f6a1ffdac4cf644e181d4db338d7cb [file] [log] [blame]
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/render_view_impl.h"
#include <algorithm>
#include <cmath>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/debug/alias.h"
#include "base/debug/trace_event.h"
#include "base/files/file_path.h"
#include "base/i18n/rtl.h"
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/process/kill.h"
#include "base/process/process.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "cc/base/switches.h"
#include "content/child/appcache/appcache_dispatcher.h"
#include "content/child/appcache/web_application_cache_host_impl.h"
#include "content/child/child_shared_bitmap_manager.h"
#include "content/child/child_thread.h"
#include "content/child/npapi/webplugin_delegate_impl.h"
#include "content/child/request_extra_data.h"
#include "content/child/webmessageportchannel_impl.h"
#include "content/common/content_constants_internal.h"
#include "content/common/database_messages.h"
#include "content/common/dom_storage/dom_storage_types.h"
#include "content/common/drag_messages.h"
#include "content/common/frame_messages.h"
#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
#include "content/common/input_messages.h"
#include "content/common/pepper_messages.h"
#include "content/common/ssl_status_serialization.h"
#include "content/common/view_messages.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/drop_data.h"
#include "content/public/common/favicon_url.h"
#include "content/public/common/file_chooser_file_info.h"
#include "content/public/common/file_chooser_params.h"
#include "content/public/common/page_state.h"
#include "content/public/common/page_zoom.h"
#include "content/public/common/ssl_status.h"
#include "content/public/common/three_d_api_types.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "content/public/common/web_preferences.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/renderer/document_state.h"
#include "content/public/renderer/navigation_state.h"
#include "content/public/renderer/render_view_observer.h"
#include "content/public/renderer/render_view_visitor.h"
#include "content/renderer/browser_plugin/browser_plugin.h"
#include "content/renderer/browser_plugin/browser_plugin_manager.h"
#include "content/renderer/devtools/devtools_agent.h"
#include "content/renderer/disambiguation_popup_helper.h"
#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
#include "content/renderer/drop_data_builder.h"
#include "content/renderer/gpu/gpu_benchmarking_extension.h"
#include "content/renderer/gpu/render_widget_compositor.h"
#include "content/renderer/history_controller.h"
#include "content/renderer/history_serialization.h"
#include "content/renderer/idle_user_detector.h"
#include "content/renderer/ime_event_guard.h"
#include "content/renderer/input/input_handler_manager.h"
#include "content/renderer/internal_document_state_data.h"
#include "content/renderer/media/audio_device_factory.h"
#include "content/renderer/media/video_capture_impl_manager.h"
#include "content/renderer/memory_benchmarking_extension.h"
#include "content/renderer/mhtml_generator.h"
#include "content/renderer/net_info_helper.h"
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_frame_proxy.h"
#include "content/renderer/render_process.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_view_mouse_lock_dispatcher.h"
#include "content/renderer/render_widget_fullscreen_pepper.h"
#include "content/renderer/renderer_webapplicationcachehost_impl.h"
#include "content/renderer/resizing_mode_selector.h"
#include "content/renderer/savable_resources.h"
#include "content/renderer/skia_benchmarking_extension.h"
#include "content/renderer/speech_recognition_dispatcher.h"
#include "content/renderer/stats_collection_controller.h"
#include "content/renderer/stats_collection_observer.h"
#include "content/renderer/text_input_client_observer.h"
#include "content/renderer/v8_value_converter_impl.h"
#include "content/renderer/web_ui_extension.h"
#include "content/renderer/web_ui_extension_data.h"
#include "content/renderer/web_ui_mojo.h"
#include "content/renderer/websharedworker_proxy.h"
#include "media/audio/audio_output_device.h"
#include "media/base/media_switches.h"
#include "media/filters/audio_renderer_impl.h"
#include "media/filters/gpu_video_accelerator_factories.h"
#include "net/base/data_url.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/http/http_util.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/WebKit/public/platform/WebCString.h"
#include "third_party/WebKit/public/platform/WebConnectionType.h"
#include "third_party/WebKit/public/platform/WebDragData.h"
#include "third_party/WebKit/public/platform/WebHTTPBody.h"
#include "third_party/WebKit/public/platform/WebImage.h"
#include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
#include "third_party/WebKit/public/platform/WebPoint.h"
#include "third_party/WebKit/public/platform/WebRect.h"
#include "third_party/WebKit/public/platform/WebSize.h"
#include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/platform/WebVector.h"
#include "third_party/WebKit/public/web/WebAXObject.h"
#include "third_party/WebKit/public/web/WebColorName.h"
#include "third_party/WebKit/public/web/WebColorSuggestion.h"
#include "third_party/WebKit/public/web/WebDOMEvent.h"
#include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
#include "third_party/WebKit/public/web/WebDataSource.h"
#include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
#include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
#include "third_party/WebKit/public/web/WebDevToolsAgent.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebFileChooserParams.h"
#include "third_party/WebKit/public/web/WebFindOptions.h"
#include "third_party/WebKit/public/web/WebFormControlElement.h"
#include "third_party/WebKit/public/web/WebFormElement.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebGlyphCache.h"
#include "third_party/WebKit/public/web/WebHistoryItem.h"
#include "third_party/WebKit/public/web/WebHitTestResult.h"
#include "third_party/WebKit/public/web/WebInputElement.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
#include "third_party/WebKit/public/web/WebNavigationPolicy.h"
#include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
#include "third_party/WebKit/public/web/WebNodeList.h"
#include "third_party/WebKit/public/web/WebPageSerializer.h"
#include "third_party/WebKit/public/web/WebPlugin.h"
#include "third_party/WebKit/public/web/WebPluginAction.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebPluginDocument.h"
#include "third_party/WebKit/public/web/WebRange.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebSearchableFormData.h"
#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
#include "third_party/WebKit/public/web/WebSettings.h"
#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "third_party/WebKit/public/web/WebWindowFeatures.h"
#include "third_party/WebKit/public/web/default/WebRenderTheme.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/icu/source/common/unicode/uscript.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/ui_base_switches_util.h"
#include "ui/events/latency_info.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/gfx/size_conversions.h"
#include "v8/include/v8.h"
#if defined(OS_ANDROID)
#include <cpu-features.h>
#include "content/renderer/android/address_detector.h"
#include "content/renderer/android/content_detector.h"
#include "content/renderer/android/email_detector.h"
#include "content/renderer/android/phone_number_detector.h"
#include "net/android/network_library.h"
#include "third_party/WebKit/public/platform/WebFloatPoint.h"
#include "third_party/WebKit/public/platform/WebFloatRect.h"
#include "ui/gfx/rect_f.h"
#elif defined(OS_WIN)
// TODO(port): these files are currently Windows only because they concern:
// * theming
#include "ui/native_theme/native_theme_win.h"
#elif defined(USE_X11)
#include "ui/native_theme/native_theme.h"
#elif defined(OS_MACOSX)
#include "skia/ext/skia_utils_mac.h"
#endif
#if defined(ENABLE_PLUGINS)
#include "content/renderer/npapi/webplugin_delegate_proxy.h"
#include "content/renderer/pepper/pepper_plugin_instance_impl.h"
#include "content/renderer/pepper/pepper_plugin_registry.h"
#endif
#if defined(ENABLE_WEBRTC)
#include "content/renderer/media/rtc_peer_connection_handler.h"
#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
#endif
using blink::WebAXObject;
using blink::WebApplicationCacheHost;
using blink::WebApplicationCacheHostClient;
using blink::WebCString;
using blink::WebColor;
using blink::WebColorName;
using blink::WebConsoleMessage;
using blink::WebData;
using blink::WebDataSource;
using blink::WebDocument;
using blink::WebDOMEvent;
using blink::WebDOMMessageEvent;
using blink::WebDragData;
using blink::WebDragOperation;
using blink::WebDragOperationsMask;
using blink::WebElement;
using blink::WebFileChooserCompletion;
using blink::WebFindOptions;
using blink::WebFormControlElement;
using blink::WebFormElement;
using blink::WebFrame;
using blink::WebGestureEvent;
using blink::WebHistoryItem;
using blink::WebHTTPBody;
using blink::WebIconURL;
using blink::WebImage;
using blink::WebInputElement;
using blink::WebInputEvent;
using blink::WebLocalFrame;
using blink::WebMediaPlayerAction;
using blink::WebMouseEvent;
using blink::WebNavigationPolicy;
using blink::WebNavigationType;
using blink::WebNode;
using blink::WebPageSerializer;
using blink::WebPageSerializerClient;
using blink::WebPeerConnection00Handler;
using blink::WebPeerConnection00HandlerClient;
using blink::WebPeerConnectionHandler;
using blink::WebPeerConnectionHandlerClient;
using blink::WebPluginAction;
using blink::WebPluginContainer;
using blink::WebPluginDocument;
using blink::WebPoint;
using blink::WebRange;
using blink::WebRect;
using blink::WebReferrerPolicy;
using blink::WebScriptSource;
using blink::WebSearchableFormData;
using blink::WebSecurityOrigin;
using blink::WebSecurityPolicy;
using blink::WebSerializedScriptValue;
using blink::WebSettings;
using blink::WebSize;
using blink::WebStorageNamespace;
using blink::WebStorageQuotaCallbacks;
using blink::WebStorageQuotaError;
using blink::WebStorageQuotaType;
using blink::WebString;
using blink::WebTextAffinity;
using blink::WebTextDirection;
using blink::WebTouchEvent;
using blink::WebURL;
using blink::WebURLError;
using blink::WebURLRequest;
using blink::WebURLResponse;
using blink::WebUserGestureIndicator;
using blink::WebVector;
using blink::WebView;
using blink::WebWidget;
using blink::WebWindowFeatures;
using blink::WebNetworkStateNotifier;
using blink::WebRuntimeFeatures;
using base::Time;
using base::TimeDelta;
#if defined(OS_ANDROID)
using blink::WebContentDetectionResult;
using blink::WebFloatPoint;
using blink::WebFloatRect;
using blink::WebHitTestResult;
#endif
namespace content {
//-----------------------------------------------------------------------------
typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
LAZY_INSTANCE_INITIALIZER;
// Time, in seconds, we delay before sending content state changes (such as form
// state and scroll position) to the browser. We delay sending changes to avoid
// spamming the browser.
// To avoid having tab/session restore require sending a message to get the
// current content state during tab closing we use a shorter timeout for the
// foreground renderer. This means there is a small window of time from which
// content state is modified and not sent to session restore, but this is
// better than having to wake up all renderers during shutdown.
const int kDelaySecondsForContentStateSyncHidden = 5;
const int kDelaySecondsForContentStateSync = 1;
#if defined(OS_ANDROID)
// Delay between tapping in content and launching the associated android intent.
// Used to allow users see what has been recognized as content.
const size_t kContentIntentDelayMilliseconds = 700;
#endif
static RenderViewImpl* (*g_create_render_view_impl)(const ViewMsg_New_Params&) =
NULL;
// static
bool RenderViewImpl::IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
}
// static
Referrer RenderViewImpl::GetReferrerFromRequest(
WebFrame* frame,
const WebURLRequest& request) {
return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
request.referrerPolicy());
}
// static
WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
WebNavigationPolicy policy) {
switch (policy) {
case blink::WebNavigationPolicyIgnore:
return IGNORE_ACTION;
case blink::WebNavigationPolicyDownload:
return SAVE_TO_DISK;
case blink::WebNavigationPolicyCurrentTab:
return CURRENT_TAB;
case blink::WebNavigationPolicyNewBackgroundTab:
return NEW_BACKGROUND_TAB;
case blink::WebNavigationPolicyNewForegroundTab:
return NEW_FOREGROUND_TAB;
case blink::WebNavigationPolicyNewWindow:
return NEW_WINDOW;
case blink::WebNavigationPolicyNewPopup:
return NEW_POPUP;
default:
NOTREACHED() << "Unexpected WebNavigationPolicy";
return IGNORE_ACTION;
}
}
// Returns true if the device scale is high enough that losing subpixel
// antialiasing won't have a noticeable effect on text quality.
static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
#if defined(OS_ANDROID)
// On Android, we never have subpixel antialiasing.
return true;
#else
return device_scale_factor > 1.5f;
#endif
}
static bool PreferCompositingToLCDText(float device_scale_factor) {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
return false;
if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
return true;
if (RenderThreadImpl::current() &&
!RenderThreadImpl::current()->is_lcd_text_enabled())
return true;
return DeviceScaleEnsuresTextQuality(device_scale_factor);
}
static bool ShouldUseTransitionCompositing(float device_scale_factor) {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
return false;
if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
return true;
// TODO(ajuma): Re-enable this by default for high-DPI once the problem
// of excessive layer promotion caused by overlap has been addressed.
// http://crbug.com/178119.
return false;
}
static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
switch (type) {
case blink::WebIconURL::TypeFavicon:
return FaviconURL::FAVICON;
case blink::WebIconURL::TypeTouch:
return FaviconURL::TOUCH_ICON;
case blink::WebIconURL::TypeTouchPrecomposed:
return FaviconURL::TOUCH_PRECOMPOSED_ICON;
case blink::WebIconURL::TypeInvalid:
return FaviconURL::INVALID_ICON;
}
return FaviconURL::INVALID_ICON;
}
static void ConvertToFaviconSizes(
const blink::WebVector<blink::WebSize>& web_sizes,
std::vector<gfx::Size>* sizes) {
DCHECK(sizes->empty());
sizes->reserve(web_sizes.size());
for (size_t i = 0; i < web_sizes.size(); ++i)
sizes->push_back(gfx::Size(web_sizes[i]));
}
///////////////////////////////////////////////////////////////////////////////
struct RenderViewImpl::PendingFileChooser {
PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
: params(p),
completion(c) {
}
FileChooserParams params;
WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
};
namespace {
class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
public:
explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
: webwidget_(webwidget) {}
void OnLockMouseACK(bool succeeded) override {
if (succeeded)
webwidget_->didAcquirePointerLock();
else
webwidget_->didNotAcquirePointerLock();
}
void OnMouseLockLost() override { webwidget_->didLosePointerLock(); }
bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
// The WebWidget handles mouse lock in WebKit's handleInputEvent().
return false;
}
private:
blink::WebWidget* webwidget_;
};
bool TouchEnabled() {
// Based on the definition of chrome::kEnableTouchIcon.
#if defined(OS_ANDROID)
return true;
#else
return false;
#endif
}
WebDragData DropDataToWebDragData(const DropData& drop_data) {
std::vector<WebDragData::Item> item_list;
// These fields are currently unused when dragging into WebKit.
DCHECK(drop_data.download_metadata.empty());
DCHECK(drop_data.file_contents.empty());
DCHECK(drop_data.file_description_filename.empty());
if (!drop_data.text.is_null()) {
WebDragData::Item item;
item.storageType = WebDragData::Item::StorageTypeString;
item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
item.stringData = drop_data.text.string();
item_list.push_back(item);
}
// TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
// meaningful to write an empty URL to the clipboard?
if (!drop_data.url.is_empty()) {
WebDragData::Item item;
item.storageType = WebDragData::Item::StorageTypeString;
item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
item.stringData = WebString::fromUTF8(drop_data.url.spec());
item.title = drop_data.url_title;
item_list.push_back(item);
}
if (!drop_data.html.is_null()) {
WebDragData::Item item;
item.storageType = WebDragData::Item::StorageTypeString;
item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
item.stringData = drop_data.html.string();
item.baseURL = drop_data.html_base_url;
item_list.push_back(item);
}
for (std::vector<ui::FileInfo>::const_iterator it =
drop_data.filenames.begin();
it != drop_data.filenames.end();
++it) {
WebDragData::Item item;
item.storageType = WebDragData::Item::StorageTypeFilename;
item.filenameData = it->path.AsUTF16Unsafe();
item.displayNameData = it->display_name.AsUTF16Unsafe();
item_list.push_back(item);
}
for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
drop_data.file_system_files.begin();
it != drop_data.file_system_files.end();
++it) {
WebDragData::Item item;
item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
item.fileSystemURL = it->url;
item.fileSystemFileSize = it->size;
item_list.push_back(item);
}
for (std::map<base::string16, base::string16>::const_iterator it =
drop_data.custom_data.begin();
it != drop_data.custom_data.end();
++it) {
WebDragData::Item item;
item.storageType = WebDragData::Item::StorageTypeString;
item.stringType = it->first;
item.stringData = it->second;
item_list.push_back(item);
}
WebDragData result;
result.initialize();
result.setItems(item_list);
result.setFilesystemId(drop_data.filesystem_id);
return result;
}
typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
const base::string16&,
UScriptCode);
void SetStandardFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->setStandardFontFamily(font, script);
}
void SetFixedFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->setFixedFontFamily(font, script);
}
void SetSerifFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->setSerifFontFamily(font, script);
}
void SetSansSerifFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->setSansSerifFontFamily(font, script);
}
void SetCursiveFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->setCursiveFontFamily(font, script);
}
void SetFantasyFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->setFantasyFontFamily(font, script);
}
void SetPictographFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->setPictographFontFamily(font, script);
}
// If |scriptCode| is a member of a family of "similar" script codes, returns
// the script code in that family that is used by WebKit for font selection
// purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
// considered equivalent for the purposes of font selection. WebKit uses the
// script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
// USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
// uses different scripts than the ones in Chrome pref names because the version
// of ICU included on certain ports does not have some of the newer scripts. If
// |scriptCode| is not a member of such a family, returns |scriptCode|.
UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
switch (scriptCode) {
case USCRIPT_HIRAGANA:
case USCRIPT_KATAKANA:
case USCRIPT_JAPANESE:
return USCRIPT_KATAKANA_OR_HIRAGANA;
case USCRIPT_KOREAN:
return USCRIPT_HANGUL;
default:
return scriptCode;
}
}
void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
SetFontFamilyWrapper setter,
WebSettings* settings) {
for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
++it) {
int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
UScriptCode code = static_cast<UScriptCode>(script);
(*setter)(settings, it->second, GetScriptForWebSettings(code));
}
}
}
} // namespace
RenderViewImpl::RenderViewImpl(const ViewMsg_New_Params& params)
: RenderWidget(blink::WebPopupTypeNone,
params.initial_size.screen_info,
params.swapped_out,
params.hidden,
params.never_visible),
webkit_preferences_(params.web_preferences),
send_content_state_immediately_(false),
enabled_bindings_(0),
send_preferred_size_changes_(false),
navigation_gesture_(NavigationGestureUnknown),
opened_by_user_gesture_(true),
opener_suppressed_(false),
suppress_dialogs_until_swap_out_(false),
page_id_(-1),
last_page_id_sent_to_browser_(-1),
next_page_id_(params.next_page_id),
history_list_offset_(-1),
history_list_length_(0),
frames_in_progress_(0),
target_url_status_(TARGET_NONE),
uses_temporary_zoom_level_(false),
#if defined(OS_ANDROID)
top_controls_constraints_(cc::BOTH),
#endif
has_scrolled_focused_editable_node_into_rect_(false),
speech_recognition_dispatcher_(NULL),
browser_plugin_manager_(NULL),
devtools_agent_(NULL),
mouse_lock_dispatcher_(NULL),
#if defined(OS_ANDROID)
expected_content_intent_id_(0),
#endif
#if defined(OS_WIN)
focused_plugin_id_(-1),
#endif
#if defined(ENABLE_PLUGINS)
plugin_find_handler_(NULL),
focused_pepper_plugin_(NULL),
pepper_last_mouse_event_target_(NULL),
#endif
enumeration_completion_id_(0),
session_storage_namespace_id_(params.session_storage_namespace_id),
next_snapshot_id_(0) {
}
void RenderViewImpl::Initialize(
const ViewMsg_New_Params& params,
bool was_created_by_renderer) {
routing_id_ = params.view_id;
surface_id_ = params.surface_id;
if (params.opener_route_id != MSG_ROUTING_NONE && was_created_by_renderer)
opener_id_ = params.opener_route_id;
// Ensure we start with a valid next_page_id_ from the browser.
DCHECK_GE(next_page_id_, 0);
main_render_frame_.reset(RenderFrameImpl::Create(
this, params.main_frame_routing_id));
// The main frame WebLocalFrame object is closed by
// RenderFrameImpl::frameDetached().
WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame_.get());
main_render_frame_->SetWebFrame(web_frame);
webwidget_ = WebView::create(this);
webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kStatsCollectionController))
stats_collection_observer_.reset(new StatsCollectionObserver(this));
#if defined(OS_ANDROID)
const std::string region_code =
command_line.HasSwitch(switches::kNetworkCountryIso)
? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
: net::android::GetTelephonyNetworkCountryIso();
content_detectors_.push_back(linked_ptr<ContentDetector>(
new AddressDetector()));
if (!region_code.empty()) {
content_detectors_.push_back(linked_ptr<ContentDetector>(
new PhoneNumberDetector(region_code)));
}
content_detectors_.push_back(linked_ptr<ContentDetector>(
new EmailDetector()));
#endif
RenderThread::Get()->AddRoute(routing_id_, this);
// Take a reference on behalf of the RenderThread. This will be balanced
// when we receive ViewMsg_ClosePage.
AddRef();
if (RenderThreadImpl::current()) {
RenderThreadImpl::current()->WidgetCreated();
if (is_hidden_)
RenderThreadImpl::current()->WidgetHidden();
}
// If this is a popup, we must wait for the CreatingNew_ACK message before
// completing initialization. Otherwise, we can finish it now.
if (opener_id_ == MSG_ROUTING_NONE) {
did_show_ = true;
CompleteInit();
}
g_view_map.Get().insert(std::make_pair(webview(), this));
g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
webview()->setDeviceScaleFactor(device_scale_factor_);
webview()->settings()->setPreferCompositingToLCDTextEnabled(
PreferCompositingToLCDText(device_scale_factor_));
webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
ShouldUseTransitionCompositing(device_scale_factor_));
webview()->settings()->setThreadedScrollingEnabled(
!command_line.HasSwitch(switches::kDisableThreadedScrolling));
webview()->settings()->setRootLayerScrolls(
command_line.HasSwitch(switches::kRootLayerScrolls));
ApplyWebPreferences(webkit_preferences_, webview());
webview()->settings()->setAllowConnectingInsecureWebSocket(
command_line.HasSwitch(switches::kAllowInsecureWebSocketFromHttpsOrigin));
RenderFrameProxy* proxy = NULL;
if (params.proxy_routing_id != MSG_ROUTING_NONE) {
CHECK(params.swapped_out);
proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
main_render_frame_.get(), params.proxy_routing_id);
main_render_frame_->set_render_frame_proxy(proxy);
}
// In --site-per-process, just use the WebRemoteFrame as the main frame.
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
proxy) {
webview()->setMainFrame(proxy->web_frame());
} else {
webview()->setMainFrame(main_render_frame_->GetWebFrame());
}
main_render_frame_->Initialize();
if (switches::IsTouchDragDropEnabled())
webview()->settings()->setTouchDragDropEnabled(true);
if (switches::IsTouchEditingEnabled())
webview()->settings()->setTouchEditingEnabled(true);
if (!params.frame_name.empty())
webview()->mainFrame()->setName(params.frame_name);
// TODO(davidben): Move this state from Blink into content.
if (params.window_was_created_with_opener)
webview()->setOpenedByDOM();
OnSetRendererPrefs(params.renderer_preferences);
if (!params.enable_auto_resize) {
OnResize(params.initial_size);
} else {
OnEnableAutoResize(params.min_size, params.max_size);
}
new MHTMLGenerator(this);
#if defined(OS_MACOSX)
new TextInputClientObserver(this);
#endif // defined(OS_MACOSX)
// The next group of objects all implement RenderViewObserver, so are deleted
// along with the RenderView automatically.
devtools_agent_ = new DevToolsAgent(main_render_frame_.get());
if (RenderWidgetCompositor* rwc = compositor()) {
webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
}
mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
history_controller_.reset(new HistoryController(this));
new IdleUserDetector(this);
if (command_line.HasSwitch(switches::kDomAutomationController))
enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
if (command_line.HasSwitch(switches::kStatsCollectionController))
enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
ProcessViewLayoutFlags(command_line);
GetContentClient()->renderer()->RenderViewCreated(this);
// If we have an opener_id but we weren't created by a renderer, then
// it's the browser asking us to set our opener to another RenderView.
if (params.opener_route_id != MSG_ROUTING_NONE && !was_created_by_renderer) {
RenderViewImpl* opener_view = FromRoutingID(params.opener_route_id);
if (opener_view)
webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
}
// If we are initially swapped out, navigate to kSwappedOutURL.
// This ensures we are in a unique origin that others cannot script.
if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
main_render_frame_->NavigateToSwappedOutURL();
}
RenderViewImpl::~RenderViewImpl() {
for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
it != disambiguation_bitmaps_.end();
++it)
delete it->second;
history_page_ids_.clear();
base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
// If file chooser is still waiting for answer, dispatch empty answer.
while (!file_chooser_completions_.empty()) {
if (file_chooser_completions_.front()->completion) {
file_chooser_completions_.front()->completion->didChooseFile(
WebVector<WebString>());
}
file_chooser_completions_.pop_front();
}
#if defined(OS_ANDROID)
// The date/time picker client is both a scoped_ptr member of this class and
// a RenderViewObserver. Reset it to prevent double deletion.
date_time_picker_client_.reset();
#endif
#ifndef NDEBUG
// Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
ViewMap* views = g_view_map.Pointer();
for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
DCHECK_NE(this, it->second) << "Failed to call Close?";
RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
for (RoutingIDViewMap::iterator it = routing_id_views->begin();
it != routing_id_views->end(); ++it)
DCHECK_NE(this, it->second) << "Failed to call Close?";
#endif
FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
}
/*static*/
RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
ViewMap* views = g_view_map.Pointer();
ViewMap::iterator it = views->find(webview);
return it == views->end() ? NULL : it->second;
}
/*static*/
RenderView* RenderView::FromWebView(blink::WebView* webview) {
return RenderViewImpl::FromWebView(webview);
}
/*static*/
RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
RoutingIDViewMap::iterator it = views->find(routing_id);
return it == views->end() ? NULL : it->second;
}
/*static*/
RenderView* RenderView::FromRoutingID(int routing_id) {
return RenderViewImpl::FromRoutingID(routing_id);
}
/* static */
size_t RenderViewImpl::GetRenderViewCount() {
return g_view_map.Get().size();
}
/*static*/
void RenderView::ForEach(RenderViewVisitor* visitor) {
ViewMap* views = g_view_map.Pointer();
for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
if (!visitor->Visit(it->second))
return;
}
}
/*static*/
void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
WebView* web_view) {
WebSettings* settings = web_view->settings();
ApplyFontsFromMap(prefs.standard_font_family_map,
SetStandardFontFamilyWrapper, settings);
ApplyFontsFromMap(prefs.fixed_font_family_map,
SetFixedFontFamilyWrapper, settings);
ApplyFontsFromMap(prefs.serif_font_family_map,
SetSerifFontFamilyWrapper, settings);
ApplyFontsFromMap(prefs.sans_serif_font_family_map,
SetSansSerifFontFamilyWrapper, settings);
ApplyFontsFromMap(prefs.cursive_font_family_map,
SetCursiveFontFamilyWrapper, settings);
ApplyFontsFromMap(prefs.fantasy_font_family_map,
SetFantasyFontFamilyWrapper, settings);
ApplyFontsFromMap(prefs.pictograph_font_family_map,
SetPictographFontFamilyWrapper, settings);
settings->setDefaultFontSize(prefs.default_font_size);
settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
settings->setMinimumFontSize(prefs.minimum_font_size);
settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
settings->setDefaultTextEncodingName(
base::ASCIIToUTF16(prefs.default_encoding));
settings->setJavaScriptEnabled(prefs.javascript_enabled);
settings->setWebSecurityEnabled(prefs.web_security_enabled);
settings->setJavaScriptCanOpenWindowsAutomatically(
prefs.javascript_can_open_windows_automatically);
settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
settings->setImagesEnabled(prefs.images_enabled);
settings->setPluginsEnabled(prefs.plugins_enabled);
settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
settings->setShrinksStandaloneImagesToFit(
prefs.shrinks_standalone_images_to_fit);
settings->setUsesEncodingDetector(prefs.uses_universal_detector);
settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
settings->setJavaScriptCanAccessClipboard(
prefs.javascript_can_access_clipboard);
WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
WebRuntimeFeatures::enableSlimmingPaint(prefs.slimming_paint_enabled);
settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
settings->setLocalStorageEnabled(prefs.local_storage_enabled);
settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
settings->setOfflineWebApplicationCacheEnabled(
prefs.application_cache_enabled);
settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
settings->setCookieEnabled(prefs.cookie_enabled);
settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
settings->setJavaEnabled(prefs.java_enabled);
// By default, allow_universal_access_from_file_urls is set to false and thus
// we mitigate attacks from local HTML files by not granting file:// URLs
// universal access. Only test shell will enable this.
settings->setAllowUniversalAccessFromFileURLs(
prefs.allow_universal_access_from_file_urls);
settings->setAllowFileAccessFromFileURLs(
prefs.allow_file_access_from_file_urls);
// Enable the web audio API if requested on the command line.
settings->setWebAudioEnabled(prefs.webaudio_enabled);
// Enable experimental WebGL support if requested on command line
// and support is compiled in.
settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
// Disable GL multisampling if requested on command line.
settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
// Enable WebGL errors to the JS console if requested.
settings->setWebGLErrorsToConsoleEnabled(
prefs.webgl_errors_to_console_enabled);
// Uses the mock theme engine for scrollbars.
settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
settings->setLayerSquashingEnabled(prefs.layer_squashing_enabled);
// Enable gpu-accelerated 2d canvas if requested on the command line.
settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
settings->setMinimumAccelerated2dCanvasSize(
prefs.minimum_accelerated_2d_canvas_size);
// Disable antialiasing for 2d canvas if requested on the command line.
settings->setAntialiased2dCanvasEnabled(
!prefs.antialiased_2d_canvas_disabled);
// Enabled antialiasing of clips for 2d canvas if requested on the command
// line.
settings->setAntialiasedClips2dCanvasEnabled(
prefs.antialiased_clips_2d_canvas_enabled);
// Set MSAA sample count for 2d canvas if requested on the command line (or
// default value if not).
settings->setAccelerated2dCanvasMSAASampleCount(
prefs.accelerated_2d_canvas_msaa_sample_count);
WebRuntimeFeatures::enableTextBlobs(prefs.text_blobs_enabled);
settings->setAsynchronousSpellCheckingEnabled(
prefs.asynchronous_spell_checking_enabled);
settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
// Tabs to link is not part of the settings. WebCore calls
// ChromeClient::tabsToLinks which is part of the glue code.
web_view->setTabsToLinks(prefs.tabs_to_links);
settings->setAllowDisplayOfInsecureContent(
prefs.allow_displaying_insecure_content);
settings->setAllowRunningOfInsecureContent(
prefs.allow_running_insecure_content);
settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
settings->setShouldClearDocumentBackground(
prefs.should_clear_document_background);
settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
settings->setRegionBasedColumnsEnabled(prefs.region_based_columns_enabled);
WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
settings->setAvailablePointerTypes(prefs.available_pointer_types);
settings->setPrimaryPointerType(
static_cast<WebSettings::PointerType>(prefs.primary_pointer_type));
settings->setAvailableHoverTypes(prefs.available_hover_types);
settings->setPrimaryHoverType(
static_cast<WebSettings::HoverType>(prefs.primary_hover_type));
settings->setDeviceSupportsTouch(prefs.device_supports_touch);
settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
settings->setDeferredImageDecodingEnabled(
prefs.deferred_image_decoding_enabled);
WebRuntimeFeatures::enableImageColorProfiles(
prefs.image_color_profiles_enabled);
settings->setShouldRespectImageOrientation(
prefs.should_respect_image_orientation);
settings->setUnsafePluginPastingEnabled(false);
settings->setEditingBehavior(
static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
settings->setViewportEnabled(prefs.viewport_enabled);
settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
settings->setMainFrameResizesAreOrientationChanges(
prefs.main_frame_resizes_are_orientation_changes);
settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
settings->setSelectionIncludesAltImageText(true);
settings->setV8CacheOptions(
static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
settings->setV8ScriptStreamingEnabled(prefs.v8_script_streaming_enabled);
settings->setV8ScriptStreamingMode(
static_cast<WebSettings::V8ScriptStreamingMode>(
prefs.v8_script_streaming_mode));
#if defined(OS_ANDROID)
settings->setAllowCustomScrollbarInMainFrame(false);
settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
settings->setFullscreenSupported(prefs.fullscreen_supported);
web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
settings->setAutoZoomFocusedNodeToLegibleScale(true);
settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
settings->setMediaControlsOverlayPlayButtonEnabled(true);
settings->setMediaPlaybackRequiresUserGesture(
prefs.user_gesture_required_for_media_playback);
settings->setDefaultVideoPosterURL(
base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
settings->setSupportDeprecatedTargetDensityDPI(
prefs.support_deprecated_target_density_dpi);
settings->setUseLegacyBackgroundSizeShorthandBehavior(
prefs.use_legacy_background_size_shorthand_behavior);
settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
settings->setUseWideViewport(prefs.use_wide_viewport);
settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
settings->setViewportMetaLayoutSizeQuirk(
prefs.viewport_meta_layout_size_quirk);
settings->setViewportMetaMergeContentQuirk(
prefs.viewport_meta_merge_content_quirk);
settings->setViewportMetaNonUserScalableQuirk(
prefs.viewport_meta_non_user_scalable_quirk);
settings->setViewportMetaZeroValuesQuirk(
prefs.viewport_meta_zero_values_quirk);
settings->setClobberUserAgentInitialScaleQuirk(
prefs.clobber_user_agent_initial_scale_quirk);
settings->setIgnoreMainFrameOverflowHiddenQuirk(
prefs.ignore_main_frame_overflow_hidden_quirk);
settings->setReportScreenSizeInPhysicalPixelsQuirk(
prefs.report_screen_size_in_physical_pixels_quirk);
bool record_full_layer =
RenderViewImpl::FromWebView(web_view)
? RenderViewImpl::FromWebView(web_view)->DoesRecordFullLayer()
: false;
settings->setMainFrameClipsContent(!record_full_layer);
settings->setShrinksStandaloneImagesToFit(false);
settings->setShrinksViewportContentToFit(true);
#endif
WebNetworkStateNotifier::setOnLine(prefs.is_online);
WebNetworkStateNotifier::setWebConnectionType(
NetConnectionTypeToWebConnectionType(prefs.connection_type));
settings->setPinchVirtualViewportEnabled(
prefs.pinch_virtual_viewport_enabled);
settings->setPinchOverlayScrollbarThickness(
prefs.pinch_overlay_scrollbar_thickness);
settings->setRubberBandingOnCompositorThread(
prefs.rubber_banding_on_compositor_thread);
settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
#if defined(OS_WIN)
settings->setShowContextMenuOnMouseUp(true);
#endif
}
/*static*/
RenderViewImpl* RenderViewImpl::Create(
const ViewMsg_New_Params& params,
bool was_created_by_renderer) {
DCHECK(params.view_id != MSG_ROUTING_NONE);
RenderViewImpl* render_view = NULL;
if (g_create_render_view_impl)
render_view = g_create_render_view_impl(params);
else
render_view = new RenderViewImpl(params);
render_view->Initialize(params, was_created_by_renderer);
return render_view;
}
// static
void RenderViewImpl::InstallCreateHook(
RenderViewImpl* (*create_render_view_impl)(const ViewMsg_New_Params&)) {
CHECK(!g_create_render_view_impl);
g_create_render_view_impl = create_render_view_impl;
}
void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
observers_.AddObserver(observer);
}
void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
observer->RenderViewGone();
observers_.RemoveObserver(observer);
}
blink::WebView* RenderViewImpl::webview() const {
return static_cast<blink::WebView*>(webwidget());
}
#if defined(ENABLE_PLUGINS)
void RenderViewImpl::PepperInstanceCreated(
PepperPluginInstanceImpl* instance) {
active_pepper_instances_.insert(instance);
}
void RenderViewImpl::PepperInstanceDeleted(
PepperPluginInstanceImpl* instance) {
active_pepper_instances_.erase(instance);
if (pepper_last_mouse_event_target_ == instance)
pepper_last_mouse_event_target_ = NULL;
if (focused_pepper_plugin_ == instance)
PepperFocusChanged(instance, false);
}
void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
bool focused) {
if (focused)
focused_pepper_plugin_ = instance;
else if (focused_pepper_plugin_ == instance)
focused_pepper_plugin_ = NULL;
UpdateTextInputType();
UpdateSelectionBounds();
}
void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
plugin_delegates_.insert(delegate);
// If the renderer is visible, set initial visibility and focus state.
if (!is_hidden()) {
#if defined(OS_MACOSX)
delegate->SetContainerVisibility(true);
if (webview() && webview()->isActive())
delegate->SetWindowFocus(true);
#endif
}
// Plugins start assuming the content has focus (so that they work in
// environments where RenderView isn't hosting them), so we always have to
// set the initial state. See webplugin_delegate_impl.h for details.
delegate->SetContentAreaFocus(has_focus());
}
void RenderViewImpl::UnregisterPluginDelegate(
WebPluginDelegateProxy* delegate) {
plugin_delegates_.erase(delegate);
}
#if defined(OS_WIN)
void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
if (focused)
focused_plugin_id_ = plugin_id;
else
focused_plugin_id_ = -1;
}
#endif
#if defined(OS_MACOSX)
void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
}
void RenderViewImpl::OnGetRenderedText() {
if (!webview())
return;
// Get rendered text from WebLocalFrame.
// TODO: Currently IPC truncates any data that has a
// size > kMaximumMessageSize. May be split the text into smaller chunks and
// send back using multiple IPC. See http://crbug.com/393444.
static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
std::string text = webview()->mainFrame()->contentAsText(
kMaximumMessageSize).utf8();
Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
}
void RenderViewImpl::StartPluginIme() {
IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
// This message can be sent during event-handling, and needs to be delivered
// within that context.
msg->set_unblock(true);
Send(msg);
}
#endif // defined(OS_MACOSX)
#endif // ENABLE_PLUGINS
void RenderViewImpl::TransferActiveWheelFlingAnimation(
const blink::WebActiveWheelFlingParameters& params) {
if (webview())
webview()->transferActiveWheelFlingAnimation(params);
}
bool RenderViewImpl::HasIMETextFocus() {
return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
}
bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
if (main_frame && main_frame->isWebLocalFrame())
GetContentClient()->SetActiveURL(main_frame->document().url());
ObserverListBase<RenderViewObserver>::Iterator it(observers_);
RenderViewObserver* observer;
while ((observer = it.GetNext()) != NULL)
if (observer->OnMessageReceived(message))
return true;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
OnScrollFocusedEditableNodeIntoRect)
IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
OnSetEditCommandsForNextKeyEvent)
IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
OnSetZoomLevelForLoadingURL)
IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
OnSetZoomLevelForView)
IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
OnResetPageEncodingToDefault)
IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
OnDragSourceSystemDragEnded)
IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
OnEnumerateDirectoryResponse)
IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
OnSuppressDialogsUntilSwapOut)
IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
OnEnablePreferredSizeChangedMode)
IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
OnDisableScrollbarsForSmallWindows)
IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
OnGetAllSavableResourceLinksForCurrentPage)
IPC_MESSAGE_HANDLER(
ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
// TODO(viettrungluu): Move to a separate message filter.
IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
OnSetHistoryLengthAndPrune)
IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
OnReleaseDisambiguationPopupBitmap)
IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
OnWindowSnapshotCompleted)
IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
#if defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
OnActivateNearestFindResult)
IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
OnUpdateTopControlsState)
IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
#elif defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
OnGetRenderedText)
IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
OnPluginImeCompositionCompleted)
IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
#endif
// Adding a new message? Add platform independent ones first, then put the
// platform specific ones at the end.
// Have the super handle all other messages.
IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
IPC_END_MESSAGE_MAP()
return handled;
}
void RenderViewImpl::OnSelectWordAroundCaret() {
if (!webview())
return;
handling_input_event_ = true;
webview()->focusedFrame()->selectWordAroundCaret();
handling_input_event_ = false;
}
bool RenderViewImpl::IsBackForwardToStaleEntry(const PageState& state,
int pending_history_list_offset,
int32 page_id,
bool is_reload) {
// Make sure this isn't a back/forward to an entry we have already cropped
// or replaced from our history, before the browser knew about it. If so,
// a new navigation has committed in the mean time, and we can ignore this.
bool is_back_forward = !is_reload && state.IsValid();
// Note: if the history_list_length_ is 0 for a back/forward, we must be
// restoring from a previous session. We'll update our state in OnNavigate.
if (!is_back_forward || history_list_length_ <= 0)
return false;
DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
// Check for whether the forward history has been cropped due to a recent
// navigation the browser didn't know about.
if (pending_history_list_offset >= history_list_length_)
return true;
// Check for whether this entry has been replaced with a new one.
int expected_page_id =
history_page_ids_[pending_history_list_offset];
if (expected_page_id > 0 && page_id != expected_page_id) {
if (page_id < expected_page_id)
return true;
// Otherwise we've removed an earlier entry and should have shifted all
// entries left. For now, it's ok to lazily update the list.
// TODO(creis): Notify all live renderers when we remove entries from
// the front of the list, so that we don't hit this case.
history_page_ids_[pending_history_list_offset] = page_id;
}
return false;
}
void RenderViewImpl::OnCopyImageAt(int x, int y) {
webview()->copyImageAt(WebPoint(x, y));
}
void RenderViewImpl::OnSaveImageAt(int x, int y) {
webview()->saveImageAt(WebPoint(x, y));
}
void RenderViewImpl::OnUpdateTargetURLAck() {
// Check if there is a targeturl waiting to be sent.
if (target_url_status_ == TARGET_PENDING)
Send(new ViewHostMsg_UpdateTargetURL(routing_id_, pending_target_url_));
target_url_status_ = TARGET_NONE;
}
void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
const std::string& value) {
if (!webview() || !webview()->focusedFrame())
return;
webview()->focusedFrame()->executeCommand(
WebString::fromUTF8(name), WebString::fromUTF8(value));
}
void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
if (!webview())
return;
Send(new InputHostMsg_MoveCaret_ACK(routing_id_));
webview()->focusedFrame()->moveCaretSelection(point);
}
void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
const gfx::Rect& rect) {
if (has_scrolled_focused_editable_node_into_rect_ &&
rect == rect_for_scrolled_focused_editable_node_) {
return;
}
blink::WebElement element = GetFocusedElement();
if (!element.isNull() && IsEditableNode(element)) {
rect_for_scrolled_focused_editable_node_ = rect;
has_scrolled_focused_editable_node_into_rect_ = true;
webview()->scrollFocusedNodeIntoRect(rect);
}
}
void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
const EditCommands& edit_commands) {
edit_commands_ = edit_commands;
}
void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
int32 minimum_page_id) {
DCHECK_GE(history_length, 0);
DCHECK(history_list_offset_ == history_list_length_ - 1);
DCHECK_GE(minimum_page_id, -1);
// Generate the new list.
std::vector<int32> new_history_page_ids(history_length, -1);
for (size_t i = 0; i < history_page_ids_.size(); ++i) {
if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
continue;
new_history_page_ids.push_back(history_page_ids_[i]);
}
new_history_page_ids.swap(history_page_ids_);
// Update indexes.
history_list_length_ = history_page_ids_.size();
history_list_offset_ = history_list_length_ - 1;
}
void RenderViewImpl::OnSetInitialFocus(bool reverse) {
if (!webview())
return;
webview()->setInitialFocus(reverse);
}
#if defined(OS_MACOSX)
void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
if (!webview())
return;
if (in_live_resize)
webview()->willStartLiveResize();
else
webview()->willEndLiveResize();
}
#endif
///////////////////////////////////////////////////////////////////////////////
// Sends the current history state to the browser so it will be saved before we
// navigate to a new page.
void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
// If we have a valid page ID at this point, then it corresponds to the page
// we are navigating away from. Otherwise, this is the first navigation, so
// there is no past session history to record.
if (page_id_ == -1)
return;
SendUpdateState(history_controller_->GetCurrentEntry());
}
void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
if (!entry)
return;
// Don't send state updates for kSwappedOutURL.
if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
return;
Send(new ViewHostMsg_UpdateState(
routing_id_, page_id_, HistoryEntryToPageState(entry)));
}
bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
// Before WebKit asks us to show an alert (etc.), it takes care of doing the
// equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
// it is particularly important that we do not call willEnterModalLoop as
// that would defer resource loads for the dialog itself.
if (RenderThreadImpl::current()) // Will be NULL during unit tests.
RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
message->EnableMessagePumping(); // Runs a nested message loop.
return Send(message);
}
void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
int id = next_snapshot_id_++;
pending_snapshots_.insert(std::make_pair(id, callback));
ui::LatencyInfo latency_info;
latency_info.AddLatencyNumber(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
0,
id);
scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
if (RenderWidgetCompositor* rwc = compositor()) {
latency_info_swap_promise_monitor =
rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
}
ScheduleCompositeWithForcedRedraw();
}
void RenderViewImpl::OnForceRedraw(int id) {
ui::LatencyInfo latency_info;
if (id) {
latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
0,
id);
}
scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
if (RenderWidgetCompositor* rwc = compositor()) {
latency_info_swap_promise_monitor =
rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
}
ScheduleCompositeWithForcedRedraw();
}
void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
const gfx::Size& size, const std::vector<unsigned char>& png) {
// Any pending snapshots with a lower ID than the one received are considered
// to be implicitly complete, and returned the same snapshot data.
PendingSnapshotMap::iterator it = pending_snapshots_.begin();
while(it != pending_snapshots_.end()) {
if (it->first <= snapshot_id) {
it->second.Run(size, png);
pending_snapshots_.erase(it++);
} else {
++it;
}
}
}
// blink::WebViewClient ------------------------------------------------------
WebView* RenderViewImpl::createView(WebLocalFrame* creator,
const WebURLRequest& request,
const WebWindowFeatures& features,
const WebString& frame_name,
WebNavigationPolicy policy,
bool suppress_opener) {
ViewHostMsg_CreateWindow_Params params;
params.opener_id = routing_id_;
params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
if (GetContentClient()->renderer()->AllowPopup())
params.user_gesture = true;
params.window_container_type = WindowFeaturesToContainerType(features);
params.session_storage_namespace_id = session_storage_namespace_id_;
if (frame_name != "_blank")
params.frame_name = frame_name;
params.opener_render_frame_id =
RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
params.opener_url = creator->document().url();
params.opener_top_level_frame_url = creator->top()->document().url();
GURL security_url(creator->document().securityOrigin().toString());
if (!security_url.is_valid())
security_url = GURL();
params.opener_security_origin = security_url;
params.opener_suppressed = suppress_opener;
params.disposition = NavigationPolicyToDisposition(policy);
if (!request.isNull()) {
params.target_url = request.url();
params.referrer = GetReferrerFromRequest(creator, request);
}
params.features = features;
for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
params.additional_features.push_back(features.additionalFeatures[i]);
int32 routing_id = MSG_ROUTING_NONE;
int32 main_frame_routing_id = MSG_ROUTING_NONE;
int32 surface_id = 0;
int64 cloned_session_storage_namespace_id = 0;
RenderThread::Get()->Send(
new ViewHostMsg_CreateWindow(params,
&routing_id,
&main_frame_routing_id,
&surface_id,
&cloned_session_storage_namespace_id));
if (routing_id == MSG_ROUTING_NONE)
return NULL;
WebUserGestureIndicator::consumeUserGesture();
// While this view may be a background extension page, it can spawn a visible
// render view. So we just assume that the new one is not another background
// page instead of passing on our own value.
// TODO(vangelis): Can we tell if the new view will be a background page?
bool never_visible = false;
ViewMsg_Resize_Params initial_size = ViewMsg_Resize_Params();
initial_size.screen_info = screen_info_;
// The initial hidden state for the RenderViewImpl here has to match what the
// browser will eventually decide for the given disposition. Since we have to
// return from this call synchronously, we just have to make our best guess
// and rely on the browser sending a WasHidden / WasShown message if it
// disagrees.
ViewMsg_New_Params view_params;
view_params.opener_route_id = routing_id_;
view_params.window_was_created_with_opener = true;
view_params.renderer_preferences = renderer_preferences_;
view_params.web_preferences = webkit_preferences_;
view_params.view_id = routing_id;
view_params.main_frame_routing_id = main_frame_routing_id;
view_params.surface_id = surface_id;
view_params.session_storage_namespace_id =
cloned_session_storage_namespace_id;
// WebCore will take care of setting the correct name.
view_params.frame_name = base::string16();
view_params.swapped_out = false;
view_params.proxy_routing_id = MSG_ROUTING_NONE;
view_params.hidden = (params.disposition == NEW_BACKGROUND_TAB);
view_params.never_visible = never_visible;
view_params.next_page_id = 1;
view_params.initial_size = initial_size;
view_params.enable_auto_resize = false;
view_params.min_size = gfx::Size();
view_params.max_size = gfx::Size();
RenderViewImpl* view = RenderViewImpl::Create(view_params, true);
view->opened_by_user_gesture_ = params.user_gesture;
// Record whether the creator frame is trying to suppress the opener field.
view->opener_suppressed_ = params.opener_suppressed;
return view->webview();
}
WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
RenderWidget* widget =
RenderWidget::Create(routing_id_, popup_type, screen_info_);
if (!widget)
return NULL;
if (screen_metrics_emulator_) {
widget->SetPopupOriginAdjustmentsForEmulation(
screen_metrics_emulator_.get());
}
return widget->webwidget();
}
WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
return new WebStorageNamespaceImpl(session_storage_namespace_id_);
}
void RenderViewImpl::printPage(WebLocalFrame* frame) {
FOR_EACH_OBSERVER(RenderViewObserver, observers_,
PrintPage(frame, handling_input_event_));
}
void RenderViewImpl::saveImageFromDataURL(const blink::WebString& data_url) {
// Note: We should basically send GURL but we use size-limited string instead
// in order to send a larger data url to save a image for <canvas> or <img>.
if (data_url.length() < kMaxLengthOfDataURLString)
Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_, data_url.utf8()));
}
bool RenderViewImpl::enumerateChosenDirectory(
const WebString& path,
WebFileChooserCompletion* chooser_completion) {
int id = enumeration_completion_id_++;
enumeration_completions_[id] = chooser_completion;
return Send(new ViewHostMsg_EnumerateDirectory(
routing_id_,
id,
base::FilePath::FromUTF16Unsafe(path)));
}
void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
DCHECK_GE(frames_in_progress_, 0);
if (frames_in_progress_ == 0)
FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
frames_in_progress_++;
}
void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
// TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
// calls DidStopLoading() without a matching DidStartLoading().
if (frames_in_progress_ == 0)
return;
frames_in_progress_--;
if (frames_in_progress_ == 0) {
DidStopLoadingIcons();
FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
}
}
void RenderViewImpl::didCancelCompositionOnSelectionChange() {
Send(new InputHostMsg_ImeCancelComposition(routing_id()));
}
bool RenderViewImpl::handleCurrentKeyboardEvent() {
if (edit_commands_.empty())
return false;
WebFrame* frame = webview()->focusedFrame();
if (!frame)
return false;
EditCommands::iterator it = edit_commands_.begin();
EditCommands::iterator end = edit_commands_.end();
bool did_execute_command = false;
for (; it != end; ++it) {
// In gtk and cocoa, it's possible to bind multiple edit commands to one
// key (but it's the exception). Once one edit command is not executed, it
// seems safest to not execute the rest.
if (!frame->executeCommand(WebString::fromUTF8(it->name),
WebString::fromUTF8(it->value),
GetFocusedElement()))
break;
did_execute_command = true;
}
return did_execute_command;
}
bool RenderViewImpl::runFileChooser(
const blink::WebFileChooserParams& params,
WebFileChooserCompletion* chooser_completion) {
// Do not open the file dialog in a hidden RenderView.
if (is_hidden())
return false;
FileChooserParams ipc_params;
if (params.directory)
ipc_params.mode = FileChooserParams::UploadFolder;
else if (params.multiSelect)
ipc_params.mode = FileChooserParams::OpenMultiple;
else if (params.saveAs)
ipc_params.mode = FileChooserParams::Save;
else
ipc_params.mode = FileChooserParams::Open;
ipc_params.title = params.title;
ipc_params.default_file_name =
base::FilePath::FromUTF16Unsafe(params.initialValue);
ipc_params.accept_types.reserve(params.acceptTypes.size());
for (size_t i = 0; i < params.acceptTypes.size(); ++i)
ipc_params.accept_types.push_back(params.acceptTypes[i]);
ipc_params.need_local_path = params.needLocalPath;
#if defined(OS_ANDROID)
ipc_params.capture = params.useMediaCapture;
#endif
return ScheduleFileChooser(ipc_params, chooser_completion);
}
void RenderViewImpl::SetValidationMessageDirection(
base::string16* wrapped_main_text,
blink::WebTextDirection main_text_hint,
base::string16* wrapped_sub_text,
blink::WebTextDirection sub_text_hint) {
if (main_text_hint == blink::WebTextDirectionLeftToRight) {
*wrapped_main_text =
base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text);
} else if (main_text_hint == blink::WebTextDirectionRightToLeft &&
!base::i18n::IsRTL()) {
base::i18n::WrapStringWithRTLFormatting(wrapped_main_text);
}
if (!wrapped_sub_text->empty()) {
if (sub_text_hint == blink::WebTextDirectionLeftToRight) {
*wrapped_sub_text =
base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text);
} else if (sub_text_hint == blink::WebTextDirectionRightToLeft) {
base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text);
}
}
}
void RenderViewImpl::showValidationMessage(
const blink::WebRect& anchor_in_root_view,
const blink::WebString& main_text,
blink::WebTextDirection main_text_hint,
const blink::WebString& sub_text,
blink::WebTextDirection sub_text_hint) {
base::string16 wrapped_main_text = main_text;
base::string16 wrapped_sub_text = sub_text;
SetValidationMessageDirection(
&wrapped_main_text, main_text_hint, &wrapped_sub_text, sub_text_hint);
Send(new ViewHostMsg_ShowValidationMessage(
routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
wrapped_main_text, wrapped_sub_text));
}
void RenderViewImpl::hideValidationMessage() {
Send(new ViewHostMsg_HideValidationMessage(routing_id()));
}
void RenderViewImpl::moveValidationMessage(
const blink::WebRect& anchor_in_root_view) {
Send(new ViewHostMsg_MoveValidationMessage(
routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
}
void RenderViewImpl::setStatusText(const WebString& text) {
}
void RenderViewImpl::UpdateTargetURL(const GURL& url,
const GURL& fallback_url) {
GURL latest_url = url.is_empty() ? fallback_url : url;
if (latest_url == target_url_)
return;
// Tell the browser to display a destination link.
if (target_url_status_ == TARGET_INFLIGHT ||
target_url_status_ == TARGET_PENDING) {
// If we have a request in-flight, save the URL to be sent when we
// receive an ACK to the in-flight request. We can happily overwrite
// any existing pending sends.
pending_target_url_ = latest_url;
target_url_status_ = TARGET_PENDING;
} else {
// URLs larger than |MaxURLChars()| cannot be sent through IPC -
// see |ParamTraits<GURL>|.
if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
latest_url = GURL();
Send(new ViewHostMsg_UpdateTargetURL(routing_id_, latest_url));
target_url_ = latest_url;
target_url_status_ = TARGET_INFLIGHT;
}
}
gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
const gfx::RectF& rect) const {
gfx::RectF window_rect = rect;
window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
return window_rect;
}
void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
// No need to update state if no page has committed yet.
if (page_id_ == -1)
return;
int delay;
if (send_content_state_immediately_)
delay = 0;
else if (is_hidden())
delay = kDelaySecondsForContentStateSyncHidden;
else
delay = kDelaySecondsForContentStateSync;
if (nav_state_sync_timer_.IsRunning()) {
// The timer is already running. If the delay of the timer maches the amount
// we want to delay by, then return. Otherwise stop the timer so that it
// gets started with the right delay.
if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
return;
nav_state_sync_timer_.Stop();
}
nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
&RenderViewImpl::SyncNavigationState);
}
void RenderViewImpl::setMouseOverURL(const WebURL& url) {
mouse_over_url_ = GURL(url);
UpdateTargetURL(mouse_over_url_, focus_url_);
}
void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
focus_url_ = GURL(url);
UpdateTargetURL(focus_url_, mouse_over_url_);
}
void RenderViewImpl::startDragging(WebLocalFrame* frame,
const WebDragData& data,
WebDragOperationsMask mask,
const WebImage& image,
const WebPoint& webImageOffset) {
DropData drop_data(DropDataBuilder::Build(data));
drop_data.referrer_policy = frame->document().referrerPolicy();
gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
Send(new DragHostMsg_StartDragging(routing_id_,
drop_data,
mask,
image.getSkBitmap(),
imageOffset,
possible_drag_event_info_));
}
bool RenderViewImpl::acceptsLoadDrops() {
return renderer_preferences_.can_accept_load_drops;
}
void RenderViewImpl::focusNext() {
Send(new ViewHostMsg_TakeFocus(routing_id_, false));
}
void RenderViewImpl::focusPrevious() {
Send(new ViewHostMsg_TakeFocus(routing_id_, true));
}
void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
has_scrolled_focused_editable_node_into_rect_ = false;
Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
// TODO(dmazzoni): this should be part of RenderFrameObserver.
GetMainRenderFrame()->FocusedNodeChanged(node);
}
void RenderViewImpl::didUpdateLayout() {
FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
// We don't always want to set up a timer, only if we've been put in that
// mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
// message.
if (!send_preferred_size_changes_ || !webview())
return;
if (check_preferred_size_timer_.IsRunning())
return;
check_preferred_size_timer_.Start(FROM_HERE,
TimeDelta::FromMilliseconds(0), this,
&RenderViewImpl::CheckPreferredSize);
}
void RenderViewImpl::navigateBackForwardSoon(int offset) {
Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
}
int RenderViewImpl::historyBackListCount() {
return history_list_offset_ < 0 ? 0 : history_list_offset_;
}
int RenderViewImpl::historyForwardListCount() {
return history_list_length_ - historyBackListCount() - 1;
}
// blink::WebWidgetClient ----------------------------------------------------
void RenderViewImpl::didFocus() {
// TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
// we won't have to test for user gesture anymore and we can
// move that code back to render_widget.cc
if (WebUserGestureIndicator::isProcessingUserGesture() &&
!RenderThreadImpl::current()->layout_test_mode()) {
Send(new ViewHostMsg_Focus(routing_id_));
}
}
void RenderViewImpl::didBlur() {
// TODO(jcivelli): see TODO above in didFocus().
if (WebUserGestureIndicator::isProcessingUserGesture() &&
!RenderThreadImpl::current()->layout_test_mode()) {
Send(new ViewHostMsg_Blur(routing_id_));
}
}
// We are supposed to get a single call to Show for a newly created RenderView
// that was created via RenderViewImpl::CreateWebView. So, we wait until this
// point to dispatch the ShowView message.
//
// This method provides us with the information about how to display the newly
// created RenderView (i.e., as a blocked popup or as a new tab).
//
void RenderViewImpl::show(WebNavigationPolicy policy) {
if (did_show_) {
// When supports_multiple_windows is disabled, popups are reusing
// the same view. In some scenarios, this makes WebKit to call show() twice.
if (webkit_preferences_.supports_multiple_windows)
NOTREACHED() << "received extraneous Show call";
return;
}
did_show_ = true;
DCHECK(opener_id_ != MSG_ROUTING_NONE);
// NOTE: initial_pos_ may still have its default values at this point, but
// that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
// browser process will impose a default position otherwise.
Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
NavigationPolicyToDisposition(policy), initial_pos_,
opened_by_user_gesture_));
SetPendingWindowRect(initial_pos_);
}
void RenderViewImpl::runModal() {
DCHECK(did_show_) << "should already have shown the view";
// Don't allow further dialogs if we are waiting to swap out, since the
// PageGroupLoadDeferrer in our stack prevents it.
if (suppress_dialogs_until_swap_out_)
return;
// We must keep WebKit's shared timer running in this case in order to allow
// showModalDialog to function properly.
//
// TODO(darin): WebKit should really be smarter about suppressing events and
// timers so that we do not need to manage the shared timer in such a heavy
// handed manner.
//
if (RenderThreadImpl::current()) // Will be NULL during unit tests.
RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
routing_id_, opener_id_));
}
bool RenderViewImpl::enterFullScreen() {
Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
return true;
}
void RenderViewImpl::exitFullScreen() {
Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
}
bool RenderViewImpl::requestPointerLock() {
return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
}
void RenderViewImpl::requestPointerUnlock() {
mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
}
bool RenderViewImpl::isPointerLocked() {
return mouse_lock_dispatcher_->IsMouseLockedTo(
webwidget_mouse_lock_target_.get());
}
void RenderViewImpl::didHandleGestureEvent(
const WebGestureEvent& event,
bool event_cancelled) {
RenderWidget::didHandleGestureEvent(event, event_cancelled);
if (!event_cancelled) {
FOR_EACH_OBSERVER(
RenderViewObserver, observers_, DidHandleGestureEvent(event));
}
// TODO(ananta): Piggyback off existing IPCs to communicate this information,
// crbug/420130.
#if defined(OS_WIN)
if (event.type != blink::WebGestureEvent::GestureTap)
return;
// TODO(estade): hit test the event against focused node to make sure
// the tap actually hit the focused node.
blink::WebTextInputType text_input_type =
GetWebView()->textInputInfo().type;
Send(new ViewHostMsg_FocusedNodeTouched(
routing_id(), text_input_type != blink::WebTextInputTypeNone));
#endif
}
void RenderViewImpl::initializeLayerTreeView() {
RenderWidget::initializeLayerTreeView();
RenderWidgetCompositor* rwc = compositor();
if (!rwc)
return;
if (webview() && webview()->devToolsAgent())
webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
bool use_threaded_event_handling = true;
#if defined(OS_MACOSX) && !defined(OS_IOS)
// Development flag because many events are still unhandled on Mac.
// http://crbug.com/138003
use_threaded_event_handling = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableThreadedEventHandlingMac);
#endif
if (use_threaded_event_handling) {
RenderThreadImpl* render_thread = RenderThreadImpl::current();
// render_thread may be NULL in tests.
InputHandlerManager* input_handler_manager =
render_thread ? render_thread->input_handler_manager() : NULL;
if (input_handler_manager) {
input_handler_manager->AddInputHandler(
routing_id_, rwc->GetInputHandler(), AsWeakPtr());
}
}
}
// blink::WebFrameClient -----------------------------------------------------
void RenderViewImpl::Repaint(const gfx::Size& size) {
OnRepaint(size);
}
void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
const std::string& value) {
EditCommands edit_commands;
edit_commands.push_back(EditCommand(name, value));
OnSetEditCommandsForNextKeyEvent(edit_commands);
}
void RenderViewImpl::ClearEditCommands() {
edit_commands_.clear();
}
SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
std::string security_info;
if (frame && frame->dataSource())
security_info = frame->dataSource()->response().securityInfo();
SSLStatus ssl_status;
DeserializeSecurityInfo(security_info,
&ssl_status.cert_id,
&ssl_status.cert_status,
&ssl_status.security_bits,
&ssl_status.connection_status,
&ssl_status.signed_certificate_timestamp_ids);
return ssl_status;
}
const std::string& RenderViewImpl::GetAcceptLanguages() const {
return renderer_preferences_.accept_languages;
}
void RenderViewImpl::didCreateDataSource(WebLocalFrame* frame,
WebDataSource* ds) {
bool content_initiated = !pending_navigation_params_.get();
// Make sure any previous redirect URLs end up in our new data source.
if (pending_navigation_params_.get()) {
for (std::vector<GURL>::const_iterator i =
pending_navigation_params_->redirects.begin();
i != pending_navigation_params_->redirects.end(); ++i) {
ds->appendRedirect(*i);
}
}
DocumentState* document_state = DocumentState::FromDataSource(ds);
if (!document_state) {
document_state = new DocumentState;
ds->setExtraData(document_state);
if (!content_initiated)
PopulateDocumentStateFromPending(document_state);
}
// Carry over the user agent override flag, if it exists.
if (content_initiated && webview() && webview()->mainFrame() &&
webview()->mainFrame()->isWebLocalFrame() &&
webview()->mainFrame()->dataSource()) {
DocumentState* old_document_state =
DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
if (old_document_state) {
InternalDocumentStateData* internal_data =
InternalDocumentStateData::FromDocumentState(document_state);
InternalDocumentStateData* old_internal_data =
InternalDocumentStateData::FromDocumentState(old_document_state);
internal_data->set_is_overriding_user_agent(
old_internal_data->is_overriding_user_agent());
}
}
// The rest of RenderView assumes that a WebDataSource will always have a
// non-null NavigationState.
if (content_initiated) {
document_state->set_navigation_state(
NavigationState::CreateContentInitiated());
} else {
document_state->set_navigation_state(CreateNavigationStateFromPending());
pending_navigation_params_.reset();
}
// DocumentState::referred_by_prefetcher_ is true if we are
// navigating from a page that used prefetching using a link on that
// page. We are early enough in the request process here that we
// can still see the DocumentState of the previous page and set
// this value appropriately.
// TODO(gavinp): catch the important case of navigation in a new
// renderer process.
if (webview()) {
if (WebFrame* old_frame = webview()->mainFrame()) {
const WebURLRequest& original_request = ds->originalRequest();
const GURL referrer(
original_request.httpHeaderField(WebString::fromUTF8("Referer")));
if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
DocumentState::FromDataSource(old_frame->dataSource())
->was_prefetcher()) {
for (; old_frame; old_frame = old_frame->traverseNext(false)) {
WebDataSource* old_frame_ds = old_frame->dataSource();
if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
document_state->set_was_referred_by_prefetcher(true);
break;
}
}
}
}
}
if (content_initiated) {
const WebURLRequest& request = ds->request();
switch (request.cachePolicy()) {
case WebURLRequest::UseProtocolCachePolicy: // normal load.
document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
break;
case WebURLRequest::ReloadIgnoringCacheData: // reload.
case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
break;
case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
document_state->set_load_type(
DocumentState::LINK_LOAD_CACHE_STALE_OK);
break;
case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
break;
default:
NOTREACHED();
}
}
FOR_EACH_OBSERVER(
RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
}
void RenderViewImpl::PopulateDocumentStateFromPending(
DocumentState* document_state) {
const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
document_state->set_request_time(params.request_time);
InternalDocumentStateData* internal_data =
InternalDocumentStateData::FromDocumentState(document_state);
if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme) &&
params.common_params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
// We're doing a load of a page that was restored from the last session. By
// default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
// can result in stale data for pages that are set to expire. We explicitly
// override that by setting the policy here so that as necessary we load
// from the network.
//
// TODO(davidben): Remove this in favor of passing a cache policy to the
// loadHistoryItem call in OnNavigate. That requires not overloading
// UseProtocolCachePolicy to mean both "normal load" and "determine cache
// policy based on load type, etc".
internal_data->set_cache_policy_override(
WebURLRequest::UseProtocolCachePolicy);
}
if (IsReload(params.common_params.navigation_type))
document_state->set_load_type(DocumentState::RELOAD);
else if (params.commit_params.page_state.IsValid())
document_state->set_load_type(DocumentState::HISTORY_LOAD);
else
document_state->set_load_type(DocumentState::NORMAL_LOAD);
internal_data->set_is_overriding_user_agent(
params.commit_params.is_overriding_user_agent);
internal_data->set_must_reset_scroll_and_scale_state(
params.common_params.navigation_type ==
FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
document_state->set_can_load_local_resources(params.can_load_local_resources);
}
NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
NavigationState* navigation_state = NULL;
// A navigation resulting from loading a javascript URL should not be treated
// as a browser initiated event. Instead, we want it to look as if the page
// initiated any load resulting from JS execution.
if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme)) {
navigation_state = NavigationState::CreateBrowserInitiated(
params.page_id,
params.pending_history_list_offset,
params.should_clear_history_list,
params.common_params.transition);
navigation_state->set_should_replace_current_entry(
params.should_replace_current_entry);
navigation_state->set_transferred_request_child_id(
params.transferred_request_child_id);
navigation_state->set_transferred_request_request_id(
params.transferred_request_request_id);
navigation_state->set_allow_download(params.common_params.allow_download);
navigation_state->set_extra_headers(params.request_params.extra_headers);
} else {
navigation_state = NavigationState::CreateContentInitiated();
}
return navigation_state;
}
void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
bool enable_viewport =
command_line.HasSwitch(switches::kEnableViewport) ||
command_line.HasSwitch(switches::kEnableViewportMeta);
// If viewport tag is enabled, then the WebKit side will take care
// of setting the fixed layout size and page scale limits.
if (enable_viewport)
return;
// When navigating to a new page, reset the page scale factor to be 1.0.
webview()->setInitialPageScaleOverride(1.f);
float maxPageScaleFactor =
command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
}
void RenderViewImpl::didClearWindowObject(WebLocalFrame* frame) {
FOR_EACH_OBSERVER(
RenderViewObserver, observers_, DidClearWindowObject(frame));
if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
WebUIExtension::Install(frame);
if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
StatsCollectionController::Install(frame);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
SkiaBenchmarking::Install(frame);
if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
GpuBenchmarking::Install(frame);
if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
MemoryBenchmarkingExtension::Install(frame);
}
void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
WebIconURL::Type icon_type) {
if (frame->parent())
return;
if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
return;
WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
std::vector<FaviconURL> urls;
for (size_t i = 0; i < icon_urls.size(); i++) {
std::vector<gfx::Size> sizes;
ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
urls.push_back(FaviconURL(
icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
}
SendUpdateFaviconURL(urls);
}
void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
StartNavStateSyncTimerIfNecessary();
}
void RenderViewImpl::CheckPreferredSize() {
// We don't always want to send the change messages over IPC, only if we've
// been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
// message.
if (!send_preferred_size_changes_ || !webview())
return;
gfx::Size size = webview()->contentsPreferredMinimumSize();
// In the presence of zoom, these sizes are still reported as if unzoomed,
// so we need to adjust.
double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
size.set_width(static_cast<int>(size.width() * zoom_factor));
size.set_height(static_cast<int>(size.height() * zoom_factor));
if (size == preferred_size_)
return;
preferred_size_ = size;
Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
preferred_size_));
}
BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
if (!browser_plugin_manager_.get())
browser_plugin_manager_ = BrowserPluginManager::Create(this);
return browser_plugin_manager_.get();
}
void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
StartNavStateSyncTimerIfNecessary();
FOR_EACH_OBSERVER(
RenderViewObserver, observers_, DidChangeScrollOffset(frame));
}
void RenderViewImpl::SendFindReply(int request_id,
int match_count,
int ordinal,
const WebRect& selection_rect,
bool final_status_update) {
Send(new ViewHostMsg_Find_Reply(routing_id_,
request_id,
match_count,
selection_rect,
ordinal,
final_status_update));
}
blink::WebString RenderViewImpl::acceptLanguages() {
return WebString::fromUTF8(renderer_preferences_.accept_languages);
}
// blink::WebPageSerializerClient implementation ------------------------------
void RenderViewImpl::didSerializeDataForFrame(
const WebURL& frame_url,
const WebCString& data,
WebPageSerializerClient::PageSerializationStatus status) {
Send(new ViewHostMsg_SendSerializedHtmlData(
routing_id(),
frame_url,
data.data(),
static_cast<int32>(status)));
}
// RenderView implementation ---------------------------------------------------
bool RenderViewImpl::Send(IPC::Message* message) {
return RenderWidget::Send(message);
}
RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
return main_render_frame_.get();
}
int RenderViewImpl::GetRoutingID() const {
return routing_id_;
}
gfx::Size RenderViewImpl::GetSize() const {
return size();
}
WebPreferences& RenderViewImpl::GetWebkitPreferences() {
return webkit_preferences_;
}
void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
OnUpdateWebPreferences(preferences);
}
blink::WebView* RenderViewImpl::GetWebView() {
return webview();
}
blink::WebElement RenderViewImpl::GetFocusedElement() const {
if (!webview())
return WebElement();
WebFrame* focused_frame = webview()->focusedFrame();
if (focused_frame) {
WebDocument doc = focused_frame->document();
if (!doc.isNull())
return doc.focusedElement();
}
return WebElement();
}
bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
if (node.isNull())
return false;
if (node.isContentEditable())
return true;
if (node.isElementNode()) {
const WebElement& element = node.toConst<WebElement>();
if (element.isTextFormControlElement()) {
if (!(element.hasAttribute("readonly") ||
element.hasAttribute("disabled")))
return true;
}
// Also return true if it has an ARIA role of 'textbox'.
for (unsigned i = 0; i < element.attributeCount(); ++i) {
if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
return true;
break;
}
}
}
return false;
}
bool RenderViewImpl::NodeContainsPoint(const WebNode& node,
const gfx::Point& point) const {
blink::WebHitTestResult hit_test =
webview()->hitTestResultAt(WebPoint(point.x(), point.y()));
return node.containsIncludingShadowDOM(hit_test.node());
}
bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
return (!send_preferred_size_changes_ ||
(disable_scrollbars_size_limit_.width() <= width ||
disable_scrollbars_size_limit_.height() <= height));
}
int RenderViewImpl::GetEnabledBindings() const {
return enabled_bindings_;
}
bool RenderViewImpl::GetContentStateImmediately() const {
return send_content_state_immediately_;
}
blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
return visibilityState();
}
void RenderViewImpl::DidStartLoading() {
main_render_frame_->didStartLoading(true);
}
void RenderViewImpl::DidStopLoading() {
main_render_frame_->didStopLoading();
}
void RenderViewImpl::SyncNavigationState() {
if (!webview())
return;
SendUpdateState(history_controller_->GetCurrentEntry());
}
blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
if (!webview())
return NULL;
WebFrame* main_frame = webview()->mainFrame();
if (main_frame->isWebLocalFrame() &&
main_frame->document().isPluginDocument())
return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
#if defined(ENABLE_PLUGINS)
if (plugin_find_handler_)
return plugin_find_handler_->container()->plugin();
#endif
return NULL;
}
void RenderViewImpl::OnFind(int request_id,
const base::string16& search_text,
const WebFindOptions& options) {
WebFrame* main_frame = webview()->mainFrame();
blink::WebPlugin* plugin = GetWebPluginForFind();
// Check if the plugin still exists in the document.
if (plugin) {
if (options.findNext) {
// Just navigate back/forward.
plugin->selectFindResult(options.forward);
} else {
if (!plugin->startFind(
search_text, options.matchCase, request_id)) {
// Send "no results".
SendFindReply(request_id, 0, 0, gfx::Rect(), true);
}
}
return;
}
WebFrame* frame_after_main = main_frame->traverseNext(true);
WebFrame* focused_frame = webview()->focusedFrame();
WebFrame* search_frame = focused_frame; // start searching focused frame.
bool multi_frame = (frame_after_main != main_frame);
// If we have multiple frames, we don't want to wrap the search within the
// frame, so we check here if we only have main_frame in the chain.
bool wrap_within_frame = !multi_frame;
WebRect selection_rect;
bool result = false;
// If something is selected when we start searching it means we cannot just
// increment the current match ordinal; we need to re-generate it.
WebRange current_selection = focused_frame->selectionRange();
do {
result = search_frame->find(
request_id, search_text, options, wrap_within_frame, &selection_rect);
if (!result) {
// don't leave text selected as you move to the next frame.
search_frame->executeCommand(WebString::fromUTF8("Unselect"),
GetFocusedElement());
// Find the next frame, but skip the invisible ones.
do {
// What is the next frame to search? (we might be going backwards). Note
// that we specify wrap=true so that search_frame never becomes NULL.
search_frame = options.forward ?
search_frame->traverseNext(true) :
search_frame->traversePrevious(true);
} while (!search_frame->hasVisibleContent() &&
search_frame != focused_frame);
// Make sure selection doesn't affect the search operation in new frame.
search_frame->executeCommand(WebString::fromUTF8("Unselect"),
GetFocusedElement());
// If we have multiple frames and we have wrapped back around to the
// focused frame, we need to search it once more allowing wrap within
// the frame, otherwise it will report 'no match' if the focused frame has
// reported matches, but no frames after the focused_frame contain a
// match for the search word(s).
if (multi_frame && search_frame == focused_frame) {
result = search_frame->find(
request_id, search_text, options, true, // Force wrapping.
&selection_rect);
}
}
webview()->setFocusedFrame(search_frame);
} while (!result && search_frame != focused_frame);
if (options.findNext && current_selection.isNull()) {
// Force the main_frame to report the actual count.
main_frame->increaseMatchCount(0, request_id);
} else {
// If nothing is found,