Commit message: None
CVE: None
Vulnerability description: None

Project: Chrome

AutoFillHelper::AutoFillHelper(RenderView* render_view)
    : render_view_(render_view),
      autofill_query_id_(0),
      autofill_action_(AUTOFILL_NONE),
      suggestions_clear_index_(-1),
      suggestions_options_index_(-1) {
}

Project: Chrome

void AutoFillHelper::DidAcceptAutoFillSuggestion(const WebNode& node,
                                                 const WebString& value,
                                                 const WebString& label,
                                                 int unique_id,
                                                 unsigned index) {
  if (suggestions_options_index_ != -1 &&
      index == static_cast<unsigned>(suggestions_options_index_)) {
    render_view_->Send(new ViewHostMsg_ShowAutoFillDialog(
        render_view_->routing_id()));
  } else if (suggestions_clear_index_ != -1 &&
             index == static_cast<unsigned>(suggestions_clear_index_)) {
    form_manager_.ClearFormWithNode(node);
  } else if (form_manager_.FormWithNodeIsAutoFilled(node) || !unique_id) {
    WebInputElement element = node.toConst<WebInputElement>();

    element.setSuggestedValue(value);
    element.setValue(value);

    WebFrame* webframe = node.document().frame();
    if (webframe)
      webframe->notifiyPasswordListenerOfAutocomplete(element);
  } else {
    QueryAutoFillFormData(node, value, label, unique_id, AUTOFILL_FILL);
  }

  suggestions_clear_index_ = -1;
  suggestions_options_index_ = -1;
}

Project: Chrome

void AutoFillHelper::DidClearAutoFillSelection(const WebNode& node) {
  form_manager_.ClearPreviewedFormWithNode(node);
}

Project: Chrome

void AutoFillHelper::DidSelectAutoFillSuggestion(const WebNode& node,
                                                 const WebString& value,
                                                 const WebString& label,
                                                 int unique_id) {
  DidClearAutoFillSelection(node);
  QueryAutoFillFormData(node, value, label, unique_id, AUTOFILL_PREVIEW);
}

Project: Chrome

void AutoFillHelper::FormDataFilled(int query_id,
                                    const webkit_glue::FormData& form) {
  if (!render_view_->webview() || query_id != autofill_query_id_)
    return;

  switch (autofill_action_) {
    case AUTOFILL_FILL:
      form_manager_.FillForm(form, autofill_query_node_);
      break;
    case AUTOFILL_PREVIEW:
      form_manager_.PreviewForm(form);
      break;
    default:
      NOTREACHED();
  }
  autofill_action_ = AUTOFILL_NONE;
}

Project: Chrome

void AutoFillHelper::FrameContentsAvailable(WebFrame* frame) {
  form_manager_.ExtractForms(frame);
  SendForms(frame);
}

Project: Chrome

 void AutoFillHelper::QueryAutoFillFormData(const WebNode& node,
                                            const WebString& value,
                                            const WebString& label,
                                           int unique_id,
                                           AutoFillAction action) {
  static int query_counter = 0;
  autofill_query_id_ = query_counter++;

  webkit_glue::FormData form;
  const WebInputElement element = node.toConst<WebInputElement>();
  if (!form_manager_.FindFormWithFormControlElement(
          element, FormManager::REQUIRE_NONE, &form))
    return;

  autofill_action_ = action;
  render_view_->Send(new ViewHostMsg_FillAutoFillFormData(
      render_view_->routing_id(), autofill_query_id_, form, value, label,
      unique_id));
}

Project: Chrome

void AutoFillHelper::QueryAutocompleteSuggestions(const WebNode& node,
                                                  const WebString& name,
                                                  const WebString& value) {
  static int query_counter = 0;
  autofill_query_id_ = query_counter++;
  autofill_query_node_ = node;

  const WebFormControlElement& element = node.toConst<WebFormControlElement>();
  webkit_glue::FormField field;
  FormManager::WebFormControlElementToFormField(element, true, &field);

  field.set_label(FormManager::LabelForElement(element));

  bool form_autofilled = form_manager_.FormWithNodeIsAutoFilled(node);
  render_view_->Send(new ViewHostMsg_QueryFormFieldAutoFill(
      render_view_->routing_id(), autofill_query_id_, form_autofilled, field));
}

Project: Chrome

void AutoFillHelper::RemoveAutocompleteSuggestion(
    const WebKit::WebString& name, const WebKit::WebString& value) {
  if (suggestions_clear_index_ != -1)
    suggestions_clear_index_--;
  if (suggestions_options_index_ != -1)
    suggestions_options_index_--;

  render_view_->Send(new ViewHostMsg_RemoveAutocompleteEntry(
      render_view_->routing_id(), name, value));
}

Project: Chrome

void AutoFillHelper::SendForms(WebFrame* frame) {
  WebKit::WebVector<WebFormElement> web_forms;
  frame->forms(web_forms);

  std::vector<webkit_glue::FormData> forms;
  for (size_t i = 0; i < web_forms.size(); ++i) {
    const WebFormElement& web_form = web_forms[i];

    webkit_glue::FormData form;
    if (FormManager::WebFormElementToFormData(
            web_form, FormManager::REQUIRE_NONE, false, &form)) {
      forms.push_back(form);
    }
  }

  if (!forms.empty()) {
    render_view_->Send(new ViewHostMsg_FormsSeen(render_view_->routing_id(),
                                                 forms));
  }
}

Project: Chrome

void AutoFillHelper::SuggestionsReceived(int query_id,
                                         const std::vector<string16>& values,
                                         const std::vector<string16>& labels,
                                         const std::vector<string16>& icons,
                                         const std::vector<int>& unique_ids) {
  WebKit::WebView* web_view = render_view_->webview();
  if (!web_view || query_id != autofill_query_id_)
    return;

  web_view->hidePopups();

  if (values.empty())
    return;

  std::vector<string16> v(values);
  std::vector<string16> l(labels);
  std::vector<string16> i(icons);
  std::vector<int> ids(unique_ids);
  int separator_index = -1;

  if (form_manager_.FormWithNodeIsAutoFilled(autofill_query_node_)) {
    v.push_back(l10n_util::GetStringUTF16(IDS_AUTOFILL_CLEAR_FORM_MENU_ITEM));
    l.push_back(string16());
    i.push_back(string16());
    ids.push_back(0);
    suggestions_clear_index_ = v.size() - 1;
    separator_index = values.size();
  }

  bool show_options = false;
  for (size_t i = 0; i < ids.size(); ++i) {
    if (ids[i] != 0) {
      show_options = true;
      break;
    }
  }
  if (show_options) {
    v.push_back(l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS));
    l.push_back(string16());
    i.push_back(string16());
    ids.push_back(0);
    suggestions_options_index_ = v.size() - 1;
    separator_index = values.size();
  }

  if (!v.empty()) {
    web_view->applyAutoFillSuggestions(
        autofill_query_node_, v, l, i, ids, separator_index);
  }
}

Project: Chrome

TransportDIB::Handle RenderView::AcceleratedSurfaceAllocTransportDIB(
    size_t size) {
  TransportDIB::Handle dib_handle;
  if (Send(new ViewHostMsg_AllocTransportDIB(size, true, &dib_handle)))
    return dib_handle;
  return TransportDIB::DefaultHandleValue();
}

Project: Chrome

void RenderView::AcceleratedSurfaceBuffersSwapped(
    gfx::PluginWindowHandle window) {
  Send(new ViewHostMsg_AcceleratedSurfaceBuffersSwapped(routing_id(), window));
}

Project: Chrome

void RenderView::AcceleratedSurfaceFreeTransportDIB(TransportDIB::Id dib_id) {
  Send(new ViewHostMsg_FreeTransportDIB(dib_id));
}

Project: Chrome

void RenderView::AcceleratedSurfaceSetTransportDIB(
    gfx::PluginWindowHandle window,
    int32 width,
    int32 height,
    TransportDIB::Handle transport_dib) {
  Send(new ViewHostMsg_AcceleratedSurfaceSetTransportDIB(
      routing_id(), window, width, height, transport_dib));
}

Project: Chrome

gfx::PluginWindowHandle RenderView::AllocateFakePluginWindowHandle(
    bool opaque, bool root) {
  gfx::PluginWindowHandle window = NULL;
  Send(new ViewHostMsg_AllocateFakePluginWindowHandle(
      routing_id(), opaque, root, &window));
  return window;
}

Project: Chrome

bool RenderView::AllowContentType(ContentSettingsType settings_type) {
  return current_content_settings_.settings[settings_type] !=
    CONTENT_SETTING_BLOCK;
}

Project: Chrome

void RenderView::AltErrorPageFinished(WebFrame* frame,
                                      const WebURLError& original_error,
                                      const std::string& html) {

  const std::string* html_to_load = &html;
  if (html.empty()) {
    NavigationState* navigation_state =
        NavigationState::FromDataSource(frame->dataSource());
    html_to_load = &navigation_state->postponed_data();
  }
  LoadNavigationErrorPage(
      frame, WebURLRequest(), original_error, *html_to_load, true);
}

Project: Chrome

void RenderView::BindDOMAutomationController(WebFrame* frame) {
  dom_automation_controller_.set_message_sender(this);
  dom_automation_controller_.set_routing_id(routing_id_);
  dom_automation_controller_.BindToJavascript(frame,
                                              L"domAutomationController");
}

Project: Chrome

static double CalculateBoringScore(SkBitmap* bitmap) {
  int histogram[256] = {0};
  color_utils::BuildLumaHistogram(bitmap, histogram);

  int color_count = *std::max_element(histogram, histogram + 256);
  int pixel_count = bitmap->width() * bitmap->height();
  return static_cast<double>(color_count) / pixel_count;
}

Project: Chrome

bool RenderView::CaptureSnapshot(WebView* view, SkBitmap* snapshot) {
  base::TimeTicks beginning_time = base::TimeTicks::Now();

  skia::PlatformCanvas canvas;
  if (!PaintViewIntoCanvas(view, canvas))
    return false;

  skia::BitmapPlatformDevice& device =
      static_cast<skia::BitmapPlatformDevice&>(canvas.getTopPlatformDevice());

  const SkBitmap& bitmap = device.accessBitmap(false);
  if (!bitmap.copyTo(snapshot, SkBitmap::kARGB_8888_Config))
    return false;

  HISTOGRAM_TIMES("Renderer4.Snapshot",
                  base::TimeTicks::Now() - beginning_time);
  return true;
}

Project: Chrome

void RenderView::CaptureText(WebFrame* frame, string16* contents) {
  contents->clear();
  if (!frame)
    return;

#ifdef TIME_TEXT_RETRIEVAL
  double begin = time_util::GetHighResolutionTimeNow();
#endif

  *contents = frame->contentAsText(kMaxIndexChars);

#ifdef TIME_TEXT_RETRIEVAL
  double end = time_util::GetHighResolutionTimeNow();
  char buf[128];
  sprintf_s(buf, "%d chars retrieved for indexing in %gms\n",
            contents.size(), (end - begin)*1000);
  OutputDebugStringA(buf);
#endif

  if (contents->size() == kMaxIndexChars) {
    size_t last_space_index = contents->find_last_of(kWhitespaceUTF16);
    if (last_space_index == std::wstring::npos)
      return;  // don't index if we got a huge block of text with no spaces
    contents->resize(last_space_index);
  }
}

Project: Chrome

bool RenderView::CaptureThumbnail(WebView* view,
                                  int w,
                                  int h,
                                  SkBitmap* thumbnail,
                                  ThumbnailScore* score) {
  base::TimeTicks beginning_time = base::TimeTicks::Now();

  skia::PlatformCanvas canvas;

  if (!PaintViewIntoCanvas(view, canvas))
    return false;

  skia::BitmapPlatformDevice& device =
      static_cast<skia::BitmapPlatformDevice&>(canvas.getTopPlatformDevice());

  const SkBitmap& src_bmp = device.accessBitmap(false);

  SkRect dest_rect = { 0, 0, SkIntToScalar(w), SkIntToScalar(h) };
  float dest_aspect = dest_rect.width() / dest_rect.height();

  SkIRect src_rect;
  if (src_bmp.width() < dest_rect.width() ||
      src_bmp.height() < dest_rect.height()) {
    src_rect.set(0, 0, static_cast<S16CPU>(dest_rect.width()),
                 static_cast<S16CPU>(dest_rect.height()));
    score->good_clipping = false;
  } else {
    float src_aspect = static_cast<float>(src_bmp.width()) / src_bmp.height();
    if (src_aspect > dest_aspect) {
      S16CPU new_width = static_cast<S16CPU>(src_bmp.height() * dest_aspect);
      S16CPU x_offset = (src_bmp.width() - new_width) / 2;
      src_rect.set(x_offset, 0, new_width + x_offset, src_bmp.height());
      score->good_clipping = false;
    } else {
      src_rect.set(0, 0, src_bmp.width(),
                   static_cast<S16CPU>(src_bmp.width() / dest_aspect));
      score->good_clipping = true;
    }
  }

  score->at_top = (view->mainFrame()->scrollOffset().height == 0);

  SkBitmap subset;
  device.accessBitmap(false).extractSubset(&subset, src_rect);

  *thumbnail = skia::ImageOperations::Resize(
      subset, skia::ImageOperations::RESIZE_LANCZOS3, w, h);

  score->boring_score = CalculateBoringScore(thumbnail);

  HISTOGRAM_TIMES("Renderer4.Thumbnail",
                  base::TimeTicks::Now() - beginning_time);
  return true;
}

Project: Chrome

void RenderView::CheckPreferredSize() {
  if (!send_preferred_size_changes_ || !webview())
    return;

  gfx::Size size(webview()->mainFrame()->contentsPreferredWidth(),
                 webview()->mainFrame()->documentElementScrollHeight());
  if (size == preferred_size_)
    return;

  preferred_size_ = size;
  Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
                                                      preferred_size_));
}

Project: Chrome

void RenderView::ClearBlockedContentSettings() {
  for (size_t i = 0; i < arraysize(content_blocked_); ++i)
    content_blocked_[i] = false;
}

Project: Chrome

void RenderView::Close() {
  WebView* doomed = webview();
  RenderWidget::Close();
  Singleton<ViewMap>::get()->erase(doomed);
}

Project: Chrome

RenderView* RenderView::Create(
    RenderThreadBase* render_thread,
    gfx::NativeViewId parent_hwnd,
    int32 opener_id,
    const RendererPreferences& renderer_prefs,
    const WebPreferences& webkit_prefs,
    SharedRenderViewCounter* counter,
    int32 routing_id,
    int64 session_storage_namespace_id,
    const string16& frame_name) {
  DCHECK(routing_id != MSG_ROUTING_NONE);
  scoped_refptr<RenderView> view = new RenderView(render_thread, webkit_prefs,
                                                  session_storage_namespace_id);
  view->Init(parent_hwnd,
             opener_id,
             renderer_prefs,
             counter,
             routing_id,
             frame_name);  // adds reference
  return view;
}

Project: Chrome

WebPlugin* RenderView::CreateNPAPIPlugin(WebFrame* frame,
                                         const WebPluginParams& params,
                                         const FilePath& path,
                                         const std::string& mime_type) {
  std::string actual_mime_type(mime_type);
  if (actual_mime_type.empty())
    actual_mime_type = params.mimeType.utf8();

  return new webkit_glue::WebPluginImpl(frame, params, path,
                                        actual_mime_type, AsWeakPtr());
}

Project: Chrome

WebPlugin* RenderView::CreatePepperPlugin(WebFrame* frame,
                                          const WebPluginParams& params,
                                          const FilePath& path,
                                          pepper::PluginModule* pepper_module) {
  WebPlugin* plugin = new pepper::WebPluginImpl(pepper_module, params,
                                                pepper_delegate_.AsWeakPtr());
  if (plugin && !frame->parent() && frame->document().isPluginDocument()) {
    FilePath pdf_path;
    PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path);
    if (path == pdf_path)
      Send(new ViewHostMsg_SetDisplayingPDFContent(routing_id_));
  }
  return plugin;
}

Project: Chrome

webkit_glue::WebPluginDelegate* RenderView::CreatePluginDelegate(
    const FilePath& file_path,
    const std::string& mime_type) {
  if (!PluginChannelHost::IsListening())
    return NULL;

  bool use_pepper_host = false;
  bool in_process_plugin = RenderProcess::current()->UseInProcessPlugins();
  const char kPepperPrefix[] = "pepper-";
  if (StartsWithASCII(mime_type, kPepperPrefix, true)) {
    if (CommandLine::ForCurrentProcess()->
            HasSwitch(switches::kInternalPepper)) {
      in_process_plugin = true;
      use_pepper_host = true;
    } else {
      return NULL;
    }
  } else {
    FilePath internal_pdf_path;
    PathService::Get(chrome::FILE_PDF_PLUGIN, &internal_pdf_path);
    if (file_path == internal_pdf_path) {
      in_process_plugin = true;
      use_pepper_host = true;
    }
  }

  if (mime_type == "application/x-nacl-srpc") {

    GURL main_frame_url(webview()->mainFrame()->url());
    const std::string &extension_id =
        RenderThread::current()->GetExtensionIdByURL(main_frame_url);
    bool in_ext = extension_id != "";
    bool explicit_enable =
        CommandLine::ForCurrentProcess()->HasSwitch(switches::kInternalNaCl);

    if (in_ext) {
      if (ExtensionProcessBindings::HasPermission(extension_id,
              Extension::kNativeClientPermission)) {
        in_process_plugin = true;
        use_pepper_host = true;
      } else {
        return NULL;
      }
    } else if (explicit_enable) {
      in_process_plugin = true;
      use_pepper_host = true;
    }
  }

  if (in_process_plugin) {
    if (use_pepper_host) {
      WebPluginDelegatePepper* pepper_plugin =
           WebPluginDelegatePepper::Create(file_path, mime_type, AsWeakPtr());
      if (!pepper_plugin)
        return NULL;

      current_oldstyle_pepper_plugins_.insert(pepper_plugin);
      return pepper_plugin;
    } else {
#if defined(OS_WIN)  // In-proc plugins aren't supported on Linux or Mac.
      return WebPluginDelegateImpl::Create(
          file_path, mime_type, gfx::NativeViewFromId(host_window_));
#else
      NOTIMPLEMENTED();
      return NULL;
#endif
    }
  }

  return new WebPluginDelegateProxy(mime_type, AsWeakPtr());
}

