1 // Copyright 2014 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
5 #include "chromeos/ime/ime_keyboard.h"
6
7 #include <cstdlib>
8 #include <cstring>
9 #include <queue>
10 #include <set>
11 #include <utility>
12
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"
24 #include "ui/gfx/x/x11_types.h"
25
26 // These includes conflict with base/tracked_objects.h so must come last.
27 #include <X11/XKBlib.h>
28 #include <X11/Xlib.h>
29
30 namespace chromeos {
31 namespace input_method {
32 namespace {
33
34 // The delay in milliseconds that we'll wait between checking if
35 // setxkbmap command finished.
36 const int kSetLayoutCommandCheckDelayMs = 100;
37
38 // The command we use to set the current XKB layout and modifier key mapping.
39 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
40 const char kSetxkbmapCommand[] = "/usr/bin/setxkbmap";
41
42 // A string for obtaining a mask value for Num Lock.
43 const char kNumLockVirtualModifierString[] = "NumLock";
44
45 const char *kISOLevel5ShiftLayoutIds[] = {
46 "ca(multix)",
47 "de(neo)",
48 };
49
50 const char *kAltGrLayoutIds[] = {
51 "be",
52 "be",
53 "be",
54 "bg",
55 "bg(phonetic)",
56 "br",
57 "ca",
58 "ca(eng)",
59 "ca(multix)",
60 "ch",
61 "ch(fr)",
62 "cz",
63 "de",
64 "de(neo)",
65 "dk",
66 "ee",
67 "es",
68 "es(cat)",
69 "fi",
70 "fr",
71 "gb(dvorak)",
72 "gb(extd)",
73 "gr",
74 "hr",
75 "il",
76 "it",
77 "latam",
78 "lt",
79 "no",
80 "pl",
81 "pt",
82 "ro",
83 "se",
84 "si",
85 "sk",
86 "tr",
87 "ua",
88 "us(altgr-intl)",
89 "us(intl)",
90 };
91
92
93 // Returns false if |layout_name| contains a bad character.
CheckLayoutName(const std::string & layout_name)94 bool CheckLayoutName(const std::string& layout_name) {
95 static const char kValidLayoutNameCharacters[] =
96 "abcdefghijklmnopqrstuvwxyz0123456789()-_";
97
98 if (layout_name.empty()) {
99 DVLOG(1) << "Invalid layout_name: " << layout_name;
100 return false;
101 }
102
103 if (layout_name.find_first_not_of(kValidLayoutNameCharacters) !=
104 std::string::npos) {
105 DVLOG(1) << "Invalid layout_name: " << layout_name;
106 return false;
107 }
108
109 return true;
110 }
111
112 class ImeKeyboardX11 : public ImeKeyboard {
113 public:
114 ImeKeyboardX11();
~ImeKeyboardX11()115 virtual ~ImeKeyboardX11() {}
116
117 // Adds/removes observer.
118 virtual void AddObserver(Observer* observer) OVERRIDE;
119 virtual void RemoveObserver(Observer* observer) OVERRIDE;
120
121 // ImeKeyboard:
122 virtual bool SetCurrentKeyboardLayoutByName(
123 const std::string& layout_name) OVERRIDE;
124 virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE;
125 virtual void ReapplyCurrentModifierLockStatus() OVERRIDE;
126 virtual void DisableNumLock() OVERRIDE;
127 virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE;
128 virtual bool CapsLockIsEnabled() OVERRIDE;
129 virtual bool IsISOLevel5ShiftAvailable() const OVERRIDE;
130 virtual bool IsAltGrAvailable() const OVERRIDE;
131 virtual bool SetAutoRepeatEnabled(bool enabled) OVERRIDE;
132 virtual bool SetAutoRepeatRate(const AutoRepeatRate& rate) OVERRIDE;
133
134 private:
135 // Returns a mask for Num Lock (e.g. 1U << 4). Returns 0 on error.
136 unsigned int GetNumLockMask();
137
138 // Sets the caps-lock status. Note that calling this function always disables
139 // the num-lock.
140 void SetLockedModifiers(bool caps_lock_enabled);
141
142 // This function is used by SetLayout() and RemapModifierKeys(). Calls
143 // setxkbmap command if needed, and updates the last_full_layout_name_ cache.
144 bool SetLayoutInternal(const std::string& layout_name, bool force);
145
146 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
147 // in the |execute_queue_|. Do nothing if the queue is empty.
148 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
149 void MaybeExecuteSetLayoutCommand();
150
151 // Polls to see setxkbmap process exits.
152 void PollUntilChildFinish(const base::ProcessHandle handle);
153
154 // Called when execve'd setxkbmap process exits.
155 void OnSetLayoutFinish();
156
157 const bool is_running_on_chrome_os_;
158 unsigned int num_lock_mask_;
159
160 // The current Caps Lock status. If true, enabled.
161 bool current_caps_lock_status_;
162
163 // The XKB layout name which we set last time like "us" and "us(dvorak)".
164 std::string current_layout_name_;
165
166 // A queue for executing setxkbmap one by one.
167 std::queue<std::string> execute_queue_;
168
169 base::ThreadChecker thread_checker_;
170
171 base::WeakPtrFactory<ImeKeyboardX11> weak_factory_;
172
173 ObserverList<Observer> observers_;
174
175 DISALLOW_COPY_AND_ASSIGN(ImeKeyboardX11);
176 };
177
ImeKeyboardX11()178 ImeKeyboardX11::ImeKeyboardX11()
179 : is_running_on_chrome_os_(base::SysInfo::IsRunningOnChromeOS()),
180 weak_factory_(this) {
181 // X must be already initialized.
182 CHECK(gfx::GetXDisplay());
183
184 num_lock_mask_ = GetNumLockMask();
185
186 if (is_running_on_chrome_os_) {
187 // Some code seems to assume that Mod2Mask is always assigned to
188 // Num Lock.
189 //
190 // TODO(yusukes): Check the assumption is really okay. If not,
191 // modify the Aura code, and then remove the CHECK below.
192 LOG_IF(ERROR, num_lock_mask_ != Mod2Mask)
193 << "NumLock is not assigned to Mod2Mask. : " << num_lock_mask_;
194 }
195
196 current_caps_lock_status_ = CapsLockIsEnabled();
197 // Disable Num Lock on X start up for http://crosbug.com/29169.
198 DisableNumLock();
199 }
200
AddObserver(Observer * observer)201 void ImeKeyboardX11::AddObserver(Observer* observer) {
202 observers_.AddObserver(observer);
203 }
204
RemoveObserver(Observer * observer)205 void ImeKeyboardX11::RemoveObserver(Observer* observer) {
206 observers_.RemoveObserver(observer);
207 }
208
GetNumLockMask()209 unsigned int ImeKeyboardX11::GetNumLockMask() {
210 DCHECK(thread_checker_.CalledOnValidThread());
211 static const unsigned int kBadMask = 0;
212
213 unsigned int real_mask = kBadMask;
214 XkbDescPtr xkb_desc =
215 XkbGetKeyboard(gfx::GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd);
216 if (!xkb_desc)
217 return kBadMask;
218
219 if (xkb_desc->dpy && xkb_desc->names) {
220 const std::string string_to_find(kNumLockVirtualModifierString);
221 for (size_t i = 0; i < XkbNumVirtualMods; ++i) {
222 const unsigned int virtual_mod_mask = 1U << i;
223 char* virtual_mod_str_raw_ptr =
224 XGetAtomName(xkb_desc->dpy, xkb_desc->names->vmods[i]);
225 if (!virtual_mod_str_raw_ptr)
226 continue;
227 const std::string virtual_mod_str = virtual_mod_str_raw_ptr;
228 XFree(virtual_mod_str_raw_ptr);
229
230 if (string_to_find == virtual_mod_str) {
231 if (!XkbVirtualModsToReal(xkb_desc, virtual_mod_mask, &real_mask)) {
232 DVLOG(1) << "XkbVirtualModsToReal failed";
233 real_mask = kBadMask; // reset the return value, just in case.
234 }
235 break;
236 }
237 }
238 }
239 XkbFreeKeyboard(xkb_desc, 0, True /* free all components */);
240 return real_mask;
241 }
242
SetLockedModifiers(bool caps_lock_enabled)243 void ImeKeyboardX11::SetLockedModifiers(bool caps_lock_enabled) {
244 DCHECK(thread_checker_.CalledOnValidThread());
245
246 // Always turn off num lock.
247 unsigned int affect_mask = num_lock_mask_;
248 unsigned int value_mask = 0;
249
250 affect_mask |= LockMask;
251 value_mask |= (caps_lock_enabled ? LockMask : 0);
252 current_caps_lock_status_ = caps_lock_enabled;
253
254 XkbLockModifiers(gfx::GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask);
255 }
256
SetLayoutInternal(const std::string & layout_name,bool force)257 bool ImeKeyboardX11::SetLayoutInternal(const std::string& layout_name,
258 bool force) {
259 if (!is_running_on_chrome_os_) {
260 // We should not try to change a layout on Linux or inside ui_tests. Just
261 // return true.
262 return true;
263 }
264
265 if (!CheckLayoutName(layout_name))
266 return false;
267
268 if (!force && (current_layout_name_ == layout_name)) {
269 DVLOG(1) << "The requested layout is already set: " << layout_name;
270 return true;
271 }
272
273 DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name;
274
275 const bool start_execution = execute_queue_.empty();
276 // If no setxkbmap command is in flight (i.e. start_execution is true),
277 // start the first one by explicitly calling MaybeExecuteSetLayoutCommand().
278 // If one or more setxkbmap commands are already in flight, just push the
279 // layout name to the queue. setxkbmap command for the layout will be called
280 // via OnSetLayoutFinish() callback later.
281 execute_queue_.push(layout_name);
282 if (start_execution)
283 MaybeExecuteSetLayoutCommand();
284
285 return true;
286 }
287
288 // Executes 'setxkbmap -layout ...' command asynchronously using a layout name
289 // in the |execute_queue_|. Do nothing if the queue is empty.
290 // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105)
MaybeExecuteSetLayoutCommand()291 void ImeKeyboardX11::MaybeExecuteSetLayoutCommand() {
292 if (execute_queue_.empty())
293 return;
294 const std::string layout_to_set = execute_queue_.front();
295
296 std::vector<std::string> argv;
297 base::ProcessHandle handle = base::kNullProcessHandle;
298
299 argv.push_back(kSetxkbmapCommand);
300 argv.push_back("-layout");
301 argv.push_back(layout_to_set);
302 argv.push_back("-synch");
303
304 if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) {
305 DVLOG(1) << "Failed to execute setxkbmap: " << layout_to_set;
306 execute_queue_ = std::queue<std::string>(); // clear the queue.
307 return;
308 }
309
310 PollUntilChildFinish(handle);
311
312 DVLOG(1) << "ExecuteSetLayoutCommand: " << layout_to_set
313 << ": pid=" << base::GetProcId(handle);
314 }
315
316 // Delay and loop until child process finishes and call the callback.
PollUntilChildFinish(const base::ProcessHandle handle)317 void ImeKeyboardX11::PollUntilChildFinish(const base::ProcessHandle handle) {
318 int exit_code;
319 DVLOG(1) << "PollUntilChildFinish: poll for pid=" << base::GetProcId(handle);
320 switch (base::GetTerminationStatus(handle, &exit_code)) {
321 case base::TERMINATION_STATUS_STILL_RUNNING:
322 DVLOG(1) << "PollUntilChildFinish: Try waiting again";
323 base::MessageLoop::current()->PostDelayedTask(
324 FROM_HERE,
325 base::Bind(&ImeKeyboardX11::PollUntilChildFinish,
326 weak_factory_.GetWeakPtr(),
327 handle),
328 base::TimeDelta::FromMilliseconds(kSetLayoutCommandCheckDelayMs));
329 return;
330
331 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
332 DVLOG(1) << "PollUntilChildFinish: Child process finished";
333 OnSetLayoutFinish();
334 return;
335
336 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
337 DVLOG(1) << "PollUntilChildFinish: Abnormal exit code: " << exit_code;
338 OnSetLayoutFinish();
339 return;
340
341 default:
342 NOTIMPLEMENTED();
343 OnSetLayoutFinish();
344 return;
345 }
346 }
347
CapsLockIsEnabled()348 bool ImeKeyboardX11::CapsLockIsEnabled() {
349 DCHECK(thread_checker_.CalledOnValidThread());
350 XkbStateRec status;
351 XkbGetState(gfx::GetXDisplay(), XkbUseCoreKbd, &status);
352 return (status.locked_mods & LockMask);
353 }
354
IsISOLevel5ShiftAvailable() const355 bool ImeKeyboardX11::IsISOLevel5ShiftAvailable() const {
356 for (size_t i = 0; i < arraysize(kISOLevel5ShiftLayoutIds); ++i) {
357 if (current_layout_name_ == kISOLevel5ShiftLayoutIds[i])
358 return true;
359 }
360 return false;
361 }
362
IsAltGrAvailable() const363 bool ImeKeyboardX11::IsAltGrAvailable() const {
364 for (size_t i = 0; i < arraysize(kAltGrLayoutIds); ++i) {
365 if (current_layout_name_ == kAltGrLayoutIds[i])
366 return true;
367 }
368 return false;
369 }
370
SetAutoRepeatEnabled(bool enabled)371 bool ImeKeyboardX11::SetAutoRepeatEnabled(bool enabled) {
372 if (enabled)
373 XAutoRepeatOn(gfx::GetXDisplay());
374 else
375 XAutoRepeatOff(gfx::GetXDisplay());
376 DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off");
377 return true;
378 }
379
SetAutoRepeatRate(const AutoRepeatRate & rate)380 bool ImeKeyboardX11::SetAutoRepeatRate(const AutoRepeatRate& rate) {
381 DVLOG(1) << "Set auto-repeat rate to: "
382 << rate.initial_delay_in_ms << " ms delay, "
383 << rate.repeat_interval_in_ms << " ms interval";
384 if (XkbSetAutoRepeatRate(gfx::GetXDisplay(), XkbUseCoreKbd,
385 rate.initial_delay_in_ms,
386 rate.repeat_interval_in_ms) != True) {
387 DVLOG(1) << "Failed to set auto-repeat rate";
388 return false;
389 }
390 return true;
391 }
392
SetCapsLockEnabled(bool enable_caps_lock)393 void ImeKeyboardX11::SetCapsLockEnabled(bool enable_caps_lock) {
394 bool old_state = current_caps_lock_status_;
395 SetLockedModifiers(enable_caps_lock);
396 if (old_state != enable_caps_lock) {
397 FOR_EACH_OBSERVER(ImeKeyboard::Observer, observers_,
398 OnCapsLockChanged(enable_caps_lock));
399 }
400 }
401
SetCurrentKeyboardLayoutByName(const std::string & layout_name)402 bool ImeKeyboardX11::SetCurrentKeyboardLayoutByName(
403 const std::string& layout_name) {
404 if (SetLayoutInternal(layout_name, false)) {
405 current_layout_name_ = layout_name;
406 return true;
407 }
408 return false;
409 }
410
ReapplyCurrentKeyboardLayout()411 bool ImeKeyboardX11::ReapplyCurrentKeyboardLayout() {
412 if (current_layout_name_.empty()) {
413 DVLOG(1) << "Can't reapply XKB layout: layout unknown";
414 return false;
415 }
416 return SetLayoutInternal(current_layout_name_, true /* force */);
417 }
418
ReapplyCurrentModifierLockStatus()419 void ImeKeyboardX11::ReapplyCurrentModifierLockStatus() {
420 SetLockedModifiers(current_caps_lock_status_);
421 }
422
DisableNumLock()423 void ImeKeyboardX11::DisableNumLock() {
424 SetCapsLockEnabled(current_caps_lock_status_);
425 }
426
OnSetLayoutFinish()427 void ImeKeyboardX11::OnSetLayoutFinish() {
428 if (execute_queue_.empty()) {
429 DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. "
430 << "base::LaunchProcess failed?";
431 return;
432 }
433 execute_queue_.pop();
434 MaybeExecuteSetLayoutCommand();
435 }
436
437 } // namespace
438
439 // static
GetAutoRepeatEnabledForTesting()440 bool ImeKeyboard::GetAutoRepeatEnabledForTesting() {
441 XKeyboardState state = {};
442 XGetKeyboardControl(gfx::GetXDisplay(), &state);
443 return state.global_auto_repeat != AutoRepeatModeOff;
444 }
445
446 // static
GetAutoRepeatRateForTesting(AutoRepeatRate * out_rate)447 bool ImeKeyboard::GetAutoRepeatRateForTesting(AutoRepeatRate* out_rate) {
448 return XkbGetAutoRepeatRate(gfx::GetXDisplay(),
449 XkbUseCoreKbd,
450 &(out_rate->initial_delay_in_ms),
451 &(out_rate->repeat_interval_in_ms)) == True;
452 }
453
454 // static
CheckLayoutNameForTesting(const std::string & layout_name)455 bool ImeKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) {
456 return CheckLayoutName(layout_name);
457 }
458
459 // static
Create()460 ImeKeyboard* ImeKeyboard::Create() { return new ImeKeyboardX11(); }
461
462 } // namespace input_method
463 } // namespace chromeos
464