File: keyboard_layout_monitor_mac.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (349 lines) | stat: -rw-r--r-- 12,293 bytes parent folder | download | duplicates (6)
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
341
342
343
344
345
346
347
348
349
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/keyboard_layout_monitor.h"

#include <Carbon/Carbon.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>

#include <memory>
#include <optional>
#include <string_view>
#include <utility>

#include "base/apple/scoped_cftyperef.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "remoting/proto/control.pb.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"

namespace remoting {

namespace {

class KeyboardLayoutMonitorMac : public KeyboardLayoutMonitor {
 public:
  explicit KeyboardLayoutMonitorMac(
      base::RepeatingCallback<void(const protocol::KeyboardLayout&)> callback);

  ~KeyboardLayoutMonitorMac() override;

  void Start() override;

 private:
  struct CallbackContext {
    scoped_refptr<base::SequencedTaskRunner> task_runner;
    base::WeakPtr<KeyboardLayoutMonitorMac> weak_ptr;
  };

  void OnLayoutChanged(const protocol::KeyboardLayout& new_layout);

  static void SelectedKeyboardInputSourceChangedCallback(
      CFNotificationCenterRef center,
      void* observer,
      CFNotificationName name,
      const void* object,
      CFDictionaryRef userInfo);

  static void QueryLayoutOnMainLoop(CallbackContext* callback_context);