Project: Chrome

WebPlugin* RenderView::CreatePluginNoCheck(WebFrame* frame,
                                           const WebPluginParams& params) {
  WebPluginInfo info;
  bool found;
  std::string mime_type;
  Send(new ViewHostMsg_GetPluginInfo(
      params.url, frame->top()->url(), params.mimeType.utf8(), &found,
      &info, &mime_type));
  if (!found || !info.enabled)
    return NULL;
  scoped_refptr<pepper::PluginModule> pepper_module =
      PepperPluginRegistry::GetInstance()->GetModule(info.path);
  if (pepper_module)
    return CreatePepperPlugin(frame, params, info.path, pepper_module.get());
  else
    return CreateNPAPIPlugin(frame, params, info.path, mime_type);
}

Project: Chrome

WebPlugin* RenderView::CreatePluginPlaceholder(WebFrame* frame,
                                               const WebPluginParams& params,
                                               PluginGroup* group) {
  BlockedPlugin* blocked_plugin = new BlockedPlugin(this, frame, params, group);
  WebViewPlugin* plugin = blocked_plugin->plugin();
  WebView* web_view = plugin->web_view();
  webkit_preferences_.Apply(web_view);
  return plugin;
}

Project: Chrome

void RenderView::CreatedPluginWindow(gfx::PluginWindowHandle window) {
#if defined(USE_X11)
  RenderThread::current()->Send(new ViewHostMsg_CreatePluginContainer(
      routing_id(), window));
#endif
}

Project: Chrome

static bool CrossesExtensionExtents(WebFrame* frame, const GURL& new_url) {
  if (!RenderThread::current())
    return false;

  GURL old_url(frame->url());
  if (old_url.is_empty() && frame->opener())
    old_url = frame->opener()->url();

  std::string old_extension =
      RenderThread::current()->GetExtensionIdByURL(old_url);
  if (!old_extension.empty()) {
    if (RenderThread::current()->GetExtensionIdByBrowseExtent(new_url) ==
        old_extension) {
      return false;
    }
  }

  std::string new_extension =
      RenderThread::current()->GetExtensionIdByURL(new_url);
  return old_extension != new_extension;
}

Project: Chrome

void RenderView::DestroyFakePluginWindowHandle(gfx::PluginWindowHandle window) {
  if (window)
    Send(new ViewHostMsg_DestroyFakePluginWindowHandle(routing_id(), window));
}

Project: Chrome

static std::string DetermineTextLanguage(const string16& text) {
  std::string language = chrome::kUnknownLanguageCode;
  int num_languages = 0;
  int text_bytes = 0;
  bool is_reliable = false;
  Language cld_language =
      DetectLanguageOfUnicodeText(NULL, text.c_str(), true, &is_reliable,
                                  &num_languages, NULL, &text_bytes);
  if (is_reliable && text_bytes >= 100 && cld_language != NUM_LANGUAGES &&
      cld_language != UNKNOWN_LANGUAGE && cld_language != TG_UNKNOWN_LANGUAGE) {
    language = LanguageCodeWithDialects(cld_language);
  }
  return language;
}

Project: Chrome

void RenderView::DidBlockContentType(ContentSettingsType settings_type) {
  if (!content_blocked_[settings_type]) {
    content_blocked_[settings_type] = true;
    Send(new ViewHostMsg_ContentBlocked(routing_id_, settings_type));
  }
}

Project: Chrome

void RenderView::DidDownloadImage(ImageResourceFetcher* fetcher,
                                  const SkBitmap& image) {
  Send(new ViewHostMsg_DidDownloadFavIcon(routing_id_,
                                          fetcher->id(),
                                          fetcher->image_url(),
                                          image.isNull(),
                                          image));
  DCHECK(image_fetchers_.find(fetcher) != image_fetchers_.end());
  image_fetchers_.erase(fetcher);
  MessageLoop::current()->DeleteSoon(FROM_HERE, fetcher);
}

Project: Chrome

void RenderView::DidFlushPaint() {
  pepper_delegate_.ViewFlushedPaint();

  std::set<WebPluginDelegatePepper*> plugins = current_oldstyle_pepper_plugins_;
  for (std::set<WebPluginDelegatePepper*>::iterator i = plugins.begin();
       i != plugins.end(); ++i) {
    if (current_oldstyle_pepper_plugins_.find(*i) !=
        current_oldstyle_pepper_plugins_.end())
      (*i)->RenderViewFlushedPaint();
  }

  WebFrame* main_frame = webview()->mainFrame();

  if (!main_frame->provisionalDataSource()) {
    WebDataSource* ds = main_frame->dataSource();
    NavigationState* navigation_state = NavigationState::FromDataSource(ds);
    DCHECK(navigation_state);

    Time now = Time::Now();
    if (navigation_state->first_paint_time().is_null()) {
      navigation_state->set_first_paint_time(now);
    }
    if (navigation_state->first_paint_after_load_time().is_null() &&
        !navigation_state->finish_load_time().is_null()) {
      navigation_state->set_first_paint_after_load_time(now);
    }
  }
}

Project: Chrome

void RenderView::DidHandleKeyEvent() {
  edit_commands_.clear();
}

Project: Chrome

void RenderView::DidInitiatePaint() {
  pepper_delegate_.ViewInitiatedPaint();

  for (std::set<WebPluginDelegatePepper*>::iterator i =
           current_oldstyle_pepper_plugins_.begin();
       i != current_oldstyle_pepper_plugins_.end(); ++i)
    (*i)->RenderViewInitiatedPaint();
}

Project: Chrome

void RenderView::DidMovePlugin(const webkit_glue::WebPluginGeometry& move) {
  SchedulePluginMove(move);
}

Project: Chrome

void RenderView::DidStartLoadingForPlugin() {
  didStartLoading();
}

Project: Chrome

void RenderView::DidStopLoadingForPlugin() {
  didStopLoading();
}

Project: Chrome

bool RenderView::DownloadImage(int id, const GURL& image_url, int image_size) {
  if (!webview())
    return false;
  image_fetchers_.insert(new ImageResourceFetcher(
      image_url, webview()->mainFrame(), id, image_size,
      NewCallback(this, &RenderView::DidDownloadImage)));
  return true;
}

Project: Chrome

void RenderView::DumpLoadHistograms() const {
  static const TimeDelta kPLTMin(TimeDelta::FromMilliseconds(10));
  static const TimeDelta kPLTMax(TimeDelta::FromMinutes(10));
  static const size_t kPLTCount(100);
  #define PLT_HISTOGRAM(name, sample) \
      UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, kPLTMin, kPLTMax, kPLTCount);

  WebFrame* main_frame = webview()->mainFrame();
  NavigationState* navigation_state =
      NavigationState::FromDataSource(main_frame->dataSource());

  if (navigation_state->load_histograms_recorded())
    return;

  Time start = navigation_state->start_load_time();
  if (start.is_null())
    return;  // Probably very premature abandonment of page.
  Time commit = navigation_state->commit_load_time();
  if (commit.is_null())
    return;  // Probably very premature abandonment of page.

  Time request = navigation_state->request_time();
  Time first_paint = navigation_state->first_paint_time();
  Time first_paint_after_load = navigation_state->first_paint_after_load_time();
  Time finish = navigation_state->finish_load_time();
  Time finish_doc = navigation_state->finish_document_load_time();

  bool abandoned_page = finish.is_null();
  if (abandoned_page) {
    finish = Time::Now();
    navigation_state->set_finish_load_time(finish);
  }

  if (finish_doc.is_null()) {
    DCHECK(abandoned_page);  // how can the doc have finished but not the page?
    if (!abandoned_page)
      return;  // Don't try to record a stat which is broken.
    finish_doc = finish;
    navigation_state->set_finish_document_load_time(finish_doc);
  }

  Time begin = request.is_null() ? start : request;
  TimeDelta begin_to_finish_doc = finish_doc - begin;
  TimeDelta begin_to_finish = finish - begin;
  TimeDelta start_to_finish = finish - start;
  TimeDelta start_to_commit = commit - start;

  NavigationState::LoadType load_type = navigation_state->load_type();

  UMA_HISTOGRAM_ENUMERATION("PLT.Abandoned", abandoned_page ? 1 : 0, 2);
  UMA_HISTOGRAM_ENUMERATION("PLT.LoadType", load_type,
      NavigationState::kLoadTypeMax);
  PLT_HISTOGRAM("PLT.StartToCommit", start_to_commit);
  PLT_HISTOGRAM("PLT.CommitToFinishDoc", finish_doc - commit);
  PLT_HISTOGRAM("PLT.FinishDocToFinish", finish - finish_doc);
  PLT_HISTOGRAM("PLT.BeginToCommit", commit - begin);
  PLT_HISTOGRAM("PLT.StartToFinish", start_to_finish);
  if (!request.is_null()) {
    PLT_HISTOGRAM("PLT.RequestToStart", start - request);
    PLT_HISTOGRAM("PLT.RequestToFinish", finish - request);
  }
  PLT_HISTOGRAM("PLT.CommitToFinish", finish - commit);
  if (!first_paint.is_null()) {
    DCHECK(begin <= first_paint);
    PLT_HISTOGRAM("PLT.BeginToFirstPaint", first_paint - begin);
    DCHECK(commit <= first_paint);
    PLT_HISTOGRAM("PLT.CommitToFirstPaint", first_paint - commit);
  }
  if (!first_paint_after_load.is_null()) {
    DCHECK(begin <= first_paint_after_load);
    PLT_HISTOGRAM("PLT.BeginToFirstPaintAfterLoad",
      first_paint_after_load - begin);
    DCHECK(commit <= first_paint_after_load);
    PLT_HISTOGRAM("PLT.CommitToFirstPaintAfterLoad",
        first_paint_after_load - commit);
    DCHECK(finish <= first_paint_after_load);
    PLT_HISTOGRAM("PLT.FinishToFirstPaintAfterLoad",
        first_paint_after_load - finish);
  }
  PLT_HISTOGRAM("PLT.BeginToFinishDoc", begin_to_finish_doc);
  PLT_HISTOGRAM("PLT.BeginToFinish", begin_to_finish);

  switch (load_type) {
    case NavigationState::UNDEFINED_LOAD:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_UndefLoad", begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_UndefLoad", begin_to_finish);
      break;
    case NavigationState::RELOAD:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_Reload", begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_Reload", begin_to_finish);
      break;
    case NavigationState::HISTORY_LOAD:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_HistoryLoad", begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_HistoryLoad", begin_to_finish);
      break;
    case NavigationState::NORMAL_LOAD:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_NormalLoad", begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_NormalLoad", begin_to_finish);
      break;
    case NavigationState::LINK_LOAD_NORMAL:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_LinkLoadNormal",
          begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_LinkLoadNormal", begin_to_finish);
      break;
    case NavigationState::LINK_LOAD_RELOAD:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_LinkLoadReload",
           begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_LinkLoadReload", begin_to_finish);
      break;
    case NavigationState::LINK_LOAD_CACHE_STALE_OK:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_LinkLoadStaleOk",
           begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_LinkLoadStaleOk", begin_to_finish);
      break;
    case NavigationState::LINK_LOAD_CACHE_ONLY:
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_LinkLoadCacheOnly",
           begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_LinkLoadCacheOnly", begin_to_finish);
      break;
    default:
      break;
  }

  static bool use_dns_histogram(FieldTrialList::Find("DnsImpact") &&
      !FieldTrialList::Find("DnsImpact")->group_name().empty());
  if (use_dns_histogram) {
    UMA_HISTOGRAM_ENUMERATION(
        FieldTrial::MakeName("PLT.Abandoned", "DnsImpact"),
        abandoned_page ? 1 : 0, 2);
    UMA_HISTOGRAM_ENUMERATION(
        FieldTrial::MakeName("PLT.LoadType", "DnsImpact"),
        load_type, NavigationState::kLoadTypeMax);
    switch (load_type) {
      case NavigationState::NORMAL_LOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_NormalLoad", "DnsImpact"), begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_NORMAL:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadNormal", "DnsImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_RELOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadReload", "DnsImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_CACHE_STALE_OK:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadStaleOk", "DnsImpact"),
            begin_to_finish);
        break;
      default:
        break;
    }
  }

  static const bool prefetching_fieldtrial =
      FieldTrialList::Find("Prefetch") &&
      !FieldTrialList::Find("Prefetch")->group_name().empty();
  static const bool prefetching_explicitly_disabled =
      CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableContentPrefetch);
  if (navigation_state->was_prefetcher()) {
    if (!prefetching_explicitly_disabled) {
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_ContentPrefetcher",
                    begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_ContentPrefetcher",
                    begin_to_finish);
    }
    if (prefetching_fieldtrial) {
      PLT_HISTOGRAM(
          FieldTrial::MakeName("PLT.BeginToFinishDoc_ContentPrefetcher",
                               "Prefetch"),
          begin_to_finish_doc);
      PLT_HISTOGRAM(
          FieldTrial::MakeName("PLT.BeginToFinish_ContentPrefetcher",
                               "Prefetch"),
          begin_to_finish);
    }
  }
  if (navigation_state->was_referred_by_prefetcher()) {
    if (!prefetching_explicitly_disabled) {
      PLT_HISTOGRAM("PLT.BeginToFinishDoc_ContentPrefetcherReferrer",
                    begin_to_finish_doc);
      PLT_HISTOGRAM("PLT.BeginToFinish_ContentPrefetcherReferrer",
                    begin_to_finish);
    }
    if (prefetching_fieldtrial) {
      PLT_HISTOGRAM(
          FieldTrial::MakeName("PLT.BeginToFinishDoc_ContentPrefetcherReferrer",
                               "Prefetch"),
          begin_to_finish_doc);
      PLT_HISTOGRAM(
          FieldTrial::MakeName("PLT.BeginToFinish_ContentPrefetcherReferrer",
                               "Prefetch"),
          begin_to_finish);
    }
  }
  if (prefetching_fieldtrial) {
    UMA_HISTOGRAM_ENUMERATION(FieldTrial::MakeName("PLT.Abandoned", "Prefetch"),
                              abandoned_page ? 1 : 0, 2);
    PLT_HISTOGRAM(FieldTrial::MakeName("PLT.BeginToFinishDoc", "Prefetch"),
                  begin_to_finish_doc);
    PLT_HISTOGRAM(FieldTrial::MakeName("PLT.BeginToFinish", "Prefetch"),
                  begin_to_finish);
  }

  static bool use_connection_impact_histogram(
      FieldTrialList::Find("ConnCountImpact") &&
      !FieldTrialList::Find("ConnCountImpact")->group_name().empty());
  if (use_connection_impact_histogram) {
    UMA_HISTOGRAM_ENUMERATION(
        FieldTrial::MakeName("PLT.Abandoned", "ConnCountImpact"),
        abandoned_page ? 1 : 0, 2);
    switch (load_type) {
      case NavigationState::NORMAL_LOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_NormalLoad", "ConnCountImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_NORMAL:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadNormal", "ConnCountImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_RELOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadReload", "ConnCountImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_CACHE_STALE_OK:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadStaleOk", "ConnCountImpact"),
            begin_to_finish);
        break;
      default:
        break;
    }
  }

  static bool use_idle_socket_timeout_histogram(
      FieldTrialList::Find("IdleSktToImpact") &&
      !FieldTrialList::Find("IdleSktToImpact")->group_name().empty());
  if (use_idle_socket_timeout_histogram) {
    UMA_HISTOGRAM_ENUMERATION(
        FieldTrial::MakeName("PLT.Abandoned", "IdleSktToImpact"),
        abandoned_page ? 1 : 0, 2);
    switch (load_type) {
      case NavigationState::NORMAL_LOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_NormalLoad", "IdleSktToImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_NORMAL:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadNormal", "IdleSktToImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_RELOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadReload", "IdleSktToImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_CACHE_STALE_OK:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadStaleOk", "IdleSktToImpact"),
            begin_to_finish);
        break;
      default:
        break;
    }
  }

  static bool use_proxy_connection_impact_histogram(
      FieldTrialList::Find("ProxyConnectionImpact") &&
      !FieldTrialList::Find("ProxyConnectionImpact")->group_name().empty());
  if (use_proxy_connection_impact_histogram) {
    UMA_HISTOGRAM_ENUMERATION(
        FieldTrial::MakeName("PLT.Abandoned", "ProxyConnectionImpact"),
        abandoned_page ? 1 : 0, 2);
    switch (load_type) {
      case NavigationState::NORMAL_LOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_NormalLoad", "ProxyConnectionImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_NORMAL:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadNormal", "ProxyConnectionImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_RELOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadReload", "ProxyConnectionImpact"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_CACHE_STALE_OK:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadStaleOk", "ProxyConnectionImpact"),
            begin_to_finish);
        break;
      default:
        break;
    }
  }

  static bool use_sdch_histogram(FieldTrialList::Find("GlobalSdch") &&
      !FieldTrialList::Find("GlobalSdch")->group_name().empty());
  if (use_sdch_histogram) {
    UMA_HISTOGRAM_ENUMERATION(
        FieldTrial::MakeName("PLT.LoadType", "GlobalSdch"),
        load_type, NavigationState::kLoadTypeMax);
    switch (load_type) {
      case NavigationState::NORMAL_LOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_NormalLoad", "GlobalSdch"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_NORMAL:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadNormal", "GlobalSdch"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_RELOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadReload", "GlobalSdch"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_CACHE_STALE_OK:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadStaleOk", "GlobalSdch"),
            begin_to_finish);
        break;
      case NavigationState::LINK_LOAD_CACHE_ONLY:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadCacheOnly", "GlobalSdch"),
            begin_to_finish);
        break;
      default:
        break;
    }
  }

  static bool use_cache_histogram1(FieldTrialList::Find("CacheSize") &&
      !FieldTrialList::Find("CacheSize")->group_name().empty());
  if (use_cache_histogram1 && NavigationState::LINK_LOAD_NORMAL <= load_type &&
      NavigationState::LINK_LOAD_CACHE_ONLY >= load_type) {
    PLT_HISTOGRAM(FieldTrial::MakeName(
        "PLT.BeginToFinishDoc_LinkLoad", "CacheSize"), begin_to_finish_doc);
  }


  GURL url = GURL(main_frame->url());

  static bool use_spdy_histogram(FieldTrialList::Find("SpdyImpact") &&
      !FieldTrialList::Find("SpdyImpact")->group_name().empty());
  if (use_spdy_histogram && url.SchemeIs("https") &&
      navigation_state->was_npn_negotiated()) {
    UMA_HISTOGRAM_ENUMERATION(
        FieldTrial::MakeName("PLT.Abandoned", "SpdyImpact"),
        abandoned_page ? 1 : 0, 2);
    switch (load_type) {
      case NavigationState::LINK_LOAD_NORMAL:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_LinkLoadNormal_SpdyTrial", "SpdyImpact"),
            begin_to_finish);
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.StartToFinish_LinkLoadNormal_SpdyTrial", "SpdyImpact"),
            start_to_finish);
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.StartToCommit_LinkLoadNormal_SpdyTrial", "SpdyImpact"),
            start_to_commit);
        break;
      case NavigationState::NORMAL_LOAD:
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.BeginToFinish_NormalLoad_SpdyTrial", "SpdyImpact"),
            begin_to_finish);
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.StartToFinish_NormalLoad_SpdyTrial", "SpdyImpact"),
            start_to_finish);
        PLT_HISTOGRAM(FieldTrial::MakeName(
            "PLT.StartToCommit_NormalLoad_SpdyTrial", "SpdyImpact"),
            start_to_commit);
        break;
      default:
        break;
    }
  }

  if (url.SchemeIs("http") &&
      navigation_state->was_alternate_protocol_available()) {
    if (!navigation_state->was_npn_negotiated()) {
      switch (load_type) {
        case NavigationState::LINK_LOAD_NORMAL:
          PLT_HISTOGRAM(
              "PLT.StartToFinish_LinkLoadNormal_AlternateProtocol_http",
              start_to_finish);
          PLT_HISTOGRAM(
              "PLT.StartToCommit_LinkLoadNormal_AlternateProtocol_http",
              start_to_commit);
          break;
        case NavigationState::NORMAL_LOAD:
          PLT_HISTOGRAM(
              "PLT.StartToFinish_NormalLoad_AlternateProtocol_http",
              start_to_finish);
          PLT_HISTOGRAM(
              "PLT.StartToCommit_NormalLoad_AlternateProtocol_http",
              start_to_commit);
          break;
        default:
          break;
      }
    } else if (navigation_state->was_fetched_via_spdy()) {
      switch (load_type) {
        case NavigationState::LINK_LOAD_NORMAL:
          PLT_HISTOGRAM(
              "PLT.StartToFinish_LinkLoadNormal_AlternateProtocol_spdy",
              start_to_finish);
          PLT_HISTOGRAM(
              "PLT.StartToCommit_LinkLoadNormal_AlternateProtocol_spdy",
              start_to_commit);
          break;
        case NavigationState::NORMAL_LOAD:
          PLT_HISTOGRAM(
              "PLT.StartToFinish_NormalLoad_AlternateProtocol_spdy",
              start_to_finish);
          PLT_HISTOGRAM(
              "PLT.StartToCommit_NormalLoad_AlternateProtocol_spdy",
              start_to_commit);
          break;
        default:
          break;
      }
    }
  }

  if (navigation_state->was_fetched_via_proxy()) {
    if (url.SchemeIs("https")) {
      PLT_HISTOGRAM("PLT.StartToFinish.Proxy.https", start_to_finish);
      UMA_HISTOGRAM_ENUMERATION("PLT.Abandoned.Proxy.https",
          abandoned_page ? 1 : 0, 2);
    } else {
      PLT_HISTOGRAM("PLT.StartToFinish.Proxy.http", start_to_finish);
      UMA_HISTOGRAM_ENUMERATION("PLT.Abandoned.Proxy.http",
          abandoned_page ? 1 : 0, 2);
    }
  } else {
    if (url.SchemeIs("https")) {
      PLT_HISTOGRAM("PLT.StartToFinish.NoProxy.https", start_to_finish);
      UMA_HISTOGRAM_ENUMERATION("PLT.Abandoned.NoProxy.https",
          abandoned_page ? 1 : 0, 2);
    } else {
      PLT_HISTOGRAM("PLT.StartToFinish.NoProxy.http", start_to_finish);
      UMA_HISTOGRAM_ENUMERATION("PLT.Abandoned.NoProxy.http",
          abandoned_page ? 1 : 0, 2);
    }
  }

  UMA_HISTOGRAM_COUNTS("SiteIsolation.PageLoadsWithCrossSiteFrameAccess",
                       cross_origin_access_count_);
  UMA_HISTOGRAM_COUNTS("SiteIsolation.PageLoadsWithSameSiteFrameAccess",
                       same_origin_access_count_);

  LogNavigationState(navigation_state, main_frame->dataSource());

  navigation_state->set_load_histograms_recorded(true);

  if (RenderThread::current()) {
    RenderThread::current()->SendHistograms(
        chrome::kHistogramSynchronizerReservedSequenceNumber);
  }
}

