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 const char *kISOLevel5ShiftLayoutIds[] = {
53 const char *kAltGrLayoutIds[] = {
96 // Returns false if |layout_name| contains a bad character.
97 bool CheckLayoutName(const std::string& layout_name) {
98 static const char kValidLayoutNameCharacters[] =
99 "abcdefghijklmnopqrstuvwxyz0123456789()-_";
101 if (layout_name.empty()) {
102 DVLOG(1) << "Invalid layout_name: " << layout_name;
106 if (layout_name.find_first_not_of(kValidLayoutNameCharacters) !=
108 DVLOG(1) << "Invalid layout_name: " << layout_name;
115 class XKeyboardImpl : public XKeyboard {
118 virtual ~XKeyboardImpl() {}
120 // Overridden from XKeyboard:
121 virtual bool SetCurrentKeyboardLayoutByName(
122 const std::string& layout_name) OVERRIDE;
123 virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE;
124 virtual void ReapplyCurrentModifierLockStatus() OVERRIDE;
125 virtual void DisableNumLock() OVERRIDE;
126 virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE;
127 virtual bool CapsLockIsEnabled() OVERRIDE;
128 virtual bool IsISOLevel5ShiftAvailable() const OVERRIDE;
129 virtual bool IsAltGrAvailable() const OVERRIDE;
130 virtual bool SetAutoRepeatEnabled(bool enabled) OVERRIDE;
131 virtual bool SetAutoRepeatRate(const AutoRepeatRate& rate) OVERRIDE;
134 // Returns a mask for Num Lock (e.g. 1U << 4). Returns 0 on error.
135 unsigned int GetNumLockMask();
137 // Sets the caps-lock status. Note that calling this function always disables
139 void SetLockedModifiers(bool caps_lock_enabled);
141 // This function is used by SetLayout() and RemapModifierKeys(). Calls
142 // setxkbmap command if needed, and updates the last_full_layout_name_ cache.
143 bool SetLayoutInternal(const std::string& layout_name, bool force);
145 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
146 // in the |execute_queue_|. Do nothing if the queue is empty.
147 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
148 void MaybeExecuteSetLayoutCommand();
150 // Polls to see setxkbmap process exits.
151 void PollUntilChildFinish(const base::ProcessHandle handle);
153 // Called when execve'd setxkbmap process exits.
154 void OnSetLayoutFinish();
156 const bool is_running_on_chrome_os_;
157 unsigned int num_lock_mask_;
159 // The current Caps Lock status. If true, enabled.
160 bool current_caps_lock_status_;
162 // The XKB layout name which we set last time like "us" and "us(dvorak)".
163 std::string current_layout_name_;
165 // A queue for executing setxkbmap one by one.
166 std::queue<std::string> execute_queue_;
168 base::ThreadChecker thread_checker_;
170 base::WeakPtrFactory<XKeyboardImpl> weak_factory_;
172 DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl);
175 XKeyboardImpl::XKeyboardImpl()
176 : is_running_on_chrome_os_(base::SysInfo::IsRunningOnChromeOS()),
177 weak_factory_(this) {
178 // X must be already initialized.
179 CHECK(GetXDisplay());
181 num_lock_mask_ = GetNumLockMask();
183 if (is_running_on_chrome_os_) {
184 // Some code seems to assume that Mod2Mask is always assigned to
187 // TODO(yusukes): Check the assumption is really okay. If not,
188 // modify the Aura code, and then remove the CHECK below.
189 LOG_IF(ERROR, num_lock_mask_ != Mod2Mask)
190 << "NumLock is not assigned to Mod2Mask. : " << num_lock_mask_;
193 current_caps_lock_status_ = CapsLockIsEnabled();
196 unsigned int XKeyboardImpl::GetNumLockMask() {
197 DCHECK(thread_checker_.CalledOnValidThread());
198 static const unsigned int kBadMask = 0;
200 unsigned int real_mask = kBadMask;
201 XkbDescPtr xkb_desc =
202 XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd);
206 if (xkb_desc->dpy && xkb_desc->names) {
207 const std::string string_to_find(kNumLockVirtualModifierString);
208 for (size_t i = 0; i < XkbNumVirtualMods; ++i) {
209 const unsigned int virtual_mod_mask = 1U << i;
210 char* virtual_mod_str_raw_ptr =
211 XGetAtomName(xkb_desc->dpy, xkb_desc->names->vmods[i]);
212 if (!virtual_mod_str_raw_ptr)
214 const std::string virtual_mod_str = virtual_mod_str_raw_ptr;
215 XFree(virtual_mod_str_raw_ptr);
217 if (string_to_find == virtual_mod_str) {
218 if (!XkbVirtualModsToReal(xkb_desc, virtual_mod_mask, &real_mask)) {
219 DVLOG(1) << "XkbVirtualModsToReal failed";
220 real_mask = kBadMask; // reset the return value, just in case.
226 XkbFreeKeyboard(xkb_desc, 0, True /* free all components */);
230 void XKeyboardImpl::SetLockedModifiers(bool caps_lock_enabled) {
231 DCHECK(thread_checker_.CalledOnValidThread());
233 // Always turn off num lock.
234 unsigned int affect_mask = num_lock_mask_;
235 unsigned int value_mask = 0;
237 affect_mask |= LockMask;
238 value_mask |= (caps_lock_enabled ? LockMask : 0);
239 current_caps_lock_status_ = caps_lock_enabled;
241 XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask);
244 bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name,
246 if (!is_running_on_chrome_os_) {
247 // We should not try to change a layout on Linux or inside ui_tests. Just
252 if (!CheckLayoutName(layout_name))
255 if (!force && (current_layout_name_ == layout_name)) {
256 DVLOG(1) << "The requested layout is already set: " << layout_name;
260 DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name;
262 const bool start_execution = execute_queue_.empty();
263 // If no setxkbmap command is in flight (i.e. start_execution is true),
264 // start the first one by explicitly calling MaybeExecuteSetLayoutCommand().
265 // If one or more setxkbmap commands are already in flight, just push the
266 // layout name to the queue. setxkbmap command for the layout will be called
267 // via OnSetLayoutFinish() callback later.
268 execute_queue_.push(layout_name);
270 MaybeExecuteSetLayoutCommand();
275 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
276 // in the |execute_queue_|. Do nothing if the queue is empty.
277 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
278 void XKeyboardImpl::MaybeExecuteSetLayoutCommand() {
279 if (execute_queue_.empty())
281 const std::string layout_to_set = execute_queue_.front();
283 std::vector<std::string> argv;
284 base::ProcessHandle handle = base::kNullProcessHandle;
286 argv.push_back(kSetxkbmapCommand);
287 argv.push_back("-layout");
288 argv.push_back(layout_to_set);
289 argv.push_back("-synch");
291 if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) {
292 DVLOG(1) << "Failed to execute setxkbmap: " << layout_to_set;
293 execute_queue_ = std::queue<std::string>(); // clear the queue.
297 PollUntilChildFinish(handle);
299 DVLOG(1) << "ExecuteSetLayoutCommand: "
300 << layout_to_set << ": pid=" << base::GetProcId(handle);
303 // Delay and loop until child process finishes and call the callback.
304 void XKeyboardImpl::PollUntilChildFinish(const base::ProcessHandle handle) {
306 DVLOG(1) << "PollUntilChildFinish: poll for pid=" << base::GetProcId(handle);
307 switch (base::GetTerminationStatus(handle, &exit_code)) {
308 case base::TERMINATION_STATUS_STILL_RUNNING:
309 DVLOG(1) << "PollUntilChildFinish: Try waiting again";
310 base::MessageLoop::current()->PostDelayedTask(
312 base::Bind(&XKeyboardImpl::PollUntilChildFinish,
313 weak_factory_.GetWeakPtr(), handle),
314 base::TimeDelta::FromMilliseconds(kSetLayoutCommandCheckDelayMs));
317 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
318 DVLOG(1) << "PollUntilChildFinish: Child process finished";
322 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
323 DVLOG(1) << "PollUntilChildFinish: Abnormal exit code: " << exit_code;
334 bool XKeyboardImpl::CapsLockIsEnabled() {
335 DCHECK(thread_checker_.CalledOnValidThread());
337 XkbGetState(GetXDisplay(), XkbUseCoreKbd, &status);
338 return (status.locked_mods & LockMask);
341 bool XKeyboardImpl::IsISOLevel5ShiftAvailable() const {
342 for (size_t i = 0; i < arraysize(kISOLevel5ShiftLayoutIds); ++i) {
343 if (current_layout_name_ == kISOLevel5ShiftLayoutIds[i])
349 bool XKeyboardImpl::IsAltGrAvailable() const {
350 for (size_t i = 0; i < arraysize(kAltGrLayoutIds); ++i) {
351 if (current_layout_name_ == kAltGrLayoutIds[i])
358 bool XKeyboardImpl::SetAutoRepeatEnabled(bool enabled) {
360 XAutoRepeatOn(GetXDisplay());
362 XAutoRepeatOff(GetXDisplay());
363 DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off");
367 bool XKeyboardImpl::SetAutoRepeatRate(const AutoRepeatRate& rate) {
368 DVLOG(1) << "Set auto-repeat rate to: "
369 << rate.initial_delay_in_ms << " ms delay, "
370 << rate.repeat_interval_in_ms << " ms interval";
371 if (XkbSetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd,
372 rate.initial_delay_in_ms,
373 rate.repeat_interval_in_ms) != True) {
374 DVLOG(1) << "Failed to set auto-repeat rate";
380 void XKeyboardImpl::SetCapsLockEnabled(bool enable_caps_lock) {
381 SetLockedModifiers(enable_caps_lock);
384 bool XKeyboardImpl::SetCurrentKeyboardLayoutByName(
385 const std::string& layout_name) {
386 if (SetLayoutInternal(layout_name, false)) {
387 current_layout_name_ = layout_name;
393 bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() {
394 if (current_layout_name_.empty()) {
395 DVLOG(1) << "Can't reapply XKB layout: layout unknown";
398 return SetLayoutInternal(current_layout_name_, true /* force */);
401 void XKeyboardImpl::ReapplyCurrentModifierLockStatus() {
402 SetLockedModifiers(current_caps_lock_status_);
405 void XKeyboardImpl::DisableNumLock() {
406 SetCapsLockEnabled(current_caps_lock_status_);
409 void XKeyboardImpl::OnSetLayoutFinish() {
410 if (execute_queue_.empty()) {
411 DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. "
412 << "base::LaunchProcess failed?";
415 execute_queue_.pop();
416 MaybeExecuteSetLayoutCommand();
422 bool XKeyboard::GetAutoRepeatEnabledForTesting() {
423 XKeyboardState state = {};
424 XGetKeyboardControl(GetXDisplay(), &state);
425 return state.global_auto_repeat != AutoRepeatModeOff;
429 bool XKeyboard::GetAutoRepeatRateForTesting(AutoRepeatRate* out_rate) {
430 return XkbGetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd,
431 &(out_rate->initial_delay_in_ms),
432 &(out_rate->repeat_interval_in_ms)) == True;
436 bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) {
437 return CheckLayoutName(layout_name);
441 XKeyboard* XKeyboard::Create() {
442 return new XKeyboardImpl();
445 } // namespace input_method
446 } // namespace chromeos