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