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 "chrome/browser/chromeos/input_method/input_method_engine.h"
12 #include "ash/ime/input_method_menu_item.h"
13 #include "ash/ime/input_method_menu_manager.h"
14 #include "ash/shell.h"
15 #include "base/logging.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/metrics/histogram.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "chromeos/ime/component_extension_ime_manager.h"
23 #include "chromeos/ime/composition_text.h"
24 #include "chromeos/ime/extension_ime_util.h"
25 #include "chromeos/ime/input_method_manager.h"
26 #include "ui/aura/window.h"
27 #include "ui/aura/window_tree_host.h"
28 #include "ui/base/ime/candidate_window.h"
29 #include "ui/base/ime/chromeos/ime_keymap.h"
30 #include "ui/events/event.h"
31 #include "ui/events/event_processor.h"
32 #include "ui/keyboard/keyboard_controller.h"
33 #include "ui/keyboard/keyboard_util.h"
36 const char* kErrorNotActive = "IME is not active";
37 const char* kErrorWrongContext = "Context is not active";
38 const char* kCandidateNotFound = "Candidate not found";
42 // Notifies InputContextHandler that the composition is changed.
43 void UpdateComposition(const CompositionText& composition_text,
46 IMEInputContextHandlerInterface* input_context =
47 IMEBridge::Get()->GetInputContextHandler();
49 input_context->UpdateCompositionText(
50 composition_text, cursor_pos, is_visible);
53 // Returns the length of characters of a UTF-8 string with unknown string
54 // length. Cannot apply faster algorithm to count characters in an utf-8
55 // string without knowing the string length, so just does a full scan.
56 size_t GetUtf8StringLength(const char* s) {
59 if ((*s & 0xC0) != 0x80)
66 std::string GetKeyFromEvent(const ui::KeyEvent& event) {
67 const std::string& code = event.code();
68 if (StartsWithASCII(code, "Control", true))
70 if (StartsWithASCII(code, "Shift", true))
72 if (StartsWithASCII(code, "Alt", true))
74 if (StartsWithASCII(code, "Arrow", true))
75 return code.substr(5);
78 if (code == "Backspace" || code == "Tab" ||
79 code == "Enter" || code == "CapsLock")
82 // Ctrl+? cases, gets key value for Ctrl is not down.
83 if (event.flags() & ui::EF_CONTROL_DOWN) {
84 ui::KeyEvent event_no_ctrl(event.type(),
86 event.flags() ^ ui::EF_CONTROL_DOWN,
88 ch = event_no_ctrl.GetCharacter();
90 ch = event.GetCharacter();
92 return base::UTF16ToUTF8(base::string16(1, ch));
95 void GetExtensionKeyboardEventFromKeyEvent(
96 const ui::KeyEvent& event,
97 InputMethodEngine::KeyboardEvent* ext_event) {
98 DCHECK(event.type() == ui::ET_KEY_RELEASED ||
99 event.type() == ui::ET_KEY_PRESSED);
101 ext_event->type = (event.type() == ui::ET_KEY_RELEASED) ? "keyup" : "keydown";
103 ext_event->code = event.code();
104 ext_event->key_code = static_cast<int>(event.key_code());
105 ext_event->alt_key = event.IsAltDown();
106 ext_event->ctrl_key = event.IsControlDown();
107 ext_event->shift_key = event.IsShiftDown();
108 ext_event->caps_lock = event.IsCapsLockDown();
109 ext_event->key = GetKeyFromEvent(event);
114 InputMethodEngine::InputMethodEngine()
115 : current_input_type_(ui::TEXT_INPUT_TYPE_NONE),
119 composition_text_(new CompositionText()),
120 composition_cursor_(0),
121 candidate_window_(new ui::CandidateWindow()),
122 window_visible_(false),
123 sent_key_event_(NULL) {}
125 InputMethodEngine::~InputMethodEngine() {
126 if (start_time_.ToInternalValue())
127 RecordHistogram("WorkingTime", (end_time_ - start_time_).InSeconds());
128 input_method::InputMethodManager::Get()->RemoveInputMethodExtension(imm_id_);
131 void InputMethodEngine::Initialize(
132 scoped_ptr<InputMethodEngineInterface::Observer> observer,
133 const char* engine_name,
134 const char* extension_id,
135 const char* engine_id,
136 const std::vector<std::string>& languages,
137 const std::vector<std::string>& layouts,
138 const GURL& options_page,
139 const GURL& input_view) {
140 DCHECK(observer) << "Observer must not be null.";
142 // TODO(komatsu): It is probably better to set observer out of Initialize.
143 observer_ = observer.Pass();
144 engine_id_ = engine_id;
145 extension_id_ = extension_id;
147 input_method::InputMethodManager* manager =
148 input_method::InputMethodManager::Get();
149 ComponentExtensionIMEManager* comp_ext_ime_manager =
150 manager->GetComponentExtensionIMEManager();
152 if (comp_ext_ime_manager && comp_ext_ime_manager->IsInitialized() &&
153 comp_ext_ime_manager->IsWhitelistedExtension(extension_id)) {
154 imm_id_ = comp_ext_ime_manager->GetId(extension_id, engine_id);
156 imm_id_ = extension_ime_util::GetInputMethodID(extension_id, engine_id);
159 input_view_url_ = input_view;
160 descriptor_ = input_method::InputMethodDescriptor(
163 std::string(), // TODO(uekawa): Set short name.
166 extension_ime_util::IsKeyboardLayoutExtension(
167 imm_id_), // is_login_keyboard
171 // TODO(komatsu): It is probably better to call AddInputMethodExtension
172 // out of Initialize.
173 manager->AddInputMethodExtension(imm_id_, this);
176 const input_method::InputMethodDescriptor& InputMethodEngine::GetDescriptor()
181 void InputMethodEngine::RecordHistogram(const char* name, int count) {
182 std::string histo_name =
183 base::StringPrintf("InputMethod.%s.%s", name, engine_id_.c_str());
184 base::HistogramBase* counter = base::Histogram::FactoryGet(
185 histo_name, 0, 1000000, 50, base::HistogramBase::kNoFlags);
190 void InputMethodEngine::NotifyImeReady() {
191 input_method::InputMethodManager* manager =
192 input_method::InputMethodManager::Get();
193 if (manager && imm_id_ == manager->GetCurrentInputMethod().id())
197 bool InputMethodEngine::SetComposition(
203 const std::vector<SegmentInfo>& segments,
204 std::string* error) {
206 *error = kErrorNotActive;
209 if (context_id != context_id_ || context_id_ == -1) {
210 *error = kErrorWrongContext;
214 composition_cursor_ = cursor;
215 composition_text_.reset(new CompositionText());
216 composition_text_->set_text(base::UTF8ToUTF16(text));
218 composition_text_->set_selection_start(selection_start);
219 composition_text_->set_selection_end(selection_end);
221 // TODO: Add support for displaying selected text in the composition string.
222 for (std::vector<SegmentInfo>::const_iterator segment = segments.begin();
223 segment != segments.end(); ++segment) {
224 CompositionText::UnderlineAttribute underline;
226 switch (segment->style) {
227 case SEGMENT_STYLE_UNDERLINE:
228 underline.type = CompositionText::COMPOSITION_TEXT_UNDERLINE_SINGLE;
230 case SEGMENT_STYLE_DOUBLE_UNDERLINE:
231 underline.type = CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE;
237 underline.start_index = segment->start;
238 underline.end_index = segment->end;
239 composition_text_->mutable_underline_attributes()->push_back(underline);
242 // TODO(nona): Makes focus out mode configuable, if necessary.
243 UpdateComposition(*composition_text_, composition_cursor_, true);
247 bool InputMethodEngine::ClearComposition(int context_id,
248 std::string* error) {
250 *error = kErrorNotActive;
253 if (context_id != context_id_ || context_id_ == -1) {
254 *error = kErrorWrongContext;
258 composition_cursor_ = 0;
259 composition_text_.reset(new CompositionText());
260 UpdateComposition(*composition_text_, composition_cursor_, false);
264 bool InputMethodEngine::CommitText(int context_id, const char* text,
265 std::string* error) {
267 // TODO: Commit the text anyways.
268 *error = kErrorNotActive;
271 if (context_id != context_id_ || context_id_ == -1) {
272 *error = kErrorWrongContext;
276 IMEBridge::Get()->GetInputContextHandler()->CommitText(text);
278 // Records times for using input method.
279 if (!start_time_.ToInternalValue())
280 start_time_ = base::Time::Now();
281 end_time_ = base::Time::Now();
282 // Records histograms for counts of commits and committed characters.
283 RecordHistogram("Commit", 1);
284 RecordHistogram("CommitCharacter", GetUtf8StringLength(text));
288 bool InputMethodEngine::SendKeyEvents(
290 const std::vector<KeyboardEvent>& events) {
294 // context_id == 0, means sending key events to non-input field.
295 // context_id_ == -1, means the focus is not in an input field.
296 if (context_id != 0 && (context_id != context_id_ || context_id_ == -1)) {
300 ui::EventProcessor* dispatcher =
301 ash::Shell::GetPrimaryRootWindow()->GetHost()->event_processor();
303 for (size_t i = 0; i < events.size(); ++i) {
304 const KeyboardEvent& event = events[i];
305 const ui::EventType type =
306 (event.type == "keyup") ? ui::ET_KEY_RELEASED : ui::ET_KEY_PRESSED;
307 ui::KeyboardCode key_code = static_cast<ui::KeyboardCode>(event.key_code);
308 if (key_code == ui::VKEY_UNKNOWN)
309 key_code = ui::DomKeycodeToKeyboardCode(event.code);
311 int flags = ui::EF_NONE;
312 flags |= event.alt_key ? ui::EF_ALT_DOWN : ui::EF_NONE;
313 flags |= event.ctrl_key ? ui::EF_CONTROL_DOWN : ui::EF_NONE;
314 flags |= event.shift_key ? ui::EF_SHIFT_DOWN : ui::EF_NONE;
315 flags |= event.caps_lock ? ui::EF_CAPS_LOCK_DOWN : ui::EF_NONE;
317 ui::KeyEvent ui_event(type,
321 false /* is_char */);
322 if (!event.key.empty())
323 ui_event.set_character(base::UTF8ToUTF16(event.key)[0]);
324 base::AutoReset<const ui::KeyEvent*> reset_sent_key(&sent_key_event_,
326 ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&ui_event);
327 if (details.dispatcher_destroyed)
333 const InputMethodEngine::CandidateWindowProperty&
334 InputMethodEngine::GetCandidateWindowProperty() const {
335 return candidate_window_property_;
338 void InputMethodEngine::SetCandidateWindowProperty(
339 const CandidateWindowProperty& property) {
340 // Type conversion from InputMethodEngineInterface::CandidateWindowProperty to
341 // CandidateWindow::CandidateWindowProperty defined in chromeos/ime/.
342 ui::CandidateWindow::CandidateWindowProperty dest_property;
343 dest_property.page_size = property.page_size;
344 dest_property.is_cursor_visible = property.is_cursor_visible;
345 dest_property.is_vertical = property.is_vertical;
346 dest_property.show_window_at_composition =
347 property.show_window_at_composition;
348 dest_property.cursor_position =
349 candidate_window_->GetProperty().cursor_position;
350 dest_property.auxiliary_text = property.auxiliary_text;
351 dest_property.is_auxiliary_text_visible = property.is_auxiliary_text_visible;
353 candidate_window_->SetProperty(dest_property);
354 candidate_window_property_ = property;
357 IMECandidateWindowHandlerInterface* cw_handler =
358 IMEBridge::Get()->GetCandidateWindowHandler();
360 cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
364 bool InputMethodEngine::SetCandidateWindowVisible(bool visible,
365 std::string* error) {
367 *error = kErrorNotActive;
371 window_visible_ = visible;
372 IMECandidateWindowHandlerInterface* cw_handler =
373 IMEBridge::Get()->GetCandidateWindowHandler();
375 cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
379 bool InputMethodEngine::SetCandidates(
381 const std::vector<Candidate>& candidates,
382 std::string* error) {
384 *error = kErrorNotActive;
387 if (context_id != context_id_ || context_id_ == -1) {
388 *error = kErrorWrongContext;
392 // TODO: Nested candidates
393 candidate_ids_.clear();
394 candidate_indexes_.clear();
395 candidate_window_->mutable_candidates()->clear();
396 for (std::vector<Candidate>::const_iterator ix = candidates.begin();
397 ix != candidates.end(); ++ix) {
398 ui::CandidateWindow::Entry entry;
399 entry.value = base::UTF8ToUTF16(ix->value);
400 entry.label = base::UTF8ToUTF16(ix->label);
401 entry.annotation = base::UTF8ToUTF16(ix->annotation);
402 entry.description_title = base::UTF8ToUTF16(ix->usage.title);
403 entry.description_body = base::UTF8ToUTF16(ix->usage.body);
405 // Store a mapping from the user defined ID to the candidate index.
406 candidate_indexes_[ix->id] = candidate_ids_.size();
407 candidate_ids_.push_back(ix->id);
409 candidate_window_->mutable_candidates()->push_back(entry);
412 IMECandidateWindowHandlerInterface* cw_handler =
413 IMEBridge::Get()->GetCandidateWindowHandler();
415 cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
420 bool InputMethodEngine::SetCursorPosition(int context_id, int candidate_id,
421 std::string* error) {
423 *error = kErrorNotActive;
426 if (context_id != context_id_ || context_id_ == -1) {
427 *error = kErrorWrongContext;
431 std::map<int, int>::const_iterator position =
432 candidate_indexes_.find(candidate_id);
433 if (position == candidate_indexes_.end()) {
434 *error = kCandidateNotFound;
438 candidate_window_->set_cursor_position(position->second);
439 IMECandidateWindowHandlerInterface* cw_handler =
440 IMEBridge::Get()->GetCandidateWindowHandler();
442 cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
446 bool InputMethodEngine::SetMenuItems(const std::vector<MenuItem>& items) {
447 return UpdateMenuItems(items);
450 bool InputMethodEngine::UpdateMenuItems(
451 const std::vector<MenuItem>& items) {
455 ash::ime::InputMethodMenuItemList menu_item_list;
456 for (std::vector<MenuItem>::const_iterator item = items.begin();
457 item != items.end(); ++item) {
458 ash::ime::InputMethodMenuItem property;
459 MenuItemToProperty(*item, &property);
460 menu_item_list.push_back(property);
463 ash::ime::InputMethodMenuManager::GetInstance()->
464 SetCurrentInputMethodMenuItemList(
469 bool InputMethodEngine::IsActive() const {
473 void InputMethodEngine::KeyEventDone(input_method::KeyEventHandle* key_data,
475 KeyEventDoneCallback* callback =
476 reinterpret_cast<KeyEventDoneCallback*>(key_data);
477 callback->Run(handled);
481 bool InputMethodEngine::DeleteSurroundingText(int context_id,
483 size_t number_of_chars,
484 std::string* error) {
486 *error = kErrorNotActive;
489 if (context_id != context_id_ || context_id_ == -1) {
490 *error = kErrorWrongContext;
494 if (offset < 0 && static_cast<size_t>(-1 * offset) != size_t(number_of_chars))
495 return false; // Currently we can only support preceding text.
497 // TODO(nona): Return false if there is ongoing composition.
499 IMEInputContextHandlerInterface* input_context =
500 IMEBridge::Get()->GetInputContextHandler();
502 input_context->DeleteSurroundingText(offset, number_of_chars);
507 void InputMethodEngine::HideInputView() {
508 keyboard::KeyboardController* keyboard_controller =
509 keyboard::KeyboardController::GetInstance();
510 if (keyboard_controller) {
511 keyboard_controller->HideKeyboard(
512 keyboard::KeyboardController::HIDE_REASON_MANUAL);
516 void InputMethodEngine::EnableInputView(bool enabled) {
517 const GURL& url = enabled ? input_view_url_ : GURL();
518 keyboard::SetOverrideContentUrl(url);
519 keyboard::KeyboardController* keyboard_controller =
520 keyboard::KeyboardController::GetInstance();
521 if (keyboard_controller)
522 keyboard_controller->Reload();
525 void InputMethodEngine::FocusIn(
526 const IMEEngineHandlerInterface::InputContext& input_context) {
527 current_input_type_ = input_context.type;
529 if (!active_ || current_input_type_ == ui::TEXT_INPUT_TYPE_NONE)
532 context_id_ = next_context_id_;
535 InputMethodEngineInterface::InputContext context;
536 context.id = context_id_;
537 switch (current_input_type_) {
538 case ui::TEXT_INPUT_TYPE_SEARCH:
539 context.type = "search";
541 case ui::TEXT_INPUT_TYPE_TELEPHONE:
542 context.type = "tel";
544 case ui::TEXT_INPUT_TYPE_URL:
545 context.type = "url";
547 case ui::TEXT_INPUT_TYPE_EMAIL:
548 context.type = "email";
550 case ui::TEXT_INPUT_TYPE_NUMBER:
551 context.type = "number";
553 case ui::TEXT_INPUT_TYPE_PASSWORD:
554 context.type = "password";
557 context.type = "text";
561 observer_->OnFocus(context);
564 void InputMethodEngine::FocusOut() {
565 if (!active_ || current_input_type_ == ui::TEXT_INPUT_TYPE_NONE)
568 current_input_type_ = ui::TEXT_INPUT_TYPE_NONE;
570 int context_id = context_id_;
572 observer_->OnBlur(context_id);
575 void InputMethodEngine::Enable() {
577 observer_->OnActivate(engine_id_);
578 current_input_type_ = IMEBridge::Get()->GetCurrentTextInputType();
579 FocusIn(IMEEngineHandlerInterface::InputContext(
580 current_input_type_, ui::TEXT_INPUT_MODE_DEFAULT));
581 EnableInputView(true);
583 start_time_ = base::Time();
584 end_time_ = base::Time();
585 RecordHistogram("Enable", 1);
588 void InputMethodEngine::Disable() {
590 observer_->OnDeactivated(engine_id_);
592 if (start_time_.ToInternalValue())
593 RecordHistogram("WorkingTime", (end_time_ - start_time_).InSeconds());
596 void InputMethodEngine::PropertyActivate(const std::string& property_name) {
597 observer_->OnMenuItemActivated(engine_id_, property_name);
600 void InputMethodEngine::Reset() {
601 observer_->OnReset(engine_id_);
604 void InputMethodEngine::ProcessKeyEvent(
605 const ui::KeyEvent& key_event,
606 const KeyEventDoneCallback& callback) {
608 KeyEventDoneCallback *handler = new KeyEventDoneCallback();
611 KeyboardEvent ext_event;
612 GetExtensionKeyboardEventFromKeyEvent(key_event, &ext_event);
614 // If the given key event is equal to the key event sent by
615 // SendKeyEvents, this engine ID is propagated to the extension IME.
616 // Note, this check relies on that ui::KeyEvent is propagated as
617 // reference without copying.
618 if (&key_event == sent_key_event_)
619 ext_event.extension_id = extension_id_;
621 observer_->OnKeyEvent(
624 reinterpret_cast<input_method::KeyEventHandle*>(handler));
627 void InputMethodEngine::CandidateClicked(uint32 index) {
628 if (index > candidate_ids_.size()) {
632 // Only left button click is supported at this moment.
633 observer_->OnCandidateClicked(
634 engine_id_, candidate_ids_.at(index), MOUSE_BUTTON_LEFT);
637 void InputMethodEngine::SetSurroundingText(const std::string& text,
640 observer_->OnSurroundingTextChanged(engine_id_,
642 static_cast<int>(cursor_pos),
643 static_cast<int>(anchor_pos));
646 // TODO(uekawa): rename this method to a more reasonable name.
647 void InputMethodEngine::MenuItemToProperty(
648 const MenuItem& item,
649 ash::ime::InputMethodMenuItem* property) {
650 property->key = item.id;
652 if (item.modified & MENU_ITEM_MODIFIED_LABEL) {
653 property->label = item.label;
655 if (item.modified & MENU_ITEM_MODIFIED_VISIBLE) {
656 // TODO(nona): Implement it.
658 if (item.modified & MENU_ITEM_MODIFIED_CHECKED) {
659 property->is_selection_item_checked = item.checked;
661 if (item.modified & MENU_ITEM_MODIFIED_ENABLED) {
662 // TODO(nona): implement sensitive entry(crbug.com/140192).
664 if (item.modified & MENU_ITEM_MODIFIED_STYLE) {
665 if (!item.children.empty()) {
666 // TODO(nona): Implement it.
668 switch (item.style) {
669 case MENU_ITEM_STYLE_NONE:
672 case MENU_ITEM_STYLE_CHECK:
673 // TODO(nona): Implement it.
675 case MENU_ITEM_STYLE_RADIO:
676 property->is_selection_item = true;
678 case MENU_ITEM_STYLE_SEPARATOR:
679 // TODO(nona): Implement it.
685 // TODO(nona): Support item.children.
688 } // namespace chromeos