  base::RepeatingCallback<void(const protocol::KeyboardLayout&)> callback_;
  std::unique_ptr<CallbackContext> callback_context_;
  base::WeakPtrFactory<KeyboardLayoutMonitorMac> weak_ptr_factory_;
};

std::optional<protocol::LayoutKeyFunction> GetFixedKeyFunction(int keycode);
std::optional<protocol::LayoutKeyFunction> GetCharFunction(UniChar char_code,
                                                           int keycode);

KeyboardLayoutMonitorMac::KeyboardLayoutMonitorMac(
    base::RepeatingCallback<void(const protocol::KeyboardLayout&)> callback)
    : callback_(std::move(callback)), weak_ptr_factory_(this) {}

KeyboardLayoutMonitorMac::~KeyboardLayoutMonitorMac() {
  if (!callback_context_) {
    return;
  }

  CFNotificationCenterRemoveObserver(
      CFNotificationCenterGetDistributedCenter(), callback_context_.get(),
      kTISNotifySelectedKeyboardInputSourceChanged, nullptr);

  // The distributed notification center posts all notifications from the
  // process's main run loop. Schedule deletion from the same loop to ensure
  // we don't delete the callback context while a notification is being
  // dispatched.
  // Store the callback context pointer in a local variable so the block
  // captures it directly instead of capturing this.
  CallbackContext* callback_context = callback_context_.release();
  CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^(void) {
    delete callback_context;
  });
  // No need to explicitly wake up the main loop here. It's fine if the
  // deletion is delayed slightly until the next time the main loop wakes up
  // normally.
}

void KeyboardLayoutMonitorMac::Start() {
  DCHECK(!callback_context_);
  callback_context_ = std::make_unique<CallbackContext>(
      CallbackContext{base::SequencedTaskRunner::GetCurrentDefault(),
                      weak_ptr_factory_.GetWeakPtr()});
  CFNotificationCenterAddObserver(
      CFNotificationCenterGetDistributedCenter(), callback_context_.get(),
      SelectedKeyboardInputSourceChangedCallback,
      kTISNotifySelectedKeyboardInputSourceChanged, nullptr,
      CFNotificationSuspensionBehaviorDeliverImmediately);

  // Get the initial layout.
  // Store the callback context pointer in a local variable so the block
  // captures it directly instead of capturing this.
  CallbackContext* callback_context = callback_context_.get();
  base::apple::ScopedCFTypeRef<CFRunLoopRef> main_loop(
      CFRunLoopGetMain(), base::scoped_policy::RETAIN);
  CFRunLoopPerformBlock(main_loop.get(), kCFRunLoopCommonModes, ^(void) {
    QueryLayoutOnMainLoop(callback_context);
  });
  CFRunLoopWakeUp(main_loop.get());
}

void KeyboardLayoutMonitorMac::OnLayoutChanged(
    const protocol::KeyboardLayout& new_layout) {
  callback_.Run(new_layout);
}

// static
void KeyboardLayoutMonitorMac::SelectedKeyboardInputSourceChangedCallback(
    CFNotificationCenterRef center,
    void* observer,
    CFNotificationName name,
    const void* object,
    CFDictionaryRef userInfo) {
  CallbackContext* callback_context = static_cast<CallbackContext*>(observer);
  QueryLayoutOnMainLoop(callback_context);
}

// static
void KeyboardLayoutMonitorMac::QueryLayoutOnMainLoop(
    KeyboardLayoutMonitorMac::CallbackContext* callback_context) {
  base::apple::ScopedCFTypeRef<TISInputSourceRef> input_source(
      TISCopyCurrentKeyboardLayoutInputSource());
  base::apple::ScopedCFTypeRef<CFDataRef> layout_data(
      static_cast<CFDataRef>(TISGetInputSourceProperty(
          input_source.get(), kTISPropertyUnicodeKeyLayoutData)),
      base::scoped_policy::RETAIN);

  if (!layout_data) {
    LOG(WARNING) << "Failed to query keyboard layout.";
    return;
  }

  protocol::KeyboardLayout layout_message;

  std::uint8_t keyboard_type = LMGetKbdType();
  PhysicalKeyboardLayoutType layout_type = KBGetLayoutType(keyboard_type);

  for (ui::DomCode key : KeyboardLayoutMonitor::kSupportedKeys) {
    // Lang1 and Lang2 are only present on JIS-style keyboards.
    if ((key == ui::DomCode::LANG1 || key == ui::DomCode::LANG2) &&
        layout_type != kKeyboardJIS) {
      continue;
    }

    // Skip Caps Lock until we decide how/if we want to handle it.
    if (key == ui::DomCode::CAPS_LOCK) {
      continue;
    }

    std::uint32_t usb_code = ui::KeycodeConverter::DomCodeToUsbKeycode(key);
    int keycode = ui::KeycodeConverter::DomCodeToNativeKeycode(key);

    auto& key_actions =
        *(*layout_message.mutable_keys())[usb_code].mutable_actions();

    for (int shift_level = 0; shift_level < 4; ++shift_level) {
      std::optional<protocol::LayoutKeyFunction> fixed_function =
          GetFixedKeyFunction(keycode);
      if (fixed_function) {
        key_actions[shift_level].set_function(*fixed_function);
        continue;
      }

      std::uint32_t modifier_state = 0;
      if (shift_level & 1) {
        modifier_state |= shiftKey;
      }
      if (shift_level & 2) {
        modifier_state |= optionKey;
      }
      std::uint32_t deadkey_state = 0;
      UniChar result_array[255];
      UniCharCount result_length = 0;
      UCKeyTranslate(reinterpret_cast<const UCKeyboardLayout*>(
                         CFDataGetBytePtr(layout_data.get())),
                     keycode, kUCKeyActionDown, modifier_state >> 8,
                     keyboard_type, kUCKeyTranslateNoDeadKeysMask,
                     &deadkey_state, std::size(result_array), &result_length,
                     result_array);

      if (result_length == 0) {
        continue;
      }

      if (result_length == 1) {
        std::optional<protocol::LayoutKeyFunction> char_function =
            GetCharFunction(result_array[0], keycode);
        if (char_function) {
          key_actions[shift_level].set_function(*char_function);
          continue;
        }
      }

      key_actions[shift_level].set_character(
          base::UTF16ToUTF8(std::u16string_view(
              reinterpret_cast<const char16_t*>(result_array), result_length)));
    }

    if (key_actions.size() == 0) {
      layout_message.mutable_keys()->erase(usb_code);
    }
  }

  callback_context->task_runner->PostTask(
      FROM_HERE,
      base::BindOnce(&KeyboardLayoutMonitorMac::OnLayoutChanged,
                     callback_context->weak_ptr, std::move(layout_message)));
}

std::optional<protocol::LayoutKeyFunction> GetFixedKeyFunction(int keycode) {
  // Some keys are not represented in the layout and always have the same
  // function.
  switch (keycode) {
    case kVK_Command:
    case kVK_RightCommand:
      return protocol::LayoutKeyFunction::COMMAND;
    case kVK_Shift:
    case kVK_RightShift:
      return protocol::LayoutKeyFunction::SHIFT;
    case kVK_CapsLock:
      return protocol::LayoutKeyFunction::CAPS_LOCK;
    case kVK_Option:
    case kVK_RightOption:
      return protocol::LayoutKeyFunction::OPTION;
    case kVK_Control:
    case kVK_RightControl:
      return protocol::LayoutKeyFunction::CONTROL;
    case kVK_F1:
      return protocol::LayoutKeyFunction::F1;
    case kVK_F2:
      return protocol::LayoutKeyFunction::F2;
    case kVK_F3:
      return protocol::LayoutKeyFunction::F3;
    case kVK_F4:
      return protocol::LayoutKeyFunction::F4;
    case kVK_F5:
      return protocol::LayoutKeyFunction::F5;
    case kVK_F6:
      return protocol::LayoutKeyFunction::F6;
    case kVK_F7:
      return protocol::LayoutKeyFunction::F7;
    case kVK_F8:
      return protocol::LayoutKeyFunction::F8;
    case kVK_F9:
      return protocol::LayoutKeyFunction::F9;
    case kVK_F10:
      return protocol::LayoutKeyFunction::F10;
    case kVK_F11:
      return protocol::LayoutKeyFunction::F11;
    case kVK_F12:
      return protocol::LayoutKeyFunction::F12;
    case kVK_F13:
      return protocol::LayoutKeyFunction::F13;
    case kVK_F14:
      return protocol::LayoutKeyFunction::F14;
    case kVK_F15:
      return protocol::LayoutKeyFunction::F15;
    case kVK_F16:
      return protocol::LayoutKeyFunction::F16;
    case kVK_F17:
      return protocol::LayoutKeyFunction::F17;
    case kVK_F18:
      return protocol::LayoutKeyFunction::F18;
    case kVK_F19:
      return protocol::LayoutKeyFunction::F19;
    case kVK_JIS_Kana:
      return protocol::LayoutKeyFunction::KANA;
    case kVK_JIS_Eisu:
      return protocol::LayoutKeyFunction::EISU;
    default:
      return std::nullopt;
  }
}

std::optional<protocol::LayoutKeyFunction> GetCharFunction(UniChar char_code,
                                                           int keycode) {
  switch (char_code) {
    case kHomeCharCode:
      return protocol::LayoutKeyFunction::HOME;
    case kEnterCharCode:
      // Numpad Enter
      return protocol::LayoutKeyFunction::ENTER;
    case kEndCharCode:
      return protocol::LayoutKeyFunction::END;
    case kHelpCharCode:
      // Old Macs called this key "Help". Newer Macs lack it altogether (and
      // have "Fn" in this position).
      // TODO(rkjnsn): See how the latest macOS handles this key, and consider
      // hiding this key or creating a distinct HELP function, as appropriate.
      return protocol::LayoutKeyFunction::INSERT;
    case kBackspaceCharCode:
      return protocol::LayoutKeyFunction::BACKSPACE;
    case kTabCharCode:
      return protocol::LayoutKeyFunction::TAB;
    case kPageUpCharCode:
      return protocol::LayoutKeyFunction::PAGE_UP;
    case kPageDownCharCode:
      return protocol::LayoutKeyFunction::PAGE_DOWN;
    case kReturnCharCode:
      // Writing system return key.
      return protocol::LayoutKeyFunction::ENTER;
    case kFunctionKeyCharCode:
      // The known keys with this char code are handled by GetFixedKeyFunction.
      return protocol::LayoutKeyFunction::UNKNOWN;
    case kEscapeCharCode:
      if (keycode == kVK_ANSI_KeypadClear) {
        return protocol::LayoutKeyFunction::CLEAR;
      }
      return protocol::LayoutKeyFunction::ESCAPE;
    case kLeftArrowCharCode:
      return protocol::LayoutKeyFunction::ARROW_LEFT;
    case kRightArrowCharCode:
      return protocol::LayoutKeyFunction::ARROW_RIGHT;
    case kUpArrowCharCode:
      return protocol::LayoutKeyFunction::ARROW_UP;
    case kDownArrowCharCode:
      return protocol::LayoutKeyFunction::ARROW_DOWN;
    case kDeleteCharCode:
      return protocol::LayoutKeyFunction::DELETE_;
    default:
      return std::nullopt;
  }
}

}  // namespace

std::unique_ptr<KeyboardLayoutMonitor> KeyboardLayoutMonitor::Create(
    base::RepeatingCallback<void(const protocol::KeyboardLayout&)> callback,
    scoped_refptr<base::SingleThreadTaskRunner> input_task_runner) {
  return std::make_unique<KeyboardLayoutMonitorMac>(std::move(callback));
}

}  // namespace remoting