1// Copyright (c) 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/browser/ui/search/search_delegate.h"
6
7#include "chrome/browser/ui/search/search_model.h"
8#include "chrome/browser/ui/search/search_tab_helper.h"
9
10SearchDelegate::SearchDelegate(SearchModel* browser_search_model)
11    : browser_model_(browser_search_model),
12      tab_model_() {
13}
14
15SearchDelegate::~SearchDelegate() {
16  DCHECK(!tab_model_) << "All tabs should have been deactivated or closed.";
17}
18
19void SearchDelegate::ModelChanged(const SearchModel::State& old_state,
20                                  const SearchModel::State& new_state) {
21  browser_model_->SetState(new_state);
22}
23
24void SearchDelegate::OnTabActivated(content::WebContents* web_contents) {
25  if (tab_model_)
26    tab_model_->RemoveObserver(this);
27  tab_model_ = SearchTabHelper::FromWebContents(web_contents)->model();
28  browser_model_->SetState(tab_model_->state());
29  tab_model_->AddObserver(this);
30}
31
32void SearchDelegate::OnTabDeactivated(content::WebContents* web_contents) {
33  StopObservingTab(web_contents);
34}
35
36void SearchDelegate::OnTabDetached(content::WebContents* web_contents) {
37  StopObservingTab(web_contents);
38}
39
40void SearchDelegate::StopObservingTab(content::WebContents* web_contents) {
41  SearchTabHelper* search_tab_helper =
42      SearchTabHelper::FromWebContents(web_contents);
43  if (search_tab_helper->model() == tab_model_) {
44    tab_model_->RemoveObserver(this);
45    tab_model_ = NULL;
46  }
47}
48