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