Home | History | Annotate | Download | only in searchbox
      1 // Copyright 2012 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/renderer/searchbox/searchbox.h"
      6 
      7 #include <string>
      8 
      9 #include "base/strings/string_number_conversions.h"
     10 #include "base/strings/string_util.h"
     11 #include "base/strings/utf_string_conversions.h"
     12 #include "chrome/common/chrome_switches.h"
     13 #include "chrome/common/favicon/favicon_types.h"
     14 #include "chrome/common/favicon/favicon_url_parser.h"
     15 #include "chrome/common/omnibox_focus_state.h"
     16 #include "chrome/common/render_messages.h"
     17 #include "chrome/common/url_constants.h"
     18 #include "chrome/renderer/searchbox/searchbox_extension.h"
     19 #include "content/public/renderer/render_view.h"
     20 #include "grit/renderer_resources.h"
     21 #include "net/base/escape.h"
     22 #include "third_party/WebKit/public/web/WebDocument.h"
     23 #include "third_party/WebKit/public/web/WebFrame.h"
     24 #include "third_party/WebKit/public/web/WebView.h"
     25 #include "ui/base/resource/resource_bundle.h"
     26 #include "url/gurl.h"
     27 
     28 namespace {
     29 
     30 // The size of the InstantMostVisitedItem cache.
     31 const size_t kMaxInstantMostVisitedItemCacheSize = 100;
     32 
     33 // Returns true if items stored in |old_item_id_pairs| and |new_items| are
     34 // equal.
     35 bool AreMostVisitedItemsEqual(
     36     const std::vector<InstantMostVisitedItemIDPair>& old_item_id_pairs,
     37     const std::vector<InstantMostVisitedItem>& new_items) {
     38   if (old_item_id_pairs.size() != new_items.size())
     39     return false;
     40 
     41   for (size_t i = 0; i < new_items.size(); ++i) {
     42     if (new_items[i].url != old_item_id_pairs[i].second.url ||
     43         new_items[i].title != old_item_id_pairs[i].second.title) {
     44       return false;
     45     }
     46   }
     47   return true;
     48 }
     49 
     50 }  // namespace
     51 
     52 namespace internal {  // for testing
     53 
     54 // Parses |path| and fills in |id| with the InstantRestrictedID obtained from
     55 // the |path|. |render_view_id| is the ID of the associated RenderView.
     56 //
     57 // |path| is a pair of |render_view_id| and |restricted_id|, and it is
     58 // contained in Instant Extended URLs. A valid |path| is in the form:
     59 // <render_view_id>/<restricted_id>
     60 //
     61 // If the |path| is valid, returns true and fills in |id| with restricted_id
     62 // value. If the |path| is invalid, returns false and |id| is not set.
     63 bool GetInstantRestrictedIDFromPath(int render_view_id,
     64                                     const std::string& path,
     65                                     InstantRestrictedID* id) {
     66   // Check that the path is of Most visited item ID form.
     67   std::vector<std::string> tokens;
     68   if (Tokenize(path, "/", &tokens) != 2)
     69     return false;
     70 
     71   int view_id = 0;
     72   if (!base::StringToInt(tokens[0], &view_id) || view_id != render_view_id)
     73     return false;
     74   return base::StringToInt(tokens[1], id);
     75 }
     76 
     77 bool GetRestrictedIDFromFaviconUrl(int render_view_id,
     78                                    const GURL& url,
     79                                    std::string* favicon_params,
     80                                    InstantRestrictedID* rid) {
     81   // Strip leading slash.
     82   std::string raw_path = url.path();
     83   DCHECK_GT(raw_path.length(), (size_t) 0);
     84   DCHECK_EQ(raw_path[0], '/');
     85   raw_path = raw_path.substr(1);
     86 
     87   chrome::ParsedFaviconPath parsed;
     88   if (!chrome::ParseFaviconPath(raw_path, chrome::FAVICON, &parsed))
     89     return false;
     90 
     91   // The part of the URL which details the favicon parameters should be returned
     92   // so the favicon URL can be reconstructed, by replacing the restricted_id
     93   // with the actual URL from which the favicon is being requested.
     94   *favicon_params = raw_path.substr(0, parsed.path_index);
     95 
     96   // The part of the favicon URL which is supposed to contain the URL from
     97   // which the favicon is being requested (i.e., the page's URL) actually
     98   // contains a pair in the format "<view_id>/<restricted_id>". If the page's
     99   // URL is not in the expected format then the execution must be stopped,
    100   // returning |true|, indicating that the favicon URL should be translated
    101   // without the page's URL part, to prevent search providers from spoofing
    102   // the user's browsing history. For example, the following favicon URL
    103   // "chrome-search://favicon/http://www.secretsite.com" it is not in the
    104   // expected format "chrome-search://favicon/<view_id>/<restricted_id>" so
    105   // the pages's URL part ("http://www.secretsite.com") should be removed
    106   // entirely from the translated URL otherwise the search engine would know
    107   // if the user has visited that page (by verifying whether the favicon URL
    108   // returns an image for a particular page's URL); the translated URL in this
    109   // case would be "chrome-search://favicon/" which would simply return the
    110   // default favicon.
    111   std::string id_part = raw_path.substr(parsed.path_index);
    112   InstantRestrictedID id;
    113   if (!GetInstantRestrictedIDFromPath(render_view_id, id_part, &id))
    114     return true;
    115 
    116   *rid = id;
    117   return true;
    118 }
    119 
    120 // Parses a thumbnail |url| and fills in |id| with the InstantRestrictedID
    121 // obtained from the |url|. |render_view_id| is the ID of the associated
    122 // RenderView.
    123 //
    124 // Valid |url| forms:
    125 // chrome-search://thumb/<view_id>/<restricted_id>
    126 //
    127 // If the |url| is valid, returns true and fills in |id| with restricted_id
    128 // value. If the |url| is invalid, returns false and |id| is not set.
    129 bool GetRestrictedIDFromThumbnailUrl(int render_view_id,
    130                                      const GURL& url,
    131                                      InstantRestrictedID* id) {
    132   // Strip leading slash.
    133   std::string path = url.path();
    134   DCHECK_GT(path.length(), (size_t) 0);
    135   DCHECK_EQ(path[0], '/');
    136   path = path.substr(1);
    137 
    138   return GetInstantRestrictedIDFromPath(render_view_id, path, id);
    139 }
    140 
    141 }  // namespace internal
    142 
    143 SearchBox::SearchBox(content::RenderView* render_view)
    144     : content::RenderViewObserver(render_view),
    145       content::RenderViewObserverTracker<SearchBox>(render_view),
    146     app_launcher_enabled_(false),
    147     is_focused_(false),
    148     is_input_in_progress_(false),
    149     is_key_capture_enabled_(false),
    150     most_visited_items_cache_(kMaxInstantMostVisitedItemCacheSize),
    151     omnibox_font_(),
    152     omnibox_font_size_(12),
    153     query_(),
    154     start_margin_(0),
    155     width_(0) {
    156 }
    157 
    158 SearchBox::~SearchBox() {
    159 }
    160 
    161 void SearchBox::CountMouseover() {
    162   render_view()->Send(new ChromeViewHostMsg_CountMouseover(
    163       render_view()->GetRoutingID(), render_view()->GetPageId()));
    164 }
    165 
    166 void SearchBox::DeleteMostVisitedItem(
    167     InstantRestrictedID most_visited_item_id) {
    168   render_view()->Send(new ChromeViewHostMsg_SearchBoxDeleteMostVisitedItem(
    169       render_view()->GetRoutingID(), render_view()->GetPageId(),
    170       GetURLForMostVisitedItem(most_visited_item_id)));
    171 }
    172 
    173 bool SearchBox::GenerateFaviconURLFromTransientURL(const GURL& transient_url,
    174                                                    GURL* url) const {
    175   std::string favicon_params;
    176   InstantRestrictedID rid = -1;
    177   bool success = internal::GetRestrictedIDFromFaviconUrl(
    178       render_view()->GetRoutingID(), transient_url, &favicon_params, &rid);
    179   if (!success)
    180     return false;
    181 
    182   InstantMostVisitedItem item;
    183   std::string item_url;
    184   if (rid != -1 && GetMostVisitedItemWithID(rid, &item))
    185     item_url = item.url.spec();
    186 
    187   *url = GURL(base::StringPrintf("chrome-search://favicon/%s%s",
    188                                  favicon_params.c_str(),
    189                                  item_url.c_str()));
    190   return true;
    191 }
    192 
    193 bool SearchBox::GenerateThumbnailURLFromTransientURL(const GURL& transient_url,
    194                                                      GURL* url) const {
    195   InstantRestrictedID rid = 0;
    196   if (!internal::GetRestrictedIDFromThumbnailUrl(render_view()->GetRoutingID(),
    197                                                  transient_url, &rid)) {
    198     return false;
    199   }
    200 
    201   GURL most_visited_item_url(GetURLForMostVisitedItem(rid));
    202   if (most_visited_item_url.is_empty())
    203     return false;
    204   *url = GURL(base::StringPrintf("chrome-search://thumb/%s",
    205                                  most_visited_item_url.spec().c_str()));
    206   return true;
    207 }
    208 
    209 void SearchBox::GetMostVisitedItems(
    210     std::vector<InstantMostVisitedItemIDPair>* items) const {
    211   return most_visited_items_cache_.GetCurrentItems(items);
    212 }
    213 
    214 bool SearchBox::GetMostVisitedItemWithID(
    215     InstantRestrictedID most_visited_item_id,
    216     InstantMostVisitedItem* item) const {
    217   return most_visited_items_cache_.GetItemWithRestrictedID(most_visited_item_id,
    218                                                            item);
    219 }
    220 
    221 const ThemeBackgroundInfo& SearchBox::GetThemeBackgroundInfo() {
    222   return theme_info_;
    223 }
    224 
    225 void SearchBox::NavigateToURL(const GURL& url,
    226                               content::PageTransition transition,
    227                               WindowOpenDisposition disposition,
    228                               bool is_search_type) {
    229   render_view()->Send(new ChromeViewHostMsg_SearchBoxNavigate(
    230       render_view()->GetRoutingID(), render_view()->GetPageId(),
    231       url, transition, disposition, is_search_type));
    232 }
    233 
    234 void SearchBox::Paste(const string16& text) {
    235   render_view()->Send(new ChromeViewHostMsg_PasteAndOpenDropdown(
    236       render_view()->GetRoutingID(), render_view()->GetPageId(), text));
    237 }
    238 
    239 void SearchBox::SetVoiceSearchSupported(bool supported) {
    240   render_view()->Send(new ChromeViewHostMsg_SetVoiceSearchSupported(
    241       render_view()->GetRoutingID(), render_view()->GetPageId(), supported));
    242 }
    243 
    244 void SearchBox::StartCapturingKeyStrokes() {
    245   render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
    246       render_view()->GetRoutingID(), render_view()->GetPageId(),
    247       OMNIBOX_FOCUS_INVISIBLE));
    248 }
    249 
    250 void SearchBox::StopCapturingKeyStrokes() {
    251   render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
    252       render_view()->GetRoutingID(), render_view()->GetPageId(),
    253       OMNIBOX_FOCUS_NONE));
    254 }
    255 
    256 void SearchBox::UndoAllMostVisitedDeletions() {
    257   render_view()->Send(
    258       new ChromeViewHostMsg_SearchBoxUndoAllMostVisitedDeletions(
    259       render_view()->GetRoutingID(), render_view()->GetPageId()));
    260 }
    261 
    262 void SearchBox::UndoMostVisitedDeletion(
    263     InstantRestrictedID most_visited_item_id) {
    264   render_view()->Send(new ChromeViewHostMsg_SearchBoxUndoMostVisitedDeletion(
    265       render_view()->GetRoutingID(), render_view()->GetPageId(),
    266       GetURLForMostVisitedItem(most_visited_item_id)));
    267 }
    268 
    269 bool SearchBox::OnMessageReceived(const IPC::Message& message) {
    270   bool handled = true;
    271   IPC_BEGIN_MESSAGE_MAP(SearchBox, message)
    272     IPC_MESSAGE_HANDLER(ChromeViewMsg_DetermineIfPageSupportsInstant,
    273                         OnDetermineIfPageSupportsInstant)
    274     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFocusChanged, OnFocusChanged)
    275     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFontInformation,
    276                         OnFontInformationReceived)
    277     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMarginChange, OnMarginChange)
    278     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMostVisitedItemsChanged,
    279                         OnMostVisitedChanged)
    280     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxPromoInformation,
    281                         OnPromoInformationReceived)
    282     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetInputInProgress,
    283                         OnSetInputInProgress)
    284     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSubmit, OnSubmit)
    285     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxThemeChanged,
    286                         OnThemeChanged)
    287     IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch,
    288                         OnToggleVoiceSearch)
    289     IPC_MESSAGE_UNHANDLED(handled = false)
    290   IPC_END_MESSAGE_MAP()
    291   return handled;
    292 }
    293 
    294 void SearchBox::OnDetermineIfPageSupportsInstant() {
    295   if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
    296     bool result = extensions_v8::SearchBoxExtension::PageSupportsInstant(
    297         render_view()->GetWebView()->mainFrame());
    298     DVLOG(1) << render_view() << " PageSupportsInstant: " << result;
    299     render_view()->Send(new ChromeViewHostMsg_InstantSupportDetermined(
    300         render_view()->GetRoutingID(), render_view()->GetPageId(), result));
    301   }
    302 }
    303 
    304 void SearchBox::OnFocusChanged(OmniboxFocusState new_focus_state,
    305                                OmniboxFocusChangeReason reason) {
    306   bool key_capture_enabled = new_focus_state == OMNIBOX_FOCUS_INVISIBLE;
    307   if (key_capture_enabled != is_key_capture_enabled_) {
    308     // Tell the page if the key capture mode changed unless the focus state
    309     // changed because of TYPING. This is because in that case, the browser
    310     // hasn't really stopped capturing key strokes.
    311     //
    312     // (More practically, if we don't do this check, the page would receive
    313     // onkeycapturechange before the corresponding onchange, and the page would
    314     // have no way of telling whether the keycapturechange happened because of
    315     // some actual user action or just because they started typing.)
    316     if (reason != OMNIBOX_FOCUS_CHANGE_TYPING &&
    317         render_view()->GetWebView() &&
    318         render_view()->GetWebView()->mainFrame()) {
    319       is_key_capture_enabled_ = key_capture_enabled;
    320       DVLOG(1) << render_view() << " OnKeyCaptureChange";
    321       extensions_v8::SearchBoxExtension::DispatchKeyCaptureChange(
    322           render_view()->GetWebView()->mainFrame());
    323     }
    324   }
    325   bool is_focused = new_focus_state == OMNIBOX_FOCUS_VISIBLE;
    326   if (is_focused != is_focused_) {
    327     is_focused_ = is_focused;
    328     DVLOG(1) << render_view() << " OnFocusChange";
    329     if (render_view()->GetWebView() &&
    330         render_view()->GetWebView()->mainFrame()) {
    331       extensions_v8::SearchBoxExtension::DispatchFocusChange(
    332           render_view()->GetWebView()->mainFrame());
    333     }
    334   }
    335 }
    336 
    337 void SearchBox::OnFontInformationReceived(const string16& omnibox_font,
    338                                           size_t omnibox_font_size) {
    339   omnibox_font_ = omnibox_font;
    340   omnibox_font_size_ = omnibox_font_size;
    341 }
    342 
    343 void SearchBox::OnMarginChange(int margin, int width) {
    344   start_margin_ = margin;
    345   width_ = width;
    346   if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
    347     extensions_v8::SearchBoxExtension::DispatchMarginChange(
    348         render_view()->GetWebView()->mainFrame());
    349   }
    350 }
    351 
    352 void SearchBox::OnMostVisitedChanged(
    353     const std::vector<InstantMostVisitedItem>& items) {
    354   std::vector<InstantMostVisitedItemIDPair> last_known_items;
    355   GetMostVisitedItems(&last_known_items);
    356 
    357   if (AreMostVisitedItemsEqual(last_known_items, items))
    358     return;  // Do not send duplicate onmostvisitedchange events.
    359 
    360   most_visited_items_cache_.AddItems(items);
    361   if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
    362     extensions_v8::SearchBoxExtension::DispatchMostVisitedChanged(
    363         render_view()->GetWebView()->mainFrame());
    364   }
    365 }
    366 
    367 void SearchBox::OnPromoInformationReceived(bool is_app_launcher_enabled) {
    368   app_launcher_enabled_ = is_app_launcher_enabled;
    369 }
    370 
    371 void SearchBox::OnSetInputInProgress(bool is_input_in_progress) {
    372   if (is_input_in_progress_ != is_input_in_progress) {
    373     is_input_in_progress_ = is_input_in_progress;
    374     DVLOG(1) << render_view() << " OnSetInputInProgress";
    375     if (render_view()->GetWebView() &&
    376         render_view()->GetWebView()->mainFrame()) {
    377       if (is_input_in_progress_) {
    378         extensions_v8::SearchBoxExtension::DispatchInputStart(
    379             render_view()->GetWebView()->mainFrame());
    380       } else {
    381         extensions_v8::SearchBoxExtension::DispatchInputCancel(
    382             render_view()->GetWebView()->mainFrame());
    383       }
    384     }
    385   }
    386 }
    387 
    388 void SearchBox::OnSubmit(const string16& query) {
    389   query_ = query;
    390   if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
    391     DVLOG(1) << render_view() << " OnSubmit";
    392     extensions_v8::SearchBoxExtension::DispatchSubmit(
    393         render_view()->GetWebView()->mainFrame());
    394   }
    395   if (!query.empty())
    396     Reset();
    397 }
    398 
    399 void SearchBox::OnThemeChanged(const ThemeBackgroundInfo& theme_info) {
    400   // Do not send duplicate notifications.
    401   if (theme_info_ == theme_info)
    402     return;
    403 
    404   theme_info_ = theme_info;
    405   if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
    406     extensions_v8::SearchBoxExtension::DispatchThemeChange(
    407         render_view()->GetWebView()->mainFrame());
    408   }
    409 }
    410 
    411 void SearchBox::OnToggleVoiceSearch() {
    412   if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
    413     extensions_v8::SearchBoxExtension::DispatchToggleVoiceSearch(
    414         render_view()->GetWebView()->mainFrame());
    415   }
    416 }
    417 
    418 GURL SearchBox::GetURLForMostVisitedItem(InstantRestrictedID item_id) const {
    419   InstantMostVisitedItem item;
    420   return GetMostVisitedItemWithID(item_id, &item) ? item.url : GURL();
    421 }
    422 
    423 void SearchBox::Reset() {
    424   query_.clear();
    425   start_margin_ = 0;
    426   width_ = 0;
    427   is_focused_ = false;
    428   is_key_capture_enabled_ = false;
    429   theme_info_ = ThemeBackgroundInfo();
    430 }
    431