1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/ui/webui/textfields_ui.h"
6
7#include <algorithm>
8#include <string>
9
10#include "base/memory/singleton.h"
11#include "base/string_piece.h"
12#include "base/values.h"
13#include "chrome/browser/profiles/profile.h"
14#include "chrome/common/jstemplate_builder.h"
15#include "chrome/common/url_constants.h"
16#include "content/browser/browser_thread.h"
17#include "content/browser/tab_contents/tab_contents.h"
18#include "grit/browser_resources.h"
19#include "ui/base/resource/resource_bundle.h"
20
21/**
22 * TextfieldsUIHTMLSource implementation.
23 */
24TextfieldsUIHTMLSource::TextfieldsUIHTMLSource()
25    : DataSource(chrome::kChromeUITextfieldsHost, MessageLoop::current()) {
26}
27
28void TextfieldsUIHTMLSource::StartDataRequest(const std::string& path,
29                                              bool is_incognito,
30                                              int request_id) {
31  const std::string full_html = ResourceBundle::GetSharedInstance()
32      .GetRawDataResource(IDR_TEXTFIELDS_HTML).as_string();
33
34  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);
35  html_bytes->data.resize(full_html.size());
36  std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin());
37
38  SendResponse(request_id, html_bytes);
39}
40
41std::string TextfieldsUIHTMLSource::GetMimeType(
42    const std::string& /* path */) const {
43  return "text/html";
44}
45
46TextfieldsUIHTMLSource::~TextfieldsUIHTMLSource() {}
47
48/**
49 * TextfieldsDOMHandler implementation.
50 */
51TextfieldsDOMHandler::TextfieldsDOMHandler() : WebUIMessageHandler() {}
52
53void TextfieldsDOMHandler::RegisterMessages() {
54  web_ui_->RegisterMessageCallback("textfieldValue",
55      NewCallback(this, &TextfieldsDOMHandler::HandleTextfieldValue));
56}
57
58void TextfieldsDOMHandler::HandleTextfieldValue(const ListValue* args) {
59  static_cast<TextfieldsUI*>(web_ui_)->set_text(
60      UTF16ToWideHack(ExtractStringValue(args)));
61}
62
63/**
64 * TextfieldsUI implementation.
65 */
66TextfieldsUI::TextfieldsUI(TabContents* contents) : WebUI(contents) {
67  TextfieldsDOMHandler* handler = new TextfieldsDOMHandler();
68  AddMessageHandler(handler);
69  handler->Attach(this);
70
71  TextfieldsUIHTMLSource* html_source = new TextfieldsUIHTMLSource();
72
73  // Set up the chrome://textfields/ source.
74  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source);
75}
76