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 "chromeos/ime/xkeyboard.h"
13 #include "base/bind.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/process/kill.h"
18 #include "base/process/launch.h"
19 #include "base/process/process_handle.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/sys_info.h"
23 #include "base/threading/thread_checker.h"
25 // These includes conflict with base/tracked_objects.h so must come last.
26 #include <X11/XKBlib.h>
30 namespace input_method {
33 Display* GetXDisplay() {
34 return base::MessagePumpForUI::GetDefaultXDisplay();
37 // The delay in milliseconds that we'll wait between checking if
38 // setxkbmap command finished.
39 const int kSetLayoutCommandCheckDelayMs = 100;
41 // The command we use to set the current XKB layout and modifier key mapping.
42 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
43 const char kSetxkbmapCommand[] = "/usr/bin/setxkbmap";
45 // A string for obtaining a mask value for Num Lock.
46 const char kNumLockVirtualModifierString[] = "NumLock";
48 // Returns false if |layout_name| contains a bad character.
49 bool CheckLayoutName(const std::string& layout_name) {
50 static const char kValidLayoutNameCharacters[] =
51 "abcdefghijklmnopqrstuvwxyz0123456789()-_";
53 if (layout_name.empty()) {
54 DVLOG(1) << "Invalid layout_name: " << layout_name;
58 if (layout_name.find_first_not_of(kValidLayoutNameCharacters) !=
60 DVLOG(1) << "Invalid layout_name: " << layout_name;
67 class XKeyboardImpl : public XKeyboard {
70 virtual ~XKeyboardImpl() {}
72 // Overridden from XKeyboard:
73 virtual bool SetCurrentKeyboardLayoutByName(
74 const std::string& layout_name) OVERRIDE;
75 virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE;
76 virtual void ReapplyCurrentModifierLockStatus() OVERRIDE;
77 virtual void SetLockedModifiers(
78 ModifierLockStatus new_caps_lock_status,
79 ModifierLockStatus new_num_lock_status) OVERRIDE;
80 virtual void SetNumLockEnabled(bool enable_num_lock) OVERRIDE;
81 virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE;
82 virtual bool NumLockIsEnabled() OVERRIDE;
83 virtual bool CapsLockIsEnabled() OVERRIDE;
84 virtual unsigned int GetNumLockMask() OVERRIDE;
85 virtual void GetLockedModifiers(bool* out_caps_lock_enabled,
86 bool* out_num_lock_enabled) OVERRIDE;
87 virtual bool SetAutoRepeatEnabled(bool enabled) OVERRIDE;
88 virtual bool SetAutoRepeatRate(const AutoRepeatRate& rate) OVERRIDE;
91 // This function is used by SetLayout() and RemapModifierKeys(). Calls
92 // setxkbmap command if needed, and updates the last_full_layout_name_ cache.
93 bool SetLayoutInternal(const std::string& layout_name, bool force);
95 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
96 // in the |execute_queue_|. Do nothing if the queue is empty.
97 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
98 void MaybeExecuteSetLayoutCommand();
100 // Polls to see setxkbmap process exits.
101 void PollUntilChildFinish(const base::ProcessHandle handle);
103 // Called when execve'd setxkbmap process exits.
104 void OnSetLayoutFinish();
106 const bool is_running_on_chrome_os_;
107 unsigned int num_lock_mask_;
109 // The current Num Lock and Caps Lock status. If true, enabled.
110 bool current_num_lock_status_;
111 bool current_caps_lock_status_;
112 // The XKB layout name which we set last time like "us" and "us(dvorak)".
113 std::string current_layout_name_;
115 // A queue for executing setxkbmap one by one.
116 std::queue<std::string> execute_queue_;
118 base::ThreadChecker thread_checker_;
120 base::WeakPtrFactory<XKeyboardImpl> weak_factory_;
122 DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl);
125 XKeyboardImpl::XKeyboardImpl()
126 : is_running_on_chrome_os_(base::SysInfo::IsRunningOnChromeOS()),
127 weak_factory_(this) {
128 // X must be already initialized.
129 CHECK(GetXDisplay());
131 num_lock_mask_ = GetNumLockMask();
133 if (is_running_on_chrome_os_) {
134 // Some code seems to assume that Mod2Mask is always assigned to
137 // TODO(yusukes): Check the assumption is really okay. If not,
138 // modify the Aura code, and then remove the CHECK below.
139 LOG_IF(ERROR, num_lock_mask_ != Mod2Mask)
140 << "NumLock is not assigned to Mod2Mask. : " << num_lock_mask_;
142 GetLockedModifiers(¤t_caps_lock_status_, ¤t_num_lock_status_);
145 bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name,
147 if (!is_running_on_chrome_os_) {
148 // We should not try to change a layout on Linux or inside ui_tests. Just
153 if (!CheckLayoutName(layout_name))
156 if (!force && (current_layout_name_ == layout_name)) {
157 DVLOG(1) << "The requested layout is already set: " << layout_name;
161 DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name;
163 const bool start_execution = execute_queue_.empty();
164 // If no setxkbmap command is in flight (i.e. start_execution is true),
165 // start the first one by explicitly calling MaybeExecuteSetLayoutCommand().
166 // If one or more setxkbmap commands are already in flight, just push the
167 // layout name to the queue. setxkbmap command for the layout will be called
168 // via OnSetLayoutFinish() callback later.
169 execute_queue_.push(layout_name);
171 MaybeExecuteSetLayoutCommand();
176 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
177 // in the |execute_queue_|. Do nothing if the queue is empty.
178 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
179 void XKeyboardImpl::MaybeExecuteSetLayoutCommand() {
180 if (execute_queue_.empty())
182 const std::string layout_to_set = execute_queue_.front();
184 std::vector<std::string> argv;
185 base::ProcessHandle handle = base::kNullProcessHandle;
187 argv.push_back(kSetxkbmapCommand);
188 argv.push_back("-layout");
189 argv.push_back(layout_to_set);
190 argv.push_back("-synch");
192 if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) {
193 DVLOG(1) << "Failed to execute setxkbmap: " << layout_to_set;
194 execute_queue_ = std::queue<std::string>(); // clear the queue.
198 PollUntilChildFinish(handle);
200 DVLOG(1) << "ExecuteSetLayoutCommand: "
201 << layout_to_set << ": pid=" << base::GetProcId(handle);
204 // Delay and loop until child process finishes and call the callback.
205 void XKeyboardImpl::PollUntilChildFinish(const base::ProcessHandle handle) {
207 DVLOG(1) << "PollUntilChildFinish: poll for pid=" << base::GetProcId(handle);
208 switch (base::GetTerminationStatus(handle, &exit_code)) {
209 case base::TERMINATION_STATUS_STILL_RUNNING:
210 DVLOG(1) << "PollUntilChildFinish: Try waiting again";
211 base::MessageLoop::current()->PostDelayedTask(
213 base::Bind(&XKeyboardImpl::PollUntilChildFinish,
214 weak_factory_.GetWeakPtr(), handle),
215 base::TimeDelta::FromMilliseconds(kSetLayoutCommandCheckDelayMs));
218 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
219 DVLOG(1) << "PollUntilChildFinish: Child process finished";
223 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
224 DVLOG(1) << "PollUntilChildFinish: Abnormal exit code: " << exit_code;
235 bool XKeyboardImpl::NumLockIsEnabled() {
236 bool num_lock_enabled = false;
237 GetLockedModifiers(NULL /* Caps Lock */, &num_lock_enabled);
238 return num_lock_enabled;
241 bool XKeyboardImpl::CapsLockIsEnabled() {
242 bool caps_lock_enabled = false;
243 GetLockedModifiers(&caps_lock_enabled, NULL /* Num Lock */);
244 return caps_lock_enabled;
247 unsigned int XKeyboardImpl::GetNumLockMask() {
248 DCHECK(thread_checker_.CalledOnValidThread());
249 static const unsigned int kBadMask = 0;
251 unsigned int real_mask = kBadMask;
252 XkbDescPtr xkb_desc =
253 XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd);
257 if (xkb_desc->dpy && xkb_desc->names && xkb_desc->names->vmods) {
258 const std::string string_to_find(kNumLockVirtualModifierString);
259 for (size_t i = 0; i < XkbNumVirtualMods; ++i) {
260 const unsigned int virtual_mod_mask = 1U << i;
261 char* virtual_mod_str_raw_ptr =
262 XGetAtomName(xkb_desc->dpy, xkb_desc->names->vmods[i]);
263 if (!virtual_mod_str_raw_ptr)
265 const std::string virtual_mod_str = virtual_mod_str_raw_ptr;
266 XFree(virtual_mod_str_raw_ptr);
268 if (string_to_find == virtual_mod_str) {
269 if (!XkbVirtualModsToReal(xkb_desc, virtual_mod_mask, &real_mask)) {
270 DVLOG(1) << "XkbVirtualModsToReal failed";
271 real_mask = kBadMask; // reset the return value, just in case.
277 XkbFreeKeyboard(xkb_desc, 0, True /* free all components */);
281 void XKeyboardImpl::GetLockedModifiers(bool* out_caps_lock_enabled,
282 bool* out_num_lock_enabled) {
283 DCHECK(thread_checker_.CalledOnValidThread());
285 if (out_num_lock_enabled && !num_lock_mask_) {
286 DVLOG(1) << "Cannot get locked modifiers. Num Lock mask unknown.";
287 if (out_caps_lock_enabled)
288 *out_caps_lock_enabled = false;
289 if (out_num_lock_enabled)
290 *out_num_lock_enabled = false;
295 XkbGetState(GetXDisplay(), XkbUseCoreKbd, &status);
296 if (out_caps_lock_enabled)
297 *out_caps_lock_enabled = status.locked_mods & LockMask;
298 if (out_num_lock_enabled)
299 *out_num_lock_enabled = status.locked_mods & num_lock_mask_;
302 bool XKeyboardImpl::SetAutoRepeatEnabled(bool enabled) {
304 XAutoRepeatOn(GetXDisplay());
306 XAutoRepeatOff(GetXDisplay());
307 DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off");
311 bool XKeyboardImpl::SetAutoRepeatRate(const AutoRepeatRate& rate) {
312 DVLOG(1) << "Set auto-repeat rate to: "
313 << rate.initial_delay_in_ms << " ms delay, "
314 << rate.repeat_interval_in_ms << " ms interval";
315 if (XkbSetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd,
316 rate.initial_delay_in_ms,
317 rate.repeat_interval_in_ms) != True) {
318 DVLOG(1) << "Failed to set auto-repeat rate";
324 void XKeyboardImpl::SetLockedModifiers(ModifierLockStatus new_caps_lock_status,
325 ModifierLockStatus new_num_lock_status) {
326 DCHECK(thread_checker_.CalledOnValidThread());
327 if (!num_lock_mask_) {
328 DVLOG(1) << "Cannot set locked modifiers. Num Lock mask unknown.";
332 unsigned int affect_mask = 0;
333 unsigned int value_mask = 0;
334 if (new_caps_lock_status != kDontChange) {
335 affect_mask |= LockMask;
336 value_mask |= ((new_caps_lock_status == kEnableLock) ? LockMask : 0);
337 current_caps_lock_status_ = (new_caps_lock_status == kEnableLock);
339 if (new_num_lock_status != kDontChange) {
340 affect_mask |= num_lock_mask_;
341 value_mask |= ((new_num_lock_status == kEnableLock) ? num_lock_mask_ : 0);
342 current_num_lock_status_ = (new_num_lock_status == kEnableLock);
346 XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask);
349 void XKeyboardImpl::SetNumLockEnabled(bool enable_num_lock) {
351 kDontChange, enable_num_lock ? kEnableLock : kDisableLock);
354 void XKeyboardImpl::SetCapsLockEnabled(bool enable_caps_lock) {
356 enable_caps_lock ? kEnableLock : kDisableLock, kDontChange);
359 bool XKeyboardImpl::SetCurrentKeyboardLayoutByName(
360 const std::string& layout_name) {
361 if (SetLayoutInternal(layout_name, false)) {
362 current_layout_name_ = layout_name;
368 bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() {
369 if (current_layout_name_.empty()) {
370 DVLOG(1) << "Can't reapply XKB layout: layout unknown";
373 return SetLayoutInternal(current_layout_name_, true /* force */);
376 void XKeyboardImpl::ReapplyCurrentModifierLockStatus() {
377 SetLockedModifiers(current_caps_lock_status_ ? kEnableLock : kDisableLock,
378 current_num_lock_status_ ? kEnableLock : kDisableLock);
381 void XKeyboardImpl::OnSetLayoutFinish() {
382 if (execute_queue_.empty()) {
383 DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. "
384 << "base::LaunchProcess failed?";
387 execute_queue_.pop();
388 MaybeExecuteSetLayoutCommand();
394 bool XKeyboard::GetAutoRepeatEnabledForTesting() {
395 XKeyboardState state = {};
396 XGetKeyboardControl(GetXDisplay(), &state);
397 return state.global_auto_repeat != AutoRepeatModeOff;
401 bool XKeyboard::GetAutoRepeatRateForTesting(AutoRepeatRate* out_rate) {
402 return XkbGetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd,
403 &(out_rate->initial_delay_in_ms),
404 &(out_rate->repeat_interval_in_ms)) == True;
408 bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) {
409 return CheckLayoutName(layout_name);
413 XKeyboard* XKeyboard::Create() {
414 return new XKeyboardImpl();
417 } // namespace input_method
418 } // namespace chromeos