Project: Chrome

void RenderView::EnsureDocumentTag() {
#if defined(OS_MACOSX)
  if (!has_document_tag_) {
    Send(new ViewHostMsg_GetDocumentTag(routing_id_, &document_tag_));
    has_document_tag_ = true;
  }
#endif
}

Project: Chrome

void RenderView::EvaluateScript(const std::wstring& frame_xpath,
                                const std::wstring& script) {
  WebFrame* web_frame = GetChildFrame(frame_xpath);
  if (!web_frame)
    return;

  web_frame->executeScript(WebScriptSource(WideToUTF16Hack(script)));
}

Project: Chrome

void RenderView::ForEach(RenderViewVisitor* visitor) {
  ViewMap* views = Singleton<ViewMap>::get();
  for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
    if (!visitor->Visit(it->second))
      return;
  }
}

Project: Chrome

RenderView* RenderView::FromWebView(WebView* webview) {
  ViewMap* views = Singleton<ViewMap>::get();
  ViewMap::iterator it = views->find(webview);
  return it == views->end() ? NULL : it->second;
}

Project: Chrome

bool RenderView::GetAllChildFrames(
    WebFrame* parent_frame,
    std::vector<WebFrame*>* frames_vector) const {
  if (!parent_frame)
    return false;
  for (WebFrame* child_frame = parent_frame->firstChild(); child_frame;
       child_frame = child_frame->nextSibling()) {
    frames_vector->push_back(child_frame);
    GetAllChildFrames(child_frame, frames_vector);
  }
  return true;
}

Project: Chrome

std::string RenderView::GetAltHTMLForTemplate(
    const DictionaryValue& error_strings, int template_resource_id) const {
  const base::StringPiece template_html(
      ResourceBundle::GetSharedInstance().GetRawDataResource(
          template_resource_id));

  if (template_html.empty()) {
    NOTREACHED() << "unable to load template. ID: " << template_resource_id;
    return "";
  }

  return jstemplate_builder::GetTemplatesHtml(
      template_html, &error_strings, "t");
}

Project: Chrome

GURL RenderView::GetAlternateErrorPageURL(const GURL& failed_url,
                                          ErrorPageType error_type) {
  if (failed_url.SchemeIsSecure()) {
    return GURL();
  }

  if (!alternate_error_page_url_.is_valid())
    return GURL();

  GURL::Replacements remove_params;
  remove_params.ClearUsername();
  remove_params.ClearPassword();
  remove_params.ClearQuery();
  remove_params.ClearRef();
  const GURL url_to_send = failed_url.ReplaceComponents(remove_params);
  std::string spec_to_send = url_to_send.spec();
  if (failed_url.has_query())
      spec_to_send.append("?");

  std::string params(alternate_error_page_url_.query());
  params.append("&url=");
  params.append(EscapeQueryParamValue(spec_to_send, true));
  params.append("&sourceid=chrome");
  params.append("&error=");
  switch (error_type) {
    case DNS_ERROR:
      params.append("dnserror");
      break;

    case HTTP_404:
      params.append("http404");
      break;

    case CONNECTION_ERROR:
      params.append("connectionfailure");
      break;

    default:
      NOTREACHED() << "unknown ErrorPageType";
  }

  GURL::Replacements link_doctor_params;
  link_doctor_params.SetQueryStr(params);
  GURL url = alternate_error_page_url_.ReplaceComponents(link_doctor_params);
  return url;
}

Project: Chrome

uint32 RenderView::GetCPBrowsingContext() {
  uint32 context = 0;
  Send(new ViewHostMsg_GetCPBrowsingContext(&context));
  return context;
}

Project: Chrome

static void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
  WebVector<WebURL> urls;
  ds->redirectChain(urls);
  result->reserve(urls.size());
  for (size_t i = 0; i < urls.size(); ++i)
    result->push_back(urls[i]);
}

Project: Chrome

RenderView::GetSearchProviderInstallState(const std::string& url) {
  GURL inquiry_url = GURL(url);
  if (inquiry_url.is_empty())
    return ViewHostMsg_GetSearchProviderInstallState_Params::Denied();
  ViewHostMsg_GetSearchProviderInstallState_Params install;
  Send(new ViewHostMsg_GetSearchProviderInstallState(routing_id_,
                                                     inquiry_url,
                                                     &install));
  return install;
}

Project: Chrome

WebKit::WebPlugin* RenderView::GetWebPluginFromPluginDocument() {
  return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
}

Project: Chrome

SkBitmap RenderView::ImageFromDataUrl(const GURL& url) const {
  std::string mime_type, char_set, data;
  if (net::DataURL::Parse(url, &mime_type, &char_set, &data) && !data.empty()) {
    webkit_glue::ImageDecoder decoder(gfx::Size(kFavIconSize, kFavIconSize));
    const unsigned char* src_data =
        reinterpret_cast<const unsigned char*>(&data[0]);

    return decoder.Decode(src_data, data.size());
  }
  return SkBitmap();
}

Project: Chrome

void RenderView::Init(gfx::NativeViewId parent_hwnd,
                      int32 opener_id,
                      const RendererPreferences& renderer_prefs,
                      SharedRenderViewCounter* counter,
                      int32 routing_id,
                      const string16& frame_name) {
  DCHECK(!webview());

  if (opener_id != MSG_ROUTING_NONE)
    opener_id_ = opener_id;

  if (counter) {
    shared_popup_counter_ = counter;
    shared_popup_counter_->data++;
    decrement_shared_popup_at_destruction_ = true;
  } else {
    shared_popup_counter_ = new SharedRenderViewCounter(0);
    decrement_shared_popup_at_destruction_ = false;
  }

  devtools_agent_.reset(new DevToolsAgent(routing_id, this));

  webwidget_ = WebView::create(this, devtools_agent_.get());
  Singleton<ViewMap>::get()->insert(std::make_pair(webview(), this));
  webkit_preferences_.Apply(webview());
  webview()->initializeMainFrame(this);
  if (!frame_name.empty())
    webview()->mainFrame()->setName(frame_name);

  OnSetRendererPrefs(renderer_prefs);

  routing_id_ = routing_id;
  render_thread_->AddRoute(routing_id_, this);
  AddRef();

  if (opener_id == MSG_ROUTING_NONE) {
    did_show_ = true;
    CompleteInit(parent_hwnd);
  }

  host_window_ = parent_hwnd;

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kDomAutomationController))
    enabled_bindings_ |= BindingsPolicy::DOM_AUTOMATION;

  audio_message_filter_ = new AudioMessageFilter(routing_id_);
  render_thread_->AddFilter(audio_message_filter_);
}

Project: Chrome

void RenderView::InjectToolstripCSS() {
  if (view_type_ != ViewType::EXTENSION_TOOLSTRIP)
    return;

  static const base::StringPiece toolstrip_css(
      ResourceBundle::GetSharedInstance().GetRawDataResource(
      IDR_EXTENSION_TOOLSTRIP_CSS));
  std::string css = toolstrip_css.as_string();
  InsertCSS(L"", css, "ToolstripDefaultCSS");
}

Project: Chrome

bool RenderView::IsNonLocalTopLevelNavigation(
    const GURL& url, WebKit::WebFrame* frame, WebKit::WebNavigationType type) {
  if (frame->parent() != NULL)
    return false;

  if (!url.SchemeIs("http") && !url.SchemeIs("https"))
    return false;

  GURL frame_url(frame->url());
  if (!frame_url.SchemeIs("http") && !frame_url.SchemeIs("https"))
    return false;

  GURL frame_origin = frame_url.GetOrigin();
  if (url.GetOrigin() != frame_origin || url.ref().empty()) {
    if (type == WebKit::WebNavigationTypeLinkClicked)
      return true;

    if (last_top_level_navigation_page_id_ != page_id_ &&
        type != WebKit::WebNavigationTypeReload &&
        type != WebKit::WebNavigationTypeFormSubmitted &&
        type != WebKit::WebNavigationTypeBackForward) {
      return true;
    }
  }
  if (type != WebKit::WebNavigationTypeReload &&
      type != WebKit::WebNavigationTypeFormSubmitted &&
      type != WebKit::WebNavigationTypeBackForward) {
    WebKit::WebFrame* opener = frame->opener();
    if (opener) {
      if (url.GetOrigin() != GURL(opener->url()).GetOrigin())
        return true;
    }
  }
  return false;
}

Project: Chrome

bool RenderView::IsPageTranslatable(WebKit::WebDocument* document) {
  std::vector<WebKit::WebElement> meta_elements;
  webkit_glue::GetMetaElementsWithName(document, ASCIIToUTF16("google"),
                                       &meta_elements);
  std::vector<WebKit::WebElement>::const_iterator iter;
  for (iter = meta_elements.begin(); iter != meta_elements.end(); ++iter) {
    WebString attribute = iter->getAttribute("value");
    if (attribute.isNull())  // We support both 'value' and 'content'.
      attribute = iter->getAttribute("content");
    if (attribute.isNull())
      continue;
    if (LowerCaseEqualsASCII(attribute, "notranslate"))
      return false;
  }
  return true;
}

Project: Chrome

static bool IsWhitelistedForContentSettings(WebFrame* frame) {
  WebSecurityOrigin origin = frame->securityOrigin();
  if (origin.isEmpty())
    return false;  // Uninitialized document?

  if (EqualsASCII(origin.protocol(), chrome::kChromeUIScheme))
    return true;  // Browser UI elements should still work.

  GURL frame_url = frame->url();
  const char* kDirProtocols[] = { "ftp", "file" };
  for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
    if (EqualsASCII(origin.protocol(), kDirProtocols[i])) {
      return frame_url.SchemeIs(kDirProtocols[i]) &&
             frame_url.ExtractFileName().empty();
    }
  }

  return false;
}

Project: Chrome

void RenderView::LoadNavigationErrorPage(WebFrame* frame,
                                         const WebURLRequest& failed_request,
                                         const WebURLError& error,
                                         const std::string& html,
                                         bool replace) {
  GURL failed_url = error.unreachableURL;

  std::string alt_html;
  if (html.empty()) {
    int resource_id;
    DictionaryValue error_strings;
    if (error.reason == net::ERR_CACHE_MISS &&
        EqualsASCII(failed_request.httpMethod(), "POST")) {
      GetFormRepostErrorValues(failed_url, &error_strings);
      resource_id = IDR_ERROR_NO_DETAILS_HTML;
    } else {
      GetLocalizedErrorValues(error, &error_strings);
      resource_id = IDR_NET_ERROR_HTML;
    }

    alt_html = GetAltHTMLForTemplate(error_strings, resource_id);
  } else {
    alt_html = html;
  }

  frame->loadHTMLString(alt_html,
                        GURL(kUnreachableWebDataURL),
                        failed_url,
                        replace);
}

Project: Chrome

void RenderView::LogNavigationState(const NavigationState* state,
                                    const WebDataSource* ds) const {
  if (logging::LOG_INFO < logging::GetMinLogLevel())
    return;

  DCHECK(state);
  DCHECK(ds);
  GURL url(ds->request().url());
  Time start = state->start_load_time();
  Time finish = state->finish_load_time();
  LOG(INFO) << "PLT: "
            << (finish - start).InMilliseconds()
            << "ms "
            << url.spec();
}

Project: Chrome

bool RenderView::MaybeLoadAlternateErrorPage(WebFrame* frame,
                                             const WebURLError& error,
                                             bool replace) {
  if (frame->parent())
    return false;

  int ec = error.reason;
  if (ec != net::ERR_NAME_NOT_RESOLVED &&
      ec != net::ERR_CONNECTION_FAILED &&
      ec != net::ERR_CONNECTION_REFUSED &&
      ec != net::ERR_ADDRESS_UNREACHABLE &&
      ec != net::ERR_CONNECTION_TIMED_OUT)
    return false;

  const GURL& error_page_url = GetAlternateErrorPageURL(error.unreachableURL,
      ec == net::ERR_NAME_NOT_RESOLVED ? DNS_ERROR : CONNECTION_ERROR);
  if (!error_page_url.is_valid())
    return false;

  frame->loadHTMLString(std::string(),
                        GURL(kUnreachableWebDataURL),
                        error.unreachableURL,
                        replace);

  NavigationState* navigation_state =
      NavigationState::FromDataSource(frame->provisionalDataSource());
  navigation_state->set_alt_error_page_fetcher(
      new AltErrorPageResourceFetcher(
          error_page_url, frame, error,
          NewCallback(this, &RenderView::AltErrorPageFinished)));
  return true;
}

Project: Chrome

void RenderView::OnAccessibilityDoDefaultAction(int acc_obj_id) {
  if (!accessibility_.get())
    return;
  if (accessibility_->isValidId(acc_obj_id)) {
    accessibility_->getObjectById(acc_obj_id).performDefaultAction();
  }
}

Project: Chrome

void RenderView::OnAdvanceToNextMisspelling() {
  if (!webview())
    return;
  webview()->focusedFrame()->executeCommand(
      WebString::fromUTF8("AdvanceToNextMisspelling"));
}

Project: Chrome

void RenderView::OnAllowScriptToClose(bool script_can_close) {
  script_can_close_ = script_can_close;
}

Project: Chrome

