summaryrefslogtreecommitdiff
path: root/chromium/ui/base/ime/win/on_screen_keyboard_display_manager_input_pane.cc
blob: f9898d22a400d1575b645da090123f1018b74390 (plain)
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/ime/win/on_screen_keyboard_display_manager_input_pane.h"

#include "base/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/trace_event/trace_event.h"
#include "base/win/com_init_util.h"
#include "base/win/core_winrt_util.h"
#include "base/win/windows_version.h"
#include "ui/base/ime/input_method_keyboard_controller_observer.h"

namespace ui {

// VirtualKeyboardInputPane class is used to store all the COM objects and
// control their lifetime, so all the COM processing is on a background
// thread.
class OnScreenKeyboardDisplayManagerInputPane::VirtualKeyboardInputPane
    : public base::RefCountedThreadSafe<VirtualKeyboardInputPane> {
 public:
  explicit VirtualKeyboardInputPane(
      const scoped_refptr<base::SingleThreadTaskRunner> task_runner)
      : main_task_runner_(task_runner) {}

  void InitVirtualKeyboardInputPaneInstance(
      base::WeakPtr<OnScreenKeyboardDisplayManagerInputPane>
          input_pane_weak_ptr) {
    keyboard_input_pane_weak_ptr_ = input_pane_weak_ptr;
  }

  // Set the virtual keyboard input pane for |OnScreenKeyboardTest| tests.
  void SetInputPaneForTestingInBackgroundThread(
      Microsoft::WRL::ComPtr<ABI::Windows::UI::ViewManagement::IInputPane>
          pane) {
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    DCHECK(!input_pane_);
    input_pane_ = pane;
    HRESULT hr = input_pane_.As(&input_pane2_);
    DCHECK(SUCCEEDED(hr));

    AddCallbacksOnInputPaneShownOrHiddenInBackgroundThread();
  }

  void TryShowInBackgroundThread(HWND hwnd) {
    // TODO(crbug.com/1031786): Remove this once TSF fix for input pane policy
    // is serviced
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    if (!EnsureInputPanePointersInBackgroundThread(hwnd))
      return;
    boolean res;
    TRACE_EVENT0("vk",
                 "OnScreenKeyboardDisplayManagerInputPane::"
                 "VirtualKeyboardInputPane::TryShowInBackgroundThread");
    input_pane2_->TryShow(&res);
  }

  void TryHideInBackgroundThread(HWND hwnd) {
    // TODO(crbug.com/1031786): Remove this once TSF fix for input pane policy
    // is serviced
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    if (!EnsureInputPanePointersInBackgroundThread(hwnd))
      return;
    boolean res;
    TRACE_EVENT0("vk",
                 "OnScreenKeyboardDisplayManagerInputPane::"
                 "VirtualKeyboardInputPane::TryHideInBackgroundThread");
    input_pane2_->TryHide(&res);
  }

 private:
  friend class base::RefCountedThreadSafe<VirtualKeyboardInputPane>;

  ~VirtualKeyboardInputPane() {
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    if (input_pane_) {
      // Remove the callbacks that were registered.
      input_pane_->remove_Showing(show_event_token_);
      input_pane_->remove_Hiding(hide_event_token_);
    }
  }

  bool EnsureInputPanePointersInBackgroundThread(HWND hwnd) {
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    if (input_pane2_)
      return true;
    if (!base::win::ResolveCoreWinRTDelayload() ||
        !base::win::ScopedHString::ResolveCoreWinRTStringDelayload()) {
      return false;
    }

    base::win::AssertComApartmentType(base::win::ComApartmentType::STA);

    base::win::ScopedHString input_pane_guid = base::win::ScopedHString::Create(
        RuntimeClass_Windows_UI_ViewManagement_InputPane);
    Microsoft::WRL::ComPtr<IInputPaneInterop> input_pane_interop;
    HRESULT hr = base::win::RoGetActivationFactory(
        input_pane_guid.get(), IID_PPV_ARGS(&input_pane_interop));
    if (FAILED(hr))
      return false;

    hr = input_pane_interop->GetForWindow(hwnd, IID_PPV_ARGS(&input_pane_));
    if (FAILED(hr))
      return false;

    if (FAILED(input_pane_.As(&input_pane2_))) {
      input_pane_.Reset();
      return false;
    }

    AddCallbacksOnInputPaneShownOrHiddenInBackgroundThread();
    return true;
  }

  // Add callbacks to notify virtual keyboard observers when the virtual
  // keyboard is visible or hidden.
  void AddCallbacksOnInputPaneShownOrHiddenInBackgroundThread() {
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    input_pane_->add_Showing(
        Microsoft::WRL::Callback<
            OnScreenKeyboardDisplayManagerInputPane::VirtualKeyboardInputPane::
                InputPaneEventHandler>(
            this, &OnScreenKeyboardDisplayManagerInputPane::
                      VirtualKeyboardInputPane::OnInputPaneShown)
            .Get(),
        &show_event_token_);

    input_pane_->add_Hiding(
        Microsoft::WRL::Callback<
            OnScreenKeyboardDisplayManagerInputPane::VirtualKeyboardInputPane::
                InputPaneEventHandler>(
            this, &OnScreenKeyboardDisplayManagerInputPane::
                      VirtualKeyboardInputPane::OnInputPaneHidden)
            .Get(),
        &hide_event_token_);
  }

  HRESULT OnInputPaneShown(
      ABI::Windows::UI::ViewManagement::IInputPane* pane,
      ABI::Windows::UI::ViewManagement::IInputPaneVisibilityEventArgs* args) {
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    // Due to timing this could be called by the OS even when input_pane_
    // is null, so just bail out to avoid crashes.
    if (!input_pane_)
      return S_OK;

    ABI::Windows::Foundation::Rect rect;
    input_pane_->get_OccludedRect(&rect);
    gfx::Rect dip_rect(rect.X, rect.Y, rect.Width, rect.Height);
    TRACE_EVENT1("vk",
                 "OnScreenKeyboardDisplayManagerInputPane::"
                 "VirtualKeyboardInputPane::OnInputPaneShown",
                 "dip_rect", dip_rect.ToString());

    main_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&OnScreenKeyboardDisplayManagerInputPane::
                                      NotifyObserversOnKeyboardShown,
                                  keyboard_input_pane_weak_ptr_, dip_rect));
    return S_OK;
  }

  HRESULT OnInputPaneHidden(
      ABI::Windows::UI::ViewManagement::IInputPane* pane,
      ABI::Windows::UI::ViewManagement::IInputPaneVisibilityEventArgs* args) {
    DCHECK(!main_task_runner_->BelongsToCurrentThread());
    // Due to timing this could be called by the OS even when input_pane_
    // is null, so just bail out to avoid crashes.
    if (!input_pane_)
      return S_OK;

    TRACE_EVENT0("vk",
                 "OnScreenKeyboardDisplayManagerInputPane::"
                 "VirtualKeyboardInputPane::OnInputPaneHidden");
    main_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&OnScreenKeyboardDisplayManagerInputPane::
                                      NotifyObserversOnKeyboardHidden,
                                  keyboard_input_pane_weak_ptr_));
    return S_OK;
  }

  using InputPaneEventHandler = ABI::Windows::Foundation::ITypedEventHandler<
      ABI::Windows::UI::ViewManagement::InputPane*,
      ABI::Windows::UI::ViewManagement::InputPaneVisibilityEventArgs*>;

  // InputPane objects are owned by VirtualKeyboardInputPane class and their
  // functions are ran on a background thread.
  Microsoft::WRL::ComPtr<ABI::Windows::UI::ViewManagement::IInputPane>
      input_pane_;
  Microsoft::WRL::ComPtr<ABI::Windows::UI::ViewManagement::IInputPane2>
      input_pane2_;

  EventRegistrationToken show_event_token_;
  EventRegistrationToken hide_event_token_;

  // |main_task_runner_| and |keyboard_input_pane_weak_ptr_| are owned by
  // OnScreenKeyboardDisplayManagerInputPane class, and they are running on the
  // main thread, which are used to post task to the main thread from the
  // background thread.
  scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
  base::WeakPtr<OnScreenKeyboardDisplayManagerInputPane>
      keyboard_input_pane_weak_ptr_;

  DISALLOW_COPY_AND_ASSIGN(VirtualKeyboardInputPane);
};

