Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / ui / app_list / speech_ui_model.cc
blob7f144db52ea8cb96956eb1ea9f43e58fbc5b1698
1 // Copyright 2013 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.
5 #include "ui/app_list/speech_ui_model.h"
7 #include <algorithm>
9 namespace app_list {
11 namespace {
13 // The default sound level, just gotten from the developer device.
14 const int16 kDefaultSoundLevel = 200;
16 } // namespace
18 SpeechUIModel::SpeechUIModel(SpeechRecognitionState initial_state)
19 : state_(initial_state),
20 minimum_sound_level_(kDefaultSoundLevel),
21 maximum_sound_level_(kDefaultSoundLevel) {}
23 SpeechUIModel::~SpeechUIModel() {}
25 void SpeechUIModel::SetSpeechResult(const base::string16& result,
26 bool is_final) {
27 if (result_ == result && is_final_ == is_final)
28 return;
30 result_ = result;
31 is_final_ = is_final;
32 FOR_EACH_OBSERVER(SpeechUIModelObserver,
33 observers_,
34 OnSpeechResult(result, is_final));
37 void SpeechUIModel::UpdateSoundLevel(int16 level) {
38 if (sound_level_ == level)
39 return;
41 sound_level_ = level;
43 // Tweak the sound level limits adaptively.
44 // - min is the minimum value during the speech recognition starts but speech
45 // itself hasn't started.
46 // - max is the maximum value when the user speaks.
47 if (state_ == SPEECH_RECOGNITION_IN_SPEECH)
48 maximum_sound_level_ = std::max(level, maximum_sound_level_);
49 else
50 minimum_sound_level_ = std::min(level, minimum_sound_level_);
52 if (maximum_sound_level_ < minimum_sound_level_) {
53 maximum_sound_level_ = std::max(
54 static_cast<int16>(minimum_sound_level_ + kDefaultSoundLevel),
55 kint16max);
58 int16 range = maximum_sound_level_ - minimum_sound_level_;
59 uint8 visible_level = 0;
60 if (range > 0) {
61 int16 visible_level_in_range =
62 std::min(std::max(minimum_sound_level_, sound_level_),
63 maximum_sound_level_);
64 visible_level =
65 (visible_level_in_range - minimum_sound_level_) * kuint8max / range;
68 FOR_EACH_OBSERVER(SpeechUIModelObserver,
69 observers_,
70 OnSpeechSoundLevelChanged(visible_level));
73 void SpeechUIModel::SetSpeechRecognitionState(
74 SpeechRecognitionState new_state) {
75 if (state_ == new_state)
76 return;
78 state_ = new_state;
79 // Revert the min/max sound level to the default.
80 if (state_ != SPEECH_RECOGNITION_RECOGNIZING &&
81 state_ != SPEECH_RECOGNITION_IN_SPEECH) {
82 minimum_sound_level_ = kDefaultSoundLevel;
83 maximum_sound_level_ = kDefaultSoundLevel;
86 FOR_EACH_OBSERVER(SpeechUIModelObserver,
87 observers_,
88 OnSpeechRecognitionStateChanged(new_state));
91 void SpeechUIModel::AddObserver(SpeechUIModelObserver* observer) {
92 observers_.AddObserver(observer);
95 void SpeechUIModel::RemoveObserver(SpeechUIModelObserver* observer) {
96 observers_.RemoveObserver(observer);
99 } // namespace app_list