void RenderView::OnAutoFillFormDataFilled(int query_id,
                                          const webkit_glue::FormData& form) {
  autofill_helper_.FormDataFilled(query_id, form);
}

Project: Chrome

void RenderView::OnAutoFillSuggestionsReturned(
    int query_id,
    const std::vector<string16>& values,
    const std::vector<string16>& labels,
    const std::vector<string16>& icons,
    const std::vector<int>& unique_ids) {
  autofill_helper_.SuggestionsReceived(
      query_id, values, labels, icons, unique_ids);
}

Project: Chrome

void RenderView::OnCSSInsertRequest(const std::wstring& frame_xpath,
                                    const std::string& css,
                                    const std::string& id) {
  InsertCSS(frame_xpath, css, id);

  Send(new ViewHostMsg_OnCSSInserted(routing_id_));
}

Project: Chrome

void RenderView::OnCaptureSnapshot() {
  SkBitmap snapshot;
  bool error = false;

  WebFrame* main_frame = webview()->mainFrame();
  if (!main_frame)
    error = true;

  if (!error && !CaptureSnapshot(webview(), &snapshot))
    error = true;

  DCHECK(error == snapshot.empty()) <<
      "Snapshot should be empty on error, non-empty otherwise.";

  Send(new ViewHostMsg_Snapshot(routing_id_, snapshot));
}

Project: Chrome

void RenderView::OnCaptureThumbnail() {
  WebFrame* main_frame = webview()->mainFrame();
  if (!main_frame)
    return;

  GURL url(main_frame->url());
  if (url.is_empty())
    return;

  if (size_.IsEmpty())
    return;  // Don't create an empty thumbnail!

  ThumbnailScore score;
  SkBitmap thumbnail;
  if (!CaptureThumbnail(webview(), kThumbnailWidth, kThumbnailHeight,
                        &thumbnail, &score))
    return;

  Send(new ViewHostMsg_Thumbnail(routing_id_, url, score, thumbnail));
}

Project: Chrome

void RenderView::OnClearFocusedNode() {
  if (webview())
    webview()->clearFocusedNode();
}

Project: Chrome

void RenderView::OnCopy() {
  if (!webview())
    return;

  webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
  UserMetricsRecordAction("Copy");
}

Project: Chrome

void RenderView::OnCopyImageAt(int x, int y) {
  webview()->copyImageAt(WebPoint(x, y));
}

Project: Chrome

void RenderView::OnCopyToFindPboard() {
  if (!webview())
    return;

  WebFrame* frame = webview()->focusedFrame();
  if (frame->hasSelection()) {
    string16 selection = frame->selectionAsText();
    RenderThread::current()->Send(
        new ViewHostMsg_ClipboardFindPboardWriteStringAsync(selection));
  }

  UserMetricsRecordAction("CopyToFindPboard");
}

Project: Chrome

void RenderView::OnCustomContextMenuAction(unsigned action) {
  webview()->performCustomContextMenuAction(action);
}

Project: Chrome

void RenderView::OnCut() {
  if (!webview())
    return;

  webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Cut"));
  UserMetricsRecordAction("Cut");
}

Project: Chrome

void RenderView::OnDelete() {
  if (!webview())
    return;

  webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Delete"));
  UserMetricsRecordAction("DeleteSelection");
}

Project: Chrome

void RenderView::OnDisableScrollbarsForSmallWindows(
    const gfx::Size& disable_scrollbar_size_limit) {
  disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
}

Project: Chrome

void RenderView::OnDisassociateFromPopupCount() {
  if (decrement_shared_popup_at_destruction_)
    shared_popup_counter_->data--;
  shared_popup_counter_ = new SharedRenderViewCounter(0);
  decrement_shared_popup_at_destruction_ = false;
}

Project: Chrome

void RenderView::OnDownloadFavIcon(int id,
                                   const GURL& image_url,
                                   int image_size) {
  bool data_image_failed = false;
  if (image_url.SchemeIs("data")) {
    SkBitmap data_image = ImageFromDataUrl(image_url);
    data_image_failed = data_image.empty();
    if (!data_image_failed) {
      Send(new ViewHostMsg_DidDownloadFavIcon(routing_id_, id, image_url, false,
                                              data_image));
    }
  }

  if (data_image_failed ||
      !DownloadImage(id, image_url, image_size)) {
    Send(new ViewHostMsg_DidDownloadFavIcon(routing_id_, id, image_url, true,
                                            SkBitmap()));
  }
}

Project: Chrome

void RenderView::OnDragSourceEndedOrMoved(const gfx::Point& client_point,
                                          const gfx::Point& screen_point,
                                          bool ended,
                                          WebDragOperation op) {
  if (ended) {
    webview()->dragSourceEndedAt(client_point, screen_point, op);
  } else {
    webview()->dragSourceMovedTo(client_point, screen_point, op);
  }
}

Project: Chrome

void RenderView::OnDragSourceSystemDragEnded() {
  webview()->dragSourceSystemDragEnded();
}

Project: Chrome

void RenderView::OnDragTargetDragLeave() {
  webview()->dragTargetDragLeave();
}

Project: Chrome

void RenderView::OnDragTargetDragOver(const gfx::Point& client_point,
                                      const gfx::Point& screen_point,
                                      WebDragOperationsMask ops) {
  WebDragOperation operation = webview()->dragTargetDragOver(
      client_point,
      screen_point,
      ops);

  Send(new ViewHostMsg_UpdateDragCursor(routing_id_, operation));
}

Project: Chrome

void RenderView::OnDragTargetDrop(const gfx::Point& client_point,
                                  const gfx::Point& screen_point) {
  webview()->dragTargetDrop(client_point, screen_point);
}

Project: Chrome

void RenderView::OnEnablePreferredSizeChangedMode(int flags) {
  DCHECK(flags != kPreferredSizeNothing);
  if (send_preferred_size_changes_)
    return;
  send_preferred_size_changes_ = true;

  if (flags & kPreferredSizeHeightThisIsSlow) {
    preferred_size_change_timer_.Start(TimeDelta::FromMilliseconds(10), this,
                                       &RenderView::CheckPreferredSize);
  }
}

Project: Chrome

void RenderView::OnEnableViewSourceMode() {
  if (!webview())
    return;
  WebFrame* main_frame = webview()->mainFrame();
  if (!main_frame)
    return;

  main_frame->enableViewSourceMode(true);
}

Project: Chrome

void RenderView::OnExecuteEditCommand(const std::string& name,
    const std::string& value) {
  if (!webview() || !webview()->focusedFrame())
    return;

  webview()->focusedFrame()->executeCommand(
      WebString::fromUTF8(name), WebString::fromUTF8(value));
}

Project: Chrome

void RenderView::OnExtensionMessageInvoke(const std::string& function_name,
                                          const ListValue& args,
                                          bool requires_incognito_access,
                                          const GURL& event_url) {
  RendererExtensionBindings::Invoke(
      function_name, args, this, requires_incognito_access, event_url);
}

Project: Chrome

void RenderView::OnExtensionResponse(int request_id,
                                     bool success,
                                     const std::string& response,
                                     const std::string& error) {
  ExtensionProcessBindings::HandleResponse(
      request_id, success, response, error);
}

Project: Chrome

void RenderView::OnFileChooserResponse(const std::vector<FilePath>& paths) {
  if (file_chooser_completions_.empty())
    return;

  WebVector<WebString> ws_file_names(paths.size());
  for (size_t i = 0; i < paths.size(); ++i)
    ws_file_names[i] = webkit_glue::FilePathToWebString(paths[i]);

  if (file_chooser_completions_.front()->completion)
    file_chooser_completions_.front()->completion->didChooseFile(ws_file_names);
  file_chooser_completions_.pop_front();

  if (!file_chooser_completions_.empty()) {
    Send(new ViewHostMsg_RunFileChooser(routing_id_,
        file_chooser_completions_.front()->params));
  }
}

Project: Chrome

void RenderView::OnFillPasswordForm(
    const webkit_glue::PasswordFormFillData& form_data) {
#if defined(WEBKIT_BUG_41283_IS_FIXED)
  password_autocomplete_manager_.ReceivedPasswordFormFillData(webview(),
                                                              form_data);
#else
  webkit_glue::FillPasswordForm(this->webview(), form_data);
#endif
}

Project: Chrome

void RenderView::OnFind(int request_id, const string16& search_text,
                        const WebFindOptions& options) {
  WebFrame* main_frame = webview()->mainFrame();

  if (main_frame->document().isPluginDocument()) {
    if (options.findNext) {
      GetWebPluginFromPluginDocument()->selectFindResult(options.forward);
    } else {
      if (GetWebPluginFromPluginDocument()->startFind(
          search_text, options.matchCase, request_id)) {
      } else {
        ReportNoFindInPageResults(request_id);
      }
    }
    return;
  }

  WebFrame* frame_after_main = main_frame->traverseNext(true);
  WebFrame* focused_frame = webview()->focusedFrame();
  WebFrame* search_frame = focused_frame;  // start searching focused frame.

  bool multi_frame = (frame_after_main != main_frame);

  bool wrap_within_frame = !multi_frame;

  WebRect selection_rect;
  bool result = false;

  WebRange current_selection = focused_frame->selectionRange();

  do {
    result = search_frame->find(
        request_id, search_text, options, wrap_within_frame, &selection_rect);

    if (!result) {
      search_frame->executeCommand(WebString::fromUTF8("Unselect"));

      do {
        search_frame = options.forward ?
            search_frame->traverseNext(true) :
            search_frame->traversePrevious(true);
      } while (!search_frame->hasVisibleContent() &&
               search_frame != focused_frame);

      search_frame->executeCommand(WebString::fromUTF8("Unselect"));

      if (multi_frame && search_frame == focused_frame) {
        result = search_frame->find(
            request_id, search_text, options, true,  // Force wrapping.
            &selection_rect);
      }
    }

    webview()->setFocusedFrame(search_frame);
  } while (!result && search_frame != focused_frame);

  if (options.findNext && current_selection.isNull()) {
    main_frame->increaseMatchCount(0, request_id);
  } else {
    int ordinal = result ? -1 : 0;  // -1 here means, we might know more later.
    int match_count = result ? 1 : 0;  // 1 here means possibly more coming.

    bool final_status_update = !result;

    Send(new ViewHostMsg_Find_Reply(routing_id_,
                                    request_id,
                                    match_count,
                                    selection_rect,
                                    ordinal,
                                    final_status_update));

    search_frame = main_frame;

    main_frame->resetMatchCount();

    do {
      search_frame->cancelPendingScopingEffort();

      if (result) {
        search_frame->scopeStringMatches(request_id,
                                         search_text,
                                         options,
                                         true);  // reset the tickmarks
      }

      search_frame = search_frame->traverseNext(true);
    } while (search_frame != main_frame);
  }
}

Project: Chrome

void RenderView::OnFindReplyAck() {
  if (queued_find_reply_message_.get()) {
    Send(queued_find_reply_message_.release());
  }
}

Project: Chrome

void RenderView::OnGetAccessibilityTree() {
  if (accessibility_.get())
    accessibility_->clear();
    accessibility_.reset(WebAccessibilityCache::create());
    accessibility_->initialize(webview());

  WebAccessibilityObject src_tree = webview()->accessibilityObject();
  webkit_glue::WebAccessibility dst_tree(src_tree, accessibility_.get());
  Send(new ViewHostMsg_AccessibilityTree(routing_id_, dst_tree));
}

Project: Chrome

void RenderView::OnGetAllSavableResourceLinksForCurrentPage(
    const GURL& page_url) {
  std::vector<GURL> resources_list;
  std::vector<GURL> referrers_list;
  std::vector<GURL> frames_list;
  webkit_glue::SavableResourcesResult result(&resources_list,
                                             &referrers_list,
                                             &frames_list);

  if (!webkit_glue::GetAllSavableResourceLinksForCurrentPage(
          webview(),
          page_url,
          &result,
          chrome::kSavableSchemes)) {
    referrers_list.clear();
    resources_list.clear();
    frames_list.clear();
  }

  Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id_,
                                                              resources_list,
                                                              referrers_list,
                                                              frames_list));
}

Project: Chrome

void RenderView::OnGetApplicationInfo(int page_id) {
  webkit_glue::WebApplicationInfo app_info;
  if (page_id == page_id_)
    webkit_glue::GetApplicationInfo(webview(), &app_info);

  for (size_t i = 0; i < app_info.icons.size(); ++i) {
    if (app_info.icons[i].url.SchemeIs(chrome::kDataScheme)) {
      app_info.icons.erase(app_info.icons.begin() + i);
      --i;
    }
  }

  Send(new ViewHostMsg_DidGetApplicationInfo(routing_id_, page_id, app_info));
}

Project: Chrome

void RenderView::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
    const std::vector<GURL>& links,
    const std::vector<FilePath>& local_paths,
    const FilePath& local_directory_name) {

  WebVector<WebURL> weburl_links(links);

  WebVector<WebString> webstring_paths(local_paths.size());
  for (size_t i = 0; i < local_paths.size(); i++)
    webstring_paths[i] = webkit_glue::FilePathToWebString(local_paths[i]);

  WebPageSerializer::serialize(webview()->mainFrame(),
                               true, this, weburl_links, webstring_paths,
                               webkit_glue::FilePathToWebString(
                                   local_directory_name));
}

Project: Chrome

void RenderView::OnHandleMessageFromExternalHost(const std::string& message,
                                                 const std::string& origin,
                                                 const std::string& target) {
  if (message.empty())
    return;
  external_host_bindings_.ForwardMessageFromExternalHost(message, origin,
                                                         target);
}

Project: Chrome

void RenderView::OnInstallMissingPlugin() {
  if (first_default_plugin_)
    first_default_plugin_->InstallMissingPlugin();
}

Project: Chrome

void RenderView::OnMediaPlayerActionAt(const gfx::Point& location,
                                       const WebMediaPlayerAction& action) {
  if (webview())
    webview()->performMediaPlayerAction(action, location);
}

Project: Chrome

void RenderView::OnMessageReceived(const IPC::Message& message) {
  WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
  if (main_frame)
    child_process_logging::SetActiveURL(main_frame->url());

  if (devtools_client_.get() && devtools_client_->OnMessageReceived(message))
    return;
  if (devtools_agent_.get() && devtools_agent_->OnMessageReceived(message))
    return;
  if (notification_provider_->OnMessageReceived(message))
    return;
  if (geolocation_dispatcher_.get() &&
      geolocation_dispatcher_->OnMessageReceived(message)) {
    return;
  }
  if (speech_input_dispatcher_.get() &&
      speech_input_dispatcher_->OnMessageReceived(message)) {
    return;
  }
  if (device_orientation_dispatcher_.get() &&
      device_orientation_dispatcher_->OnMessageReceived(message)) {
    return;
  }

  IPC_BEGIN_MESSAGE_MAP(RenderView, message)
    IPC_MESSAGE_HANDLER(ViewMsg_CaptureThumbnail, OnCaptureThumbnail)
    IPC_MESSAGE_HANDLER(ViewMsg_CaptureSnapshot, OnCaptureSnapshot)
    IPC_MESSAGE_HANDLER(ViewMsg_PrintPages, OnPrintPages)
    IPC_MESSAGE_HANDLER(ViewMsg_PrintingDone, OnPrintingDone)
    IPC_MESSAGE_HANDLER(ViewMsg_Navigate, OnNavigate)
    IPC_MESSAGE_HANDLER(ViewMsg_Stop, OnStop)
    IPC_MESSAGE_HANDLER(ViewMsg_ReloadFrame, OnReloadFrame)
    IPC_MESSAGE_HANDLER(ViewMsg_Undo, OnUndo)
    IPC_MESSAGE_HANDLER(ViewMsg_Redo, OnRedo)
    IPC_MESSAGE_HANDLER(ViewMsg_Cut, OnCut)
    IPC_MESSAGE_HANDLER(ViewMsg_Copy, OnCopy)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(ViewMsg_CopyToFindPboard, OnCopyToFindPboard)
#endif
    IPC_MESSAGE_HANDLER(ViewMsg_Paste, OnPaste)
    IPC_MESSAGE_HANDLER(ViewMsg_Replace, OnReplace)
    IPC_MESSAGE_HANDLER(ViewMsg_ToggleSpellPanel, OnToggleSpellPanel)
    IPC_MESSAGE_HANDLER(ViewMsg_AdvanceToNextMisspelling,
                        OnAdvanceToNextMisspelling)
    IPC_MESSAGE_HANDLER(ViewMsg_ToggleSpellCheck, OnToggleSpellCheck)
    IPC_MESSAGE_HANDLER(ViewMsg_Delete, OnDelete)
    IPC_MESSAGE_HANDLER(ViewMsg_SelectAll, OnSelectAll)
    IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
    IPC_MESSAGE_HANDLER(ViewMsg_ExecuteEditCommand, OnExecuteEditCommand)
    IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
    IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
    IPC_MESSAGE_HANDLER(ViewMsg_FindReplyACK, OnFindReplyAck)
    IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
    IPC_MESSAGE_HANDLER(ViewMsg_SetContentSettingsForLoadingURL,
                        OnSetContentSettingsForLoadingURL)
    IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
                        OnSetZoomLevelForLoadingURL)
    IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
    IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
                        OnResetPageEncodingToDefault)
    IPC_MESSAGE_HANDLER(ViewMsg_SetupDevToolsClient, OnSetupDevToolsClient)
    IPC_MESSAGE_HANDLER(ViewMsg_DownloadFavIcon, OnDownloadFavIcon)
    IPC_MESSAGE_HANDLER(ViewMsg_ScriptEvalRequest, OnScriptEvalRequest)
    IPC_MESSAGE_HANDLER(ViewMsg_CSSInsertRequest, OnCSSInsertRequest)
    IPC_MESSAGE_HANDLER(ViewMsg_AddMessageToConsole, OnAddMessageToConsole)
    IPC_MESSAGE_HANDLER(ViewMsg_ReservePageIDRange, OnReservePageIDRange)
    IPC_MESSAGE_HANDLER(ViewMsg_FillPasswordForm, OnFillPasswordForm)
    IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDragEnter, OnDragTargetDragEnter)
    IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDragOver, OnDragTargetDragOver)
    IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDragLeave, OnDragTargetDragLeave)
    IPC_MESSAGE_HANDLER(ViewMsg_DragTargetDrop, OnDragTargetDrop)
    IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
    IPC_MESSAGE_HANDLER(ViewMsg_SetDOMUIProperty, OnSetDOMUIProperty)
    IPC_MESSAGE_HANDLER(ViewMsg_DragSourceEndedOrMoved,
                        OnDragSourceEndedOrMoved)
    IPC_MESSAGE_HANDLER(ViewMsg_DragSourceSystemDragEnded,
                        OnDragSourceSystemDragEnded)
    IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
    IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
    IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
    IPC_MESSAGE_HANDLER(ViewMsg_SetAltErrorPageURL, OnSetAltErrorPageURL)
    IPC_MESSAGE_HANDLER(ViewMsg_InstallMissingPlugin, OnInstallMissingPlugin)
    IPC_MESSAGE_HANDLER(ViewMsg_LoadBlockedPlugins, OnLoadBlockedPlugins)
    IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
    IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
    IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
                        OnGetAllSavableResourceLinksForCurrentPage)
    IPC_MESSAGE_HANDLER(
        ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
        OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
    IPC_MESSAGE_HANDLER(ViewMsg_GetApplicationInfo, OnGetApplicationInfo)
    IPC_MESSAGE_HANDLER(ViewMsg_ShouldClose, OnShouldClose)
    IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
    IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
    IPC_MESSAGE_HANDLER(ViewMsg_HandleMessageFromExternalHost,
                        OnHandleMessageFromExternalHost)
    IPC_MESSAGE_HANDLER(ViewMsg_DisassociateFromPopupCount,
                        OnDisassociateFromPopupCount)
    IPC_MESSAGE_HANDLER(ViewMsg_AutoFillSuggestionsReturned,
                        OnAutoFillSuggestionsReturned)
    IPC_MESSAGE_HANDLER(ViewMsg_AutoFillFormDataFilled,
                        OnAutoFillFormDataFilled)
    IPC_MESSAGE_HANDLER(ViewMsg_AllowScriptToClose,
                        OnAllowScriptToClose)
    IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
    IPC_MESSAGE_HANDLER(ViewMsg_ExtensionResponse, OnExtensionResponse)
    IPC_MESSAGE_HANDLER(ViewMsg_ExtensionMessageInvoke,
                        OnExtensionMessageInvoke)
    IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedNode, OnClearFocusedNode)
    IPC_MESSAGE_HANDLER(ViewMsg_SetBackground, OnSetBackground)
    IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
                        OnEnablePreferredSizeChangedMode)
    IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
                        OnDisableScrollbarsForSmallWindows)
    IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
    IPC_MESSAGE_HANDLER(ViewMsg_UpdateBrowserWindowId,
                        OnUpdateBrowserWindowId)
    IPC_MESSAGE_HANDLER(ViewMsg_NotifyRenderViewType,
                        OnNotifyRendererViewType)
    IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
    IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
    IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
