rule_based_engine.cc 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // Copyright 2018 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. #include "ash/services/ime/rule_based_engine.h"
  5. #include "base/i18n/icu_string_conversions.h"
  6. #include "base/notreached.h"
  7. #include "base/strings/string_util.h"
  8. #include "base/strings/utf_string_conversions.h"
  9. #include "base/values.h"
  10. namespace ash {
  11. namespace ime {
  12. namespace {
  13. std::u16string ConvertToUtf16AndNormalize(const std::string& str) {
  14. // TODO(https://crbug.com/1185629): Add a new helper in
  15. // base/i18n/icu_string_conversions.h that does the conversion directly
  16. // without a redundant UTF16->UTF8 conversion.
  17. std::string normalized_str;
  18. base::ConvertToUtf8AndNormalize(str, base::kCodepageUTF8, &normalized_str);
  19. return base::UTF8ToUTF16(normalized_str);
  20. }
  21. std::string GetIdFromImeSpec(const std::string& ime_spec) {
  22. static const std::string kPrefix("m17n:");
  23. return base::StartsWith(ime_spec, kPrefix, base::CompareCase::SENSITIVE)
  24. ? ime_spec.substr(kPrefix.length())
  25. : std::string();
  26. }
  27. uint8_t GenerateModifierValue(const mojom::ModifierStatePtr& modifier_state,
  28. bool is_alt_right_key_down) {
  29. uint8_t modifiers = 0;
  30. if (modifier_state->shift)
  31. modifiers |= rulebased::MODIFIER_SHIFT;
  32. if (modifier_state->alt_graph || is_alt_right_key_down)
  33. modifiers |= rulebased::MODIFIER_ALTGR;
  34. if (modifier_state->caps_lock)
  35. modifiers |= rulebased::MODIFIER_CAPSLOCK;
  36. return modifiers;
  37. }
  38. mojom::KeyEventResult HandleEngineResult(
  39. const rulebased::ProcessKeyResult& result,
  40. mojo::AssociatedRemote<mojom::InputMethodHost>& host) {
  41. if (!result.commit_text.empty()) {
  42. host->CommitText(ConvertToUtf16AndNormalize(result.commit_text),
  43. mojom::CommitTextCursorBehavior::kMoveCursorAfterText);
  44. }
  45. // Still need to set composition when the key is handled and commit_text and
  46. // composition_text are both empty.
  47. // That is the case of using Backspace to delete the last character in
  48. // composition.
  49. if (!result.composition_text.empty() ||
  50. (result.key_handled && result.commit_text.empty())) {
  51. std::u16string text = ConvertToUtf16AndNormalize(result.composition_text);
  52. std::vector<mojom::CompositionSpanPtr> spans;
  53. spans.push_back(mojom::CompositionSpan::New(
  54. 0, text.length(), mojom::CompositionSpanStyle::kDefault));
  55. const int new_cursor_position = text.length();
  56. host->SetComposition(std::move(text), std::move(spans),
  57. new_cursor_position);
  58. }
  59. return result.key_handled ? mojom::KeyEventResult::kConsumedByIme
  60. : mojom::KeyEventResult::kNeedsHandlingBySystem;
  61. }
  62. bool IsModifierKey(const mojom::DomCode code) {
  63. switch (code) {
  64. case mojom::DomCode::kAltLeft:
  65. case mojom::DomCode::kAltRight:
  66. case mojom::DomCode::kShiftLeft:
  67. case mojom::DomCode::kShiftRight:
  68. case mojom::DomCode::kControlLeft:
  69. case mojom::DomCode::kControlRight:
  70. case mojom::DomCode::kCapsLock:
  71. return true;
  72. default:
  73. return false;
  74. }
  75. }
  76. // Returns whether the given ime_spec is supported by rulebased engine.
  77. bool IsImeSupportedByRulebased(const std::string& ime_spec) {
  78. return rulebased::Engine::IsImeSupported(GetIdFromImeSpec(ime_spec));
  79. }
  80. } // namespace
  81. std::unique_ptr<RuleBasedEngine> RuleBasedEngine::Create(
  82. const std::string& ime_spec,
  83. mojo::PendingAssociatedReceiver<mojom::InputMethod> receiver,
  84. mojo::PendingAssociatedRemote<mojom::InputMethodHost> host) {
  85. // RuleBasedEngine constructor is private, so have to use WrapUnique here.
  86. return IsImeSupportedByRulebased(ime_spec)
  87. ? base::WrapUnique(new RuleBasedEngine(
  88. ime_spec, std::move(receiver), std::move(host)))
  89. : nullptr;
  90. }
  91. RuleBasedEngine::~RuleBasedEngine() = default;
  92. void RuleBasedEngine::OnFocus(mojom::InputFieldInfoPtr input_field_info,
  93. mojom::InputMethodSettingsPtr settings,
  94. OnFocusCallback callback) {
  95. std::move(callback).Run(false);
  96. }
  97. bool RuleBasedEngine::IsConnected() {
  98. // `receiver_` will reset upon disconnection, so bound state is equivalent to
  99. // connected state.
  100. return receiver_.is_bound();
  101. }
  102. void RuleBasedEngine::OnCompositionCanceledBySystem() {
  103. engine_.Reset();
  104. is_alt_right_key_down_ = false;
  105. }
  106. void RuleBasedEngine::ProcessKeyEvent(mojom::PhysicalKeyEventPtr event,
  107. ProcessKeyEventCallback callback) {
  108. // According to the W3C spec, |altKey| is false if the AltGr key
  109. // is pressed [1]. However, all rule-based input methods on Chrome OS use
  110. // the US QWERTY layout as a base layout, with AltGr implemented at this
  111. // layer. This means the right Alt key reports as being a normal Alt key, so
  112. // |altKey| is true. Thus, we need to take |altKey| and exclude the
  113. // right Alt key to determine the status of the "true" Alt key.
  114. // [1] https://www.w3.org/TR/uievents-key/#keys-modifier
  115. // TODO(https://crbug.com/1014778): Change the base layouts for the
  116. // rule-based input methods so that |altKey| is false when AltGr is pressed.
  117. if (event->code == mojom::DomCode::kAltRight) {
  118. is_alt_right_key_down_ = event->type == mojom::KeyEventType::kKeyDown;
  119. }
  120. const bool is_alt_down = event->modifier_state->alt && !is_alt_right_key_down_;
  121. // - Shift/AltRight/Caps/Ctrl are modifier keys for the characters which the
  122. // Mojo service may accept, but don't send the keys themselves to Mojo.
  123. // - Ctrl+? and Alt+? are shortcut keys, so don't send them to the rule based
  124. // engine.
  125. if (event->type != mojom::KeyEventType::kKeyDown ||
  126. (IsModifierKey(event->code) || event->modifier_state->control ||
  127. is_alt_down)) {
  128. std::move(callback).Run(mojom::KeyEventResult::kNeedsHandlingBySystem);
  129. return;
  130. }
  131. std::move(callback).Run(HandleEngineResult(
  132. engine_.ProcessKey(
  133. event->code,
  134. GenerateModifierValue(event->modifier_state, is_alt_right_key_down_)),
  135. host_));
  136. }
  137. void RuleBasedEngine::OnCandidateSelected(uint32_t selected_candidate_index) {
  138. // Rule-based engines don't use candidates.
  139. NOTREACHED();
  140. }
  141. void RuleBasedEngine::OnQuickSettingsUpdated(
  142. mojom::InputMethodQuickSettingsPtr quick_settings) {
  143. // Rule-based engines don't use quick settings.
  144. NOTREACHED();
  145. }
  146. void RuleBasedEngine::IsReadyForTesting(IsReadyForTestingCallback callback) {
  147. // Rule-based engines load instantly, so they are always ready.
  148. std::move(callback).Run(true);
  149. }
  150. RuleBasedEngine::RuleBasedEngine(
  151. const std::string& ime_spec,
  152. mojo::PendingAssociatedReceiver<mojom::InputMethod> receiver,
  153. mojo::PendingAssociatedRemote<mojom::InputMethodHost> host)
  154. : receiver_(this, std::move(receiver)), host_(std::move(host)) {
  155. DCHECK(IsImeSupportedByRulebased(ime_spec));
  156. engine_.Activate(GetIdFromImeSpec(ime_spec));
  157. receiver_.set_disconnect_handler(
  158. base::BindOnce(&mojo::AssociatedReceiver<mojom::InputMethod>::reset,
  159. base::Unretained(&receiver_)));
  160. }
  161. } // namespace ime
  162. } // namespace ash