File: input_ime_api.cc

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 (259 lines) | stat: -rw-r--r-- 10,380 bytes parent folder | download | duplicates (4)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/input_ime/input_ime_api.h"

#include <utility>
#include "base/lazy_instance.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/extensions/api/input_method_private.h"
#include "extensions/browser/extension_registry.h"
#include "ui/base/ime/ash/ime_keymap.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"

namespace {

namespace input_ime = extensions::api::input_ime;
namespace KeyEventHandled = extensions::api::input_ime::KeyEventHandled;
namespace SetComposition = extensions::api::input_ime::SetComposition;
namespace CommitText = extensions::api::input_ime::CommitText;
namespace SendKeyEvents = extensions::api::input_ime::SendKeyEvents;

const char kErrorRouterNotAvailable[] = "The router is not available.";
const char kErrorSetKeyEventsFail[] = "Could not send key events.";

using ::ash::input_method::InputMethodEngine;

InputMethodEngine* GetEngineIfActive(Profile* profile,
                                     const std::string& extension_id,
                                     std::string* error) {
  extensions::InputImeEventRouter* event_router =
      extensions::GetInputImeEventRouter(profile);
  DCHECK(event_router) << kErrorRouterNotAvailable;
  InputMethodEngine* engine =
      event_router->GetEngineIfActive(extension_id, error);
  return engine;
}

ui::KeyEvent ConvertKeyboardEventToUIKeyEvent(
    const input_ime::KeyboardEvent& event) {
  const ui::EventType type =
      event.type == input_ime::KeyboardEventType::kKeydown
          ? ui::EventType::kKeyPressed
          : ui::EventType::kKeyReleased;

  const auto key_code = static_cast<ui::KeyboardCode>(
      event.key_code && *event.key_code != ui::VKEY_UNKNOWN
          ? *event.key_code
          : ash::DomKeycodeToKeyboardCode(event.code));

  int flags = ui::EF_NONE;
  flags |= event.alt_key && *event.alt_key ? ui::EF_ALT_DOWN : ui::EF_NONE;
  flags |=
      event.altgr_key && *event.altgr_key ? ui::EF_ALTGR_DOWN : ui::EF_NONE;
  flags |=
      event.ctrl_key && *event.ctrl_key ? ui::EF_CONTROL_DOWN : ui::EF_NONE;
  flags |=
      event.shift_key && *event.shift_key ? ui::EF_SHIFT_DOWN : ui::EF_NONE;
  flags |=
      event.caps_lock && *event.caps_lock ? ui::EF_CAPS_LOCK_ON : ui::EF_NONE;

  return ui::KeyEvent(type, key_code,
                      ui::KeycodeConverter::CodeStringToDomCode(event.code),
                      flags, ui::KeycodeConverter::KeyStringToDomKey(event.key),
                      ui::EventTimeForNow());
}

}  // namespace