#endif
    IPC_MESSAGE_HANDLER(ViewMsg_SetEditCommandsForNextKeyEvent,
                        OnSetEditCommandsForNextKeyEvent)
    IPC_MESSAGE_HANDLER(ViewMsg_ExecuteCode,
                        OnExecuteCode)
    IPC_MESSAGE_HANDLER(ViewMsg_CustomContextMenuAction,
                        OnCustomContextMenuAction)
    IPC_MESSAGE_HANDLER(ViewMsg_TranslatePage, OnTranslatePage)
    IPC_MESSAGE_HANDLER(ViewMsg_RevertTranslation, OnRevertTranslation)
    IPC_MESSAGE_HANDLER(ViewMsg_GetAccessibilityTree, OnGetAccessibilityTree)
    IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityFocus, OnSetAccessibilityFocus)
    IPC_MESSAGE_HANDLER(ViewMsg_AccessibilityDoDefaultAction,
                        OnAccessibilityDoDefaultAction)

    IPC_MESSAGE_UNHANDLED(RenderWidget::OnMessageReceived(message))
  IPC_END_MESSAGE_MAP()
}

Project: Chrome

void RenderView::OnMissingPluginStatus(
    WebPluginDelegateProxy* delegate,
    int status) {
#if defined(OS_WIN)
  if (!first_default_plugin_) {
    if (status == default_plugin::MISSING_PLUGIN_AVAILABLE) {
      first_default_plugin_ = delegate->AsWeakPtr();
      Send(new ViewHostMsg_MissingPluginStatus(routing_id_, status));
    }
  } else {
    if (status == default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD) {
      Send(new ViewHostMsg_MissingPluginStatus(routing_id_, status));
    }
  }
#else
  NOTIMPLEMENTED();
#endif
}

Project: Chrome

void RenderView::OnMoveOrResizeStarted() {
  if (webview())
    webview()->hidePopups();
}

Project: Chrome

void RenderView::OnNavigate(const ViewMsg_Navigate_Params& params) {
  if (!webview())
    return;

  history_list_offset_ = params.current_history_list_offset;
  history_list_length_ = params.current_history_list_length;

  if (devtools_agent_.get())
    devtools_agent_->OnNavigate();

  if (notification_provider_.get())
    notification_provider_->OnNavigate();

  child_process_logging::SetActiveURL(params.url);

  AboutHandler::MaybeHandle(params.url);

  bool is_reload =
      params.navigation_type == ViewMsg_Navigate_Params::RELOAD ||
      params.navigation_type == ViewMsg_Navigate_Params::RELOAD_IGNORING_CACHE;

  WebFrame* main_frame = webview()->mainFrame();
  if (is_reload && main_frame->currentHistoryItem().isNull()) {
    is_reload = false;
  }

  if (!params.url.SchemeIs(chrome::kJavaScriptScheme)) {
    NavigationState* state = NavigationState::CreateBrowserInitiated(
        params.page_id,
        params.pending_history_list_offset,
        params.transition,
        params.request_time);
    if (params.navigation_type == ViewMsg_Navigate_Params::RESTORE) {
      state->set_cache_policy_override(WebURLRequest::UseProtocolCachePolicy);
    }
    pending_navigation_state_.reset(state);
  }

  NavigationState* navigation_state = pending_navigation_state_.get();

  if (is_reload) {
    if (navigation_state)
      navigation_state->set_load_type(NavigationState::RELOAD);
    bool ignore_cache = (params.navigation_type ==
                             ViewMsg_Navigate_Params::RELOAD_IGNORING_CACHE);
    main_frame->reload(ignore_cache);
  } else if (!params.state.empty()) {
    DCHECK_NE(params.page_id, -1);
    if (navigation_state)
      navigation_state->set_load_type(NavigationState::HISTORY_LOAD);
    main_frame->loadHistoryItem(
        webkit_glue::HistoryItemFromString(params.state));
  } else {
    WebURLRequest request(params.url);

    DCHECK_EQ(params.page_id, -1);

    if (main_frame->isViewSourceModeEnabled())
      request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);

    if (params.referrer.is_valid()) {
      request.setHTTPHeaderField(WebString::fromUTF8("Referer"),
                                 WebString::fromUTF8(params.referrer.spec()));
    }

    if (navigation_state)
      navigation_state->set_load_type(NavigationState::NORMAL_LOAD);
    main_frame->loadRequest(request);
  }

  pending_navigation_state_.reset();
}

Project: Chrome

void RenderView::OnNotifyRendererViewType(ViewType::Type type) {
  if (view_type_ != ViewType::INVALID) {
    if (type == ViewType::EXTENSION_MOLE ||
        type == ViewType::EXTENSION_TOOLSTRIP) {
      ExtensionProcessBindings::SetViewType(webview(), type);
    }
  }
  view_type_ = type;
}

Project: Chrome

void RenderView::OnPageTranslated() {
  WebFrame* frame = webview()->mainFrame();
  if (!frame)
    return;

  autofill_helper_.FrameContentsAvailable(frame);
}

Project: Chrome

void RenderView::OnPepperPluginDestroy(
    WebPluginDelegatePepper* pepper_plugin) {
  std::set<WebPluginDelegatePepper*>::iterator found_pepper =
      current_oldstyle_pepper_plugins_.find(pepper_plugin);
  if (found_pepper == current_oldstyle_pepper_plugins_.end()) {
    NOTREACHED();
    return;
  }
  current_oldstyle_pepper_plugins_.erase(found_pepper);

  for (std::deque< linked_ptr<PendingFileChooser> >::iterator i =
           file_chooser_completions_.begin();
       i != file_chooser_completions_.end(); /* nothing */) {
    if ((*i)->completion == pepper_plugin) {
      if (i == file_chooser_completions_.begin())
        (*i)->completion = NULL;
      else
        i = file_chooser_completions_.erase(i);
    } else {
      ++i;
    }
  }
}

Project: Chrome

void RenderView::OnPrintPages() {
  DCHECK(webview());
  if (webview()) {
    if (webview()->focusedFrame()->hasSelection())
      Print(webview()->focusedFrame(), false);
    else
      Print(webview()->mainFrame(), false);
  }
}

Project: Chrome

void RenderView::OnPrintingDone(int document_cookie, bool success) {
  DCHECK(print_helper_.get());
  if (print_helper_.get() != NULL) {
    print_helper_->DidFinishPrinting(success);
  }
}

Project: Chrome

void RenderView::OnRedo() {
  if (!webview())
    return;

  webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Redo"));
  UserMetricsRecordAction("Redo");
}

Project: Chrome

void RenderView::OnReloadFrame() {
  if (webview() && webview()->focusedFrame()) {
    webview()->focusedFrame()->reload(false);
  }
}

Project: Chrome

void RenderView::OnReplace(const string16& text) {
  if (!webview())
    return;

  WebFrame* frame = webview()->focusedFrame();
  if (!frame->hasSelection())
    frame->selectWordAroundCaret();
  frame->replaceSelection(text);
}

Project: Chrome

void RenderView::OnReservePageIDRange(int size_of_range) {
  next_page_id_ += size_of_range + 1;
}

Project: Chrome

void RenderView::OnResize(const gfx::Size& new_size,
                          const gfx::Rect& resizer_rect) {
  if (webview()) {
    webview()->hidePopups();

    if (send_preferred_size_changes_) {
      bool allow_scrollbars = (
          disable_scrollbars_size_limit_.width() <= new_size.width() ||
          disable_scrollbars_size_limit_.height() <= new_size.height());
      webview()->mainFrame()->setCanHaveScrollbars(allow_scrollbars);
    }
  }

  RenderWidget::OnResize(new_size, resizer_rect);
}

Project: Chrome

void RenderView::OnRevertTranslation(int page_id) {
  translate_helper_.RevertTranslation(page_id);
}

Project: Chrome

void RenderView::OnSelectAll() {
  if (!webview())
    return;

  webview()->focusedFrame()->executeCommand(
      WebString::fromUTF8("SelectAll"));
  UserMetricsRecordAction("SelectAll");
}

Project: Chrome

void RenderView::OnSetAccessibilityFocus(int acc_obj_id) {
  if (!accessibility_.get())
    return;
  if (accessibility_->isValidId(acc_obj_id)) {
    if (acc_obj_id == 1000)
      webview()->clearFocusedNode();
    else
      accessibility_->getObjectById(acc_obj_id).setFocused(true);
  }
}

Project: Chrome

void RenderView::OnSetActive(bool active) {
  if (webview())
    webview()->setIsActive(active);

#if defined(OS_MACOSX)
  std::set<WebPluginDelegateProxy*>::iterator plugin_it;
  for (plugin_it = plugin_delegates_.begin();
       plugin_it != plugin_delegates_.end(); ++plugin_it) {
    (*plugin_it)->SetWindowFocus(active);
  }
#endif
}

Project: Chrome

void RenderView::OnSetAltErrorPageURL(const GURL& url) {
  alternate_error_page_url_ = url;
}

Project: Chrome

void RenderView::OnSetBackground(const SkBitmap& background) {
  if (webview())
    webview()->setIsTransparent(!background.empty());

  SetBackground(background);
}

Project: Chrome

void RenderView::OnSetContentSettingsForLoadingURL(
    const GURL& url,
    const ContentSettings& content_settings) {
  host_content_settings_[url] = content_settings;
}

Project: Chrome

void RenderView::OnSetDOMUIProperty(const std::string& name,
                                    const std::string& value) {
  DCHECK(BindingsPolicy::is_dom_ui_enabled(enabled_bindings_));
  dom_ui_bindings_.SetProperty(name, value);
}

Project: Chrome

void RenderView::OnSetEditCommandsForNextKeyEvent(
    const EditCommands& edit_commands) {
  edit_commands_ = edit_commands;
}

Project: Chrome

void RenderView::OnSetFocus(bool enable) {
  RenderWidget::OnSetFocus(enable);

  if (webview() && webview()->isActive()) {
    std::set<WebPluginDelegateProxy*>::iterator plugin_it;
    for (plugin_it = plugin_delegates_.begin();
         plugin_it != plugin_delegates_.end(); ++plugin_it) {
      if (enable)
        (*plugin_it)->SetWindowFocus(true);
      (*plugin_it)->SetContentAreaFocus(enable);
    }
  }
}

Project: Chrome

void RenderView::OnSetInitialFocus(bool reverse) {
  if (!webview())
    return;
  webview()->setInitialFocus(reverse);
}

Project: Chrome

void RenderView::OnSetPageEncoding(const std::string& encoding_name) {
  webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
}

Project: Chrome

void RenderView::OnSetRendererPrefs(const RendererPreferences& renderer_prefs) {
  renderer_preferences_ = renderer_prefs;
  UpdateFontRenderingFromRendererPrefs();
#if defined(TOOLKIT_GTK)
  WebColorName name = WebKit::WebColorWebkitFocusRingColor;
  WebKit::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
  WebKit::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);

  if (webview()) {
    webview()->setScrollbarColors(
        renderer_prefs.thumb_inactive_color,
        renderer_prefs.thumb_active_color,
        renderer_prefs.track_color);
    webview()->setSelectionColors(
        renderer_prefs.active_selection_bg_color,
        renderer_prefs.active_selection_fg_color,
        renderer_prefs.inactive_selection_bg_color,
        renderer_prefs.inactive_selection_fg_color);
    didInvalidateRect(gfx::Rect(size_));
  }
#endif
}

Project: Chrome

void RenderView::OnSetWindowVisibility(bool visible) {
  std::set<WebPluginDelegateProxy*>::iterator plugin_it;
  for (plugin_it = plugin_delegates_.begin();
       plugin_it != plugin_delegates_.end(); ++plugin_it) {
    (*plugin_it)->SetContainerVisibility(visible);
  }
}

Project: Chrome

void RenderView::OnSetZoomLevelForLoadingURL(const GURL& url,
                                             int zoom_level) {
  host_zoom_levels_[url] = zoom_level;
}

Project: Chrome

void RenderView::OnSetupDevToolsClient() {
  DCHECK(!devtools_client_.get());
  devtools_client_.reset(new DevToolsClient(this));
}

Project: Chrome

void RenderView::OnShouldClose() {
  bool should_close = webview()->dispatchBeforeUnloadEvent();
  Send(new ViewHostMsg_ShouldClose_ACK(routing_id_, should_close));
}

Project: Chrome

void RenderView::OnStop() {
  if (webview())
    webview()->mainFrame()->stopLoading();
}

Project: Chrome

void RenderView::OnStopFinding(const ViewMsg_StopFinding_Params& params) {
  WebView* view = webview();
  if (!view)
    return;

  WebDocument doc = view->mainFrame()->document();
  if (doc.isPluginDocument()) {
    GetWebPluginFromPluginDocument()->stopFind();
    return;
  }

  bool clear_selection =
      params.action == ViewMsg_StopFinding_Params::kClearSelection;
  if (clear_selection)
    view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"));

  WebFrame* frame = view->mainFrame();
  while (frame) {
    frame->stopFinding(clear_selection);
    frame = frame->traverseNext(false);
  }

  if (params.action == ViewMsg_StopFinding_Params::kActivateSelection) {
    WebFrame* focused_frame = view->focusedFrame();
    if (focused_frame) {
      WebDocument doc = focused_frame->document();
      if (!doc.isNull()) {
        WebNode node = doc.focusedNode();
        if (!node.isNull())
          node.simulateClick();
      }
    }
  }
}

Project: Chrome

void RenderView::OnThemeChanged() {
#if defined(OS_WIN)
  gfx::NativeTheme::instance()->CloseHandles();
  didInvalidateRect(gfx::Rect(size_));
#else  // defined(OS_WIN)
  NOTIMPLEMENTED();
#endif
}

Project: Chrome

void RenderView::OnToggleSpellCheck() {
  if (!webview())
    return;

  WebFrame* frame = webview()->focusedFrame();
  frame->enableContinuousSpellChecking(
      !frame->isContinuousSpellCheckingEnabled());
}

Project: Chrome

void RenderView::OnToggleSpellPanel(bool is_currently_visible) {
  if (!webview())
    return;
  spelling_panel_visible_ = is_currently_visible;
  webview()->focusedFrame()->executeCommand(
      WebString::fromUTF8("ToggleSpellPanel"));
}

Project: Chrome

void RenderView::OnTranslatePage(int page_id,
                                 const std::string& translate_script,
                                 const std::string& source_lang,
                                 const std::string& target_lang) {
  translate_helper_.TranslatePage(page_id, source_lang, target_lang,
                                  translate_script);
}

Project: Chrome

void RenderView::OnUndo() {
  if (!webview())
    return;

  webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Undo"));
  UserMetricsRecordAction("Undo");
}

Project: Chrome

void RenderView::OnUpdateBrowserWindowId(int window_id) {
  browser_window_id_ = window_id;
}

Project: Chrome

void RenderView::OnUpdateTargetURLAck() {
  if (target_url_status_ == TARGET_PENDING) {
    Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
                                         pending_target_url_));
  }

  target_url_status_ = TARGET_NONE;
}

Project: Chrome

void RenderView::OnUpdateWebPreferences(const WebPreferences& prefs) {
  webkit_preferences_ = prefs;
  webkit_preferences_.Apply(webview());
}

Project: Chrome

void RenderView::OnWasHidden() {
  RenderWidget::OnWasHidden();

  std::set<WebPluginDelegateProxy*>::iterator plugin_it;
  for (plugin_it = plugin_delegates_.begin();
       plugin_it != plugin_delegates_.end(); ++plugin_it) {
    (*plugin_it)->SetContainerVisibility(false);
  }
}

