File: autocorrect_manager.h

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (285 lines) | stat: -rw-r--r-- 11,788 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_ASH_INPUT_METHOD_AUTOCORRECT_MANAGER_H_
#define CHROME_BROWSER_ASH_INPUT_METHOD_AUTOCORRECT_MANAGER_H_

#include <optional>
#include <string>

#include "ash/system/federated/federated_client_manager.h"
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "chrome/browser/ash/input_method/assistive_input_denylist.h"
#include "chrome/browser/ash/input_method/assistive_window_controller.h"
#include "chrome/browser/ash/input_method/autocorrect_enums.h"
#include "chrome/browser/ash/input_method/diacritics_insensitive_string_comparator.h"
#include "chrome/browser/ash/input_method/input_method_engine.h"
#include "chrome/browser/ash/input_method/suggestion_handler_interface.h"
#include "chrome/browser/ash/input_method/text_field_contextual_info_fetcher.h"
#include "chromeos/ash/services/ime/public/cpp/autocorrect.h"

namespace ash {
namespace input_method {

// Implements functionality for chrome.input.ime.autocorrect() extension API.
// This function shows UI to indicate that autocorrect has happened and allows
// it to be undone easily.
class AutocorrectManager {
 public:
  // `profile` and `suggestion_handler` must be alive for the lifetime of this
  // instance.
  explicit AutocorrectManager(SuggestionHandlerInterface* suggestion_handler,
                              Profile* profile);
  ~AutocorrectManager();

  AutocorrectManager(const AutocorrectManager&) = delete;
  AutocorrectManager& operator=(const AutocorrectManager&) = delete;

  // Mark `autocorrect_range` with an underline. `autocorrect_range` is based on
  // the `current_text` contents.
  // NOTE: Technically redundant to require client to supply `current_text` as
  // AutocorrectManager can retrieve it from current text editing state known to
  // IMF. However, due to async situation between browser-process IMF and
  // render-process TextInputClient, it may just get a stale value that way.
  // TODO(crbug/1194424): Remove technically redundant `current_text` param
  // to avoid situation with multiple conflicting sources of truth.
  void HandleAutocorrect(gfx::Range autocorrect_range,
                         const std::u16string& original_text,
                         const std::u16string& current_text);

  // Called when a new input method is activated.
  void OnActivate(const std::string& engine_id);

  // Handles interactions with Undo UI.
  bool OnKeyEvent(const ui::KeyEvent& event);

  // Indicates a new text field is focused, used to save context ID.
  void OnFocus(int context_id);

  // Triggered whenever a connection to the external autocorrect suggestion
  // provider has been initialized successfully.
  void OnConnectedToSuggestionProvider(
      const ime::AutocorrectSuggestionProvider& suggestion_provider);

  // Handles OnBlur event and processes any pending autocorrect range.
  void OnBlur();

  // Processes the state where a user leaves or focuses a text field. At this
  // stage any pending autocorrect range is cleared and relevant metrics are
  // recorded.
  void ProcessTextFieldChange();

  // To show the undo window when cursor is in an autocorrected word, this class
  // is notified of surrounding text changes.
  void OnSurroundingTextChanged(const std::u16string& text,
                                gfx::Range selection_range);

  // Hides undo window if there is any visible.
  void HideUndoWindow();

  void UndoAutocorrect();

  // Whether autocorrect is disabled by some rule.
  bool DisabledByRule();

  // Whether autocorrect is disabled by an "invalid" experiment context. An
  // example of an invalid experiment context could be a provider or decoder
  // parameter set that is not allowed with the currently enabled experiments.
  bool DisabledByInvalidExperimentContext();

  const federated::FederatedClientManager& GetFederatedClientManagerForTest()
      const {
    return federated_manager_;
  }

 private:
  void LogAssistiveAutocorrectAction(AutocorrectActions action);
  void LogRejectionInteractions(AutocorrectActions action);
  void MeasureAndLogAssistiveAutocorrectQualityBreakdown(
      AutocorrectActions action);
  void LogAssistiveAutocorrectInternalState(
      AutocorrectInternalStates internal_state);
  bool AutoCorrectPrefIsPkEnabledByDefault();
  void LogAssistiveAutocorrectQualityBreakdown(
      AutocorrectQualityBreakdown quality_breakdown,
      bool suggestion_accepted,
      bool virtual_keyboard_visible);

  void OnTextFieldContextualInfoChanged(const TextFieldContextualInfo& info);

  // Forces to accept or clear a pending autocorrect suggestion if any. If the
  // autocorrect range is empty, it means the user interacted with the
  // pending autocorrect suggestion and made it invalid, so it considers
  // the autocorrect suggestion as "cleared". Otherwise, it considers the
  // autocorrect suggestion as "accepted". For the both cases, relevant
  // metrics are recorded, state variables are reset and autocorrect range is
  // set to empty.
  void AcceptOrClearPendingAutocorrect();

  // Shows undo window and record the relevant metric if undo window is
  // not already visible.
  void ShowUndoWindow(gfx::Range range, const std::u16string& text);

  // Highlights the appropriate undo or learn more buttons in the undo window
  void HighlightButtons(bool should_highlight_undo,
                        bool should_highlight_learn_more);

