keyboard_layout_mac.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2016 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 "ui/events/test/keyboard_layout.h"
  5. #include "base/check_op.h"
  6. namespace ui {
  7. PlatformKeyboardLayout GetPlatformKeyboardLayout(KeyboardLayout layout) {
  8. // Right now tests only need US English. If other layouts need to be
  9. // supported in the future this code should be extended.
  10. DCHECK_EQ(KEYBOARD_LAYOUT_ENGLISH_US, layout);
  11. const char kUsInputSourceId[] = "com.apple.keylayout.US";
  12. base::ScopedCFTypeRef<CFMutableDictionaryRef> input_source_list_filter(
  13. CFDictionaryCreateMutable(kCFAllocatorDefault, 1,
  14. &kCFTypeDictionaryKeyCallBacks,
  15. &kCFTypeDictionaryValueCallBacks));
  16. base::ScopedCFTypeRef<CFStringRef> input_source_id_ref(
  17. CFStringCreateWithCString(kCFAllocatorDefault, kUsInputSourceId,
  18. kCFStringEncodingUTF8));
  19. CFDictionaryAddValue(input_source_list_filter, kTISPropertyInputSourceID,
  20. input_source_id_ref);
  21. base::ScopedCFTypeRef<CFArrayRef> input_source_list(
  22. TISCreateInputSourceList(input_source_list_filter, true));
  23. if (CFArrayGetCount(input_source_list) != 1)
  24. return PlatformKeyboardLayout();
  25. return base::ScopedCFTypeRef<TISInputSourceRef>(
  26. (TISInputSourceRef)CFArrayGetValueAtIndex(input_source_list, 0),
  27. base::scoped_policy::RETAIN);
  28. }
  29. PlatformKeyboardLayout ScopedKeyboardLayout::GetActiveLayout() {
  30. return PlatformKeyboardLayout(TISCopyCurrentKeyboardInputSource());
  31. }
  32. void ScopedKeyboardLayout::ActivateLayout(PlatformKeyboardLayout layout) {
  33. DCHECK(layout);
  34. // According to the documentation in HIToolbox's TextInputSources.h
  35. // (recommended reading), TISSelectInputSource() can fail if the input source
  36. // isn't "selectable" or "enabled".
  37. //
  38. // On the bots, for some reason, sometimes the US keyboard layout isn't
  39. // "enabled" even though it is present - we aren't sure why this happens,
  40. // perhaps if input sources have never been switched on this bot before? In
  41. // any case, it's harmless to re-enable it here if it's already enabled.
  42. OSStatus result = TISEnableInputSource(layout);
  43. DCHECK_EQ(noErr, result);
  44. result = TISSelectInputSource(layout);
  45. DCHECK_EQ(noErr, result);
  46. }
  47. } // namespace ui