Project: Chrome

void RenderView::OnWindowFrameChanged(const gfx::Rect& window_frame,
                                      const gfx::Rect& view_frame) {
  std::set<WebPluginDelegateProxy*>::iterator plugin_it;
  for (plugin_it = plugin_delegates_.begin();
       plugin_it != plugin_delegates_.end(); ++plugin_it) {
    (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
  }
}

Project: Chrome

void RenderView::OnZoom(PageZoom::Function function) {
  if (!webview())  // Not sure if this can happen, but no harm in being safe.
    return;

  webview()->hidePopups();

  int zoom_level = webview()->zoomLevel();
  int new_zoom_level = webview()->setZoomLevel(false,
      (function == PageZoom::RESET) ? 0 : (zoom_level + function));

  Send(new ViewHostMsg_DidZoomURL(
      GURL(webview()->mainFrame()->url()), new_zoom_level));
}

Project: Chrome

void RenderView::OpenURL(
    const GURL& url, const GURL& referrer, WebNavigationPolicy policy) {
  Send(new ViewHostMsg_OpenURL(
      routing_id_, url, referrer, NavigationPolicyToDisposition(policy)));
}

Project: Chrome

static bool PaintViewIntoCanvas(WebView* view,
                                skia::PlatformCanvas& canvas) {
  view->layout();
  const WebSize& size = view->size();

  if (!canvas.initialize(size.width, size.height, true))
    return false;

  view->paint(webkit_glue::ToWebCanvas(&canvas),
              WebRect(0, 0, size.width, size.height));

  return true;
}

Project: Chrome

  PendingFileChooser(const ViewHostMsg_RunFileChooser_Params& p,
                     WebFileChooserCompletion* c)
      : params(p),
        completion(c) {
  }

Project: Chrome

void RenderView::PluginCrashed(const FilePath& plugin_path) {
  Send(new ViewHostMsg_CrashedPlugin(routing_id_, plugin_path));
}

Project: Chrome

void RenderView::Print(WebFrame* frame, bool script_initiated) {
  DCHECK(frame);
  if (print_helper_.get() == NULL) {
    print_helper_.reset(new PrintWebViewHelper(this));
  }
  print_helper_->Print(frame, script_initiated);
}

Project: Chrome

void RenderView::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
  plugin_delegates_.insert(delegate);
}

Project: Chrome

RenderView::RenderView(RenderThreadBase* render_thread,
                       const WebPreferences& webkit_preferences,
                       int64 session_storage_namespace_id)
    : RenderWidget(render_thread, WebKit::WebPopupTypeNone),
      webkit_preferences_(webkit_preferences),
      send_content_state_immediately_(false),
      enabled_bindings_(0),
      send_preferred_size_changes_(false),
      script_can_close_(true),
      is_loading_(false),
      navigation_gesture_(NavigationGestureUnknown),
      opened_by_user_gesture_(true),
      opener_suppressed_(false),
      page_id_(-1),
      last_page_id_sent_to_browser_(-1),
      last_indexed_page_id_(-1),
      last_top_level_navigation_page_id_(-1),
      history_list_offset_(-1),
      history_list_length_(0),
      has_unload_listener_(false),
#if defined(OS_MACOSX)
      has_document_tag_(false),
#endif
      document_tag_(0),
      cross_origin_access_count_(0),
      same_origin_access_count_(0),
      target_url_status_(TARGET_NONE),
      spelling_panel_visible_(false),
      view_type_(ViewType::INVALID),
      browser_window_id_(-1),
      ALLOW_THIS_IN_INITIALIZER_LIST(pepper_delegate_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(translate_helper_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(password_autocomplete_manager_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(autofill_helper_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(cookie_jar_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          notification_provider_(new NotificationProvider(this))),
      session_storage_namespace_id_(session_storage_namespace_id),
      decrement_shared_popup_at_destruction_(false) {
  ClearBlockedContentSettings();
}

Project: Chrome

void RenderView::ReportNoFindInPageResults(int request_id) {
  Send(new ViewHostMsg_Find_Reply(routing_id_,
                                  request_id,
                                  0,
                                  gfx::Rect(),
                                  0,
                                  true));
}

Project: Chrome

bool RenderView::RunJavaScriptMessage(int type,
                                      const std::wstring& message,
                                      const std::wstring& default_value,
                                      const GURL& frame_url,
                                      std::wstring* result) {
  bool success = false;
  std::wstring result_temp;
  if (!result)
    result = &result_temp;

  SendAndRunNestedMessageLoop(new ViewHostMsg_RunJavaScriptMessage(
      routing_id_, message, default_value, frame_url, type, &success, result));
  return success;
}

Project: Chrome

bool RenderView::ScheduleFileChooser(
    const ViewHostMsg_RunFileChooser_Params& params,
    WebFileChooserCompletion* completion) {
  static const size_t kMaximumPendingFileChooseRequests = 4;
  if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
    return false;
  }

  file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
      new PendingFileChooser(params, completion)));
  if (file_chooser_completions_.size() == 1) {
    Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
  }
  return true;
}

Project: Chrome

bool RenderView::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
  if (RenderThread::current())  // Will be NULL during unit tests.
    RenderThread::current()->DoNotNotifyWebKitOfModalLoop();

  message->EnableMessagePumping();  // Runs a nested message loop.
  return Send(message);
}

Project: Chrome

void RenderView::SetContentSettings(const ContentSettings& settings) {
  current_content_settings_ = settings;
}

Project: Chrome

void RenderView::SetNextPageID(int32 next_page_id) {
  DCHECK_EQ(next_page_id_, 1);
  DCHECK(next_page_id >= next_page_id_);
  next_page_id_ = next_page_id;
}

Project: Chrome

void RenderView::ShowModalHTMLDialogForPlugin(
    const GURL& url,
    const gfx::Size& size,
    const std::string& json_arguments,
    std::string* json_retval) {
  SendAndRunNestedMessageLoop(new ViewHostMsg_ShowModalHTMLDialog(
      routing_id_, url, size.width(), size.height(), json_arguments,
      json_retval));
}

Project: Chrome

void RenderView::StartNavStateSyncTimerIfNecessary() {
  int delay;
  if (send_content_state_immediately_)
    delay = 0;
  else if (is_hidden())
    delay = kDelaySecondsForContentStateSyncHidden;
  else
    delay = kDelaySecondsForContentStateSync;

  if (nav_state_sync_timer_.IsRunning()) {
    if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
      return;
    nav_state_sync_timer_.Stop();
  }

  nav_state_sync_timer_.Start(
      TimeDelta::FromSeconds(delay), this, &RenderView::SyncNavigationState);
}

Project: Chrome

void RenderView::SyncNavigationState() {
  if (!webview())
    return;

  const WebHistoryItem& item = webview()->mainFrame()->currentHistoryItem();
  if (item.isNull())
    return;

  Send(new ViewHostMsg_UpdateState(
      routing_id_, page_id_, webkit_glue::HistoryItemToString(item)));
}

Project: Chrome

void RenderView::UnregisterPluginDelegate(WebPluginDelegateProxy* delegate) {
  plugin_delegates_.erase(delegate);
}

Project: Chrome

void RenderView::UpdateSessionHistory(WebFrame* frame) {
  if (page_id_ == -1)
    return;

  const WebHistoryItem& item =
      webview()->mainFrame()->previousHistoryItem();
  if (item.isNull())
    return;

  Send(new ViewHostMsg_UpdateState(
      routing_id_, page_id_, webkit_glue::HistoryItemToString(item)));
}

Project: Chrome

void RenderView::UpdateTitle(WebFrame* frame, const string16& title) {
  if (!frame->parent()) {
    Send(new ViewHostMsg_UpdateTitle(
        routing_id_,
        page_id_,
        UTF16ToWideHack(title.length() > chrome::kMaxTitleChars ?
            title.substr(0, chrome::kMaxTitleChars) : title)));
  }
}

Project: Chrome

void RenderView::UpdateURL(WebFrame* frame) {
  WebDataSource* ds = frame->dataSource();
  DCHECK(ds);

  const WebURLRequest& request = ds->request();
  const WebURLRequest& original_request = ds->originalRequest();
  const WebURLResponse& response = ds->response();

  NavigationState* navigation_state = NavigationState::FromDataSource(ds);
  DCHECK(navigation_state);

  ViewHostMsg_FrameNavigate_Params params;
  params.http_status_code = response.httpStatusCode();
  params.is_post = false;
  params.page_id = page_id_;
  params.is_content_filtered = response.isContentFiltered();
  if (!navigation_state->security_info().empty()) {
    DCHECK(response.securityInfo().isEmpty());
    params.security_info = navigation_state->security_info();
  } else {
    params.security_info = response.securityInfo();
  }

  if (ds->hasUnreachableURL()) {
    params.url = ds->unreachableURL();
  } else {
    params.url = request.url();
  }

  GetRedirectChain(ds, &params.redirects);
  params.should_update_history = !ds->hasUnreachableURL() &&
      !response.isMultipartPayload();

  params.searchable_form_url = navigation_state->searchable_form_url();
  params.searchable_form_encoding =
      navigation_state->searchable_form_encoding();

  const PasswordForm* password_form_data =
      navigation_state->password_form_data();
  if (password_form_data)
    params.password_form = *password_form_data;

  params.gesture = navigation_gesture_;
  navigation_gesture_ = NavigationGestureUnknown;

  if (!frame->parent()) {

    ClearBlockedContentSettings();

    HostContentSettings::iterator host_content_settings =
        host_content_settings_.find(GURL(request.url()));
    if (host_content_settings != host_content_settings_.end()) {
      SetContentSettings(host_content_settings->second);

      host_content_settings_.erase(host_content_settings);
    } else if (frame->opener()) {
      if (WebView* opener_view = frame->opener()->view()) {
        RenderView* opener = FromWebView(opener_view);
        SetContentSettings(opener->current_content_settings_);
      }
    }

    HostZoomLevels::iterator host_zoom =
        host_zoom_levels_.find(GURL(request.url()));
    if (host_zoom != host_zoom_levels_.end()) {
      webview()->setZoomLevel(false, host_zoom->second);
      host_zoom_levels_.erase(host_zoom);
    }

    params.contents_mime_type = ds->response().mimeType().utf8();

    params.transition = navigation_state->transition_type();
    if (!PageTransition::IsMainFrame(params.transition)) {
      params.transition = PageTransition::LINK;
    }

    if (completed_client_redirect_src_.is_valid()) {
      DCHECK(completed_client_redirect_src_ == params.redirects[0]);
      params.referrer = completed_client_redirect_src_;
      params.transition = static_cast<PageTransition::Type>(
          params.transition | PageTransition::CLIENT_REDIRECT);
    } else {
      params.referrer = GURL(
          original_request.httpHeaderField(WebString::fromUTF8("Referer")));
    }

    string16 method = request.httpMethod();
    if (EqualsASCII(method, "POST"))
      params.is_post = true;

    UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
                               webkit_glue::GetGlyphPageCount());

    Send(new ViewHostMsg_FrameNavigate(routing_id_, params));
  } else {
    if (page_id_ > last_page_id_sent_to_browser_)
      params.transition = PageTransition::MANUAL_SUBFRAME;
    else
      params.transition = PageTransition::AUTO_SUBFRAME;

    Send(new ViewHostMsg_FrameNavigate(routing_id_, params));
  }

  last_page_id_sent_to_browser_ =
      std::max(last_page_id_sent_to_browser_, page_id_);

  navigation_state->set_transition_type(PageTransition::LINK);

  if (accessibility_.get()) {
    accessibility_->clear();
    accessibility_.reset();
  }
}

Project: Chrome

static bool UrlMatchesPermissions(
    const GURL& url, const std::vector<URLPattern>& host_permissions) {
  for (size_t i = 0; i < host_permissions.size(); ++i) {
    if (host_permissions[i].MatchesUrl(url))
      return true;
  }

  return false;
}

Project: Chrome

void RenderView::WillDestroyPluginWindow(gfx::PluginWindowHandle window) {
#if defined(USE_X11)
  RenderThread::current()->Send(new ViewHostMsg_DestroyPluginContainer(
      routing_id(), window));
#endif
  CleanupWindowInPluginMoves(window);
}

Project: Chrome

bool RenderView::acceptsLoadDrops() {
  return renderer_preferences_.can_accept_load_drops;
}

Project: Chrome

bool RenderView::allowDatabase(
    WebFrame* frame, const WebString& name, const WebString& display_name,
    unsigned long estimated_size) {
  WebSecurityOrigin origin = frame->securityOrigin();
  if (origin.isEmpty())
    return false;  // Uninitialized document?

  bool result;
  if (!Send(new ViewHostMsg_AllowDatabase(routing_id_,
      origin.toString().utf8(), name, display_name, estimated_size, &result)))
    return false;
  Send(new ViewHostMsg_WebDatabaseAccessed(routing_id_,
                                           GURL(origin.toString().utf8()),
                                           name,
                                           display_name,
                                           estimated_size,
                                           !result));
  return result;
}

Project: Chrome

bool RenderView::allowImages(WebFrame* frame, bool enabled_per_settings) {
  if (enabled_per_settings &&
      AllowContentType(CONTENT_SETTINGS_TYPE_IMAGES))
    return true;

  if (IsWhitelistedForContentSettings(frame))
    return true;

  DidBlockContentType(CONTENT_SETTINGS_TYPE_IMAGES);
  return false;  // Other protocols fall through here.
}

Project: Chrome

bool RenderView::allowScript(WebFrame* frame, bool enabled_per_settings) {
  if (enabled_per_settings &&
      AllowContentType(CONTENT_SETTINGS_TYPE_JAVASCRIPT))
    return true;

  if (IsWhitelistedForContentSettings(frame))
    return true;

  return false;  // Other protocols fall through here.
}

Project: Chrome

void RenderView::assignIdentifierToRequest(
    WebFrame* frame, unsigned identifier, const WebURLRequest& request) {
}

Project: Chrome

WebString RenderView::autoCorrectWord(const WebKit::WebString& word) {
  string16 autocorrect_word;
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kExperimentalSpellcheckerFeatures)) {
    EnsureDocumentTag();
    RenderThread* thread = RenderThread::current();
    if (thread) {
      autocorrect_word =
          thread->spellchecker()->GetAutoCorrectionWord(
              word, document_tag_);
    }
  }
  return autocorrect_word;
}

Project: Chrome

bool RenderView::canHandleRequest(
    WebFrame* frame, const WebURLRequest& request) {
  return true;
}

Project: Chrome

void RenderView::closeWidgetSoon() {
  translate_helper_.CancelPendingTranslation();

  if (script_can_close_)
    RenderWidget::closeWidgetSoon();
}

Project: Chrome

WebCookieJar* RenderView::cookieJar() {
   return &cookie_jar_;
 }

Project: Chrome

WebApplicationCacheHost* RenderView::createApplicationCacheHost(
    WebFrame* frame, WebApplicationCacheHostClient* client) {
  return new RendererWebApplicationCacheHostImpl(
      FromWebView(frame->view()), client,
      RenderThread::current()->appcache_dispatcher()->backend_proxy());
}

Project: Chrome

WebMediaPlayer* RenderView::createMediaPlayer(
    WebFrame* frame, WebMediaPlayerClient* client) {
  scoped_refptr<media::FilterFactoryCollection> factory =
      new media::FilterFactoryCollection();
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (!cmd_line->HasSwitch(switches::kDisableAudio)) {
    factory->AddFactory(
        AudioRendererImpl::CreateFactory(audio_message_filter()));
  }

  if (cmd_line->HasSwitch(switches::kEnableAcceleratedDecoding) &&
      cmd_line->HasSwitch(switches::kEnableAcceleratedCompositing)) {
    factory->AddFactory(
        media::IpcVideoDecoder::CreateFactory(MessageLoop::current()));
  }

  WebApplicationCacheHostImpl* appcache_host =
      WebApplicationCacheHostImpl::FromFrame(frame);

  webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory =
      new webkit_glue::MediaResourceLoaderBridgeFactory(
          GURL(),  // referrer
          "null",  // frame origin
          "null",  // main_frame_origin
          base::GetCurrentProcId(),
          appcache_host ? appcache_host->host_id() : appcache::kNoHostId,
          routing_id());

  media::FilterFactory* simple_data_source_factory =
      webkit_glue::SimpleDataSource::CreateFactory(MessageLoop::current(),
                                                   bridge_factory);
  media::FilterFactory* buffered_data_source_factory =
      webkit_glue::BufferedDataSource::CreateFactory(MessageLoop::current(),
                                                     bridge_factory);
  if (cmd_line->HasSwitch(switches::kSimpleDataSource)) {
    factory->AddFactory(simple_data_source_factory);
    factory->AddFactory(buffered_data_source_factory);
  } else {
    factory->AddFactory(buffered_data_source_factory);
    factory->AddFactory(simple_data_source_factory);
  }

  webkit_glue::WebVideoRendererFactoryFactory* factory_factory = NULL;
  if (cmd_line->HasSwitch(switches::kEnableVideoLayering)) {
    factory_factory = new IPCVideoRenderer::FactoryFactory(routing_id_);
  } else {
    bool pts_logging = cmd_line->HasSwitch(switches::kEnableVideoLogging);
    factory_factory =
        new webkit_glue::VideoRendererImpl::FactoryFactory(pts_logging);
  }

  return new webkit_glue::WebMediaPlayerImpl(client, factory, factory_factory);
}

Project: Chrome