namespace extensions {

InputImeEventRouterFactory* InputImeEventRouterFactory::GetInstance() {
  return base::Singleton<InputImeEventRouterFactory>::get();
}

InputImeEventRouterFactory::InputImeEventRouterFactory() = default;
InputImeEventRouterFactory::~InputImeEventRouterFactory() = default;

InputImeEventRouter* InputImeEventRouterFactory::GetRouter(Profile* profile) {
  if (!profile)
    return nullptr;
  // The |router_map_| is keyed by the original profile.
  // Refers to the comments in |RemoveProfile| method for the reason.
  profile = profile->GetOriginalProfile();
  InputImeEventRouter* router = router_map_[profile];
  if (!router) {
    // The router must attach to the profile from which the extension can
    // receive events. If |profile| has an off-the-record profile, attach the
    // off-the-record profile. e.g. In guest mode, the extension is running with
    // the incognito profile instead of its original profile.
    router = new InputImeEventRouter(
        profile->HasPrimaryOTRProfile()
            ? profile->GetPrimaryOTRProfile(/*create_if_needed=*/true)
            : profile);
    router_map_[profile] = router;
  }
  return router;
}

void InputImeEventRouterFactory::RemoveProfile(Profile* profile) {
  if (!profile || router_map_.empty())
    return;
  auto it = router_map_.find(profile);
  // The routers are common between an incognito profile and its original
  // profile, and are keyed on the original profiles.
  // When a profile is removed, exact matching is used to ensure that the router
  // is deleted only when the original profile is removed.
  if (it != router_map_.end() && it->first == profile) {
    delete it->second;
    router_map_.erase(it);
  }
}

ExtensionFunction::ResponseAction InputImeKeyEventHandledFunction::Run() {
  std::optional<KeyEventHandled::Params> params =
      KeyEventHandled::Params::Create(args());
  std::string error;
  InputMethodEngine* engine = GetEngineIfActive(
      Profile::FromBrowserContext(browser_context()), extension_id(), &error);
  if (!engine)
    return RespondNow(Error(InformativeError(error, static_function_name())));

  engine->KeyEventHandled(extension_id(), params->request_id, params->response);
  return RespondNow(NoArguments());
}

ExtensionFunction::ResponseAction InputImeSetCompositionFunction::Run() {
  std::string error;
  InputMethodEngine* engine = GetEngineIfActive(
      Profile::FromBrowserContext(browser_context()), extension_id(), &error);
  if (!engine)
    return RespondNow(Error(InformativeError(error, static_function_name())));

  std::optional<SetComposition::Params> parent_params =
      SetComposition::Params::Create(args());
  const SetComposition::Params::Parameters& params = parent_params->parameters;
  std::vector<InputMethodEngine::SegmentInfo> segments;
  if (params.segments) {
    for (const auto& segments_arg : *params.segments) {
      EXTENSION_FUNCTION_VALIDATE(segments_arg.style !=
                                  input_ime::UnderlineStyle::kNone);
      InputMethodEngine::SegmentInfo segment_info;
      segment_info.start = segments_arg.start;
      segment_info.end = segments_arg.end;
      if (segments_arg.style == input_ime::UnderlineStyle::kUnderline) {
        segment_info.style = InputMethodEngine::SEGMENT_STYLE_UNDERLINE;
      } else if (segments_arg.style ==
                 input_ime::UnderlineStyle::kDoubleUnderline) {
        segment_info.style = InputMethodEngine::SEGMENT_STYLE_DOUBLE_UNDERLINE;
      } else {
        segment_info.style = InputMethodEngine::SEGMENT_STYLE_NO_UNDERLINE;
      }
      segments.push_back(segment_info);
    }
  }
  int selection_start =
      params.selection_start ? *params.selection_start : params.cursor;
  int selection_end =
      params.selection_end ? *params.selection_end : params.cursor;
  if (!engine->SetComposition(params.context_id, params.text.c_str(),
                              selection_start, selection_end, params.cursor,
                              segments, &error)) {
    base::Value::List results;
    results.Append(false);
    return RespondNow(ErrorWithArgumentsDoNotUse(
        std::move(results), InformativeError(error, static_function_name())));
  }
  return RespondNow(WithArguments(true));
}

ExtensionFunction::ResponseAction InputImeCommitTextFunction::Run() {
  std::string error;
  InputMethodEngine* engine = GetEngineIfActive(
      Profile::FromBrowserContext(browser_context()), extension_id(), &error);
  if (!engine)
    return RespondNow(Error(InformativeError(error, static_function_name())));

  std::optional<CommitText::Params> parent_params =
      CommitText::Params::Create(args());
  const CommitText::Params::Parameters& params = parent_params->parameters;
  if (!engine->CommitText(params.context_id, base::UTF8ToUTF16(params.text),
                          &error)) {
    base::Value::List results;
    results.Append(false);
    return RespondNow(ErrorWithArgumentsDoNotUse(
        std::move(results), InformativeError(error, static_function_name())));
  }
  return RespondNow(WithArguments(true));
}

ExtensionFunction::ResponseAction InputImeSendKeyEventsFunction::Run() {
  std::string error;
  InputMethodEngine* engine = GetEngineIfActive(
      Profile::FromBrowserContext(browser_context()), extension_id(), &error);
  if (!engine)
    return RespondNow(Error(InformativeError(error, static_function_name())));

  std::optional<SendKeyEvents::Params> parent_params =
      SendKeyEvents::Params::Create(args());
  EXTENSION_FUNCTION_VALIDATE(parent_params);
  const SendKeyEvents::Params::Parameters& params = parent_params->parameters;

  std::vector<ui::KeyEvent> key_data_out;
  key_data_out.reserve(params.key_data.size());
  for (const auto& key_event : params.key_data) {
    key_data_out.emplace_back(ConvertKeyboardEventToUIKeyEvent(key_event));
  }

  if (!engine->SendKeyEvents(params.context_id, key_data_out, &error))
    return RespondNow(Error(InformativeError(
        base::StringPrintf("%s %s", kErrorSetKeyEventsFail, error.c_str()),
        static_function_name())));
  return RespondNow(NoArguments());
}

InputImeAPI::InputImeAPI(content::BrowserContext* context)
    : browser_context_(context) {
  extension_registry_observation_.Observe(
      ExtensionRegistry::Get(browser_context_));

  EventRouter* event_router = EventRouter::Get(browser_context_);
  event_router->RegisterObserver(this, input_ime::OnFocus::kEventName);
  event_router->RegisterObserver(
      this, api::input_method_private::OnFocus::kEventName);
  event_router->RegisterObserver(this, input_ime::OnKeyEvent::kEventName);
}

InputImeAPI::~InputImeAPI() = default;

void InputImeAPI::Shutdown() {
  extension_registry_observation_.Reset();
  InputImeEventRouterFactory::GetInstance()->RemoveProfile(
      Profile::FromBrowserContext(browser_context_));
  EventRouter::Get(browser_context_)->UnregisterObserver(this);
}

static base::LazyInstance<BrowserContextKeyedAPIFactory<InputImeAPI>>::
    DestructorAtExit g_input_ime_factory = LAZY_INSTANCE_INITIALIZER;

// static
BrowserContextKeyedAPIFactory<InputImeAPI>* InputImeAPI::GetFactoryInstance() {
  return g_input_ime_factory.Pointer();
}

InputImeEventRouter* GetInputImeEventRouter(Profile* profile) {
  if (!profile)
    return nullptr;
  return InputImeEventRouterFactory::GetInstance()->GetRouter(profile);
}

std::string InformativeError(const std::string& error,
                             const char* function_name) {
  return base::StringPrintf("[%s]: %s", function_name, error.c_str());
}

}  // namespace extensions