OnScreenKeyboardDisplayManagerInputPane::
    OnScreenKeyboardDisplayManagerInputPane(HWND hwnd)
    : hwnd_(hwnd),
      main_task_runner_(base::ThreadTaskRunnerHandle::Get()),
      background_task_runner_(
          base::ThreadPool::CreateCOMSTATaskRunner({base::MayBlock()})),
      virtual_keyboard_input_pane_(
          base::MakeRefCounted<OnScreenKeyboardDisplayManagerInputPane::
                                   VirtualKeyboardInputPane>(
              main_task_runner_)),
      is_keyboard_visible_(false) {
  DCHECK_GE(base::win::GetVersion(), base::win::Version::WIN10_RS1);
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  // 300ms is the timer we chose after experimenting with users on windows touch
  // devices.
  debouncer_ = std::make_unique<VirtualKeyboardDebounceTimer>(300);

  // We post the initiation of |virtual_keyboard_input_pane_| to the background
  // thread first, and any other tasks posted to the background thread are
  // executed after its initiation.
  background_task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(
          &OnScreenKeyboardDisplayManagerInputPane::VirtualKeyboardInputPane::
              InitVirtualKeyboardInputPaneInstance,
          base::RetainedRef(virtual_keyboard_input_pane_),
          weak_factory_.GetWeakPtr()));
}

