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