  // Processes the result of a set autocorrect range call. An unsuccessful
  // result could mean that autocorrect was not supported by the text input
  // client, so the autocorrect suggestion can be ignored. Otherwise, the
  // autocorrect suggestion will be set as pending and its relevant
  // interactions and metrics will be managed here.
  void ProcessSetAutocorrectRangeDone(const gfx::Range& autocorrect_range,
                                      const std::u16string& original_text,
                                      const std::u16string& current_text,
                                      bool set_range_success);

  // Records any pending metrics that are awaiting a key press from the user.
  void RecordPendingMetricsAwaitingKeyPress();

  struct PendingAutocorrectState {
    explicit PendingAutocorrectState(const std::u16string& original_text,
                                     const std::u16string& suggested_text,
                                     const base::TimeTicks& start_time,
                                     bool virtual_keyboard_visible = false,
                                     bool learn_more_button_visible = false);
    PendingAutocorrectState(const PendingAutocorrectState& other);
    ~PendingAutocorrectState();

    // Original text that is now corrected by autocorrect.
    std::u16string original_text;

    // Autocorrect suggestion that replaced original text.
    std::u16string suggested_text;

    // Specifies if the suggestion is validated in the surrounding text.
    bool is_validated = false;

    // Number of times that validation of autocorrect suggestion in the
    // surrounding text failed.
    int validation_tries = 0;

    // Number of characters inserted anytime after setting the pending
    // autocorrect range. Negative means no autocorrect range is pending or a
    // range has just been set to pending with no OnSurroundingTextChanged
    // called yet.
    int num_inserted_chars = -1;

    // Last known text length from OnSurroundingTextChanged after setting
    // the pending autocorrect range. Negative means no autocorrect range is
    // pending or a range has just been set to pending with no
    // OnSurroundingTextChanged called yet.
    int text_length = -1;

    // Specifies if undo window is visible or not.
    bool undo_window_visible = false;

    // Specifies if undo button is highlighted or not.
    bool undo_button_highlighted = false;

    // Specifies if learn more button is highlighted or not.
    bool learn_more_button_highlighted = false;

    // Specifies if window_shown metric is already incremented for the pending
    // autocorrect or not.
    bool window_shown_logged = false;

    // The time of setting the pending range.
    base::TimeTicks start_time;

    // Specifies if virtual keyboard was visible when suggesting the pending
    // autocorrect or not.
    bool virtual_keyboard_visible = false;

    // Specifies if learn more button is visible or not.
    bool learn_more_button_visible = false;

    // Records the most recent keypress and if control was down for use in
    // metrics.
    std::optional<ui::KeyEvent> last_key_event;

    // The range of the current pending autocorrect.
    gfx::Range last_autocorrect_range = gfx::Range();

    // The range of the selected text or (cursor_pos, cursor_pos] if no text is
    // selected.
    gfx::Range last_selection_range = gfx::Range();

    // Records the difference in length between the previous text and the
    // current |current text| - |prev text|.
    int text_length_diff = 0;
  };

  struct PendingPhysicalKeyboardUserPrefMetric {
    // The currently active engine id.
    std::string engine_id;
  };

  struct PendingSuggestionProviderMetric {
    // Suggestion provider that has been connected.
    ime::AutocorrectSuggestionProvider provider;
  };

  // State variable for pending autocorrect, nullopt means no autocorrect
  // suggestion is pending. The state is kept to avoid issue where
  // InputContext returns stale autocorrect range.
  std::optional<PendingAutocorrectState> pending_autocorrect_;

  // Specifies if the last try for hiding undo window failed. This means
  // undo window is possibly visible while it must not be.
  bool error_on_hiding_undo_window_ = false;

  // The number of autocorrect suggestions that have been handled since
  // focusing on the text field.
  int num_handled_autocorrect_in_text_field_ = 0;

  // Holds the currently active engine_id. There are cases where this could be
  // a nullopt, for example, when the object has been constructed and the
  // OnActivate method has not been invoked.
  std::optional<std::string> active_engine_id_;

  // Holds a pending physical keyboard user preference metric ready to be
  // recorded. This metric should be recorded once per input focused, and only
  // if the user is currently using the physical keyboard.
  std::optional<PendingPhysicalKeyboardUserPrefMetric>
      pending_user_pref_metric_;

  // Holds a pending suggestion provider metric. This metric should be recorded
  // only once per input, and only if the user is currently using the physical
  // keyboard.
  std::optional<PendingSuggestionProviderMetric>
      pending_suggestion_provider_metric_;

  // Holds the suggestion provider enabled for the current input method.
  std::optional<ime::AutocorrectSuggestionProvider> suggestion_provider_;

  // Used to determine if autocorrect should be enabled for a particular input.
  AssistiveInputDenylist denylist_;

  // Holds the identifier of the currently focused input field.
  int context_id_ = 0;

  // Not owned by this class.
  raw_ptr<SuggestionHandlerInterface> suggestion_handler_;
  raw_ptr<Profile> profile_;

  // For logging examples to the CrOS Federated Service.
  federated::FederatedClientManager federated_manager_;

  DiacriticsInsensitiveStringComparator
      diacritics_insensitive_string_comparator_;

  ui::ime::AssistiveWindowButton undo_button_;
  ui::ime::AssistiveWindowButton learn_more_button_;

  bool disabled_by_rule_ = false;

  base::WeakPtrFactory<AutocorrectManager> weak_ptr_factory_{this};
};

}  // namespace input_method
}  // namespace ash

#endif  // CHROME_BROWSER_ASH_INPUT_METHOD_AUTOCORRECT_MANAGER_H_