void OnScreenKeyboardDisplayManagerInputPane::Run() {
  // Execute show() or hide() on the background thread after the debounce
  // expires.
  switch (last_vk_visibility_request_) {
    case mojom::VirtualKeyboardVisibilityRequest::SHOW: {
      background_task_runner_->PostTask(
          FROM_HERE,
          base::BindOnce(
              &OnScreenKeyboardDisplayManagerInputPane::
                  VirtualKeyboardInputPane::TryShowInBackgroundThread,
              base::RetainedRef(virtual_keyboard_input_pane_), hwnd_));
      break;
    }
    case mojom::VirtualKeyboardVisibilityRequest::HIDE: {
      background_task_runner_->PostTask(
          FROM_HERE,
          base::BindOnce(
              &OnScreenKeyboardDisplayManagerInputPane::
                  VirtualKeyboardInputPane::TryHideInBackgroundThread,
              base::RetainedRef(virtual_keyboard_input_pane_), hwnd_));
      break;
    }
    case mojom::VirtualKeyboardVisibilityRequest::NONE: {
      break;
    }
  }
  // Reset the VK visibility state to none so we can keep track of subsequent
  // API calls.
  last_vk_visibility_request_ = mojom::VirtualKeyboardVisibilityRequest::NONE;
}

bool OnScreenKeyboardDisplayManagerInputPane::DisplayVirtualKeyboard() {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  last_vk_visibility_request_ = mojom::VirtualKeyboardVisibilityRequest::SHOW;
  debouncer_->RequestRun(base::BindOnce(
      &OnScreenKeyboardDisplayManagerInputPane::Run, base::Unretained(this)));
  return true;
}

void OnScreenKeyboardDisplayManagerInputPane::DismissVirtualKeyboard() {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  last_vk_visibility_request_ = mojom::VirtualKeyboardVisibilityRequest::HIDE;
  debouncer_->RequestRun(base::BindOnce(
      &OnScreenKeyboardDisplayManagerInputPane::Run, base::Unretained(this)));
}

void OnScreenKeyboardDisplayManagerInputPane::AddObserver(
    InputMethodKeyboardControllerObserver* observer) {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  observers_.AddObserver(observer);
}

void OnScreenKeyboardDisplayManagerInputPane::RemoveObserver(
    InputMethodKeyboardControllerObserver* observer) {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  observers_.RemoveObserver(observer);
}

bool OnScreenKeyboardDisplayManagerInputPane::IsKeyboardVisible() {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  return is_keyboard_visible_;
}

void OnScreenKeyboardDisplayManagerInputPane::SetInputPaneForTesting(
    Microsoft::WRL::ComPtr<ABI::Windows::UI::ViewManagement::IInputPane> pane) {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  base::ThreadPool::CreateCOMSTATaskRunner({base::MayBlock()})
      ->PostTask(FROM_HERE,
                 base::BindOnce(
                     &OnScreenKeyboardDisplayManagerInputPane::
                         VirtualKeyboardInputPane::
                             SetInputPaneForTestingInBackgroundThread,
                     base::RetainedRef(virtual_keyboard_input_pane_), pane));
}

void OnScreenKeyboardDisplayManagerInputPane::NotifyObserversOnKeyboardShown(
    gfx::Rect dip_rect) {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  is_keyboard_visible_ = true;
  for (InputMethodKeyboardControllerObserver& observer : observers_)
    observer.OnKeyboardVisible(dip_rect);
}

void OnScreenKeyboardDisplayManagerInputPane::
    NotifyObserversOnKeyboardHidden() {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  is_keyboard_visible_ = false;
  for (InputMethodKeyboardControllerObserver& observer : observers_)
    observer.OnKeyboardHidden();
}

OnScreenKeyboardDisplayManagerInputPane::
    ~OnScreenKeyboardDisplayManagerInputPane() {
  DCHECK(main_task_runner_->BelongsToCurrentThread());
  // In-case there is a debouncer task running, cancel it.
  debouncer_->CancelRequest();
  if (virtual_keyboard_input_pane_.get()) {
    background_task_runner_->ReleaseSoon(
        FROM_HERE, std::move(virtual_keyboard_input_pane_));
  }
}

}  // namespace ui