WebPlugin* RenderView::createPlugin(WebFrame* frame,
                                    const WebPluginParams& params) {
  bool found = false;
  WebPluginInfo info;
  GURL url(params.url);
  std::string actual_mime_type;
  Send(new ViewHostMsg_GetPluginInfo(url,
                                     frame->top()->url(),
                                     params.mimeType.utf8(),
                                     &found,
                                     &info,
                                     &actual_mime_type));

  if (!found)
    return NULL;

  scoped_ptr<PluginGroup> group(PluginGroup::FindHardcodedPluginGroup(info));
  group->AddPlugin(info, 0);

  if (!info.enabled) {
    if (CommandLine::ForCurrentProcess()->HasSwitch(
            switches::kDisableOutdatedPlugins) &&
        group->IsVulnerable()) {
      Send(new ViewHostMsg_DisabledOutdatedPlugin(routing_id_,
                                                  group->GetGroupName(),
                                                  GURL(group->GetUpdateURL())));
      return CreatePluginPlaceholder(frame, params, group.get());
    }
    return NULL;
  }

  if (info.path.value() != kDefaultPluginLibraryName) {
    if (!AllowContentType(CONTENT_SETTINGS_TYPE_PLUGINS)) {
      DCHECK(CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableClickToPlay));
      didNotAllowPlugins(frame);
      return CreatePluginPlaceholder(frame, params, NULL);
    }
    scoped_refptr<pepper::PluginModule> pepper_module =
        PepperPluginRegistry::GetInstance()->GetModule(info.path);
    if (pepper_module)
      return CreatePepperPlugin(frame, params, info.path, pepper_module.get());
    if (CommandLine::ForCurrentProcess()->HasSwitch(
            switches::kBlockNonSandboxedPlugins)) {
      Send(new ViewHostMsg_NonSandboxedPluginBlocked(routing_id_,
                                                     group->GetGroupName()));
      return CreatePluginPlaceholder(frame, params, NULL);
    }
  }
  return CreateNPAPIPlugin(frame, params, info.path, actual_mime_type);
}

Project: Chrome

WebWidget* RenderView::createPopupMenu(WebKit::WebPopupType popup_type) {
  RenderWidget* widget = RenderWidget::Create(routing_id_,
                                              render_thread_,
                                              popup_type);
  return widget->webwidget();
}

Project: Chrome

WebStorageNamespace* RenderView::createSessionStorageNamespace(unsigned quota) {
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess))
    return WebStorageNamespace::createSessionStorageNamespace(quota);
  CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
  return new RendererWebStorageNamespaceImpl(DOM_STORAGE_SESSION,
                                             session_storage_namespace_id_);
}

Project: Chrome

WebSharedWorker* RenderView::createSharedWorker(
    WebFrame* frame, const WebURL& url, const WebString& name,
    unsigned long long document_id) {

  int route_id = MSG_ROUTING_NONE;
  bool exists = false;
  bool url_mismatch = false;
  ViewHostMsg_CreateWorker_Params params;
  params.url = url;
  params.is_shared = true;
  params.name = name;
  params.document_id = document_id;
  params.render_view_route_id = routing_id_;
  params.route_id = MSG_ROUTING_NONE;
  params.parent_appcache_host_id = 0;
  params.script_resource_appcache_id = 0;
  Send(new ViewHostMsg_LookupSharedWorker(
      params, &exists, &route_id, &url_mismatch));
  if (url_mismatch) {
    return NULL;
  } else {
    return new WebSharedWorkerProxy(RenderThread::current(),
                                    document_id,
                                    exists,
                                    route_id,
                                    routing_id_);
  }
}

Project: Chrome

WebView* RenderView::createView(
    WebFrame* creator,
    const WebWindowFeatures& features,
    const WebString& frame_name) {
  if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups)
    return NULL;

  script_can_close_ = false;

  ViewHostMsg_CreateWindow_Params params;
  params.opener_id = routing_id_;
  params.user_gesture = creator->isProcessingUserGesture();
  params.window_container_type = WindowFeaturesToContainerType(features);
  params.session_storage_namespace_id = session_storage_namespace_id_;
  params.frame_name = frame_name;

  int32 routing_id = MSG_ROUTING_NONE;
  int64 cloned_session_storage_namespace_id;
  bool opener_suppressed = creator->willSuppressOpenerInNewFrame();

  render_thread_->Send(
      new ViewHostMsg_CreateWindow(params,
                                   &routing_id,
                                   &cloned_session_storage_namespace_id));
  if (routing_id == MSG_ROUTING_NONE)
    return NULL;

  RenderView* view = RenderView::Create(render_thread_,
                                        0,
                                        routing_id_,
                                        renderer_preferences_,
                                        webkit_preferences_,
                                        shared_popup_counter_,
                                        routing_id,
                                        cloned_session_storage_namespace_id,
                                        frame_name);
  view->opened_by_user_gesture_ = params.user_gesture;

  view->opener_suppressed_ = opener_suppressed;

  GURL creator_url(creator->securityOrigin().toString().utf8());
  if (!creator_url.is_valid() || !creator_url.IsStandard())
    creator_url = GURL();
  view->creator_url_ = creator_url;

  view->alternate_error_page_url_ = alternate_error_page_url_;

  return view->webview();
}

Project: Chrome

WebWorker* RenderView::createWorker(WebFrame* frame, WebWorkerClient* client) {
  WebApplicationCacheHostImpl* appcache_host =
      WebApplicationCacheHostImpl::FromFrame(frame);
  int appcache_host_id = appcache_host ? appcache_host->host_id() : 0;
  return new WebWorkerProxy(client, RenderThread::current(), routing_id_,
                            appcache_host_id);
}

Project: Chrome

WebNavigationPolicy RenderView::decidePolicyForNavigation(
    WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
    const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
  const GURL& url = request.url();

  if (renderer_preferences_.browser_handles_top_level_requests &&
      IsNonLocalTopLevelNavigation(url, frame, type)) {
    last_top_level_navigation_page_id_ = page_id_;
    GURL referrer(request.httpHeaderField(WebString::fromUTF8("Referer")));
    OpenURL(url, referrer, default_policy);
    return WebKit::WebNavigationPolicyIgnore;  // Suppress the load here.
  }

  bool is_content_initiated =
      NavigationState::FromDataSource(frame->provisionalDataSource())->
          is_content_initiated();

  if (default_policy == WebKit::WebNavigationPolicyCurrentTab &&
      is_content_initiated && frame->parent() == NULL &&
      type != WebKit::WebNavigationTypeFormSubmitted &&
      !url.SchemeIs(chrome::kAboutScheme)) {
    if (CrossesExtensionExtents(frame, url) ||
        BindingsPolicy::is_dom_ui_enabled(enabled_bindings_) ||
        frame->isViewSourceModeEnabled() ||
        url.SchemeIs(chrome::kViewSourceScheme)) {
      OpenURL(url, GURL(), default_policy);
      return WebKit::WebNavigationPolicyIgnore;  // Suppress the load here.
    }

    if (BindingsPolicy::is_extension_enabled(enabled_bindings_) &&
        IsNonLocalTopLevelNavigation(url, frame, type)) {
        OpenURL(url, GURL(), default_policy);
        return WebKit::WebNavigationPolicyIgnore;  // Suppress the load here.
    }
  }

  bool is_fork =
      GURL(frame->url()) == GURL(chrome::kAboutBlankURL) &&
      historyBackListCount() < 1 &&
      historyForwardListCount() < 1 &&
      frame->opener() == NULL &&
      frame->parent() == NULL &&
      is_content_initiated &&
      default_policy == WebKit::WebNavigationPolicyCurrentTab &&
      type == WebKit::WebNavigationTypeOther;

  bool is_noreferrer_and_blank_target =
      frame->parent() == NULL &&
      frame->url().isEmpty() &&
      historyBackListCount() < 1 &&
      historyForwardListCount() < 1 &&
      request.httpHeaderField(WebString::fromUTF8("Referer")).isNull() &&
      opener_suppressed_ &&
      frame->opener() == NULL &&
      frame->name().isNull() &&
      !creator_url_.is_empty() &&
      is_content_initiated &&
      default_policy == WebKit::WebNavigationPolicyCurrentTab &&
      type == WebKit::WebNavigationTypeOther;

  if (is_fork || is_noreferrer_and_blank_target) {
    OpenURL(url, GURL(), default_policy);
    return WebKit::WebNavigationPolicyIgnore;
  }

  return default_policy;
}

Project: Chrome

WebKit::WebDeviceOrientationClient* RenderView::deviceOrientationClient() {
  if (!device_orientation_dispatcher_.get())
    device_orientation_dispatcher_.reset(new DeviceOrientationDispatcher(this));
  return device_orientation_dispatcher_.get();
}

Project: Chrome

void RenderView::didAcceptAutoFillSuggestion(const WebKit::WebNode& node,
                                             const WebKit::WebString& value,
                                             const WebKit::WebString& label,
                                             int unique_id,
                                             unsigned index) {
  autofill_helper_.DidAcceptAutoFillSuggestion(node, value, label, unique_id,
                                               index);
}

Project: Chrome

void RenderView::didAcceptAutocompleteSuggestion(
    const WebKit::WebInputElement& user_element) {
#if defined(WEBKIT_BUG_41283_IS_FIXED)
  bool result = password_autocomplete_manager_.FillPassword(user_element);
  DCHECK(result);
#endif
}

Project: Chrome

void RenderView::didCancelClientRedirect(WebFrame* frame) {
}

Project: Chrome

void RenderView::didChangeAccessibilityObjectState(
    const WebKit::WebAccessibilityObject& acc_obj) {
#if defined(OS_WIN)
  if (!accessibility_.get())
    return;

  int acc_obj_id = accessibility_->addOrGetId(acc_obj);

  if (acc_obj_id >= 0)
    Send(new ViewHostMsg_AccessibilityObjectStateChange(routing_id_,
                                                        acc_obj_id));

#else  // defined(OS_WIN)
  NOTIMPLEMENTED();
#endif
}

Project: Chrome

void RenderView::didChangeContentsSize(WebFrame* frame, const WebSize& size) {
  CheckPreferredSize();
}

Project: Chrome

void RenderView::didChangeScrollOffset(WebFrame* frame) {
  StartNavStateSyncTimerIfNecessary();
}

Project: Chrome

void RenderView::didChangeSelection(bool is_empty_selection) {
#if defined(USE_X11)
  if (!handling_input_event_)
      return;
  if (!is_empty_selection) {
    const std::string& this_selection =
        webview()->focusedFrame()->selectionAsText().utf8();
    if (this_selection == last_selection_)
      return;

    Send(new ViewHostMsg_SelectionChanged(routing_id_,
         this_selection));
    last_selection_ = this_selection;
  } else {
    last_selection_.clear();
  }
#endif
}

Project: Chrome

void RenderView::didClearAutoFillSelection(const WebKit::WebNode& node) {
  autofill_helper_.DidClearAutoFillSelection(node);
}

Project: Chrome

void RenderView::didClearWindowObject(WebFrame* frame) {
  if (BindingsPolicy::is_dom_automation_enabled(enabled_bindings_))
    BindDOMAutomationController(frame);
  if (BindingsPolicy::is_dom_ui_enabled(enabled_bindings_)) {
    dom_ui_bindings_.set_message_sender(this);
    dom_ui_bindings_.set_routing_id(routing_id_);
    dom_ui_bindings_.BindToJavascript(frame, L"chrome");
  }
  if (BindingsPolicy::is_external_host_enabled(enabled_bindings_)) {
    external_host_bindings_.set_message_sender(this);
    external_host_bindings_.set_routing_id(routing_id_);
    external_host_bindings_.BindToJavascript(frame, L"externalHost");
  }
}

Project: Chrome

void RenderView::didCommitProvisionalLoad(WebFrame* frame,
                                          bool is_new_navigation) {
  NavigationState* navigation_state =
      NavigationState::FromDataSource(frame->dataSource());

  navigation_state->set_commit_load_time(Time::Now());
  if (is_new_navigation) {
    UpdateSessionHistory(frame);

    page_id_ = next_page_id_++;

    translate_helper_.CancelPendingTranslation();

    history_list_offset_++;
    if (history_list_offset_ >= chrome::kMaxSessionHistoryEntries)
      history_list_offset_ = chrome::kMaxSessionHistoryEntries - 1;
    history_list_length_ = history_list_offset_ + 1;

    MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        method_factory_.NewRunnableMethod(&RenderView::CapturePageInfo,
                                          page_id_, true),
        kDelayForForcedCaptureMs);
  } else {
    if (navigation_state->pending_page_id() != -1 &&
        navigation_state->pending_page_id() != page_id_ &&
        !navigation_state->request_committed()) {
      UpdateSessionHistory(frame);
      page_id_ = navigation_state->pending_page_id();

      history_list_offset_ = navigation_state->pending_history_list_offset();
    }
  }

  navigation_state->set_request_committed(true);

  UpdateURL(frame);

  completed_client_redirect_src_ = GURL();

  UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
}

Project: Chrome

void RenderView::didCompleteClientRedirect(
    WebFrame* frame, const WebURL& from) {
  if (!frame->parent())
    completed_client_redirect_src_ = from;
}

Project: Chrome

void RenderView::didCreateDataSource(WebFrame* frame, WebDataSource* ds) {
  bool content_initiated = !pending_navigation_state_.get();
  NavigationState* state = content_initiated ?
      NavigationState::CreateContentInitiated() :
      pending_navigation_state_.release();

  const WebURLRequest& original_request = ds->originalRequest();
  const WebURLRequest& request = ds->request();

  if (webview()) {
    if( WebFrame* old_frame = webview()->mainFrame()) {
      const GURL referrer(
          original_request.httpHeaderField(WebString::fromUTF8("Referer")));
      if (!referrer.is_empty() &&
          NavigationState::FromDataSource(
              old_frame->dataSource())->was_prefetcher()) {
        for (;old_frame;old_frame = old_frame->traverseNext(false)) {
          WebDataSource* old_frame_ds = old_frame->dataSource();
          if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
            state->set_was_referred_by_prefetcher(true);
            break;
          }
        }
      }
    }
  }

  if (content_initiated) {
    switch (request.cachePolicy()) {
      case WebURLRequest::UseProtocolCachePolicy:  // normal load.
        state->set_load_type(NavigationState::LINK_LOAD_NORMAL);
        break;
      case WebURLRequest::ReloadIgnoringCacheData:  // reload.
        state->set_load_type(NavigationState::LINK_LOAD_RELOAD);
        break;
      case WebURLRequest::ReturnCacheDataElseLoad:  // allow stale data.
        state->set_load_type(NavigationState::LINK_LOAD_CACHE_STALE_OK);
        break;
      case WebURLRequest::ReturnCacheDataDontLoad:  // Don't re-post.
        state->set_load_type(NavigationState::LINK_LOAD_CACHE_ONLY);
        break;
    }
  }

  state->set_user_script_idle_scheduler(
      new UserScriptIdleScheduler(this, frame));
  ds->setExtraData(state);
}

Project: Chrome

void RenderView::didCreateDocumentElement(WebFrame* frame) {
  if (RenderThread::current()) {  // Will be NULL during unit tests.
    RenderThread::current()->user_script_slave()->InjectScripts(
        frame, UserScript::DOCUMENT_START);
  }
  if (view_type_ == ViewType::EXTENSION_TOOLSTRIP ||
      view_type_ == ViewType::EXTENSION_MOLE) {
    InjectToolstripCSS();
    ExtensionProcessBindings::SetViewType(webview(), view_type_);
  }

  GURL url = frame->url();
  if (url.is_valid() && url.spec() != chrome::kAboutBlankURL) {
    if (frame == webview()->mainFrame())
      Send(new ViewHostMsg_DocumentAvailableInMainFrame(routing_id_));
  }
}

Project: Chrome

void RenderView::didCreateIsolatedScriptContext(WebFrame* frame) {
  EventBindings::HandleContextCreated(frame, true);
}

Project: Chrome

void RenderView::didCreateScriptContext(WebFrame* frame) {
  EventBindings::HandleContextCreated(frame, false);
}

Project: Chrome

void RenderView::didDestroyScriptContext(WebFrame* frame) {
  EventBindings::HandleContextDestroyed(frame);
}

Project: Chrome

void RenderView::didDisplayInsecureContent(WebFrame* frame) {
  Send(new ViewHostMsg_DidDisplayInsecureContent(routing_id_));
}

Project: Chrome

void RenderView::didExecuteCommand(const WebString& command_name) {
  const std::string& name = UTF16ToUTF8(command_name);
  if (StartsWithASCII(name, "Move", true) ||
      StartsWithASCII(name, "Insert", true) ||
      StartsWithASCII(name, "Delete", true))
    return;
  UserMetricsRecordAction(name);
}

Project: Chrome

void RenderView::didExhaustMemoryAvailableForScript(WebFrame* frame) {
  Send(new ViewHostMsg_JSOutOfMemory(routing_id_));
}

Project: Chrome

void RenderView::didFailResourceLoad(
    WebFrame* frame, unsigned identifier, const WebURLError& error) {
}

Project: Chrome

void RenderView::didFinishDocumentLoad(WebFrame* frame) {
  WebDataSource* ds = frame->dataSource();
  NavigationState* navigation_state = NavigationState::FromDataSource(ds);
  DCHECK(navigation_state);
  navigation_state->set_finish_document_load_time(Time::Now());

  Send(new ViewHostMsg_DocumentLoadedInFrame(routing_id_));

  autofill_helper_.FrameContentsAvailable(frame);
  password_autocomplete_manager_.SendPasswordForms(frame, false);

  UpdateEncoding(frame, frame->view()->pageEncoding().utf8());

  if (RenderThread::current()) {  // Will be NULL during unit tests.
    RenderThread::current()->user_script_slave()->InjectScripts(
        frame, UserScript::DOCUMENT_END);
  }

  navigation_state->user_script_idle_scheduler()->DidFinishDocumentLoad();
}

Project: Chrome

void RenderView::didHandleOnloadEvents(WebFrame* frame) {
  if (webview()->mainFrame() == frame)
    Send(new ViewHostMsg_DocumentOnLoadCompletedInMainFrame(routing_id_));
}

Project: Chrome

void RenderView::didLoadResourceFromMemoryCache(
    WebFrame* frame, const WebURLRequest& request,
    const WebURLResponse& response) {
  Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
      routing_id_,
      request.url(),
      frame->securityOrigin().toString().utf8(),
      frame->top()->securityOrigin().toString().utf8(),
      response.securityInfo()));
}

Project: Chrome

void RenderView::didNavigateWithinPage(
    WebFrame* frame, bool is_new_navigation) {

  NavigationState* state =
    NavigationState::FromDataSource(frame->dataSource());
  bool idle_scheduler_ran = state->user_script_idle_scheduler()->has_run();

  didCreateDataSource(frame, frame->dataSource());

  if (idle_scheduler_ran) {
    NavigationState* new_state =
        NavigationState::FromDataSource(frame->dataSource());
    new_state->user_script_idle_scheduler()->set_has_run(true);
  }

  didCommitProvisionalLoad(frame, is_new_navigation);

  UpdateTitle(frame, frame->view()->mainFrame()->dataSource()->pageTitle());
}

