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 // Adds/removes observer.
121 virtual void AddObserver(Observer* observer) OVERRIDE;
122 virtual void RemoveObserver(Observer* observer) OVERRIDE;
124 // Overridden from XKeyboard:
125 virtual bool SetCurrentKeyboardLayoutByName(
126 const std::string& layout_name) OVERRIDE;
127 virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE;
128 virtual void ReapplyCurrentModifierLockStatus() OVERRIDE;
129 virtual void DisableNumLock() OVERRIDE;
130 virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE;
131 virtual bool CapsLockIsEnabled() OVERRIDE;
132 virtual bool IsISOLevel5ShiftAvailable() const OVERRIDE;
133 virtual bool IsAltGrAvailable() const OVERRIDE;
134 virtual bool SetAutoRepeatEnabled(bool enabled) OVERRIDE;
135 virtual bool SetAutoRepeatRate(const AutoRepeatRate& rate) OVERRIDE;
138 // Returns a mask for Num Lock (e.g. 1U << 4). Returns 0 on error.
139 unsigned int GetNumLockMask();
141 // Sets the caps-lock status. Note that calling this function always disables
143 void SetLockedModifiers(bool caps_lock_enabled);
145 // This function is used by SetLayout() and RemapModifierKeys(). Calls
146 // setxkbmap command if needed, and updates the last_full_layout_name_ cache.
147 bool SetLayoutInternal(const std::string& layout_name, bool force);
149 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
150 // in the |execute_queue_|. Do nothing if the queue is empty.
151 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
152 void MaybeExecuteSetLayoutCommand();
154 // Polls to see setxkbmap process exits.
155 void PollUntilChildFinish(const base::ProcessHandle handle);
157 // Called when execve'd setxkbmap process exits.
158 void OnSetLayoutFinish();
160 const bool is_running_on_chrome_os_;
161 unsigned int num_lock_mask_;
163 // The current Caps Lock status. If true, enabled.
164 bool current_caps_lock_status_;
166 // The XKB layout name which we set last time like "us" and "us(dvorak)".
167 std::string current_layout_name_;
169 // A queue for executing setxkbmap one by one.
170 std::queue<std::string> execute_queue_;
172 base::ThreadChecker thread_checker_;
174 base::WeakPtrFactory<XKeyboardImpl> weak_factory_;
176 ObserverList<Observer> observers_;
178 DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl);
181 XKeyboardImpl::XKeyboardImpl()
182 : is_running_on_chrome_os_(base::SysInfo::IsRunningOnChromeOS()),
183 weak_factory_(this) {
184 // X must be already initialized.
185 CHECK(GetXDisplay());
187 num_lock_mask_ = GetNumLockMask();
189 if (is_running_on_chrome_os_) {
190 // Some code seems to assume that Mod2Mask is always assigned to
193 // TODO(yusukes): Check the assumption is really okay. If not,
194 // modify the Aura code, and then remove the CHECK below.
195 LOG_IF(ERROR, num_lock_mask_ != Mod2Mask)
196 << "NumLock is not assigned to Mod2Mask. : " << num_lock_mask_;
199 current_caps_lock_status_ = CapsLockIsEnabled();
202 void XKeyboardImpl::AddObserver(XKeyboard::Observer* observer) {
203 observers_.AddObserver(observer);
206 void XKeyboardImpl::RemoveObserver(XKeyboard::Observer* observer) {
207 observers_.RemoveObserver(observer);
210 unsigned int XKeyboardImpl::GetNumLockMask() {
211 DCHECK(thread_checker_.CalledOnValidThread());
212 static const unsigned int kBadMask = 0;
214 unsigned int real_mask = kBadMask;
215 XkbDescPtr xkb_desc =
216 XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd);
220 if (xkb_desc->dpy && xkb_desc->names) {
221 const std::string string_to_find(kNumLockVirtualModifierString);
222 for (size_t i = 0; i < XkbNumVirtualMods; ++i) {
223 const unsigned int virtual_mod_mask = 1U << i;
224 char* virtual_mod_str_raw_ptr =
225 XGetAtomName(xkb_desc->dpy, xkb_desc->names->vmods[i]);
226 if (!virtual_mod_str_raw_ptr)
228 const std::string virtual_mod_str = virtual_mod_str_raw_ptr;
229 XFree(virtual_mod_str_raw_ptr);
231 if (string_to_find == virtual_mod_str) {
232 if (!XkbVirtualModsToReal(xkb_desc, virtual_mod_mask, &real_mask)) {
233 DVLOG(1) << "XkbVirtualModsToReal failed";
234 real_mask = kBadMask; // reset the return value, just in case.
240 XkbFreeKeyboard(xkb_desc, 0, True /* free all components */);
244 void XKeyboardImpl::SetLockedModifiers(bool caps_lock_enabled) {
245 DCHECK(thread_checker_.CalledOnValidThread());
247 // Always turn off num lock.
248 unsigned int affect_mask = num_lock_mask_;
249 unsigned int value_mask = 0;
251 affect_mask |= LockMask;
252 value_mask |= (caps_lock_enabled ? LockMask : 0);
253 current_caps_lock_status_ = caps_lock_enabled;
255 XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask);
258 bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name,
260 if (!is_running_on_chrome_os_) {
261 // We should not try to change a layout on Linux or inside ui_tests. Just
266 if (!CheckLayoutName(layout_name))
269 if (!force && (current_layout_name_ == layout_name)) {
270 DVLOG(1) << "The requested layout is already set: " << layout_name;
274 DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name;
276 const bool start_execution = execute_queue_.empty();
277 // If no setxkbmap command is in flight (i.e. start_execution is true),
278 // start the first one by explicitly calling MaybeExecuteSetLayoutCommand().
279 // If one or more setxkbmap commands are already in flight, just push the
280 // layout name to the queue. setxkbmap command for the layout will be called
281 // via OnSetLayoutFinish() callback later.
282 execute_queue_.push(layout_name);
284 MaybeExecuteSetLayoutCommand();
289 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
290 // in the |execute_queue_|. Do nothing if the queue is empty.
291 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
292 void XKeyboardImpl::MaybeExecuteSetLayoutCommand() {
293 if (execute_queue_.empty())
295 const std::string layout_to_set = execute_queue_.front();
297 std::vector<std::string> argv;
298 base::ProcessHandle handle = base::kNullProcessHandle;
300 argv.push_back(kSetxkbmapCommand);
301 argv.push_back("-layout");
302 argv.push_back(layout_to_set);
303 argv.push_back("-synch");
305 if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) {
306 DVLOG(1) << "Failed to execute setxkbmap: " << layout_to_set;
307 execute_queue_ = std::queue<std::string>(); // clear the queue.
311 PollUntilChildFinish(handle);
313 DVLOG(1) << "ExecuteSetLayoutCommand: "
314 << layout_to_set << ": pid=" << base::GetProcId(handle);
317 // Delay and loop until child process finishes and call the callback.
318 void XKeyboardImpl::PollUntilChildFinish(const base::ProcessHandle handle) {
320 DVLOG(1) << "PollUntilChildFinish: poll for pid=" << base::GetProcId(handle);
321 switch (base::GetTerminationStatus(handle, &exit_code)) {
322 case base::TERMINATION_STATUS_STILL_RUNNING:
323 DVLOG(1) << "PollUntilChildFinish: Try waiting again";
324 base::MessageLoop::current()->PostDelayedTask(
326 base::Bind(&XKeyboardImpl::PollUntilChildFinish,
327 weak_factory_.GetWeakPtr(), handle),
328 base::TimeDelta::FromMilliseconds(kSetLayoutCommandCheckDelayMs));
331 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
332 DVLOG(1) << "PollUntilChildFinish: Child process finished";
336 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
337 DVLOG(1) << "PollUntilChildFinish: Abnormal exit code: " << exit_code;
348 bool XKeyboardImpl::CapsLockIsEnabled() {
349 DCHECK(thread_checker_.CalledOnValidThread());
351 XkbGetState(GetXDisplay(), XkbUseCoreKbd, &status);
352 return (status.locked_mods & LockMask);
355 bool XKeyboardImpl::IsISOLevel5ShiftAvailable() const {
356 for (size_t i = 0; i < arraysize(kISOLevel5ShiftLayoutIds); ++i) {
357 if (current_layout_name_ == kISOLevel5ShiftLayoutIds[i])
363 bool XKeyboardImpl::IsAltGrAvailable() const {
364 for (size_t i = 0; i < arraysize(kAltGrLayoutIds); ++i) {
365 if (current_layout_name_ == kAltGrLayoutIds[i])
372 bool XKeyboardImpl::SetAutoRepeatEnabled(bool enabled) {
374 XAutoRepeatOn(GetXDisplay());
376 XAutoRepeatOff(GetXDisplay());
377 DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off");
381 bool XKeyboardImpl::SetAutoRepeatRate(const AutoRepeatRate& rate) {
382 DVLOG(1) << "Set auto-repeat rate to: "
383 << rate.initial_delay_in_ms << " ms delay, "
384 << rate.repeat_interval_in_ms << " ms interval";
385 if (XkbSetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd,
386 rate.initial_delay_in_ms,
387 rate.repeat_interval_in_ms) != True) {
388 DVLOG(1) << "Failed to set auto-repeat rate";
394 void XKeyboardImpl::SetCapsLockEnabled(bool enable_caps_lock) {
395 bool old_state = current_caps_lock_status_;
396 SetLockedModifiers(enable_caps_lock);
397 if (old_state != enable_caps_lock) {
398 FOR_EACH_OBSERVER(XKeyboard::Observer, observers_,
399 OnCapsLockChanged(enable_caps_lock));
403 bool XKeyboardImpl::SetCurrentKeyboardLayoutByName(
404 const std::string& layout_name) {
405 if (SetLayoutInternal(layout_name, false)) {
406 current_layout_name_ = layout_name;
412 bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() {
413 if (current_layout_name_.empty()) {
414 DVLOG(1) << "Can't reapply XKB layout: layout unknown";
417 return SetLayoutInternal(current_layout_name_, true /* force */);
420 void XKeyboardImpl::ReapplyCurrentModifierLockStatus() {
421 SetLockedModifiers(current_caps_lock_status_);
424 void XKeyboardImpl::DisableNumLock() {
425 SetCapsLockEnabled(current_caps_lock_status_);
428 void XKeyboardImpl::OnSetLayoutFinish() {
429 if (execute_queue_.empty()) {
430 DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. "
431 << "base::LaunchProcess failed?";
434 execute_queue_.pop();
435 MaybeExecuteSetLayoutCommand();
441 bool XKeyboard::GetAutoRepeatEnabledForTesting() {
442 XKeyboardState state = {};
443 XGetKeyboardControl(GetXDisplay(), &state);
444 return state.global_auto_repeat != AutoRepeatModeOff;
448 bool XKeyboard::GetAutoRepeatRateForTesting(AutoRepeatRate* out_rate) {
449 return XkbGetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd,
450 &(out_rate->initial_delay_in_ms),
451 &(out_rate->repeat_interval_in_ms)) == True;
455 bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) {
456 return CheckLayoutName(layout_name);
460 XKeyboard* XKeyboard::Create() {
461 return new XKeyboardImpl();
464 } // namespace input_method
465 } // namespace chromeos