#001
// Autocomplete provider for searches and suggestions from a search engine.
#002
//
#003
// After construction, the autocomplete controller repeatedly calls Start()
#004
// with some user input, each time expecting to receive a small set of the best
#005
// matches (either synchronously or asynchronously).
#006
//
#007
// Initially the provider creates a match that searches for the current input
#008
// text.
It also starts a task to query the Suggest servers.
When that data
#009
// comes back, the provider creates and returns matches for the best
#010
// suggestions.
SearchProvider
类是继承
AutocompleteProvider
和
URLFetcher
类,
AutocompleteProvider
提供一个自动完成的结果,
URLFetcher
主要提供从
URL
获取数据和状态。
#011
class SearchProvider : public AutocompleteProvider,
#012
public URLFetcher::Delegate {
#013
public:
#014
SearchProvider(ACProviderListener* listener, Profile* profile)
#015
: AutocompleteProvider(listener, profile, "Search"),
#016
last_default_provider_(NULL),
#017
fetcher_(NULL),
#018
history_request_pending_(false),
#019
have_history_results_(false),
#020
suggest_results_pending_(false),
#021
have_suggest_results_(false) {
#022
}
#023
开始获取。
#024
// AutocompleteProvider
#025
virtual void Start(const AutocompleteInput& input,
#026
bool minimal_changes,
#027
bool synchronous_only);
停止查找。
#028
virtual void Stop();
#029
当获取到数据回来时响应。
#030
// URLFetcher::Delegate
#031
virtual void OnURLFetchComplete(const URLFetcher* source,
#032
const GURL& url,
#033
const URLRequestStatus& status,
#034
int response_code,
#035
const ResponseCookies& cookies,
#036
const std::string& data);
#037
#038
private:
#039
struct NavigationResult {
#040
NavigationResult(const std::wstring& url, const std::wstring& site_name)
#041
: url(url),
#042
site_name(site_name) {
#043
}
#044
#045
// The URL.
#046
std::wstring url;
#047
#048
// Name for the site.
#049
std::wstring site_name;
#050
};
#051
保存返回的结果。
#052
typedef std::vector<std::wstring> SuggestResults;
#053
typedef std::vector<NavigationResult> NavigationResults;
#054
typedef std::vector<history::KeywordSearchTermVisit> HistoryResults;
#055
typedef std::map<std::wstring, AutocompleteMatch> MatchMap;
#056
运行获取搜索引擎数据。
#057
// Called when timer_ expires.
#058
void Run();
#059
#060
// Determines whether an asynchronous subcomponent query should run for the
#061
// current input.
If so, starts it if necessary; otherwise stops it.
#062
// NOTE: These functions do not update |done_|.
Callers must do so.
#063
void StartOrStopHistoryQuery(bool minimal_changes, bool synchronous_only);
#064
void StartOrStopSuggestQuery(bool minimal_changes, bool synchronous_only);
#065
#066
// Functions to stop the separate asynchronous subcomponents.
#067
// NOTE: These functions do not update |done_|.
Callers must do so.
#068
void StopHistory();
#069
void StopSuggest();
#070
#071
// Called back by the history system to return searches that begin with the
#072
// input text.
#073
void OnGotMostRecentKeywordSearchTerms(
#074
CancelableRequestProvider::Handle handle,
#075
HistoryResults* results);
#076
#077
// Parses the results from the Suggest server and stores up to kMaxMatches of
#078
// them in server_results_.
Returns whether parsing succeeded.
#079
bool ParseSuggestResults(Value* root_val);
#080
#081
// Converts the parsed server results in server_results_ to a set of
#082
// AutocompleteMatches and adds them to |matches_|.
This also sets |done_|
#083
// correctly.
#084
void ConvertResultsToAutocompleteMatches();
#085
#086
// Determines the relevance for a particular match.
We use different scoring
#087
// algorithms for the different types of matches.
#088
int CalculateRelevanceForWhatYouTyped() const;
#089
// |time| is the time at which this query was last seen.
#090
int CalculateRelevanceForHistory(const Time& time) const;
#091
// |suggestion_value| is which suggestion this is in the list returned from
#092
// the server; the best suggestion is suggestion number 0.
#093
int CalculateRelevanceForSuggestion(size_t suggestion_value) const;
#094
// |suggestion_value| is same as above.
#095
int CalculateRelevanceForNavigation(size_t suggestion_value) const;
#096
#097
// Creates an AutocompleteMatch for "Search <engine> for |query_string|" with
#098
// the supplied relevance.
Adds this match to |map|; if such a match already
#099
// exists, whichever one has lower relevance is eliminated.
#100
void AddMatchToMap(const std::wstring& query_string,
#101
int relevance,
#102
int accepted_suggestion,
#103
MatchMap* map);
#104
// Returns an AutocompleteMatch for a navigational suggestion.
#105
AutocompleteMatch NavigationToMatch(const NavigationResult& query_string,
#106
int relevance);
#107
#108
// Trims "http:" and up to two subsequent slashes from |url|.
Returns the
#109
// number of characters that were trimmed.
#110
// TODO(
#111
static size_t TrimHttpPrefix(std::wstring* url);
#112
#113
// Don't send any queries to the server until some time has elapsed after
#114
// the last keypress, to avoid flooding the server with requests we are
#115
// likely to end up throwing away anyway.
#116
static const int kQueryDelayMs;
#117
#118
// The user's input.
#119
AutocompleteInput input_;
#120
#121
TemplateURL default_provider_;
// Cached across the life of a query so we
#122
// behave consistently even if the user
#123
// changes their default while the query is
#124
// running.
#125
const TemplateURL* last_default_provider_;
#126
// TODO(pkasting): http://b/1162970
We
#127
// shouldn't need this.
#128
#129
// An object we can use to cancel history requests.
#130
CancelableRequestConsumer history_request_consumer_;
#131
#132
// Searches in the user's history that begin with the input text.
#133
HistoryResults history_results_;
#134
#135
// Whether history_results_ is valid (so we can tell invalid apart from
#136
// empty).
#137
bool have_history_results_;
#138
#139
// Whether we are waiting for a history request to finish.
#140
bool history_request_pending_;
#141
#142
// True if we're expecting suggest results that haven't yet arrived.
This
#143
// could be because either |timer_| or |fetcher| is still running (see below).
#144
bool suggest_results_pending_;
#145
#146
// A timer to start a query to the suggest server after the user has stopped
#147
// typing for long enough.
#148
base::OneShotTimer<SearchProvider> timer_;
#149
#150
// The fetcher that retrieves suggest results from the server.
#151
scoped_ptr<URLFetcher> fetcher_;
#152
#153
// Suggestions returned by the Suggest server for the input text.
#154
SuggestResults suggest_results_;
#155
#156
// Navigational suggestions returned by the server.
#157
NavigationResults navigation_results_;
#158
#159
// Whether suggest_results_ is valid.
#160
bool have_suggest_results_;
#161
#162
DISALLOW_EVIL_CONSTRUCTORS(SearchProvider);
#163
};
#164
在这个类里先调用函数
SearchProvider::Start
来获取缺省的搜索引擎,然后停止以前的搜索,接着
SearchProvider::Run()
函数里使用
URLFetcher
获取数据回来,它的代码如下:
#001
void SearchProvider::Run() {
#002
// Start a new request with the current input.
#003
DCHECK(!done_);
获取搜索的
URL
。
#004
const TemplateURLRef* const suggestions_url =
#005
default_provider_.suggestions_url();
建议代替的字符。
#006
DCHECK(suggestions_url->SupportsReplacement());
开始新的搜索。
#007
fetcher_.reset(new URLFetcher(GURL(suggestions_url->ReplaceSearchTerms(
#008
default_provider_, input_.text(),
#009
TemplateURLRef::NO_SUGGESTIONS_AVAILABLE, std::wstring())),
#010
URLFetcher::GET, this));
#011
fetcher_->set_request_context(profile_->GetRequestContext());
#012
fetcher_->Start();
#013
}
当前上面的搜索完成时,就会通知
SearchProvider::OnURLFetchComplete
函数来分析返回的结果,最后调用
SearchProvider::ConvertResultsToAutocompleteMatches()
函数来把结果转换自动完成的列表项。
通过上面的分析,就了解通过
GOOGLE
搜索引擎自动完成功能的实现。