1// Copyright (c) 2012 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
5#include "base/win/text_services_message_filter.h"
6
7namespace base {
8namespace win {
9
10TextServicesMessageFilter::TextServicesMessageFilter()
11    : client_id_(TF_CLIENTID_NULL),
12      is_initialized_(false) {
13}
14
15TextServicesMessageFilter::~TextServicesMessageFilter() {
16  if (is_initialized_)
17    thread_mgr_->Deactivate();
18}
19
20bool TextServicesMessageFilter::Init() {
21  if (FAILED(thread_mgr_.CreateInstance(CLSID_TF_ThreadMgr)))
22    return false;
23
24  if (FAILED(message_pump_.QueryFrom(thread_mgr_)))
25    return false;
26
27  if (FAILED(keystroke_mgr_.QueryFrom(thread_mgr_)))
28    return false;
29
30  if (FAILED(thread_mgr_->Activate(&client_id_)))
31    return false;
32
33  is_initialized_ = true;
34  return is_initialized_;
35}
36
37// Wraps for ITfMessagePump::PeekMessage with win32 PeekMessage signature.
38// Obtains messages from application message queue.
39BOOL TextServicesMessageFilter::DoPeekMessage(MSG* msg,
40                                              HWND window_handle,
41                                              UINT msg_filter_min,
42                                              UINT msg_filter_max,
43                                              UINT remove_msg) {
44  BOOL result = FALSE;
45  if (FAILED(message_pump_->PeekMessage(msg, window_handle,
46                                        msg_filter_min, msg_filter_max,
47                                        remove_msg, &result))) {
48    result = FALSE;
49  }
50
51  return result;
52}
53
54// Sends message to Text Service Manager.
55// The message will be used to input composition text.
56// Returns true if |message| was consumed by text service manager.
57bool TextServicesMessageFilter::ProcessMessage(const MSG& msg) {
58  if (msg.message == WM_KEYDOWN) {
59    BOOL eaten = FALSE;
60    HRESULT hr = keystroke_mgr_->TestKeyDown(msg.wParam, msg.lParam, &eaten);
61    if (FAILED(hr) && !eaten)
62      return false;
63    eaten = FALSE;
64    hr = keystroke_mgr_->KeyDown(msg.wParam, msg.lParam, &eaten);
65    return (SUCCEEDED(hr) && !!eaten);
66  }
67
68  if (msg.message == WM_KEYUP) {
69    BOOL eaten = FALSE;
70    HRESULT hr = keystroke_mgr_->TestKeyUp(msg.wParam, msg.lParam, &eaten);
71    if (FAILED(hr) && !eaten)
72      return false;
73    eaten = FALSE;
74    hr = keystroke_mgr_->KeyUp(msg.wParam, msg.lParam, &eaten);
75    return (SUCCEEDED(hr) && !!eaten);
76  }
77
78  return false;
79}
80
81}  // namespace win
82}  // namespace base
83