Project: Chrome

void RenderView::didNotAllowPlugins(WebKit::WebFrame* frame) {
  DidBlockContentType(CONTENT_SETTINGS_TYPE_PLUGINS);
}

Project: Chrome

void RenderView::didNotAllowScript(WebKit::WebFrame* frame) {
  DidBlockContentType(CONTENT_SETTINGS_TYPE_JAVASCRIPT);
}

Project: Chrome

void RenderView::didReceiveDocumentData(
    WebFrame* frame, const char* data, size_t data_len,
    bool& prevent_default) {
  NavigationState* navigation_state =
      NavigationState::FromDataSource(frame->dataSource());
  if (!navigation_state->postpone_loading_data())
    return;

  prevent_default = true;

  navigation_state->append_postponed_data(data, data_len);
  if (navigation_state->postponed_data().size() >= 512) {
    navigation_state->set_postpone_loading_data(false);
    frame->commitDocumentData(navigation_state->postponed_data().data(),
                              navigation_state->postponed_data().size());
    navigation_state->clear_postponed_data();
  }
}

Project: Chrome

void RenderView::didReceiveResponse(
    WebFrame* frame, unsigned identifier, const WebURLResponse& response) {

  SiteIsolationMetrics::LogMimeTypeForCrossOriginRequest(frame,
                                                         identifier,
                                                         response);

  if (!frame->provisionalDataSource() || frame->parent())
    return;

  if (frame->isViewSourceModeEnabled())
    return;

  NavigationState* navigation_state =
      NavigationState::FromDataSource(frame->provisionalDataSource());
  CHECK(navigation_state);

  navigation_state->set_was_fetched_via_spdy(response.wasFetchedViaSPDY());
  navigation_state->set_was_npn_negotiated(response.wasNpnNegotiated());
  navigation_state->set_was_alternate_protocol_available(
      response.wasAlternateProtocolAvailable());
  navigation_state->set_was_fetched_via_proxy(response.wasFetchedViaProxy());

  if (response.httpStatusCode() != 404)
    return;

  if (!GetAlternateErrorPageURL(response.url(), HTTP_404).is_valid())
    return;

  navigation_state->set_postpone_loading_data(true);
  navigation_state->clear_postponed_data();
}

Project: Chrome

void RenderView::didReceiveServerRedirectForProvisionalLoad(WebFrame* frame) {
  if (frame->parent())
    return;
  WebDataSource* data_source = frame->provisionalDataSource();
  if (!data_source) {
    NOTREACHED();
    return;
  }
  std::vector<GURL> redirects;
  GetRedirectChain(data_source, &redirects);
  if (redirects.size() >= 2) {
    Send(new ViewHostMsg_DidRedirectProvisionalLoad(routing_id_, page_id_,
        redirects[redirects.size() - 2], redirects.back()));
  }
}

Project: Chrome

void RenderView::didReceiveTitle(WebFrame* frame, const WebString& title) {
  UpdateTitle(frame, title);

  UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
}

Project: Chrome

void RenderView::didRunInsecureContent(
    WebFrame* frame, const WebSecurityOrigin& origin) {
  Send(new ViewHostMsg_DidRunInsecureContent(
      routing_id_,
      origin.toString().utf8()));
}

Project: Chrome

void RenderView::didSelectAutoFillSuggestion(const WebKit::WebNode& node,
                                             const WebKit::WebString& value,
                                             const WebKit::WebString& label,
                                             int unique_id) {
  autofill_helper_.DidSelectAutoFillSuggestion(node, value, label, unique_id);
}

Project: Chrome

void RenderView::didSerializeDataForFrame(const WebURL& frame_url,
    const WebCString& data,
    WebPageSerializerClient::PageSerializationStatus status) {
  Send(new ViewHostMsg_SendSerializedHtmlData(
    routing_id_,
    frame_url,
    data.data(),
    static_cast<int32>(status)));
}

Project: Chrome

void RenderView::didStopLoading() {
  if (!is_loading_) {
    DLOG(WARNING) << "DidStopLoading called while not loading";
    return;
  }

  is_loading_ = false;

  GURL favicon_url(webview()->mainFrame()->favIconURL());
  if (!favicon_url.is_empty())
    Send(new ViewHostMsg_UpdateFavIconURL(routing_id_, page_id_, favicon_url));

  AddGURLSearchProvider(webview()->mainFrame()->openSearchDescriptionURL(),
                        true);  // autodetected

  Send(new ViewHostMsg_DidStopLoading(routing_id_));

  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      method_factory_.NewRunnableMethod(&RenderView::CapturePageInfo, page_id_,
                                        false),
      kDelayForCaptureMs);
}

Project: Chrome

void RenderView::didUpdateCurrentHistoryItem(WebFrame* frame) {
  StartNavStateSyncTimerIfNecessary();
}

Project: Chrome

void RenderView::didUpdateInspectorSetting(const WebString& key,
                                           const WebString& value) {
  Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_,
                                              key.utf8(),
                                              value.utf8()));
}

Project: Chrome

void RenderView::enterFullscreenForNode(const WebKit::WebNode& node) {
  NOTIMPLEMENTED();
}

Project: Chrome

void RenderView::focusAccessibilityObject(
    const WebAccessibilityObject& acc_obj) {
#if defined(OS_WIN)
  if (!accessibility_.get())
    return;

  int acc_obj_id = accessibility_->addOrGetId(acc_obj);

  if (acc_obj_id >= 0)
    Send(new ViewHostMsg_AccessibilityFocusChange(routing_id_, acc_obj_id));

#else  // defined(OS_WIN)
  NOTIMPLEMENTED();
#endif
}

Project: Chrome

void RenderView::focusNext() {
  Send(new ViewHostMsg_TakeFocus(routing_id_, false));
}

Project: Chrome

void RenderView::focusPrevious() {
  Send(new ViewHostMsg_TakeFocus(routing_id_, true));
}

Project: Chrome

void RenderView::focusedNodeChanged(const WebNode& node) {
  Send(new ViewHostMsg_FocusedNodeChanged(routing_id_));
}

Project: Chrome

WebKit::WebGeolocationService* RenderView::geolocationService() {
  if (!geolocation_dispatcher_.get())
    geolocation_dispatcher_.reset(new GeolocationDispatcher(this));
  return geolocation_dispatcher_.get();
}

Project: Chrome

bool RenderView::handleCurrentKeyboardEvent() {
  if (edit_commands_.empty())
    return false;

  WebFrame* frame = webview()->focusedFrame();
  if (!frame)
    return false;

  EditCommands::iterator it = edit_commands_.begin();
  EditCommands::iterator end = edit_commands_.end();

  bool did_execute_command = false;
  for (; it != end; ++it) {
    if (!frame->executeCommand(WebString::fromUTF8(it->name),
                               WebString::fromUTF8(it->value)))
      break;
    did_execute_command = true;
  }

  return did_execute_command;
}

Project: Chrome

int RenderView::historyBackListCount() {
  return history_list_offset_ < 0 ? 0 : history_list_offset_;
}

Project: Chrome

int RenderView::historyForwardListCount() {
  return history_list_length_ - historyBackListCount() - 1;
}

Project: Chrome

bool RenderView::isSelectTrailingWhitespaceEnabled() {
#if defined(OS_WIN)
  return true;
#else
  return false;
#endif
}

Project: Chrome

bool RenderView::isShowingSpellingUI() {
  return spelling_panel_visible_;
}

Project: Chrome

void RenderView::logCrossFramePropertyAccess(WebFrame* frame,
                                             WebFrame* target,
                                             bool cross_origin,
                                             const WebString& property_name,
                                             unsigned long long event_id) {
  if (cross_origin)
    cross_origin_access_count_++;
  else
    same_origin_access_count_++;
}

Project: Chrome

void RenderView::navigateBackForwardSoon(int offset) {
  Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
}

Project: Chrome

WebKit::WebNotificationPresenter* RenderView::notificationPresenter() {
  return notification_provider_.get();
}

Project: Chrome

void RenderView::queryAutofillSuggestions(const WebNode& node,
                                          const WebString& name,
                                          const WebString& value) {
  autofill_helper_.QueryAutocompleteSuggestions(node, name, value);
}

Project: Chrome

void RenderView::removeAutofillSuggestions(const WebString& name,
                                           const WebString& value) {
  autofill_helper_.RemoveAutocompleteSuggestion(name, value);
}

Project: Chrome

void RenderView::reportFindInPageMatchCount(int request_id, int count,
                                            bool final_update) {
  if (queued_find_reply_message_.get()) {
    IPC::Message* msg = new ViewHostMsg_Find_Reply(
        routing_id_,
        request_id,
        count,
        gfx::Rect(),
        -1,  // Don't update active match ordinal.
        final_update);
    queued_find_reply_message_.reset(msg);
  } else {
    Send(new ViewHostMsg_Find_Reply(
        routing_id_,
        request_id,
        count,
        gfx::Rect(),
        -1,  // Don't update active match ordinal.
        final_update));
  }
}

Project: Chrome

void RenderView::reportFindInPageSelection(int request_id,
                                           int active_match_ordinal,
                                           const WebRect& selection_rect) {
  Send(new ViewHostMsg_Find_Reply(routing_id_,
                                  request_id,
                                  -1,
                                  selection_rect,
                                  active_match_ordinal,
                                  false));
}

Project: Chrome

bool RenderView::runFileChooser(
    const WebKit::WebFileChooserParams& params,
    WebFileChooserCompletion* chooser_completion) {
  ViewHostMsg_RunFileChooser_Params ipc_params;
  ipc_params.mode = params.multiSelect ?
      ViewHostMsg_RunFileChooser_Params::OpenMultiple :
      ViewHostMsg_RunFileChooser_Params::Open;
  ipc_params.title = params.title;
  ipc_params.default_file_name =
      webkit_glue::WebStringToFilePath(params.initialValue);

  return ScheduleFileChooser(ipc_params, chooser_completion);
}

Project: Chrome

void RenderView::runModal() {
  DCHECK(did_show_) << "should already have shown the view";

  if (RenderThread::current())  // Will be NULL during unit tests.
    RenderThread::current()->DoNotSuspendWebKitSharedTimer();

  SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(routing_id_));
}

Project: Chrome

void RenderView::runModalAlertDialog(
    WebFrame* frame, const WebString& message) {
  RunJavaScriptMessage(MessageBoxFlags::kIsJavascriptAlert,
                       UTF16ToWideHack(message),
                       std::wstring(),
                       frame->url(),
                       NULL);
}

Project: Chrome

bool RenderView::runModalBeforeUnloadDialog(
    WebFrame* frame, const WebString& message) {
  bool success = false;
  std::wstring ignored_result;
  SendAndRunNestedMessageLoop(new ViewHostMsg_RunBeforeUnloadConfirm(
      routing_id_, frame->url(), UTF16ToWideHack(message), &success,
      &ignored_result));
  return success;
}

Project: Chrome

bool RenderView::runModalConfirmDialog(
    WebFrame* frame, const WebString& message) {
  return RunJavaScriptMessage(MessageBoxFlags::kIsJavascriptConfirm,
                              UTF16ToWideHack(message),
                              std::wstring(),
                              frame->url(),
                              NULL);
}

Project: Chrome

bool RenderView::runModalPromptDialog(
    WebFrame* frame, const WebString& message, const WebString& default_value,
    WebString* actual_value) {
  std::wstring result;
  bool ok = RunJavaScriptMessage(MessageBoxFlags::kIsJavascriptPrompt,
                                 UTF16ToWideHack(message),
                                 UTF16ToWideHack(default_value),
                                 frame->url(),
                                 &result);
  if (ok)
    actual_value->assign(WideToUTF16Hack(result));
  return ok;
}

Project: Chrome

void RenderView::setKeyboardFocusURL(const WebURL& url) {
  focus_url_ = GURL(url);
  UpdateTargetURL(focus_url_, mouse_over_url_);
}

Project: Chrome

void RenderView::setMouseOverURL(const WebURL& url) {
  mouse_over_url_ = GURL(url);
  UpdateTargetURL(mouse_over_url_, focus_url_);
}

Project: Chrome

void RenderView::setStatusText(const WebString& text) {
}

Project: Chrome

void RenderView::setToolTipText(const WebString& text, WebTextDirection hint) {
  Send(new ViewHostMsg_SetTooltipText(routing_id_, UTF16ToWideHack(text),
                                      hint));
}

Project: Chrome

void RenderView::show(WebNavigationPolicy policy) {
  DCHECK(!did_show_) << "received extraneous Show call";
  DCHECK(opener_id_ != MSG_ROUTING_NONE);

  if (did_show_)
    return;
  did_show_ = true;

  if (!opened_by_user_gesture_) {
    if (policy != WebKit::WebNavigationPolicyNewBackgroundTab)
      policy = WebKit::WebNavigationPolicyNewPopup;
  }

  Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
      NavigationPolicyToDisposition(policy), initial_pos_,
      opened_by_user_gesture_));
  SetPendingWindowRect(initial_pos_);
}

Project: Chrome

WebKit::WebSpeechInputController* RenderView::speechInputController(
    WebKit::WebSpeechInputListener* listener) {
  if (!speech_input_dispatcher_.get())
    speech_input_dispatcher_.reset(new SpeechInputDispatcher(this, listener));
  return speech_input_dispatcher_.get();
}

Project: Chrome

void RenderView::startDragging(const WebDragData& data,
                               WebDragOperationsMask mask,
                               const WebImage& image,
                               const WebPoint& imageOffset) {
#if WEBKIT_USING_SKIA
  SkBitmap bitmap(image.getSkBitmap());
#elif WEBKIT_USING_CG
  SkBitmap bitmap = gfx::CGImageToSkBitmap(image.getCGImageRef());
#endif

  Send(new ViewHostMsg_StartDragging(routing_id_,
                                     WebDropData(data),
                                     mask,
                                     bitmap,
                                     imageOffset));
}

Project: Chrome

void RenderView::textFieldDidBeginEditing(
    const WebKit::WebInputElement& element) {
#if defined(WEBKIT_BUG_41283_IS_FIXED)
  password_autocomplete_manager_.TextFieldDidBeginEditing(element);
#endif
}

Project: Chrome

void RenderView::textFieldDidChange(const WebKit::WebInputElement& element) {
#if defined(WEBKIT_BUG_41283_IS_FIXED)
  password_autocomplete_manager_.TextDidChangeInTextField(element);
#endif
}

Project: Chrome

void RenderView::textFieldDidEndEditing(
    const WebKit::WebInputElement& element) {
#if defined(WEBKIT_BUG_41283_IS_FIXED)
  password_autocomplete_manager_.TextFieldDidEndEditing(element);
#endif
}

Project: Chrome

void RenderView::textFieldDidReceiveKeyDown(
    const WebKit::WebInputElement& element,
    const WebKit::WebKeyboardEvent& event) {
#if defined(WEBKIT_BUG_41283_IS_FIXED)
  password_autocomplete_manager_.TextFieldHandlingKeyDown(element, event);
#endif
}

Project: Chrome

void RenderView::unableToImplementPolicyWithError(
    WebFrame*, const WebURLError&) {
  NOTREACHED();  // Since we said we can handle all requests.
}

Project: Chrome

void RenderView::updateSpellingUIWithMisspelledWord(const WebString& word) {
  Send(new ViewHostMsg_UpdateSpellingPanelWithMisspelledWord(routing_id_,
                                                             word));
}

Project: Chrome

WebKit::WebView* RenderView::webview() const {
  return static_cast<WebKit::WebView*>(webwidget());
}

Project: Chrome

void RenderView::willPerformClientRedirect(
    WebFrame* frame, const WebURL& from, const WebURL& to, double interval,
    double fire_time) {
}

Project: Chrome

void RenderView::willSendRequest(
    WebFrame* frame, unsigned identifier, WebURLRequest& request,
    const WebURLResponse& redirect_response) {
  WebFrame* top_frame = frame->top();
  if (!top_frame)
    top_frame = frame;
  WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
  WebDataSource* top_data_source = top_frame->dataSource();
  WebDataSource* data_source =
      provisional_data_source ? provisional_data_source : top_data_source;
  if (data_source) {
    NavigationState* state = NavigationState::FromDataSource(data_source);
    if (state && state->is_cache_policy_override_set())
      request.setCachePolicy(state->cache_policy_override());
  }

  if (top_data_source) {
    NavigationState* state = NavigationState::FromDataSource(top_data_source);
    if (state && request.targetType() == WebURLRequest::TargetIsPrefetch)
      state->set_was_prefetcher(true);
  }

  request.setRequestorID(routing_id_);
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoReferrers))
    request.clearHTTPHeaderField("Referer");

  SiteIsolationMetrics::AddRequest(identifier, request.targetType());
}

Project: Chrome

void RenderView::willSendSubmitEvent(WebKit::WebFrame* frame,
    const WebKit::WebFormElement& form) {
  NavigationState* navigation_state =
      NavigationState::FromDataSource(frame->dataSource());
  navigation_state->set_password_form_data(
      PasswordFormDomManager::CreatePasswordForm(form));
}

Project: Chrome

RenderView::~RenderView() {
  if (decrement_shared_popup_at_destruction_)
    shared_popup_counter_->data--;

  for (ImageResourceFetcherSet::iterator i = image_fetchers_.begin();
       i != image_fetchers_.end(); ++i) {
    delete *i;
  }

  while (!file_chooser_completions_.empty()) {
    if (file_chooser_completions_.front()->completion) {
      file_chooser_completions_.front()->completion->didChooseFile(
          WebVector<WebString>());
    }
    file_chooser_completions_.pop_front();
  }

#if defined(OS_MACOSX)
  if (has_document_tag_)
    Send(new ViewHostMsg_DocumentWithTagClosed(routing_id_, document_tag_));
#endif

  render_thread_->RemoveFilter(audio_message_filter_);

#ifndef NDEBUG
  ViewMap* views = Singleton<ViewMap>::get();
  for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
    DCHECK_NE(this, it->second) << "Failed to call Close?";
#endif
}