blob: 66a5092aa24aca4812abfc7027fc4300ebe5cad4 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/renderer/render_view.h"
6
7#include <algorithm>
8#include <string>
9#include <vector>
10
11#include "base/command_line.h"
[email protected]8a2820a2008-10-09 21:58:0512#include "base/gfx/gdi_util.h"
[email protected]b49cbcf22008-08-14 17:47:0013#include "base/gfx/bitmap_platform_device_win.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/gfx/image_operations.h"
15#include "base/gfx/native_theme.h"
16#include "base/gfx/vector_canvas.h"
17#include "base/gfx/png_encoder.h"
18#include "base/string_piece.h"
19#include "base/string_util.h"
20#include "chrome/app/theme/theme_resources.h"
21#include "chrome/common/chrome_switches.h"
22#include "chrome/common/gfx/emf.h"
23#include "chrome/common/gfx/favicon_size.h"
24#include "chrome/common/gfx/color_utils.h"
25#include "chrome/common/jstemplate_builder.h"
26#include "chrome/common/l10n_util.h"
[email protected]630e26b2008-10-14 22:55:1727#include "chrome/common/page_zoom.h"
initial.commit09911bf2008-07-26 23:55:2928#include "chrome/common/resource_bundle.h"
initial.commit09911bf2008-07-26 23:55:2929#include "chrome/common/thumbnail_score.h"
[email protected]173de1b2008-08-15 18:36:4630#include "chrome/common/chrome_plugin_lib.h"
initial.commit09911bf2008-07-26 23:55:2931#include "chrome/renderer/about_handler.h"
[email protected]173de1b2008-08-15 18:36:4632#include "chrome/renderer/chrome_plugin_host.h"
initial.commit09911bf2008-07-26 23:55:2933#include "chrome/renderer/debug_message_handler.h"
[email protected]1e0f70402008-10-16 23:57:4734#include "chrome/renderer/greasemonkey_slave.h"
initial.commit09911bf2008-07-26 23:55:2935#include "chrome/renderer/localized_error.h"
36#include "chrome/renderer/renderer_resources.h"
37#include "chrome/renderer/visitedlink_slave.h"
38#include "chrome/renderer/webplugin_delegate_proxy.h"
39#include "chrome/views/message_box_view.h"
40#include "net/base/escape.h"
41#include "net/base/net_errors.h"
42#include "webkit/default_plugin/default_plugin_shared.h"
43#include "webkit/glue/dom_operations.h"
44#include "webkit/glue/dom_serializer.h"
45#include "webkit/glue/password_form.h"
46#include "webkit/glue/plugins/plugin_list.h"
47#include "webkit/glue/searchable_form_data.h"
48#include "webkit/glue/webdatasource.h"
49#include "webkit/glue/webdropdata.h"
50#include "webkit/glue/weberror.h"
51#include "webkit/glue/webframe.h"
52#include "webkit/glue/webhistoryitem.h"
53#include "webkit/glue/webinputevent.h"
54#include "webkit/glue/webkit_glue.h"
55#include "webkit/glue/webpreferences.h"
56#include "webkit/glue/webresponse.h"
57#include "webkit/glue/weburlrequest.h"
58#include "webkit/glue/webview.h"
59#include "webkit/glue/plugins/webplugin_delegate_impl.h"
[email protected]99c72202008-10-31 03:49:4960//#include "webkit/port/platform/graphics/PlatformContextSkia.h"
initial.commit09911bf2008-07-26 23:55:2961
62#include "generated_resources.h"
63
[email protected]e1acf6f2008-10-27 20:43:3364using base::TimeDelta;
65
initial.commit09911bf2008-07-26 23:55:2966//-----------------------------------------------------------------------------
67
68// define to write the time necessary for thumbnail/DOM text retrieval,
69// respectively, into the system debug log
70// #define TIME_BITMAP_RETRIEVAL
71// #define TIME_TEXT_RETRIEVAL
72
73// maximum number of characters in the document to index, any text beyond this
74// point will be clipped
75static const int kMaxIndexChars = 65535;
76
77// Size of the thumbnails that we'll generate
78static const int kThumbnailWidth = 196;
79static const int kThumbnailHeight = 136;
80
81// Delay in milliseconds that we'll wait before capturing the page contents
82// and thumbnail.
83static const int kDelayForCaptureMs = 500;
84
85// Typically, we capture the page data once the page is loaded.
86// Sometimes, the page never finishes to load, preventing the page capture
87// To workaround this problem, we always perform a capture after the following
88// delay.
89static const int kDelayForForcedCaptureMs = 6000;
90
91// How often we will sync the navigation state when the user is changing form
92// elements or scroll position.
93const TimeDelta kDelayForNavigationSync = TimeDelta::FromSeconds(5);
94
95// The next available page ID to use. This ensures that the page IDs are
96// globally unique in the renderer.
97static int32 next_page_id_ = 1;
98
[email protected]0aa55312008-10-17 21:53:0899// The maximum number of popups that can be spawned from one page.
100static const int kMaximumNumberOfUnacknowledgedPopups = 25;
101
initial.commit09911bf2008-07-26 23:55:29102static const char* const kUnreachableWebDataURL =
103 "chrome-resource://chromewebdata/";
104
[email protected]50b691c2008-10-31 19:08:35105static const char* const kBackForwardNavigationScheme = "history";
106
initial.commit09911bf2008-07-26 23:55:29107namespace {
108
109// Associated with browser-initiated navigations to hold tracking data.
110class RenderViewExtraRequestData : public WebRequest::ExtraData {
111 public:
112 RenderViewExtraRequestData(int32 pending_page_id,
113 PageTransition::Type transition,
114 const GURL& url)
115 : pending_page_id_(pending_page_id),
116 transition_type(transition),
117 request_committed(false) {
118 }
119
120 // Contains the page_id for this navigation or -1 if there is none yet.
121 int32 pending_page_id() const { return pending_page_id_; }
122
123 // Is this a new navigation?
124 bool is_new_navigation() const { return pending_page_id_ == -1; }
125
126 // Contains the transition type that the browser specified when it
127 // initiated the load.
128 PageTransition::Type transition_type;
129
130 // True if we have already processed the "DidCommitLoad" event for this
131 // request. Used by session history.
132 bool request_committed;
133
134 private:
135 int32 pending_page_id_;
136
137 DISALLOW_EVIL_CONSTRUCTORS(RenderViewExtraRequestData);
138};
139
140} // namespace
141
142///////////////////////////////////////////////////////////////////////////////
143
144RenderView::RenderView()
[email protected]0ebf3872008-11-07 21:35:03145 : RenderWidget(RenderThread::current(), true),
initial.commit09911bf2008-07-26 23:55:29146 is_loading_(false),
147 page_id_(-1),
148 last_page_id_sent_to_browser_(-1),
149 last_indexed_page_id_(-1),
150 method_factory_(this),
initial.commit09911bf2008-07-26 23:55:29151 opened_by_user_gesture_(true),
152 enable_dom_automation_(false),
153 enable_dom_ui_bindings_(false),
154 target_url_status_(TARGET_NONE),
155 printed_document_width_(0),
156 first_default_plugin_(NULL),
157 navigation_gesture_(NavigationGestureUnknown),
158 history_back_list_count_(0),
159 history_forward_list_count_(0),
160 disable_popup_blocking_(false),
[email protected]1e0f70402008-10-16 23:57:47161 has_unload_listener_(false),
[email protected]0aa55312008-10-17 21:53:08162 decrement_shared_popup_at_destruction_(false),
[email protected]06828b92008-10-20 21:25:46163 greasemonkey_enabled_(false),
[email protected]0ebf3872008-11-07 21:35:03164 waiting_for_create_window_ack_(false),
165 form_field_autofill_request_id_(0) {
initial.commit09911bf2008-07-26 23:55:29166 resource_dispatcher_ = new ResourceDispatcher(this);
[email protected]3a453fa2008-08-15 18:46:34167#ifdef CHROME_PERSONALIZATION
168 personalization_ = Personalization::CreateRendererPersonalization();
169#endif
initial.commit09911bf2008-07-26 23:55:29170}
171
172RenderView::~RenderView() {
[email protected]0aa55312008-10-17 21:53:08173 if (decrement_shared_popup_at_destruction_)
174 shared_popup_counter_->data--;
175
initial.commit09911bf2008-07-26 23:55:29176 resource_dispatcher_->ClearMessageSender();
177 // Clear any back-pointers that might still be held by plugins.
178 PluginDelegateList::iterator it = plugin_delegates_.begin();
179 while (it != plugin_delegates_.end()) {
180 (*it)->DropRenderView();
181 it = plugin_delegates_.erase(it);
182 }
183
184 RenderThread::current()->RemoveFilter(debug_message_handler_);
[email protected]3a453fa2008-08-15 18:46:34185
186#ifdef CHROME_PERSONALIZATION
187 Personalization::CleanupRendererPersonalization(personalization_);
188 personalization_ = NULL;
189#endif
initial.commit09911bf2008-07-26 23:55:29190}
191
192/*static*/
[email protected]0aa55312008-10-17 21:53:08193RenderView* RenderView::Create(
194 HWND parent_hwnd,
195 HANDLE modal_dialog_event,
196 int32 opener_id,
197 const WebPreferences& webkit_prefs,
198 SharedRenderViewCounter* counter,
199 int32 routing_id) {
initial.commit09911bf2008-07-26 23:55:29200 DCHECK(routing_id != MSG_ROUTING_NONE);
201 scoped_refptr<RenderView> view = new RenderView();
202 view->Init(parent_hwnd,
203 modal_dialog_event,
204 opener_id,
205 webkit_prefs,
[email protected]0aa55312008-10-17 21:53:08206 counter,
initial.commit09911bf2008-07-26 23:55:29207 routing_id); // adds reference
208 return view;
209}
210
211/*static*/
212void RenderView::SetNextPageID(int32 next_page_id) {
213 // This method should only be called during process startup, and the given
214 // page id had better not exceed our current next page id!
215 DCHECK(next_page_id_ == 1);
216 DCHECK(next_page_id >= next_page_id_);
217 next_page_id_ = next_page_id;
218}
219
220void RenderView::PluginDestroyed(WebPluginDelegateProxy* proxy) {
221 PluginDelegateList::iterator it =
222 std::find(plugin_delegates_.begin(), plugin_delegates_.end(), proxy);
223 DCHECK(it != plugin_delegates_.end());
224 plugin_delegates_.erase(it);
225 // If the plugin is deleted, we need to clear our reference in case user
226 // clicks the info bar to install. Unfortunately we are getting
227 // PluginDestroyed in single process mode. However, that is not a huge
228 // concern.
229 if (proxy == first_default_plugin_)
230 first_default_plugin_ = NULL;
231}
232
233void RenderView::PluginCrashed(const std::wstring& plugin_path) {
234 Send(new ViewHostMsg_CrashedPlugin(routing_id_, plugin_path));
235}
236
237
238void RenderView::JSOutOfMemory() {
239 Send(new ViewHostMsg_JSOutOfMemory(routing_id_));
240}
241
242void RenderView::Init(HWND parent_hwnd,
243 HANDLE modal_dialog_event,
244 int32 opener_id,
245 const WebPreferences& webkit_prefs,
[email protected]0aa55312008-10-17 21:53:08246 SharedRenderViewCounter* counter,
initial.commit09911bf2008-07-26 23:55:29247 int32 routing_id) {
248 DCHECK(!webview());
249
250 if (opener_id != MSG_ROUTING_NONE)
251 opener_id_ = opener_id;
252
[email protected]0aa55312008-10-17 21:53:08253 if (counter) {
254 shared_popup_counter_ = counter;
255 shared_popup_counter_->data++;
256 decrement_shared_popup_at_destruction_ = true;
257 } else {
258 shared_popup_counter_ = new SharedRenderViewCounter(0);
259 decrement_shared_popup_at_destruction_ = false;
260 }
261
initial.commit09911bf2008-07-26 23:55:29262 // Avoid a leak here by not assigning, since WebView::Create addrefs for us.
263 WebWidget* view = WebView::Create(this, webkit_prefs);
264 webwidget_.swap(&view);
265
266 // Don't let WebCore keep a B/F list - we have our own.
267 // We let it keep 1 entry because FrameLoader::goToItem expects an item in the
268 // backForwardList, which is used only in ASSERTs.
269 webview()->SetBackForwardListSize(1);
270
271 routing_id_ = routing_id;
272 RenderThread::current()->AddRoute(routing_id_, this);
273 // Take a reference on behalf of the RenderThread. This will be balanced
274 // when we receive ViewMsg_Close.
275 AddRef();
276
277 // If this is a popup, we must wait for the CreatingNew_ACK message before
278 // completing initialization. Otherwise, we can finish it now.
279 if (opener_id == MSG_ROUTING_NONE) {
280 did_show_ = true;
281 CompleteInit(parent_hwnd);
282 }
283
284 host_window_ = parent_hwnd;
285 modal_dialog_event_.Set(modal_dialog_event);
286
287 CommandLine command_line;
288 enable_dom_automation_ =
289 command_line.HasSwitch(switches::kDomAutomationController);
290 disable_popup_blocking_ =
291 command_line.HasSwitch(switches::kDisablePopupBlocking);
[email protected]1e0f70402008-10-16 23:57:47292 greasemonkey_enabled_ =
293 command_line.HasSwitch(switches::kEnableGreasemonkey);
initial.commit09911bf2008-07-26 23:55:29294
295 debug_message_handler_ = new DebugMessageHandler(this);
296 RenderThread::current()->AddFilter(debug_message_handler_);
297}
298
299void RenderView::OnMessageReceived(const IPC::Message& message) {
[email protected]06828b92008-10-20 21:25:46300 // If the current RenderView instance represents a popup, then we
301 // need to wait for ViewMsg_CreatingNew_ACK to be sent by the browser.
302 // As part of this ack we also receive the browser window handle, which
303 // parents any plugins instantiated in this RenderView instance.
304 // Plugins can be instantiated only when we receive the parent window
305 // handle as they are child windows.
306 if (waiting_for_create_window_ack_ &&
307 resource_dispatcher_->IsResourceMessage(message)) {
308 queued_resource_messages_.push(new IPC::Message(message));
309 return;
310 }
311
initial.commit09911bf2008-07-26 23:55:29312 // Let the resource dispatcher intercept resource messages first.
313 if (resource_dispatcher_->OnMessageReceived(message))
314 return;
[email protected]06828b92008-10-20 21:25:46315
initial.commit09911bf2008-07-26 23:55:29316 IPC_BEGIN_MESSAGE_MAP(RenderView, message)
317 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
318 IPC_MESSAGE_HANDLER(ViewMsg_CaptureThumbnail, SendThumbnail)
319 IPC_MESSAGE_HANDLER(ViewMsg_GetPrintedPagesCount, OnGetPrintedPagesCount)
320 IPC_MESSAGE_HANDLER(ViewMsg_PrintPages, OnPrintPages)
321 IPC_MESSAGE_HANDLER(ViewMsg_Navigate, OnNavigate)
322 IPC_MESSAGE_HANDLER(ViewMsg_Stop, OnStop)
323 IPC_MESSAGE_HANDLER(ViewMsg_LoadAlternateHTMLText, OnLoadAlternateHTMLText)
324 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
325 IPC_MESSAGE_HANDLER(ViewMsg_Undo, OnUndo)
326 IPC_MESSAGE_HANDLER(ViewMsg_Redo, OnRedo)
327 IPC_MESSAGE_HANDLER(ViewMsg_Cut, OnCut)
328 IPC_MESSAGE_HANDLER(ViewMsg_Copy, OnCopy)
329 IPC_MESSAGE_HANDLER(ViewMsg_Paste, OnPaste)
330 IPC_MESSAGE_HANDLER(ViewMsg_Replace, OnReplace)
331 IPC_MESSAGE_HANDLER(ViewMsg_Delete, OnDelete)
332 IPC_MESSAGE_HANDLER(ViewMsg_SelectAll, OnSelectAll)
333 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
334 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
[email protected]630e26b2008-10-14 22:55:17335 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
initial.commit09911bf2008-07-26 23:55:29336 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
337 IPC_MESSAGE_HANDLER(ViewMsg_InspectElement, OnInspectElement)
338 IPC_MESSAGE_HANDLER(ViewMsg_ShowJavaScriptConsole, OnShowJavaScriptConsole)
339 IPC_MESSAGE_HANDLER(ViewMsg_DownloadImage, OnDownloadImage)
340 IPC_MESSAGE_HANDLER(ViewMsg_ScriptEvalRequest, OnScriptEvalRequest)
341 IPC_MESSAGE_HANDLER(ViewMsg_AddMessageToConsole, OnAddMessageToConsole)
342 IPC_MESSAGE_HANDLER(ViewMsg_DebugAttach, OnDebugAttach)
[email protected]88010e082008-08-29 11:07:40343 IPC_MESSAGE_HANDLER(ViewMsg_DebugDetach, OnDebugDetach)
initial.commit09911bf2008-07-26 23:55:29344 IPC_MESSAGE_HANDLER(ViewMsg_ReservePageIDRange, OnReservePageIDRange)
345 IPC_MESSAGE_HANDLER(ViewMsg_UploadFile, OnUploadFileRequest)
346 IPC_MESSAGE_HANDLER(ViewMsg_FormFill, OnFormFill)
347 IPC_MESSAGE_HANDLER(ViewMsg_FillPasswordForm, OnFillPasswordForm)
348 IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDragEnter, OnDragTargetDragEnter)
349 IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDragOver, OnDragTargetDragOver)
350 IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDragLeave, OnDragTargetDragLeave)
351 IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDrop, OnDragTargetDrop)
352 IPC_MESSAGE_HANDLER(ViewMsg_AllowDomAutomationBindings,
353 OnAllowDomAutomationBindings)
[email protected]18cb2572008-08-21 20:34:45354 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
initial.commit09911bf2008-07-26 23:55:29355 IPC_MESSAGE_HANDLER(ViewMsg_SetDOMUIProperty, OnSetDOMUIProperty)
[email protected]266eb6f2008-09-30 23:56:50356 IPC_MESSAGE_HANDLER(ViewMsg_DragSourceEndedOrMoved,
357 OnDragSourceEndedOrMoved)
initial.commit09911bf2008-07-26 23:55:29358 IPC_MESSAGE_HANDLER(ViewMsg_DragSourceSystemDragEnded,
359 OnDragSourceSystemDragEnded)
360 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
361 IPC_MESSAGE_HANDLER(ViewMsg_FindReplyACK, OnFindReplyAck)
362 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
363 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
364 IPC_MESSAGE_HANDLER(ViewMsg_SetAltErrorPageURL, OnSetAltErrorPageURL)
365 IPC_MESSAGE_HANDLER(ViewMsg_InstallMissingPlugin, OnInstallMissingPlugin)
366 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
367 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
368 IPC_MESSAGE_HANDLER(ViewMsg_UpdateBackForwardListCount,
369 OnUpdateBackForwardListCount)
370 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
371 OnGetAllSavableResourceLinksForCurrentPage)
372 IPC_MESSAGE_HANDLER(ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
373 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
374 IPC_MESSAGE_HANDLER(ViewMsg_GetApplicationInfo, OnGetApplicationInfo)
[email protected]266eb6f2008-09-30 23:56:50375 IPC_MESSAGE_HANDLER(ViewMsg_GetAccessibilityInfo, OnGetAccessibilityInfo)
376 IPC_MESSAGE_HANDLER(ViewMsg_ClearAccessibilityInfo,
377 OnClearAccessibilityInfo)
initial.commit09911bf2008-07-26 23:55:29378 IPC_MESSAGE_HANDLER(ViewMsg_ShouldClose, OnMsgShouldClose)
379 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
380 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
[email protected]3c17b9c2008-08-26 02:08:00381#ifdef CHROME_PERSONALIZATION
[email protected]1cc879642008-08-26 01:27:35382 IPC_MESSAGE_HANDLER(ViewMsg_PersonalizationEvent, OnPersonalizationEvent)
[email protected]3c17b9c2008-08-26 02:08:00383#endif
[email protected]18cb2572008-08-21 20:34:45384 IPC_MESSAGE_HANDLER(ViewMsg_HandleMessageFromExternalHost,
385 OnMessageFromExternalHost)
[email protected]0aa55312008-10-17 21:53:08386 IPC_MESSAGE_HANDLER(ViewMsg_DisassociateFromPopupCount,
387 OnDisassociateFromPopupCount)
[email protected]0ebf3872008-11-07 21:35:03388 IPC_MESSAGE_HANDLER(ViewMsg_AutofillSuggestions,
389 OnReceivedAutofillSuggestions)
initial.commit09911bf2008-07-26 23:55:29390 // Have the super handle all other messages.
391 IPC_MESSAGE_UNHANDLED(RenderWidget::OnMessageReceived(message))
392 IPC_END_MESSAGE_MAP()
393}
394
395// Got a response from the browser after the renderer decided to create a new
396// view.
397void RenderView::OnCreatingNewAck(HWND parent) {
398 CompleteInit(parent);
[email protected]06828b92008-10-20 21:25:46399
400 waiting_for_create_window_ack_ = false;
401
402 while (!queued_resource_messages_.empty()) {
403 IPC::Message* queued_msg = queued_resource_messages_.front();
404 queued_resource_messages_.pop();
405 resource_dispatcher_->OnMessageReceived(*queued_msg);
406 delete queued_msg;
407 }
initial.commit09911bf2008-07-26 23:55:29408}
409
410void RenderView::SendThumbnail() {
411 WebFrame* main_frame = webview()->GetMainFrame();
412 if (!main_frame)
413 return;
414
415 // get the URL for this page
416 GURL url(main_frame->GetURL());
417 if (url.is_empty())
418 return;
419
420 if (size_.IsEmpty())
421 return; // Don't create an empty thumbnail!
422
423 ThumbnailScore score;
424 SkBitmap thumbnail;
425 CaptureThumbnail(main_frame, kThumbnailWidth, kThumbnailHeight, &thumbnail,
426 &score);
427 // send the thumbnail message to the browser process
428 IPC::Message* thumbnail_msg = new IPC::Message(routing_id_,
429 ViewHostMsg_Thumbnail::ID, IPC::Message::PRIORITY_NORMAL);
430 IPC::ParamTraits<GURL>::Write(thumbnail_msg, url);
431 IPC::ParamTraits<ThumbnailScore>::Write(thumbnail_msg, score);
432 IPC::ParamTraits<SkBitmap>::Write(thumbnail_msg, thumbnail);
433 Send(thumbnail_msg);
434}
435
436int RenderView::SwitchFrameToPrintMediaType(const ViewMsg_Print_Params& params,
437 WebFrame* frame) {
438 float ratio = static_cast<float>(params.desired_dpi / params.dpi);
439 float paper_width = params.printable_size.width() * ratio;
440 float paper_height = params.printable_size.height() * ratio;
441 float minLayoutWidth = static_cast<float>(paper_width * params.min_shrink);
442 float maxLayoutWidth = static_cast<float>(paper_width * params.max_shrink);
443
444 // Safari uses: 765 & 1224. Margins aren't exactly the same either.
445 // Scale = 2.222 for MDI printer.
446 int pages;
447 if (!frame->SetPrintingMode(true,
448 minLayoutWidth,
449 maxLayoutWidth,
450 &printed_document_width_)) {
451 NOTREACHED();
452 pages = 0;
453 } else {
454 // Force to recalculate the height, otherwise it reuse the current window
455 // height as the default.
456 float effective_shrink = printed_document_width_ / paper_width;
457 gfx::Size page_size(printed_document_width_,
458 static_cast<int>(paper_height * effective_shrink) - 1);
459 WebView* view = frame->GetView();
460 if (view) {
461 // Hack around an issue where if the current view height is higher than
462 // the page height, empty pages will be printed even if the bottom of the
463 // web page is empty.
464 printing_view_size_ = view->GetSize();
465 view->Resize(page_size);
466 view->Layout();
467 }
468 pages = frame->ComputePageRects(params.printable_size);
469 DCHECK(pages);
470 }
471 return pages;
472}
473
474void RenderView::SwitchFrameToDisplayMediaType(WebFrame* frame) {
475 // Set the layout back to "normal" document; i.e. CSS media type = "screen".
476 frame->SetPrintingMode(false, 0, 0, NULL);
477 WebView* view = frame->GetView();
478 if (view) {
479 // Restore from the hack described at SwitchFrameToPrintMediaType().
480 view->Resize(printing_view_size_);
481 view->Layout();
482 printing_view_size_.SetSize(0, 0);
483 }
484 printed_document_width_ = 0;
485}
486
487void RenderView::OnPrintPage(const ViewMsg_PrintPage_Params& params) {
488 DCHECK(webview());
489 if (webview())
490 PrintPage(params, webview()->GetMainFrame());
491}
492
493void RenderView::PrintPage(const ViewMsg_PrintPage_Params& params,
494 WebFrame* frame) {
495 if (printed_document_width_ <= 0) {
496 NOTREACHED();
497 return;
498 }
499
500 // Generate a memory-based EMF file. The EMF will use the current screen's
501 // DPI.
502 gfx::Emf emf;
503
504 emf.CreateDc(NULL, NULL);
505 HDC hdc = emf.hdc();
506 DCHECK(hdc);
[email protected]b49cbcf22008-08-14 17:47:00507 gfx::PlatformDeviceWin::InitializeDC(hdc);
initial.commit09911bf2008-07-26 23:55:29508
509 gfx::Rect rect;
510 frame->GetPageRect(params.page_number, &rect);
511 DCHECK(rect.height());
512 DCHECK(rect.width());
513 double shrink = static_cast<double>(printed_document_width_) /
514 params.params.printable_size.width();
515 // This check would fire each time the page would get truncated on the
516 // right. This is not worth a DCHECK() but should be looked into, for
517 // example, wouldn't be worth trying in landscape?
518 // DCHECK_LE(rect.width(), printed_document_width_);
519
520 // Buffer one page at a time.
521 int src_size_x = printed_document_width_;
522 int src_size_y =
523 static_cast<int>(ceil(params.params.printable_size.height() *
524 shrink));
525#if 0
526 // TODO(maruel): This code is kept for testing until the 100% GDI drawing
527 // code is stable. maruels use this code's output as a reference when the
528 // GDI drawing code fails.
529
530 // Mix of Skia and GDI based.
[email protected]b49cbcf22008-08-14 17:47:00531 gfx::PlatformCanvasWin canvas(src_size_x, src_size_y, true);
initial.commit09911bf2008-07-26 23:55:29532 canvas.drawARGB(255, 255, 255, 255, SkPorterDuff::kSrc_Mode);
533 PlatformContextSkia context(&canvas);
534 if (!frame->SpoolPage(params.page_number, &context)) {
535 NOTREACHED() << "Printing page " << params.page_number << " failed.";
536 return;
537 }
538
539 // Create a BMP v4 header that we can serialize.
540 BITMAPV4HEADER bitmap_header;
541 gfx::CreateBitmapV4Header(src_size_x, src_size_y, &bitmap_header);
542 const SkBitmap& src_bmp = canvas.getDevice()->accessBitmap(true);
543 SkAutoLockPixels src_lock(src_bmp);
544 int retval = StretchDIBits(hdc,
545 0,
546 0,
547 src_size_x, src_size_y,
548 0, 0,
549 src_size_x, src_size_y,
550 src_bmp.getPixels(),
551 reinterpret_cast<BITMAPINFO*>(&bitmap_header),
552 DIB_RGB_COLORS,
553 SRCCOPY);
554 DCHECK(retval != GDI_ERROR);
555#else
556 // 100% GDI based.
557 gfx::VectorCanvas canvas(hdc, src_size_x, src_size_y);
initial.commit09911bf2008-07-26 23:55:29558 // Set the clipping region to be sure to not overflow.
559 SkRect clip_rect;
560 clip_rect.set(0, 0, SkIntToScalar(src_size_x), SkIntToScalar(src_size_y));
561 canvas.clipRect(clip_rect);
[email protected]99c72202008-10-31 03:49:49562 if (!frame->SpoolPage(params.page_number, &canvas)) {
initial.commit09911bf2008-07-26 23:55:29563 NOTREACHED() << "Printing page " << params.page_number << " failed.";
564 return;
565 }
566#endif
567
568 // Done printing. Close the device context to retrieve the compiled EMF.
569 if (!emf.CloseDc()) {
570 NOTREACHED() << "EMF failed";
571 }
572
573 // Get the size of the compiled EMF.
574 unsigned buf_size = emf.GetDataSize();
575 DCHECK(buf_size > 128);
576 ViewHostMsg_DidPrintPage_Params page_params;
577 page_params.data_size = 0;
578 page_params.emf_data_handle = NULL;
579 page_params.page_number = params.page_number;
580 page_params.document_cookie = params.params.document_cookie;
581 page_params.actual_shrink = shrink;
582 SharedMemory shared_buf;
583
584 // http://msdn2.microsoft.com/en-us/library/ms535522.aspx
585 // Windows 2000/XP: When a page in a spooled file exceeds approximately 350
586 // MB, it can fail to print and not send an error message.
587 if (buf_size < 350*1024*1024) {
588 // Allocate a shared memory buffer to hold the generated EMF data.
589 if (shared_buf.Create(L"", false, false, buf_size) &&
590 shared_buf.Map(buf_size)) {
591 // Copy the bits into shared memory.
592 if (emf.GetData(shared_buf.memory(), buf_size)) {
593 page_params.emf_data_handle = shared_buf.handle();
594 page_params.data_size = buf_size;
595 } else {
596 NOTREACHED() << "GetData() failed";
597 }
598 shared_buf.Unmap();
599 } else {
600 NOTREACHED() << "Buffer allocation failed";
601 }
602 } else {
603 NOTREACHED() << "Buffer too large: " << buf_size;
604 }
605 emf.CloseEmf();
606 if (Send(new ViewHostMsg_DuplicateSection(routing_id_,
607 page_params.emf_data_handle,
608 &page_params.emf_data_handle))) {
609 Send(new ViewHostMsg_DidPrintPage(routing_id_, page_params));
610 }
611}
612
613void RenderView::OnGetPrintedPagesCount(const ViewMsg_Print_Params& params) {
614 DCHECK(webview());
615 if (!webview()) {
616 Send(new ViewHostMsg_DidGetPrintedPagesCount(routing_id_,
617 params.document_cookie,
618 0));
619 return;
620 }
621 WebFrame* frame = webview()->GetMainFrame();
622 int expected_pages = SwitchFrameToPrintMediaType(params, frame);
623 Send(new ViewHostMsg_DidGetPrintedPagesCount(routing_id_,
624 params.document_cookie,
625 expected_pages));
626 SwitchFrameToDisplayMediaType(frame);
627}
628
629void RenderView::OnPrintPages(const ViewMsg_PrintPages_Params& params) {
630 DCHECK(webview());
631 if (webview())
632 PrintPages(params, webview()->GetMainFrame());
633}
634
635void RenderView::PrintPages(const ViewMsg_PrintPages_Params& params,
636 WebFrame* frame) {
637 int pages = SwitchFrameToPrintMediaType(params.params, frame);
638 Send(new ViewHostMsg_DidGetPrintedPagesCount(routing_id_,
639 params.params.document_cookie,
640 pages));
641 if (pages) {
642 ViewMsg_PrintPage_Params page_params;
643 page_params.params = params.params;
644 if (params.pages.empty()) {
645 for (int i = 0; i < pages; ++i) {
646 page_params.page_number = i;
647 PrintPage(page_params, frame);
648 }
649 } else {
650 for (size_t i = 0; i < params.pages.size(); ++i) {
651 page_params.page_number = params.pages[i];
652 PrintPage(page_params, frame);
653 }
654 }
655 }
656 SwitchFrameToDisplayMediaType(frame);
657}
658
659void RenderView::CapturePageInfo(int load_id, bool preliminary_capture) {
660 if (load_id != page_id_)
661 return; // this capture call is no longer relevant due to navigation
662 if (load_id == last_indexed_page_id_)
663 return; // we already indexed this page
664
665 if (!webview())
666 return;
667
668 WebFrame* main_frame = webview()->GetMainFrame();
669 if (!main_frame)
670 return;
671
672 // Don't index/capture pages that are in view source mode.
673 if (main_frame->GetInViewSourceMode())
674 return;
675
676 // Don't index/capture pages that failed to load. This only checks the top
677 // level frame so the thumbnail may contain a frame that failed to load.
678 WebDataSource* ds = main_frame->GetDataSource();
679 if (ds && ds->HasUnreachableURL())
680 return;
681
682 if (!preliminary_capture)
683 last_indexed_page_id_ = load_id;
684
685 // get the URL for this page
686 GURL url(main_frame->GetURL());
687 if (url.is_empty())
688 return;
689
690 // full text
691 std::wstring contents;
692 CaptureText(main_frame, &contents);
693 if (contents.size()) {
694 // Send the text to the browser for indexing.
695 Send(new ViewHostMsg_PageContents(url, load_id, contents));
696 }
697
698 // thumbnail
699 SendThumbnail();
700}
701
702void RenderView::CaptureText(WebFrame* frame, std::wstring* contents) {
703 contents->clear();
704 if (!frame)
705 return;
706
[email protected]0faf0bd92008-09-09 20:53:27707 // Don't index any https pages. People generally don't want their bank
708 // accounts, etc. indexed on their computer, especially since some of these
709 // things are not marked cachable.
710 // TODO(brettw) we may want to consider more elaborate heuristics such as
711 // the cachability of the page. We may also want to consider subframes (this
712 // test will still index subframes if the subframe is SSL).
713 if (frame->GetURL().SchemeIsSecure())
714 return;
715
initial.commit09911bf2008-07-26 23:55:29716#ifdef TIME_TEXT_RETRIEVAL
717 double begin = time_util::GetHighResolutionTimeNow();
718#endif
719
720 // get the contents of the frame
721 frame->GetContentAsPlainText(kMaxIndexChars, contents);
722
723#ifdef TIME_TEXT_RETRIEVAL
724 double end = time_util::GetHighResolutionTimeNow();
725 char buf[128];
726 sprintf_s(buf, "%d chars retrieved for indexing in %gms\n",
727 contents.size(), (end - begin)*1000);
728 OutputDebugStringA(buf);
729#endif
730
731 // When the contents are clipped to the maximum, we don't want to have a
732 // partial word indexed at the end that might have been clipped. Therefore,
733 // terminate the string at the last space to ensure no words are clipped.
734 if (contents->size() == kMaxIndexChars) {
735 size_t last_space_index = contents->find_last_of(kWhitespaceWide);
736 if (last_space_index == std::wstring::npos)
737 return; // don't index if we got a huge block of text with no spaces
738 contents->resize(last_space_index);
739 }
740}
741
742void RenderView::CaptureThumbnail(WebFrame* frame,
743 int w,
744 int h,
745 SkBitmap* thumbnail,
746 ThumbnailScore* score) {
747#ifdef TIME_BITMAP_RETRIEVAL
748 double begin = time_util::GetHighResolutionTimeNow();
749#endif
750
[email protected]b49cbcf22008-08-14 17:47:00751 gfx::BitmapPlatformDeviceWin device(frame->CaptureImage(true));
initial.commit09911bf2008-07-26 23:55:29752 const SkBitmap& src_bmp = device.accessBitmap(false);
753
754 SkRect dest_rect;
755 dest_rect.set(0, 0, SkIntToScalar(w), SkIntToScalar(h));
756 float dest_aspect = dest_rect.width() / dest_rect.height();
757
758 // Get the src rect so that we can preserve the aspect ratio while filling
759 // the destination.
760 SkIRect src_rect;
761 if (src_bmp.width() < dest_rect.width() ||
762 src_bmp.height() < dest_rect.height()) {
763 // Source image is smaller: we clip the part of source image within the
764 // dest rect, and then stretch it to fill the dest rect. We don't respect
765 // the aspect ratio in this case.
766 src_rect.set(0, 0, static_cast<S16CPU>(dest_rect.width()),
767 static_cast<S16CPU>(dest_rect.height()));
768 score->good_clipping = false;
769 } else {
770 float src_aspect = static_cast<float>(src_bmp.width()) / src_bmp.height();
771 if (src_aspect > dest_aspect) {
772 // Wider than tall, clip horizontally: we center the smaller thumbnail in
773 // the wider screen.
774 S16CPU new_width = static_cast<S16CPU>(src_bmp.height() * dest_aspect);
775 S16CPU x_offset = (src_bmp.width() - new_width) / 2;
776 src_rect.set(x_offset, 0, new_width + x_offset, src_bmp.height());
777 score->good_clipping = false;
778 } else {
779 src_rect.set(0, 0, src_bmp.width(),
780 static_cast<S16CPU>(src_bmp.width() / dest_aspect));
781 score->good_clipping = true;
782 }
783 }
784
785 score->at_top = (frame->ScrollOffset().height() == 0);
786
787 SkBitmap subset;
788 device.accessBitmap(false).extractSubset(&subset, src_rect);
789
790 // Resample the subset that we want to get it the right size.
791 *thumbnail = gfx::ImageOperations::Resize(
792 subset, gfx::ImageOperations::RESIZE_LANCZOS3, gfx::Size(w, h));
793
794 score->boring_score = CalculateBoringScore(thumbnail);
795
796#ifdef TIME_BITMAP_RETRIEVAL
797 double end = time_util::GetHighResolutionTimeNow();
798 char buf[128];
799 sprintf_s(buf, "thumbnail in %gms\n", (end - begin) * 1000);
800 OutputDebugStringA(buf);
801#endif
802}
803
804double RenderView::CalculateBoringScore(SkBitmap* bitmap) {
805 int histogram[256] = {0};
806 color_utils::BuildLumaHistogram(bitmap, histogram);
807
808 int color_count = *std::max_element(histogram, histogram + 256);
809 int pixel_count = bitmap->width() * bitmap->height();
810 return static_cast<double>(color_count) / pixel_count;
811}
812
813void RenderView::OnNavigate(const ViewMsg_Navigate_Params& params) {
814 if (!webview())
815 return;
816
817 AboutHandler::MaybeHandle(params.url);
818
819 bool is_reload = params.reload;
820
821 WebFrame* main_frame = webview()->GetMainFrame();
822 if (is_reload && !main_frame->HasCurrentState()) {
823 // We cannot reload if we do not have any history state. This happens, for
824 // example, when recovering from a crash. Our workaround here is a bit of
825 // a hack since it means that reload after a crashed tab does not cause an
826 // end-to-end cache validation.
827 is_reload = false;
828 }
829
830 WebRequestCachePolicy cache_policy;
831 if (is_reload) {
832 cache_policy = WebRequestReloadIgnoringCacheData;
833 } else if (params.page_id != -1 || main_frame->GetInViewSourceMode()) {
834 cache_policy = WebRequestReturnCacheDataElseLoad;
835 } else {
836 cache_policy = WebRequestUseProtocolCachePolicy;
837 }
838
839 scoped_ptr<WebRequest> request(WebRequest::Create(params.url));
840 request->SetCachePolicy(cache_policy);
841 request->SetExtraData(new RenderViewExtraRequestData(
842 params.page_id, params.transition, params.url));
843
844 // If we are reloading, then WebKit will use the state of the current page.
845 // Otherwise, we give it the state to navigate to.
846 if (!is_reload)
847 request->SetHistoryState(params.state);
848
[email protected]4c6f2c92008-10-28 20:26:15849 if (params.referrer.is_valid()) {
[email protected]c0588052008-10-27 23:01:50850 request->SetHttpHeaderValue(L"Referer",
851 UTF8ToWide(params.referrer.spec()));
852 }
853
initial.commit09911bf2008-07-26 23:55:29854 main_frame->LoadRequest(request.get());
855}
856
857// Stop loading the current page
858void RenderView::OnStop() {
859 if (webview())
860 webview()->StopLoading();
861}
862
863void RenderView::OnLoadAlternateHTMLText(const std::string& html_contents,
864 bool new_navigation,
865 const GURL& display_url,
866 const std::string& security_info) {
867 if (!webview())
868 return;
869
870 scoped_ptr<WebRequest> request(WebRequest::Create(
871 GURL(kUnreachableWebDataURL)));
872 request->SetSecurityInfo(security_info);
873
874 webview()->GetMainFrame()->LoadAlternateHTMLString(request.get(),
875 html_contents,
876 display_url,
877 !new_navigation);
878}
879
880void RenderView::OnCopyImageAt(int x, int y) {
881 webview()->CopyImageAt(x, y);
882}
883
884void RenderView::OnInspectElement(int x, int y) {
885 webview()->InspectElement(x, y);
886}
887
888void RenderView::OnShowJavaScriptConsole() {
889 webview()->ShowJavaScriptConsole();
890}
891
892void RenderView::OnStopFinding(bool clear_selection) {
893 WebView* view = webview();
894 if (!view)
895 return;
896
897 if (clear_selection)
898 view->GetFocusedFrame()->ClearSelection();
899
900 WebFrame* frame = view->GetMainFrame();
901 while (frame) {
[email protected]65134c432008-09-26 21:47:20902 frame->StopFinding(clear_selection);
initial.commit09911bf2008-07-26 23:55:29903 frame = view->GetNextFrameAfter(frame, false);
904 }
905}
906
907void RenderView::OnFindReplyAck() {
908 // Check if there is any queued up request waiting to be sent.
909 if (queued_find_reply_message_.get()) {
910 // Send the search result over to the browser process.
911 Send(queued_find_reply_message_.get());
912 queued_find_reply_message_.release();
913 }
914}
915
916void RenderView::OnUpdateTargetURLAck() {
917 // Check if there is a targeturl waiting to be sent.
918 if (target_url_status_ == TARGET_PENDING) {
919 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
920 pending_target_url_));
921 }
922
923 target_url_status_ = TARGET_NONE;
924}
925
926void RenderView::OnUndo() {
927 if (!webview())
928 return;
929
930 webview()->GetFocusedFrame()->Undo();
931}
932
933void RenderView::OnRedo() {
934 if (!webview())
935 return;
936
937 webview()->GetFocusedFrame()->Redo();
938}
939
940void RenderView::OnCut() {
941 if (!webview())
942 return;
943
944 webview()->GetFocusedFrame()->Cut();
945}
946
947void RenderView::OnCopy() {
948 if (!webview())
949 return;
950
951 webview()->GetFocusedFrame()->Copy();
952}
953
954void RenderView::OnPaste() {
955 if (!webview())
956 return;
957
958 webview()->GetFocusedFrame()->Paste();
959}
960
961void RenderView::OnReplace(const std::wstring& text) {
962 if (!webview())
963 return;
964
965 webview()->GetFocusedFrame()->Replace(text);
966}
967
968void RenderView::OnDelete() {
969 if (!webview())
970 return;
971
972 webview()->GetFocusedFrame()->Delete();
973}
974
975void RenderView::OnSelectAll() {
976 if (!webview())
977 return;
978
979 webview()->GetFocusedFrame()->SelectAll();
980}
981
982void RenderView::OnSetInitialFocus(bool reverse) {
983 if (!webview())
984 return;
985 webview()->SetInitialFocus(reverse);
986}
987
988///////////////////////////////////////////////////////////////////////////////
989
990// Tell the embedding application that the URL of the active page has changed
991void RenderView::UpdateURL(WebFrame* frame) {
992 WebDataSource* ds = frame->GetDataSource();
993 DCHECK(ds);
994
995 const WebRequest& request = ds->GetRequest();
996 const WebRequest& initial_request = ds->GetInitialRequest();
997 const WebResponse& response = ds->GetResponse();
998
999 // We don't hold a reference to the extra data. The request's reference will
1000 // be sufficient because we won't modify it during our call. MAY BE NULL.
1001 RenderViewExtraRequestData* extra_data =
1002 static_cast<RenderViewExtraRequestData*>(request.GetExtraData());
1003
1004 ViewHostMsg_FrameNavigate_Params params;
1005 params.is_post = false;
1006 params.page_id = page_id_;
[email protected]8a3422c92008-09-24 17:42:421007 params.is_content_filtered = response.IsContentFiltered();
initial.commit09911bf2008-07-26 23:55:291008 if (!request.GetSecurityInfo().empty()) {
1009 // SSL state specified in the request takes precedence over the one in the
1010 // response.
1011 // So far this is only intended for error pages that are not expected to be
1012 // over ssl, so we should not get any clash.
1013 DCHECK(response.GetSecurityInfo().empty());
1014 params.security_info = request.GetSecurityInfo();
1015 } else {
1016 params.security_info = response.GetSecurityInfo();
1017 }
1018
1019 // Set the URL to be displayed in the browser UI to the user.
1020 if (ds->HasUnreachableURL()) {
1021 params.url = ds->GetUnreachableURL();
1022 } else {
1023 params.url = request.GetURL();
1024 }
1025
1026 params.redirects = ds->GetRedirectChain();
1027 params.should_update_history = !ds->HasUnreachableURL();
1028
1029 const SearchableFormData* searchable_form_data =
1030 frame->GetDataSource()->GetSearchableFormData();
1031 if (searchable_form_data) {
1032 params.searchable_form_url = searchable_form_data->url();
1033 params.searchable_form_element_name = searchable_form_data->element_name();
1034 params.searchable_form_encoding = searchable_form_data->encoding();
1035 }
1036
1037 const PasswordForm* password_form_data =
1038 frame->GetDataSource()->GetPasswordFormData();
1039 if (password_form_data)
1040 params.password_form = *password_form_data;
1041
1042 params.gesture = navigation_gesture_;
1043 navigation_gesture_ = NavigationGestureUnknown;
1044
1045 if (webview()->GetMainFrame() == frame) {
1046 // Top-level navigation.
1047
1048 // Update contents MIME type for main frame.
1049 std::wstring mime_type = ds->GetResponseMimeType();
1050 params.contents_mime_type = WideToASCII(mime_type);
1051
1052 // We assume top level navigations initiated by the renderer are link
1053 // clicks.
1054 params.transition = extra_data ?
1055 extra_data->transition_type : PageTransition::LINK;
1056 if (!PageTransition::IsMainFrame(params.transition)) {
1057 // If the main frame does a load, it should not be reported as a subframe
1058 // navigation. This can occur in the following case:
1059 // 1. You're on a site with frames.
1060 // 2. You do a subframe navigation. This is stored with transition type
1061 // MANUAL_SUBFRAME.
1062 // 3. You navigate to some non-frame site, say, google.com.
1063 // 4. You navigate back to the page from step 2. Since it was initially
1064 // MANUAL_SUBFRAME, it will be that same transition type here.
1065 // We don't want that, because any navigation that changes the toplevel
1066 // frame should be tracked as a toplevel navigation (this allows us to
1067 // update the URL bar, etc).
1068 params.transition = PageTransition::LINK;
1069 }
1070
1071 if (params.transition == PageTransition::LINK &&
1072 frame->GetDataSource()->IsFormSubmit()) {
1073 params.transition = PageTransition::FORM_SUBMIT;
1074 }
1075
1076 // If we have a valid consumed client redirect source,
1077 // the page contained a client redirect (meta refresh, document.loc...),
1078 // so we set the referrer and transition to match.
1079 if (completed_client_redirect_src_.is_valid()) {
[email protected]77e09a92008-08-01 18:11:041080 DCHECK(completed_client_redirect_src_ == params.redirects[0]);
initial.commit09911bf2008-07-26 23:55:291081 params.referrer = completed_client_redirect_src_;
1082 params.transition = static_cast<PageTransition::Type>(
1083 params.transition | PageTransition::CLIENT_REDIRECT);
1084 } else {
1085 // Bug 654101: the referrer will be empty on https->http transitions. It
1086 // would be nice if we could get the real referrer from somewhere.
1087 params.referrer = GURL(initial_request.GetHttpReferrer());
1088 }
1089
1090 std::wstring method = request.GetHttpMethod();
1091 if (method == L"POST")
1092 params.is_post = true;
1093
1094 Send(new ViewHostMsg_FrameNavigate(routing_id_, params));
1095 } else {
1096 // Subframe navigation: the type depends on whether this navigation
1097 // generated a new session history entry. When they do generate a session
1098 // history entry, it means the user initiated the navigation and we should
1099 // mark it as such. This test checks if this is the first time UpdateURL
1100 // has been called since WillNavigateToURL was called to initiate the load.
1101 if (page_id_ > last_page_id_sent_to_browser_)
1102 params.transition = PageTransition::MANUAL_SUBFRAME;
1103 else
1104 params.transition = PageTransition::AUTO_SUBFRAME;
1105
1106 // The browser should never initiate a subframe navigation.
1107 DCHECK(!extra_data);
1108 Send(new ViewHostMsg_FrameNavigate(routing_id_, params));
1109 }
1110
1111 last_page_id_sent_to_browser_ =
1112 std::max(last_page_id_sent_to_browser_, page_id_);
1113
1114 // If we end up reusing this WebRequest (for example, due to a #ref click),
1115 // we don't want the transition type to persist.
1116 if (extra_data)
1117 extra_data->transition_type = PageTransition::LINK; // Just clear it.
[email protected]266eb6f2008-09-30 23:56:501118
1119 if (glue_accessibility_.get()) {
1120 // Clear accessibility info cache.
1121 glue_accessibility_->ClearIAccessibleMap(-1, true);
1122 }
initial.commit09911bf2008-07-26 23:55:291123}
1124
1125// Tell the embedding application that the title of the active page has changed
1126void RenderView::UpdateTitle(WebFrame* frame, const std::wstring& title) {
1127 // Ignore all but top level navigations...
1128 if (webview()->GetMainFrame() == frame)
1129 Send(new ViewHostMsg_UpdateTitle(routing_id_, page_id_, title));
1130}
1131
1132void RenderView::UpdateEncoding(WebFrame* frame,
[email protected]e38f40152008-09-12 23:08:301133 const std::wstring& encoding_name) {
initial.commit09911bf2008-07-26 23:55:291134 // Only update main frame's encoding_name.
1135 if (webview()->GetMainFrame() == frame &&
1136 last_encoding_name_ != encoding_name) {
[email protected]e38f40152008-09-12 23:08:301137 // Save the encoding name for later comparing.
initial.commit09911bf2008-07-26 23:55:291138 last_encoding_name_ = encoding_name;
1139
[email protected]e38f40152008-09-12 23:08:301140 Send(new ViewHostMsg_UpdateEncoding(routing_id_, last_encoding_name_));
initial.commit09911bf2008-07-26 23:55:291141 }
1142}
1143
1144void RenderView::UpdateSessionHistory(WebFrame* frame) {
1145 // If we have a valid page ID at this point, then it corresponds to the page
1146 // we are navigating away from. Otherwise, this is the first navigation, so
1147 // there is no past session history to record.
1148 if (page_id_ == -1)
1149 return;
1150
1151 GURL url;
1152 std::wstring title;
1153 std::string state;
1154 if (!webview()->GetMainFrame()->GetPreviousState(&url, &title, &state))
1155 return;
1156
1157 Send(new ViewHostMsg_UpdateState(routing_id_, page_id_, url, title, state));
1158}
1159
1160///////////////////////////////////////////////////////////////////////////////
1161// WebViewDelegate
1162
1163void RenderView::DidStartLoading(WebView* webview) {
1164 if (is_loading_) {
1165 DLOG(WARNING) << "DidStartLoading called while loading";
1166 return;
1167 }
1168
1169 is_loading_ = true;
1170 // Clear the pointer so that we can assign it only when there is an unknown
1171 // plugin on a page.
1172 first_default_plugin_ = NULL;
1173
1174 Send(new ViewHostMsg_DidStartLoading(routing_id_, page_id_));
1175}
1176
1177void RenderView::DidStopLoading(WebView* webview) {
1178 if (!is_loading_) {
1179 DLOG(WARNING) << "DidStopLoading called while not loading";
1180 return;
1181 }
1182
1183 is_loading_ = false;
1184
1185 // NOTE: For now we're doing the safest thing, and sending out notification
1186 // when done loading. This currently isn't an issue as the favicon is only
1187 // displayed when done loading. Ideally we would send notification when
1188 // finished parsing the head, but webkit doesn't support that yet.
1189 // The feed discovery code would also benefit from access to the head.
1190 GURL favicon_url(webview->GetMainFrame()->GetFavIconURL());
1191 if (!favicon_url.is_empty())
1192 Send(new ViewHostMsg_UpdateFavIconURL(routing_id_, page_id_, favicon_url));
1193
1194 AddGURLSearchProvider(webview->GetMainFrame()->GetOSDDURL(),
1195 true); // autodetected
1196
1197 Send(new ViewHostMsg_DidStopLoading(routing_id_, page_id_));
1198
1199 MessageLoop::current()->PostDelayedTask(FROM_HERE,
1200 method_factory_.NewRunnableMethod(&RenderView::CapturePageInfo, page_id_,
1201 false),
1202 kDelayForCaptureMs);
1203
1204 // The page is loaded. Try to process the file we need to upload if any.
1205 ProcessPendingUpload();
1206
1207 // Since the page is done loading, we are sure we don't need to try
1208 // again.
1209 ResetPendingUpload();
1210}
1211
1212void RenderView::DidStartProvisionalLoadForFrame(
1213 WebView* webview,
1214 WebFrame* frame,
1215 NavigationGesture gesture) {
[email protected]77e09a92008-08-01 18:11:041216 if (webview->GetMainFrame() == frame) {
initial.commit09911bf2008-07-26 23:55:291217 navigation_gesture_ = gesture;
[email protected]266eb6f2008-09-30 23:56:501218
[email protected]77e09a92008-08-01 18:11:041219 // Make sure redirect tracking state is clear for the new load.
1220 completed_client_redirect_src_ = GURL();
1221 }
initial.commit09911bf2008-07-26 23:55:291222
1223 Send(new ViewHostMsg_DidStartProvisionalLoadForFrame(
1224 routing_id_, webview->GetMainFrame() == frame,
1225 frame->GetProvisionalDataSource()->GetRequest().GetURL()));
1226}
1227
1228bool RenderView::DidLoadResourceFromMemoryCache(WebView* webview,
1229 const WebRequest& request,
1230 const WebResponse& response,
1231 WebFrame* frame) {
1232 // Let the browser know we loaded a resource from the memory cache. This
1233 // message is needed to display the correct SSL indicators.
1234 Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(routing_id_,
1235 request.GetURL(), response.GetSecurityInfo()));
1236
1237 return false;
1238}
1239
1240void RenderView::DidReceiveProvisionalLoadServerRedirect(WebView* webview,
1241 WebFrame* frame) {
1242 if (frame == webview->GetMainFrame()) {
1243 // Received a redirect on the main frame.
1244 WebDataSource* data_source =
1245 webview->GetMainFrame()->GetProvisionalDataSource();
1246 if (!data_source) {
1247 // Should only be invoked when we have a data source.
1248 NOTREACHED();
1249 return;
1250 }
1251 const std::vector<GURL>& redirects = data_source->GetRedirectChain();
1252 if (redirects.size() >= 2) {
1253 Send(new ViewHostMsg_DidRedirectProvisionalLoad(
1254 routing_id_, page_id_, redirects[redirects.size() - 2],
1255 redirects[redirects.size() - 1]));
1256 }
1257 }
1258}
1259
1260void RenderView::DidFailProvisionalLoadWithError(WebView* webview,
1261 const WebError& error,
1262 WebFrame* frame) {
1263 // Notify the browser that we failed a provisional load with an error.
1264 //
1265 // Note: It is important this notification occur before DidStopLoading so the
1266 // SSL manager can react to the provisional load failure before being
1267 // notified the load stopped.
1268 //
1269 WebDataSource* ds = frame->GetProvisionalDataSource();
1270 DCHECK(ds);
1271
1272 const WebRequest& failed_request = ds->GetRequest();
1273
1274 bool show_repost_interstitial =
1275 (error.GetErrorCode() == net::ERR_CACHE_MISS &&
1276 LowerCaseEqualsASCII(failed_request.GetHttpMethod(), "post"));
1277 Send(new ViewHostMsg_DidFailProvisionalLoadWithError(
1278 routing_id_, frame == webview->GetMainFrame(),
1279 error.GetErrorCode(), error.GetFailedURL(),
1280 show_repost_interstitial));
1281
initial.commit09911bf2008-07-26 23:55:291282 // Don't display an error page if this is simply a cancelled load. Aside
1283 // from being dumb, WebCore doesn't expect it and it will cause a crash.
1284 if (error.GetErrorCode() == net::ERR_ABORTED)
1285 return;
1286
1287 // If this is a failed back/forward/reload navigation, then we need to do a
1288 // 'replace' load. This is necessary to avoid messing up session history.
1289 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
1290 // as session history is concerned.
1291 RenderViewExtraRequestData* extra_data =
1292 static_cast<RenderViewExtraRequestData*>(failed_request.GetExtraData());
1293 bool replace = extra_data && !extra_data->is_new_navigation();
1294
[email protected]5df266ac2008-10-15 19:50:131295 // Use the alternate error page service if this is a DNS failure or
1296 // connection failure. ERR_CONNECTION_FAILED can be dropped once we no longer
1297 // use winhttp.
1298 int ec = error.GetErrorCode();
1299 if (ec == net::ERR_NAME_NOT_RESOLVED ||
1300 ec == net::ERR_CONNECTION_FAILED ||
1301 ec == net::ERR_CONNECTION_REFUSED ||
1302 ec == net::ERR_ADDRESS_UNREACHABLE ||
1303 ec == net::ERR_TIMED_OUT) {
1304 const GURL& failed_url = error.GetFailedURL();
1305 const GURL& error_page_url = GetAlternateErrorPageURL(failed_url,
1306 ec == net::ERR_NAME_NOT_RESOLVED ? WebViewDelegate::DNS_ERROR
1307 : WebViewDelegate::CONNECTION_ERROR);
1308 if (error_page_url.is_valid()) {
1309 // Ask the WebFrame to fetch the alternate error page for us.
1310 frame->LoadAlternateHTMLErrorPage(&failed_request, error, error_page_url,
1311 replace, GURL(kUnreachableWebDataURL));
1312 return;
1313 }
initial.commit09911bf2008-07-26 23:55:291314 }
[email protected]5df266ac2008-10-15 19:50:131315
1316 // Fallback to a local error page.
1317 LoadNavigationErrorPage(frame, &failed_request, error, std::string(),
1318 replace);
initial.commit09911bf2008-07-26 23:55:291319}
1320
1321void RenderView::LoadNavigationErrorPage(WebFrame* frame,
1322 const WebRequest* failed_request,
1323 const WebError& error,
1324 const std::string& html,
1325 bool replace) {
1326 const GURL& failed_url = error.GetFailedURL();
1327
1328 std::string alt_html;
1329 if (html.empty()) {
1330 // Use a local error page.
1331 int resource_id;
1332 DictionaryValue error_strings;
1333 if (error.GetErrorCode() == net::ERR_CACHE_MISS &&
1334 LowerCaseEqualsASCII(failed_request->GetHttpMethod(), "post")) {
1335 GetFormRepostErrorValues(failed_url, &error_strings);
1336 resource_id = IDR_ERROR_NO_DETAILS_HTML;
1337 } else {
1338 GetLocalizedErrorValues(error, &error_strings);
1339 resource_id = IDR_NET_ERROR_HTML;
1340 }
1341 error_strings.SetString(L"textdirection",
1342 (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ?
1343 L"rtl" : L"ltr");
1344
1345 alt_html = GetAltHTMLForTemplate(error_strings, resource_id);
1346 } else {
1347 alt_html = html;
1348 }
1349
1350 // Use a data: URL as the site URL to prevent against XSS attacks.
1351 scoped_ptr<WebRequest> request(failed_request->Clone());
1352 request->SetURL(GURL(kUnreachableWebDataURL));
1353
1354 frame->LoadAlternateHTMLString(request.get(), alt_html, failed_url,
1355 replace);
1356}
1357
1358void RenderView::DidCommitLoadForFrame(WebView *webview, WebFrame* frame,
1359 bool is_new_navigation) {
1360 const WebRequest& request =
1361 webview->GetMainFrame()->GetDataSource()->GetRequest();
1362 RenderViewExtraRequestData* extra_data =
1363 static_cast<RenderViewExtraRequestData*>(request.GetExtraData());
1364
1365 if (is_new_navigation) {
1366 // When we perform a new navigation, we need to update the previous session
1367 // history entry with state for the page we are leaving.
1368 UpdateSessionHistory(frame);
1369
1370 // We bump our Page ID to correspond with the new session history entry.
1371 page_id_ = next_page_id_++;
1372
1373 MessageLoop::current()->PostDelayedTask(FROM_HERE,
1374 method_factory_.NewRunnableMethod(&RenderView::CapturePageInfo,
1375 page_id_, true),
1376 kDelayForForcedCaptureMs);
1377 } else {
1378 // Inspect the extra_data on the main frame (set in our Navigate method) to
1379 // see if the navigation corresponds to a session history navigation...
1380 // Note: |frame| may or may not be the toplevel frame, but for the case
1381 // of capturing session history, the first committed frame suffices. We
1382 // keep track of whether we've seen this commit before so that only capture
1383 // session history once per navigation.
1384 if (extra_data && !extra_data->is_new_navigation() &&
1385 !extra_data->request_committed) {
1386 // This is a successful session history navigation!
1387 UpdateSessionHistory(frame);
1388
1389 page_id_ = extra_data->pending_page_id();
1390 }
1391 }
1392
1393 // Remember that we've already processed this request, so we don't update
1394 // the session history again. We do this regardless of whether this is
1395 // a session history navigation, because if we attempted a session history
1396 // navigation without valid HistoryItem state, WebCore will think it is a
1397 // new navigation.
1398 if (extra_data)
1399 extra_data->request_committed = true;
1400
1401 UpdateURL(frame);
1402
1403 // If this committed load was initiated by a client redirect, we're
1404 // at the last stop now, so clear it.
1405 completed_client_redirect_src_ = GURL();
1406
1407 // Check whether we have new encoding name.
1408 UpdateEncoding(frame, webview->GetMainFrameEncodingName());
1409}
1410
1411void RenderView::DidReceiveTitle(WebView* webview,
1412 const std::wstring& title,
1413 WebFrame* frame) {
1414 UpdateTitle(frame, title);
1415
1416 // Also check whether we have new encoding name.
1417 UpdateEncoding(frame, webview->GetMainFrameEncodingName());
1418}
1419
1420void RenderView::DidFinishLoadForFrame(WebView* webview, WebFrame* frame) {
1421}
1422
1423void RenderView::DidFailLoadWithError(WebView* webview,
1424 const WebError& error,
1425 WebFrame* frame) {
1426}
1427
1428void RenderView::DidFinishDocumentLoadForFrame(WebView* webview,
1429 WebFrame* frame) {
1430 // Check whether we have new encoding name.
1431 UpdateEncoding(frame, webview->GetMainFrameEncodingName());
[email protected]1e0f70402008-10-16 23:57:471432
1433 // Inject any Greasemonkey scripts. Do not inject into chrome UI pages, but
1434 // do inject into any other document.
1435 if (greasemonkey_enabled_) {
1436 const GURL &gurl = frame->GetURL();
1437 if (gurl.SchemeIs("file") ||
1438 gurl.SchemeIs("http") ||
1439 gurl.SchemeIs("https")) {
1440 RenderThread::current()->greasemonkey_slave()->InjectScripts(frame);
1441 }
1442 }
initial.commit09911bf2008-07-26 23:55:291443}
1444
1445void RenderView::DidHandleOnloadEventsForFrame(WebView* webview,
1446 WebFrame* frame) {
1447}
1448
1449void RenderView::DidChangeLocationWithinPageForFrame(WebView* webview,
1450 WebFrame* frame,
1451 bool is_new_navigation) {
1452 DidCommitLoadForFrame(webview, frame, is_new_navigation);
[email protected]de56f3782008-10-01 22:31:351453 const std::wstring& title =
1454 webview->GetMainFrame()->GetDataSource()->GetPageTitle();
1455 UpdateTitle(frame, title);
initial.commit09911bf2008-07-26 23:55:291456}
1457
1458void RenderView::DidReceiveIconForFrame(WebView* webview,
1459 WebFrame* frame) {
1460}
1461
1462void RenderView::WillPerformClientRedirect(WebView* webview,
1463 WebFrame* frame,
1464 const GURL& src_url,
1465 const GURL& dest_url,
1466 unsigned int delay_seconds,
1467 unsigned int fire_date) {
1468}
1469
1470void RenderView::DidCancelClientRedirect(WebView* webview,
1471 WebFrame* frame) {
1472}
1473
1474void RenderView::DidCompleteClientRedirect(WebView* webview,
1475 WebFrame* frame,
1476 const GURL& source) {
1477 if (webview->GetMainFrame() == frame)
1478 completed_client_redirect_src_ = source;
1479}
1480
1481void RenderView::BindDOMAutomationController(WebFrame* webframe) {
1482 dom_automation_controller_.set_message_sender(this);
1483 dom_automation_controller_.set_routing_id(routing_id_);
1484 dom_automation_controller_.BindToJavascript(webframe,
1485 L"domAutomationController");
1486}
1487
1488void RenderView::WindowObjectCleared(WebFrame* webframe) {
1489 external_js_object_.set_render_view(this);
1490 external_js_object_.BindToJavascript(webframe, L"external");
1491 if (enable_dom_automation_)
1492 BindDOMAutomationController(webframe);
1493 if (enable_dom_ui_bindings_) {
1494 dom_ui_bindings_.set_message_sender(this);
1495 dom_ui_bindings_.set_routing_id(routing_id_);
1496 dom_ui_bindings_.BindToJavascript(webframe, L"chrome");
1497 }
[email protected]18cb2572008-08-21 20:34:451498 if (enable_external_host_bindings_) {
1499 external_host_bindings_.set_message_sender(this);
1500 external_host_bindings_.set_routing_id(routing_id_);
1501 external_host_bindings_.BindToJavascript(webframe, L"externalHost");
1502 }
[email protected]9a2051d2008-08-15 20:12:421503
[email protected]3a453fa2008-08-15 18:46:341504#ifdef CHROME_PERSONALIZATION
1505 Personalization::ConfigureRendererPersonalization(personalization_, this,
1506 routing_id_, webframe);
1507#endif
initial.commit09911bf2008-07-26 23:55:291508}
1509
1510WindowOpenDisposition RenderView::DispositionForNavigationAction(
1511 WebView* webview,
1512 WebFrame* frame,
1513 const WebRequest* request,
1514 WebNavigationType type,
1515 WindowOpenDisposition disposition,
1516 bool is_redirect) {
1517 // Webkit is asking whether to navigate to a new URL.
1518 // This is fine normally, except if we're showing UI from one security
1519 // context and they're trying to navigate to a different context.
1520 const GURL& url = request->GetURL();
1521 // We only care about navigations that are within the current tab (as opposed
1522 // to, for example, opening a new window).
1523 // But we sometimes navigate to about:blank to clear a tab, and we want to
1524 // still allow that.
1525 if (disposition == CURRENT_TAB && !(url.SchemeIs("about"))) {
1526 // GetExtraData is NULL when we did not issue the request ourselves (see
1527 // OnNavigate), and so such a request may correspond to a link-click,
1528 // script, or drag-n-drop initiated navigation.
1529 if (frame == webview->GetMainFrame() && !request->GetExtraData()) {
1530 // When we received such unsolicited navigations, we sometimes want to
1531 // punt them up to the browser to handle.
1532 if (enable_dom_ui_bindings_ ||
1533 frame->GetInViewSourceMode() ||
1534 url.SchemeIs("view-source")) {
[email protected]c0588052008-10-27 23:01:501535 OpenURL(webview, url, GURL(), disposition);
initial.commit09911bf2008-07-26 23:55:291536 return IGNORE_ACTION; // Suppress the load here.
[email protected]50b691c2008-10-31 19:08:351537 } else if (url.SchemeIs(kBackForwardNavigationScheme)) {
1538 std::string offset_str = url.ExtractFileName();
1539 int offset;
1540 if (StringToInt(offset_str, &offset)) {
[email protected]0c0383772008-11-04 00:48:311541 GoToEntryAtOffset(offset);
[email protected]50b691c2008-10-31 19:08:351542 return IGNORE_ACTION; // The browser process handles this one.
1543 }
initial.commit09911bf2008-07-26 23:55:291544 }
1545 }
1546 }
1547
1548 // Detect when a page is "forking" a new tab that can be safely rendered in
1549 // its own process. This is done by sites like Gmail that try to open links
1550 // in new windows without script connections back to the original page. We
1551 // treat such cases as browser navigations (in which we will create a new
1552 // renderer for a cross-site navigation), rather than WebKit navigations.
1553 //
1554 // We use the following heuristic to decide whether to fork a new page in its
1555 // own process:
1556 // The parent page must open a new tab to about:blank, set the new tab's
1557 // window.opener to null, and then redirect the tab to a cross-site URL using
1558 // JavaScript.
1559 bool is_fork =
1560 // Must start from a tab showing about:blank, which is later redirected.
1561 frame->GetURL() == GURL("about:blank") &&
1562 // Must be the first real navigation of the tab.
1563 GetHistoryBackListCount() < 1 &&
1564 GetHistoryForwardListCount() < 1 &&
1565 // The parent page must have set the child's window.opener to null before
1566 // redirecting to the desired URL.
1567 frame->GetOpener() == NULL &&
1568 // Must be a top-level frame.
1569 frame->GetParent() == NULL &&
1570 // Must not have issued the request from this page. GetExtraData is NULL
1571 // when the navigation is being done by something outside the page.
1572 !request->GetExtraData() &&
1573 // Must be targeted at the current tab.
1574 disposition == CURRENT_TAB &&
1575 // Must be a JavaScript navigation, which appears as "other".
1576 type == WebNavigationTypeOther;
1577 if (is_fork) {
1578 // Open the URL via the browser, not via WebKit.
[email protected]c0588052008-10-27 23:01:501579 OpenURL(webview, url, GURL(), disposition);
initial.commit09911bf2008-07-26 23:55:291580 return IGNORE_ACTION;
1581 }
1582
1583 return disposition;
1584}
1585
1586void RenderView::RunJavaScriptAlert(WebView* webview,
1587 const std::wstring& message) {
1588 RunJavaScriptMessage(MessageBoxView::kIsJavascriptAlert,
1589 message,
1590 std::wstring(),
1591 NULL);
1592}
1593
1594bool RenderView::RunJavaScriptConfirm(WebView* webview,
1595 const std::wstring& message) {
1596 return RunJavaScriptMessage(MessageBoxView::kIsJavascriptConfirm,
1597 message,
1598 std::wstring(),
1599 NULL);
1600}
1601
1602bool RenderView::RunJavaScriptPrompt(WebView* webview,
1603 const std::wstring& message,
1604 const std::wstring& default_value,
1605 std::wstring* result) {
1606 return RunJavaScriptMessage(MessageBoxView::kIsJavascriptPrompt,
1607 message,
1608 default_value,
1609 result);
1610}
1611
1612bool RenderView::RunJavaScriptMessage(int type,
1613 const std::wstring& message,
1614 const std::wstring& default_value,
1615 std::wstring* result) {
1616 bool success = false;
1617 std::wstring result_temp;
1618 if (!result)
1619 result = &result_temp;
1620 IPC::SyncMessage* msg = new ViewHostMsg_RunJavaScriptMessage(
1621 routing_id_, message, default_value, type, &success, result);
1622
1623 msg->set_pump_messages_event(modal_dialog_event_);
1624 Send(msg);
1625
1626 return success;
1627}
1628
1629void RenderView::AddGURLSearchProvider(const GURL& osd_url, bool autodetected) {
1630 if (!osd_url.is_empty())
1631 Send(new ViewHostMsg_PageHasOSDD(routing_id_, page_id_, osd_url,
1632 autodetected));
1633}
1634
1635bool RenderView::RunBeforeUnloadConfirm(WebView* webview,
1636 const std::wstring& message) {
1637 bool success = false;
1638 // This is an ignored return value, but is included so we can accept the same
1639 // response as RunJavaScriptMessage.
1640 std::wstring ignored_result;
1641 IPC::SyncMessage* msg = new ViewHostMsg_RunBeforeUnloadConfirm(
1642 routing_id_, message, &success, &ignored_result);
1643
1644 msg->set_pump_messages_event(modal_dialog_event_);
1645 Send(msg);
1646
1647 return success;
1648}
1649
[email protected]0578a502008-11-10 19:34:431650void RenderView::EnableSuddenTermination() {
1651 Send(new ViewHostMsg_UnloadListenerChanged(routing_id_, false));
1652}
1653
1654void RenderView::DisableSuddenTermination() {
1655 Send(new ViewHostMsg_UnloadListenerChanged(routing_id_, true));
initial.commit09911bf2008-07-26 23:55:291656}
1657
[email protected]0ebf3872008-11-07 21:35:031658void RenderView::QueryFormFieldAutofill(const std::wstring& field_name,
1659 const std::wstring& text,
1660 int64 node_id) {
1661 static int message_id_counter = 0;
1662 form_field_autofill_request_id_ = message_id_counter++;
1663 Send(new ViewHostMsg_QueryFormFieldAutofill(routing_id_,
1664 field_name, text,
1665 node_id,
1666 form_field_autofill_request_id_));
1667}
1668
1669void RenderView::OnReceivedAutofillSuggestions(
1670 int64 node_id,
1671 int request_id,
[email protected]f0961cfd2008-11-08 02:38:041672 const std::vector<std::wstring> suggestions,
[email protected]0ebf3872008-11-07 21:35:031673 int default_suggestion_index) {
1674 if (!webview() || request_id != form_field_autofill_request_id_)
1675 return;
1676
1677 webview()->AutofillSuggestionsForNode(node_id, suggestions,
1678 default_suggestion_index);
1679}
1680
initial.commit09911bf2008-07-26 23:55:291681void RenderView::ShowModalHTMLDialog(const GURL& url, int width, int height,
1682 const std::string& json_arguments,
1683 std::string* json_retval) {
1684 IPC::SyncMessage* msg = new ViewHostMsg_ShowModalHTMLDialog(
1685 routing_id_, url, width, height, json_arguments, json_retval);
1686
1687 msg->set_pump_messages_event(modal_dialog_event_);
1688 Send(msg);
1689}
1690
1691uint32 RenderView::GetCPBrowsingContext() {
1692 uint32 context = 0;
1693 Send(new ViewHostMsg_GetCPBrowsingContext(&context));
1694 return context;
1695}
1696
1697// Tell the browser to display a destination link.
1698void RenderView::UpdateTargetURL(WebView* webview, const GURL& url) {
1699 if (url != target_url_) {
1700 if (target_url_status_ == TARGET_INFLIGHT ||
1701 target_url_status_ == TARGET_PENDING) {
1702 // If we have a request in-flight, save the URL to be sent when we
1703 // receive an ACK to the in-flight request. We can happily overwrite
1704 // any existing pending sends.
1705 pending_target_url_ = url;
1706 target_url_status_ = TARGET_PENDING;
1707 } else {
1708 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_, url));
1709 target_url_ = url;
1710 target_url_status_ = TARGET_INFLIGHT;
1711 }
1712 }
1713}
1714
1715void RenderView::RunFileChooser(const std::wstring& default_filename,
1716 WebFileChooserCallback* file_chooser) {
1717 if (file_chooser_.get()) {
1718 // TODO(brettw): bug 1235154: This should be a synchronous message to deal
1719 // with the fact that web pages can programatically trigger this. With the
1720 // asnychronous messages, we can get an additional call when one is pending,
1721 // which this test is for. For now, we just ignore the additional file
1722 // chooser request. WebKit doesn't do anything to expect the callback, so
1723 // we can just ignore calling it.
1724 delete file_chooser;
1725 return;
1726 }
1727 file_chooser_.reset(file_chooser);
1728 Send(new ViewHostMsg_RunFileChooser(routing_id_, default_filename));
1729}
1730
1731void RenderView::AddMessageToConsole(WebView* webview,
1732 const std::wstring& message,
1733 unsigned int line_no,
1734 const std::wstring& source_id) {
1735 Send(new ViewHostMsg_AddMessageToConsole(routing_id_, message,
1736 static_cast<int32>(line_no),
1737 source_id));
1738}
1739
1740void RenderView::AddSearchProvider(const std::string& url) {
1741 AddGURLSearchProvider(GURL(url),
1742 false); // not autodetected
1743}
1744
1745void RenderView::DebuggerOutput(const std::wstring& out) {
1746 Send(new ViewHostMsg_DebuggerOutput(routing_id_, out));
1747}
1748
1749WebView* RenderView::CreateWebView(WebView* webview, bool user_gesture) {
[email protected]0aa55312008-10-17 21:53:081750 // Check to make sure we aren't overloading on popups.
1751 if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups)
1752 return NULL;
1753
initial.commit09911bf2008-07-26 23:55:291754 int32 routing_id = MSG_ROUTING_NONE;
[email protected]1829fcc2008-09-29 23:52:321755 HANDLE modal_dialog_event = NULL;
initial.commit09911bf2008-07-26 23:55:291756 bool result = RenderThread::current()->Send(
[email protected]15787f8f2008-10-17 15:29:031757 new ViewHostMsg_CreateWindow(routing_id_, user_gesture, &routing_id,
1758 &modal_dialog_event));
initial.commit09911bf2008-07-26 23:55:291759 if (routing_id == MSG_ROUTING_NONE) {
1760 DCHECK(modal_dialog_event == NULL);
1761 return NULL;
1762 }
1763
1764 // The WebView holds a reference to this new RenderView
1765 const WebPreferences& prefs = webview->GetPreferences();
1766 RenderView* view = RenderView::Create(NULL, modal_dialog_event, routing_id_,
[email protected]0aa55312008-10-17 21:53:081767 prefs, shared_popup_counter_,
1768 routing_id);
initial.commit09911bf2008-07-26 23:55:291769 view->set_opened_by_user_gesture(user_gesture);
[email protected]06828b92008-10-20 21:25:461770 view->set_waiting_for_create_window_ack(true);
initial.commit09911bf2008-07-26 23:55:291771
1772 // Copy over the alternate error page URL so we can have alt error pages in
1773 // the new render view (we don't need the browser to send the URL back down).
1774 view->alternate_error_page_url_ = alternate_error_page_url_;
1775
1776 return view->webview();
1777}
1778
[email protected]0ebf3872008-11-07 21:35:031779WebWidget* RenderView::CreatePopupWidget(WebView* webview,
1780 bool focus_on_show) {
[email protected]8085dbc82008-09-26 22:53:441781 RenderWidget* widget = RenderWidget::Create(routing_id_,
[email protected]0ebf3872008-11-07 21:35:031782 RenderThread::current(),
1783 focus_on_show);
initial.commit09911bf2008-07-26 23:55:291784 return widget->webwidget();
1785}
1786
[email protected]173de1b2008-08-15 18:36:461787static bool ShouldLoadPluginInProcess(const std::string& mime_type,
1788 bool* is_gears) {
1789 if (RenderProcess::ShouldLoadPluginsInProcess())
1790 return true;
1791
1792 if (mime_type == "application/x-googlegears") {
1793 *is_gears = true;
1794 CommandLine cmd;
1795 return cmd.HasSwitch(switches::kGearsInRenderer);
1796 }
1797
1798 return false;
1799}
1800
initial.commit09911bf2008-07-26 23:55:291801WebPluginDelegate* RenderView::CreatePluginDelegate(
1802 WebView* webview,
1803 const GURL& url,
1804 const std::string& mime_type,
1805 const std::string& clsid,
1806 std::string* actual_mime_type) {
[email protected]173de1b2008-08-15 18:36:461807 bool is_gears = false;
1808 if (ShouldLoadPluginInProcess(mime_type, &is_gears)) {
initial.commit09911bf2008-07-26 23:55:291809 std::wstring path;
1810 RenderThread::current()->Send(
1811 new ViewHostMsg_GetPluginPath(url, mime_type, clsid, &path,
1812 actual_mime_type));
1813 if (path.empty())
1814 return NULL;
1815
1816 std::string mime_type_to_use;
1817 if (actual_mime_type && !actual_mime_type->empty())
1818 mime_type_to_use = *actual_mime_type;
1819 else
1820 mime_type_to_use = mime_type;
1821
[email protected]173de1b2008-08-15 18:36:461822 if (is_gears)
1823 ChromePluginLib::Create(path, GetCPBrowserFuncsForRenderer());
initial.commit09911bf2008-07-26 23:55:291824 return WebPluginDelegateImpl::Create(path, mime_type_to_use, host_window_);
1825 }
1826
1827 WebPluginDelegateProxy* proxy =
1828 WebPluginDelegateProxy::Create(url, mime_type, clsid, this);
1829 if (!proxy)
1830 return NULL;
1831
1832 // We hold onto the proxy so we can poke it when we are painting. See our
1833 // DidPaint implementation below.
1834 plugin_delegates_.push_back(proxy);
1835
1836 return proxy;
1837}
1838
1839void RenderView::OnMissingPluginStatus(WebPluginDelegate* delegate,
1840 int status) {
1841 if (first_default_plugin_ == NULL) {
1842 // Show the InfoBar for the first available plugin.
1843 if (status == default_plugin::MISSING_PLUGIN_AVAILABLE) {
1844 first_default_plugin_ = delegate;
1845 Send(new ViewHostMsg_MissingPluginStatus(routing_id_, status));
1846 }
1847 } else {
1848 // Closes the InfoBar if user clicks on the plugin (instead of the InfoBar)
1849 // to start the download/install.
1850 if (status == default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD) {
1851 Send(new ViewHostMsg_MissingPluginStatus(routing_id_, status));
1852 }
1853 }
1854}
1855
1856void RenderView::OpenURL(WebView* webview, const GURL& url,
[email protected]c0588052008-10-27 23:01:501857 const GURL& referrer,
initial.commit09911bf2008-07-26 23:55:291858 WindowOpenDisposition disposition) {
[email protected]c0588052008-10-27 23:01:501859 Send(new ViewHostMsg_OpenURL(routing_id_, url, referrer, disposition));
initial.commit09911bf2008-07-26 23:55:291860}
1861
1862// We are supposed to get a single call to Show for a newly created RenderView
1863// that was created via RenderView::CreateWebView. So, we wait until this
1864// point to dispatch the ShowView message.
1865//
1866// This method provides us with the information about how to display the newly
1867// created RenderView (i.e., as a constrained popup or as a new tab).
1868//
1869void RenderView::Show(WebWidget* webwidget, WindowOpenDisposition disposition) {
1870 DCHECK(!did_show_) << "received extraneous Show call";
1871 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1872
1873 if (did_show_)
1874 return;
1875 did_show_ = true;
1876
1877 // NOTE: initial_pos_ may still have its default values at this point, but
1878 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
1879 // browser process will impose a default position otherwise.
1880 Send(new ViewHostMsg_ShowView(
1881 opener_id_, routing_id_, disposition, initial_pos_,
1882 WasOpenedByUserGestureHelper()));
1883}
1884
1885void RenderView::RunModal(WebWidget* webwidget) {
1886 DCHECK(did_show_) << "should already have shown the view";
1887
1888 IPC::SyncMessage* msg = new ViewHostMsg_RunModal(routing_id_);
1889
1890 msg->set_pump_messages_event(modal_dialog_event_);
1891 Send(msg);
1892}
1893
1894void RenderView::SyncNavigationState() {
1895 if (!webview())
1896 return;
1897
1898 GURL url;
1899 std::wstring title;
1900 std::string state;
1901 if (!webview()->GetMainFrame()->GetCurrentState(&url, &title, &state))
1902 return;
1903
1904 Send(new ViewHostMsg_UpdateState(routing_id_, page_id_, url, title, state));
1905}
1906
1907void RenderView::ShowContextMenu(WebView* webview,
1908 ContextNode::Type type,
1909 int x,
1910 int y,
1911 const GURL& link_url,
1912 const GURL& image_url,
1913 const GURL& page_url,
1914 const GURL& frame_url,
1915 const std::wstring& selection_text,
1916 const std::wstring& misspelled_word,
[email protected]6aa376b2008-09-23 18:49:521917 int edit_flags,
1918 const std::string& security_info) {
initial.commit09911bf2008-07-26 23:55:291919 ViewHostMsg_ContextMenu_Params params;
1920 params.type = type;
1921 params.x = x;
1922 params.y = y;
1923 params.image_url = image_url;
1924 params.link_url = link_url;
1925 params.page_url = page_url;
1926 params.frame_url = frame_url;
1927 params.selection_text = selection_text;
1928 params.misspelled_word = misspelled_word;
1929 params.edit_flags = edit_flags;
[email protected]6aa376b2008-09-23 18:49:521930 params.security_info = security_info;
initial.commit09911bf2008-07-26 23:55:291931 Send(new ViewHostMsg_ContextMenu(routing_id_, params));
1932}
1933
1934void RenderView::StartDragging(WebView* webview, const WebDropData& drop_data) {
1935 Send(new ViewHostMsg_StartDragging(routing_id_, drop_data));
1936}
1937
1938void RenderView::TakeFocus(WebView* webview, bool reverse) {
1939 Send(new ViewHostMsg_TakeFocus(routing_id_, reverse));
1940}
1941
1942void RenderView::DidDownloadImage(int id,
1943 const GURL& image_url,
1944 bool errored,
1945 const SkBitmap& image) {
1946 Send(new ViewHostMsg_DidDownloadImage(routing_id_, id, image_url, errored,
1947 image));
1948}
1949
1950
1951void RenderView::OnDownloadImage(int id,
1952 const GURL& image_url,
1953 int image_size) {
1954 if (!webview()->DownloadImage(id, image_url, image_size))
1955 Send(new ViewHostMsg_DidDownloadImage(routing_id_, id, image_url, true,
1956 SkBitmap()));
1957}
1958
1959void RenderView::OnGetApplicationInfo(int page_id) {
1960 webkit_glue::WebApplicationInfo app_info;
1961 if (page_id == page_id_)
1962 webkit_glue::GetApplicationInfo(webview(), &app_info);
1963
1964 // Prune out any data URLs in the set of icons. The browser process expects
1965 // any icon with a data URL to have originated from a favicon. We don't want
1966 // to decode arbitrary data URLs in the browser process. See
1967 // http://b/issue?id=1162972
1968 for (size_t i = 0; i < app_info.icons.size(); ++i) {
1969 if (app_info.icons[i].url.SchemeIs("data")) {
1970 app_info.icons.erase(app_info.icons.begin() + i);
1971 --i;
1972 }
1973 }
1974
1975 Send(new ViewHostMsg_DidGetApplicationInfo(routing_id_, page_id, app_info));
1976}
1977
1978GURL RenderView::GetAlternateErrorPageURL(const GURL& failedURL,
1979 ErrorPageType error_type) {
1980 if (failedURL.SchemeIsSecure()) {
1981 // If the URL that failed was secure, then the embedding web page was not
1982 // expecting a network attacker to be able to manipulate its contents. As
1983 // we fetch alternate error pages over HTTP, we would be allowing a network
1984 // attacker to manipulate the contents of the response if we tried to use
1985 // the link doctor here.
1986 return GURL::EmptyGURL();
1987 }
1988
1989 // Grab the base URL from the browser process.
1990 if (!alternate_error_page_url_.is_valid())
1991 return GURL::EmptyGURL();
1992
1993 // Strip query params from the failed URL.
1994 GURL::Replacements remove_params;
1995 remove_params.ClearUsername();
1996 remove_params.ClearPassword();
1997 remove_params.ClearQuery();
1998 remove_params.ClearRef();
1999 const GURL url_to_send = failedURL.ReplaceComponents(remove_params);
2000
2001 // Construct the query params to send to link doctor.
2002 std::string params(alternate_error_page_url_.query());
2003 params.append("&url=");
2004 params.append(EscapeQueryParamValue(url_to_send.spec()));
2005 params.append("&sourceid=chrome");
2006 params.append("&error=");
2007 switch (error_type) {
2008 case DNS_ERROR:
2009 params.append("dnserror");
2010 break;
2011
2012 case HTTP_404:
2013 params.append("http404");
2014 break;
2015
[email protected]5df266ac2008-10-15 19:50:132016 case CONNECTION_ERROR:
2017 params.append("connectionerror");
2018 break;
2019
initial.commit09911bf2008-07-26 23:55:292020 default:
2021 NOTREACHED() << "unknown ErrorPageType";
2022 }
2023
2024 // OK, build the final url to return.
2025 GURL::Replacements link_doctor_params;
2026 link_doctor_params.SetQueryStr(params);
2027 GURL url = alternate_error_page_url_.ReplaceComponents(link_doctor_params);
2028 return url;
2029}
2030
2031void RenderView::OnFind(const FindInPageRequest& request) {
2032 WebFrame* main_frame = webview()->GetMainFrame();
2033 WebFrame* frame_after_main = webview()->GetNextFrameAfter(main_frame, true);
2034 WebFrame* focused_frame = webview()->GetFocusedFrame();
2035 WebFrame* search_frame = focused_frame; // start searching focused frame.
2036
2037 bool multi_frame = (frame_after_main != main_frame);
2038
2039 // If we have multiple frames, we don't want to wrap the search within the
2040 // frame, so we check here if we only have main_frame in the chain.
2041 bool wrap_within_frame = !multi_frame;
2042
2043 gfx::Rect selection_rect;
2044 bool result = false;
2045
2046 do {
2047 if (request.find_next)
2048 result = search_frame->FindNext(request, wrap_within_frame);
2049 else
2050 result = search_frame->Find(request, wrap_within_frame, &selection_rect);
2051
2052 if (!result) {
2053 // don't leave text selected as you move to the next frame.
2054 search_frame->ClearSelection();
2055
2056 // Find the next frame, but skip the invisible ones.
2057 do {
2058 // What is the next frame to search? (we might be going backwards). Note
2059 // that we specify wrap=true so that search_frame never becomes NULL.
2060 search_frame = request.forward ?
2061 webview()->GetNextFrameAfter(search_frame, true) :
2062 webview()->GetPreviousFrameBefore(search_frame, true);
2063 } while (!search_frame->Visible() && search_frame != focused_frame);
2064
2065 // make sure selection doesn't affect the search operation in new frame.
2066 search_frame->ClearSelection();
2067
2068 // If we have multiple frames and we have wrapped back around to the
2069 // focused frame, we need to search it once more allowing wrap within
2070 // the frame, otherwise it will report 'no match' if the focused frame has
2071 // reported matches, but no frames after the focused_frame contain a
2072 // match for the search word(s).
2073 if (multi_frame && search_frame == focused_frame) {
2074 if (request.find_next)
2075 result = search_frame->FindNext(request, true); // Force wrapping.
2076 else
2077 result = search_frame->Find(request, true, // Force wrapping.
2078 &selection_rect);
2079 }
2080 }
2081
2082 // TODO(jcampan): http://b/issue?id=1157486 Remove StoreForFocus call once
2083 // we have the fix for 792423.
2084 search_frame->GetView()->StoreFocusForFrame(search_frame);
2085 webview()->SetFocusedFrame(search_frame);
2086 } while (!result && search_frame != focused_frame);
2087
2088 // Make sure we don't leave any frame focused or the focus won't be restored
2089 // properly in WebViewImpl::SetFocus(). Note that we are talking here about
2090 // focused on the SelectionController, not FocusController.
2091 // webview()->GetFocusedFrame() will still return the last focused frame (as
2092 // it queries the FocusController).
2093 // TODO(jcampan): http://b/issue?id=1157486 Remove next line once we have the
2094 // fix for 792423.
2095 webview()->SetFocusedFrame(NULL);
2096
2097 // We send back word that we found some matches, because we don't want to lag
2098 // when notifying the user that we found something. At this point we only know
2099 // that we found 1 match, but the scoping effort will tell us more. However,
2100 // if this is a FindNext request, the scoping effort is already under way, or
2101 // done already, so we have partial results. In that case we set it to -1 so
2102 // that it gets ignored by the FindInPageController.
2103 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2104 if (request.find_next)
2105 match_count = -1;
2106
2107 // If we find no matches (or if this is Find Next) then this will be our last
2108 // status update. Otherwise the scoping effort will send more results.
2109 bool final_status_update = !result || request.find_next;
2110
2111 // Send the search result over to the browser process.
2112 Send(new ViewHostMsg_Find_Reply(routing_id_, request.request_id,
2113 match_count,
2114 selection_rect,
2115 -1, // Don't update active match ordinal.
2116 final_status_update));
2117
2118 if (!request.find_next) {
2119 // Scoping effort begins, starting with the mainframe.
2120 search_frame = main_frame;
2121
2122 main_frame->ResetMatchCount();
2123
2124 do {
2125 // Cancel all old scoping requests before starting a new one.
2126 search_frame->CancelPendingScopingEffort();
2127
2128 // We don't start another scoping effort unless at least one match has
2129 // been found.
2130 if (result) {
2131 // Start new scoping request. If the scoping function determines that it
2132 // needs to scope, it will defer until later.
2133 search_frame->ScopeStringMatches(request,
2134 true); // reset the tickmarks
2135 }
2136
2137 // Iterate to the next frame. The frame will not necessarily scope, for
2138 // example if it is not visible.
2139 search_frame = webview()->GetNextFrameAfter(search_frame, true);
2140 } while (search_frame != main_frame);
2141 }
2142}
2143
2144void RenderView::ReportFindInPageMatchCount(int count, int request_id,
2145 bool final_update) {
2146 // If we have a message that has been queued up, then we should just replace
2147 // it. The ACK from the browser will make sure it gets sent when the browser
2148 // wants it.
2149 if (queued_find_reply_message_.get()) {
2150 IPC::Message* msg = new ViewHostMsg_Find_Reply(
2151 routing_id_,
2152 request_id,
2153 count,
2154 gfx::Rect(0, 0, 0, 0),
2155 -1, // Don't update active match ordinal.
2156 final_update);
2157 queued_find_reply_message_.reset(msg);
2158 } else {
2159 // Send the search result over to the browser process.
2160 Send(new ViewHostMsg_Find_Reply(
2161 routing_id_,
2162 request_id,
2163 count,
2164 gfx::Rect(0, 0, 0, 0),
2165 -1, // // Don't update active match ordinal.
2166 final_update));
2167 }
2168}
2169
2170void RenderView::ReportFindInPageSelection(int request_id,
2171 int active_match_ordinal,
2172 const gfx::Rect& selection_rect) {
2173 // Send the search result over to the browser process.
2174 Send(new ViewHostMsg_Find_Reply(routing_id_,
2175 request_id,
2176 -1,
2177 selection_rect,
2178 active_match_ordinal,
2179 false));
2180}
2181
2182bool RenderView::WasOpenedByUserGesture(WebView* webview) const {
2183 return WasOpenedByUserGestureHelper();
2184}
2185
2186bool RenderView::WasOpenedByUserGestureHelper() const {
2187 // If pop-up blocking has been disabled, then treat all new windows as if
2188 // they were opened by a user gesture. This will prevent them from being
2189 // blocked. This is a bit of a hack, there should be a more straightforward
2190 // way to disable pop-up blocking.
2191 if (disable_popup_blocking_)
2192 return true;
2193
2194 return opened_by_user_gesture_;
2195}
2196
2197void RenderView::SpellCheck(const std::wstring& word, int& misspell_location,
2198 int& misspell_length) {
2199 Send(new ViewHostMsg_SpellCheck(routing_id_, word, &misspell_location,
2200 &misspell_length));
2201}
2202
2203void RenderView::SetInputMethodState(bool enabled) {
2204 // Save the updated IME status and mark the input focus has been updated.
2205 // The IME status is to be sent to a browser process next time when
2206 // the input caret is rendered.
2207 ime_control_updated_ = true;
2208 ime_control_new_state_ = enabled;
2209}
2210
2211void RenderView::ScriptedPrint(WebFrame* frame) {
2212 // Retrieve the default print settings to calculate the expected number of
2213 // pages.
2214 ViewMsg_Print_Params default_settings;
2215 IPC::SyncMessage* msg =
2216 new ViewHostMsg_GetDefaultPrintSettings(routing_id_, &default_settings);
2217 if (Send(msg)) {
2218 msg = NULL;
2219 // Continue only if the settings are valid.
2220 if (default_settings.dpi && default_settings.document_cookie) {
2221 int expected_pages_count = SwitchFrameToPrintMediaType(default_settings,
2222 frame);
2223 DCHECK(expected_pages_count);
2224 SwitchFrameToDisplayMediaType(frame);
2225
2226 // Ask the browser to show UI to retrieve the final print settings.
2227 ViewMsg_PrintPages_Params print_settings;
2228 // host_window_ may be NULL at this point if the current window is a popup
2229 // and the print() command has been issued from the parent. The receiver
2230 // of this message has to deal with this.
2231 msg = new ViewHostMsg_ScriptedPrint(routing_id_,
2232 host_window_,
2233 default_settings.document_cookie,
2234 expected_pages_count,
2235 &print_settings);
2236 if (Send(msg)) {
2237 msg = NULL;
2238
2239 // If the settings are invalid, early quit.
2240 if (print_settings.params.dpi &&
2241 print_settings.params.document_cookie) {
2242 // Render the printed pages. It will implicitly revert the document to
2243 // display CSS media type.
2244 PrintPages(print_settings, frame);
2245 // All went well.
2246 return;
2247 } else {
2248 // The user cancelled.
2249 }
2250 } else {
2251 // Send() failed.
2252 NOTREACHED();
2253 }
2254 } else {
2255 // The user cancelled.
2256 }
2257 } else {
2258 // Send() failed.
2259 NOTREACHED();
2260 }
2261 // TODO(maruel): bug 1123882 Alert the user that printing failed.
2262}
2263
2264void RenderView::WebInspectorOpened(int num_resources) {
2265 Send(new ViewHostMsg_InspectElement_Reply(routing_id_, num_resources));
2266}
2267
2268void RenderView::UserMetricsRecordAction(const std::wstring& action) {
2269 Send(new ViewHostMsg_UserMetricsRecordAction(routing_id_, action));
2270}
2271
2272void RenderView::DnsPrefetch(const std::vector<std::string>& host_names) {
2273 Send(new ViewHostMsg_DnsPrefetch(host_names));
2274}
2275
[email protected]630e26b2008-10-14 22:55:172276void RenderView::OnZoom(int function) {
2277 static const bool kZoomIsTextOnly = false;
2278 switch (function) {
2279 case PageZoom::SMALLER:
2280 webview()->ZoomOut(kZoomIsTextOnly);
initial.commit09911bf2008-07-26 23:55:292281 break;
[email protected]630e26b2008-10-14 22:55:172282 case PageZoom::STANDARD:
2283 webview()->ResetZoom();
initial.commit09911bf2008-07-26 23:55:292284 break;
[email protected]630e26b2008-10-14 22:55:172285 case PageZoom::LARGER:
2286 webview()->ZoomIn(kZoomIsTextOnly);
initial.commit09911bf2008-07-26 23:55:292287 break;
2288 default:
2289 NOTREACHED();
2290 }
2291}
2292
[email protected]e38f40152008-09-12 23:08:302293void RenderView::OnSetPageEncoding(const std::wstring& encoding_name) {
initial.commit09911bf2008-07-26 23:55:292294 webview()->SetPageEncoding(encoding_name);
2295}
2296
2297void RenderView::OnPasswordFormsSeen(WebView* webview,
2298 const std::vector<PasswordForm>& forms) {
2299 Send(new ViewHostMsg_PasswordFormsSeen(routing_id_, forms));
2300}
2301
initial.commit09911bf2008-07-26 23:55:292302WebHistoryItem* RenderView::GetHistoryEntryAtOffset(int offset) {
[email protected]50b691c2008-10-31 19:08:352303 // Our history list is kept in the browser process on the UI thread. Since
2304 // we can't make a sync IPC call to that thread without risking deadlock,
2305 // we use a trick: construct a fake history item of the form:
2306 // history://go/OFFSET
2307 // When WebCore tells us to navigate to it, we tell the browser process to
2308 // do a back/forward navigation instead.
2309
2310 GURL url(StringPrintf("%s://go/%d", kBackForwardNavigationScheme, offset));
2311 history_navigation_item_ = WebHistoryItem::Create(url, L"", "", NULL);
2312 return history_navigation_item_.get();
initial.commit09911bf2008-07-26 23:55:292313}
2314
[email protected]0c0383772008-11-04 00:48:312315void RenderView::GoToEntryAtOffset(int offset) {
[email protected]f46aff62008-10-16 07:58:052316 history_back_list_count_ += offset;
2317 history_forward_list_count_ -= offset;
2318
initial.commit09911bf2008-07-26 23:55:292319 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
2320}
2321
2322int RenderView::GetHistoryBackListCount() {
2323 return history_back_list_count_;
2324}
2325
2326int RenderView::GetHistoryForwardListCount() {
2327 return history_forward_list_count_;
2328}
2329
2330void RenderView::OnNavStateChanged(WebView* webview) {
[email protected]aeab57ea2008-08-28 20:50:122331 if (!nav_state_sync_timer_.IsRunning())
2332 nav_state_sync_timer_.Start(kDelayForNavigationSync, this,
2333 &RenderView::SyncNavigationState);
initial.commit09911bf2008-07-26 23:55:292334}
2335
2336void RenderView::SetTooltipText(WebView* webview,
2337 const std::wstring& tooltip_text) {
2338 Send(new ViewHostMsg_SetTooltipText(routing_id_, tooltip_text));
2339}
2340
2341void RenderView::DownloadUrl(const GURL& url, const GURL& referrer) {
2342 Send(new ViewHostMsg_DownloadUrl(routing_id_, url, referrer));
2343}
2344
2345WebFrame* RenderView::GetChildFrame(const std::wstring& frame_xpath) const {
2346 WebFrame* web_frame;
2347 if (frame_xpath.empty()) {
2348 web_frame = webview()->GetMainFrame();
2349 } else {
2350 web_frame = webview()->GetMainFrame()->GetChildFrame(frame_xpath);
2351 }
2352
2353 return web_frame;
2354}
2355
[email protected]f29acf52008-11-03 20:08:332356void RenderView::EvaluateScript(const std::wstring& frame_xpath,
2357 const std::wstring& script) {
initial.commit09911bf2008-07-26 23:55:292358 WebFrame* web_frame = GetChildFrame(frame_xpath);
2359 if (!web_frame)
2360 return;
2361
[email protected]f29acf52008-11-03 20:08:332362 web_frame->ExecuteJavaScript(WideToUTF8(script), "");
initial.commit09911bf2008-07-26 23:55:292363}
2364
2365void RenderView::OnScriptEvalRequest(const std::wstring& frame_xpath,
2366 const std::wstring& jscript) {
[email protected]f29acf52008-11-03 20:08:332367 EvaluateScript(frame_xpath, jscript);
initial.commit09911bf2008-07-26 23:55:292368}
2369
2370void RenderView::OnAddMessageToConsole(const std::wstring& frame_xpath,
2371 const std::wstring& msg,
2372 ConsoleMessageLevel level) {
2373 WebFrame* web_frame = GetChildFrame(frame_xpath);
2374 if (!web_frame)
2375 return;
2376
2377 web_frame->AddMessageToConsole(msg, level);
2378}
2379
2380void RenderView::OnDebugAttach() {
initial.commit09911bf2008-07-26 23:55:292381 Send(new ViewHostMsg_DidDebugAttach(routing_id_));
2382 // Tell the plugin host to stop accepting messages in order to avoid
2383 // hangs while the renderer is paused.
2384 // TODO(1243929): It might be an improvement to add more plumbing to do this
2385 // when the renderer is actually paused vs. just the debugger being attached.
2386 PluginChannelHost::SetListening(false);
2387}
2388
2389void RenderView::OnDebugDetach() {
2390 // Tell the plugin host to start accepting plugin messages again.
2391 PluginChannelHost::SetListening(true);
2392}
2393
2394void RenderView::OnAllowDomAutomationBindings(bool allow_bindings) {
2395 enable_dom_automation_ = allow_bindings;
2396}
2397
[email protected]18cb2572008-08-21 20:34:452398void RenderView::OnAllowBindings(bool enable_dom_ui_bindings,
[email protected]266eb6f2008-09-30 23:56:502399 bool enable_external_host_bindings) {
[email protected]18cb2572008-08-21 20:34:452400 enable_dom_ui_bindings_ = enable_dom_ui_bindings;
2401 enable_external_host_bindings_ = enable_external_host_bindings;
initial.commit09911bf2008-07-26 23:55:292402}
2403
2404void RenderView::OnSetDOMUIProperty(const std::string& name,
2405 const std::string& value) {
2406 DCHECK(enable_dom_ui_bindings_);
2407 dom_ui_bindings_.SetProperty(name, value);
2408}
2409
2410void RenderView::OnReservePageIDRange(int size_of_range) {
2411 next_page_id_ += size_of_range + 1;
2412}
2413
2414void RenderView::OnDragSourceEndedOrMoved(int client_x,
2415 int client_y,
2416 int screen_x,
2417 int screen_y,
2418 bool ended) {
2419 if (ended)
2420 webview()->DragSourceEndedAt(client_x, client_y, screen_x, screen_y);
2421 else
2422 webview()->DragSourceMovedTo(client_x, client_y, screen_x, screen_y);
2423}
2424
2425void RenderView::OnDragSourceSystemDragEnded() {
2426 webview()->DragSourceSystemDragEnded();
2427}
2428
2429void RenderView::OnUploadFileRequest(const ViewMsg_UploadFile_Params& p) {
2430 webkit_glue::FileUploadData* f = new webkit_glue::FileUploadData;
2431 f->file_path = p.file_path;
2432 f->form_name = p.form;
2433 f->file_name = p.file;
2434 f->submit_name = p.submit;
2435
2436 // Build the other form values map.
2437 if (!p.other_values.empty()) {
2438 std::vector<std::wstring> e;
2439 std::vector<std::wstring> kvp;
2440 std::vector<std::wstring>::iterator i;
2441
2442 SplitString(p.other_values, L'\n', &e);
2443 for (i = e.begin(); i != e.end(); ++i) {
2444 SplitString(*i, L'=', &kvp);
2445 if (kvp.size() == 2)
2446 f->other_form_values[kvp[0]] = kvp[1];
2447 kvp.clear();
2448 }
2449 }
2450
2451 pending_upload_data_.reset(f);
2452 ProcessPendingUpload();
2453}
2454
2455void RenderView::ProcessPendingUpload() {
2456 webkit_glue::FileUploadData* f = pending_upload_data_.get();
2457 if (f && webview() && webkit_glue::FillFormToUploadFile(webview(), *f))
2458 ResetPendingUpload();
2459}
2460
2461void RenderView::ResetPendingUpload() {
2462 pending_upload_data_.reset();
2463}
2464
2465void RenderView::OnFormFill(const FormData& form) {
2466 webkit_glue::FillForm(this->webview(), form);
2467}
2468
2469void RenderView::OnFillPasswordForm(
2470 const PasswordFormDomManager::FillData& form_data) {
2471 webkit_glue::FillPasswordForm(this->webview(), form_data);
2472}
2473
2474void RenderView::OnDragTargetDragEnter(const WebDropData& drop_data,
2475 const gfx::Point& client_pt, const gfx::Point& screen_pt) {
2476 bool is_drop_target = webview()->DragTargetDragEnter(drop_data,
2477 client_pt.x(), client_pt.y(), screen_pt.x(), screen_pt.y());
2478
2479 Send(new ViewHostMsg_UpdateDragCursor(routing_id_, is_drop_target));
2480}
2481
2482void RenderView::OnDragTargetDragOver(const gfx::Point& client_pt,
2483 const gfx::Point& screen_pt) {
2484 bool is_drop_target = webview()->DragTargetDragOver(client_pt.x(),
2485 client_pt.y(), screen_pt.x(), screen_pt.y());
2486
2487 Send(new ViewHostMsg_UpdateDragCursor(routing_id_, is_drop_target));
2488}
2489
2490void RenderView::OnDragTargetDragLeave() {
2491 webview()->DragTargetDragLeave();
2492}
2493
2494void RenderView::OnDragTargetDrop(const gfx::Point& client_pt,
2495 const gfx::Point& screen_pt) {
2496 webview()->DragTargetDrop(client_pt.x(), client_pt.y(), screen_pt.x(),
2497 screen_pt.y());
2498}
2499
2500void RenderView::OnUpdateWebPreferences(const WebPreferences& prefs) {
2501 webview()->SetPreferences(prefs);
2502}
2503
2504void RenderView::OnSetAltErrorPageURL(const GURL& url) {
2505 alternate_error_page_url_ = url;
2506}
2507
2508void RenderView::DidPaint() {
2509 PluginDelegateList::iterator it = plugin_delegates_.begin();
2510 while (it != plugin_delegates_.end()) {
2511 (*it)->FlushGeometryUpdates();
2512 ++it;
2513 }
2514}
2515
2516void RenderView::OnInstallMissingPlugin() {
2517 // This could happen when the first default plugin is deleted.
2518 if (first_default_plugin_ == NULL)
2519 return;
2520 first_default_plugin_->InstallMissingPlugin();
2521}
2522
2523void RenderView::OnFileChooserResponse(const std::wstring& file_name) {
2524 file_chooser_->OnFileChoose(file_name);
2525 file_chooser_.reset();
2526}
2527
2528void RenderView::OnEnableViewSourceMode() {
2529 if (!webview())
2530 return;
2531 WebFrame* main_frame = webview()->GetMainFrame();
2532 if (!main_frame)
2533 return;
2534
2535 main_frame->SetInViewSourceMode(true);
2536}
2537
2538void RenderView::OnUpdateBackForwardListCount(int back_list_count,
2539 int forward_list_count) {
2540 history_back_list_count_ = back_list_count;
2541 history_forward_list_count_ = forward_list_count;
2542}
2543
[email protected]266eb6f2008-09-30 23:56:502544void RenderView::OnGetAccessibilityInfo(
2545 const ViewMsg_Accessibility_In_Params& in_params,
2546 ViewHostMsg_Accessibility_Out_Params* out_params) {
2547
2548 if (!glue_accessibility_.get())
2549 glue_accessibility_.reset(new GlueAccessibility());
2550
2551 if (!glue_accessibility_->
2552 GetAccessibilityInfo(webview(), in_params, out_params)) {
2553 return;
2554 }
2555}
2556
2557void RenderView::OnClearAccessibilityInfo(int iaccessible_id, bool clear_all) {
2558 if (!glue_accessibility_.get()) {
2559 // If accessibility is not activated, ignore clearing message.
2560 return;
2561 }
2562
2563 if (!glue_accessibility_->ClearIAccessibleMap(iaccessible_id, clear_all))
2564 return;
2565}
2566
initial.commit09911bf2008-07-26 23:55:292567void RenderView::OnGetAllSavableResourceLinksForCurrentPage(
2568 const GURL& page_url) {
2569 // Prepare list to storage all savable resource links.
2570 std::vector<GURL> resources_list;
2571 std::vector<GURL> referrers_list;
2572 std::vector<GURL> frames_list;
2573 webkit_glue::SavableResourcesResult result(&resources_list,
2574 &referrers_list,
2575 &frames_list);
2576
2577 if (!webkit_glue::GetAllSavableResourceLinksForCurrentPage(webview(),
2578 page_url,
2579 &result)) {
2580 // If something is wrong when collecting all savable resource links,
2581 // send empty list to embedder(browser) to tell it failed.
2582 referrers_list.clear();
2583 resources_list.clear();
2584 frames_list.clear();
2585 }
2586
2587 // Send result of all savable resource links to embedder.
2588 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id_,
2589 resources_list,
2590 referrers_list,
2591 frames_list));
2592}
2593
2594void RenderView::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
2595 const std::vector<std::wstring>& links,
2596 const std::vector<std::wstring>& local_paths,
2597 const std::wstring& local_directory_name) {
2598 webkit_glue::DomSerializer dom_serializer(webview()->GetMainFrame(),
2599 true,
2600 this,
2601 links,
2602 local_paths,
2603 local_directory_name);
2604 dom_serializer.SerializeDom();
2605}
2606
2607void RenderView::DidSerializeDataForFrame(const GURL& frame_url,
2608 const std::string& data, PageSavingSerializationStatus status) {
2609 Send(new ViewHostMsg_SendSerializedHtmlData(routing_id_,
2610 frame_url, data, static_cast<int32>(status)));
2611}
2612
[email protected]04b4a6c2008-08-02 00:44:472613void RenderView::OnMsgShouldClose() {
initial.commit09911bf2008-07-26 23:55:292614 bool should_close = webview()->ShouldClose();
[email protected]04b4a6c2008-08-02 00:44:472615 Send(new ViewHostMsg_ShouldClose_ACK(routing_id_, should_close));
initial.commit09911bf2008-07-26 23:55:292616}
2617
2618void RenderView::OnClosePage(int new_render_process_host_id,
[email protected]04b4a6c2008-08-02 00:44:472619 int new_request_id) {
initial.commit09911bf2008-07-26 23:55:292620 // TODO(creis): We'd rather use webview()->Close() here, but that currently
2621 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
2622 // in the onunload handler from appearing. For now, we're bypassing that and
2623 // calling the FrameLoader's CloseURL method directly. This should be
2624 // revisited to avoid having two ways to close a page. Having a single way
2625 // to close that can run onunload is also useful for fixing
2626 // http://b/issue?id=753080.
2627 WebFrame* main_frame = webview()->GetMainFrame();
2628 if (main_frame)
2629 main_frame->ClosePage();
2630
2631 Send(new ViewHostMsg_ClosePage_ACK(routing_id_,
2632 new_render_process_host_id,
[email protected]04b4a6c2008-08-02 00:44:472633 new_request_id));
initial.commit09911bf2008-07-26 23:55:292634}
2635
2636void RenderView::OnThemeChanged() {
2637 gfx::NativeTheme::instance()->CloseHandles();
2638 gfx::Rect view_rect(0, 0, size_.width(), size_.height());
2639 DidInvalidateRect(webwidget_, view_rect);
2640}
2641
[email protected]f386cca792008-08-26 02:02:182642#ifdef CHROME_PERSONALIZATION
[email protected]1cc879642008-08-26 01:27:352643void RenderView::OnPersonalizationEvent(std::string event_name,
2644 std::string event_args) {
2645 Personalization::HandleViewMsgPersonalizationEvent(personalization_,
2646 webview(),
2647 event_name,
2648 event_args);
2649}
[email protected]f386cca792008-08-26 02:02:182650#endif
[email protected]1cc879642008-08-26 01:27:352651
2652void RenderView::TransitionToCommittedForNewPage() {
[email protected]f386cca792008-08-26 02:02:182653#ifdef CHROME_PERSONALIZATION
[email protected]1cc879642008-08-26 01:27:352654 Personalization::HandleTransitionToCommittedForNewPage(personalization_);
[email protected]f386cca792008-08-26 02:02:182655#endif
[email protected]1cc879642008-08-26 01:27:352656}
2657
[email protected]f46aff62008-10-16 07:58:052658void RenderView::DidAddHistoryItem() {
[email protected]f8901082008-10-31 23:34:032659 // We don't want to update the history length for the start page
2660 // navigation.
2661 WebFrame* main_frame = webview()->GetMainFrame();
2662 DCHECK(main_frame != NULL);
2663
2664 WebDataSource* ds = main_frame->GetDataSource();
2665 DCHECK(ds != NULL);
2666
2667 const WebRequest& request = ds->GetRequest();
2668 RenderViewExtraRequestData* extra_data =
2669 static_cast<RenderViewExtraRequestData*>(request.GetExtraData());
2670
2671 if (extra_data && extra_data->transition_type == PageTransition::START_PAGE)
2672 return;
2673
[email protected]f46aff62008-10-16 07:58:052674 history_back_list_count_++;
2675 history_forward_list_count_ = 0;
2676}
2677
[email protected]18cb2572008-08-21 20:34:452678void RenderView::OnMessageFromExternalHost(
2679 const std::string& target, const std::string& message) {
[email protected]3ac14a052008-08-15 21:22:152680 if (message.empty())
2681 return;
2682
2683 WebFrame* main_frame = webview()->GetMainFrame();
2684 if (!main_frame)
2685 return;
2686
2687 std::string script = "javascript:";
2688 script += target;
2689 script += "(";
2690 script += "'";
2691 script += message;
2692 script += "'";
2693 script += ");void(0);";
2694
2695 GURL script_url(script);
2696 scoped_ptr<WebRequest> request(WebRequest::Create(script_url));
2697 // TODO(iyengar)
2698 // Need a mechanism to send results back.
2699 main_frame->LoadRequest(request.get());
2700}
2701
[email protected]0aa55312008-10-17 21:53:082702void RenderView::OnDisassociateFromPopupCount() {
2703 if (decrement_shared_popup_at_destruction_)
2704 shared_popup_counter_->data--;
2705 shared_popup_counter_ = new SharedRenderViewCounter(0);
2706 decrement_shared_popup_at_destruction_ = false;
2707}
2708
initial.commit09911bf2008-07-26 23:55:292709std::string RenderView::GetAltHTMLForTemplate(
2710 const DictionaryValue& error_strings, int template_resource_id) const {
2711 const StringPiece template_html(
2712 ResourceBundle::GetSharedInstance().GetRawDataResource(
2713 template_resource_id));
2714
2715 if (template_html.empty()) {
2716 NOTREACHED() << "unable to load template. ID: " << template_resource_id;
2717 return "";
2718 }
2719 // "t" is the id of the templates root node.
2720 return jstemplate_builder::GetTemplateHtml(
2721 template_html, &error_strings, "t");
2722}