b2f55f14443e77a403ce47d27889b11c3a7fc658
[platform/framework/web/crosswalk.git] / src / chromeos / ime / xkeyboard.cc
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.
4
5 #include "chromeos/ime/xkeyboard.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
25 // These includes conflict with base/tracked_objects.h so must come last.
26 #include <X11/XKBlib.h>
27 #include <X11/Xlib.h>
28
29 namespace chromeos {
30 namespace input_method {
31 namespace {
32
33 Display* GetXDisplay() {
34   return base::MessagePumpForUI::GetDefaultXDisplay();
35 }
36
37 // The delay in milliseconds that we'll wait between checking if
38 // setxkbmap command finished.
39 const int kSetLayoutCommandCheckDelayMs = 100;
40
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";
44
45 // A string for obtaining a mask value for Num Lock.
46 const char kNumLockVirtualModifierString[] = "NumLock";
47
48 const char *kISOLevel5ShiftLayoutIds[] = {
49   "ca(multix)",
50   "de(neo)",
51 };
52
53 const char *kAltGrLayoutIds[] = {
54   "be",
55   "be",
56   "be",
57   "bg",
58   "bg(phonetic)",
59   "br",
60   "ca",
61   "ca(eng)",
62   "ca(multix)",
63   "ch",
64   "ch(fr)",
65   "cz",
66   "de",
67   "de(neo)",
68   "dk",
69   "ee",
70   "es",
71   "es(cat)",
72   "fi",
73   "fr",
74   "gb(dvorak)",
75   "gb(extd)",
76   "gr",
77   "hr",
78   "il",
79   "it",
80   "latam",
81   "lt",
82   "no",
83   "pl",
84   "pt",
85   "ro",
86   "se",
87   "si",
88   "sk",
89   "tr",
90   "ua",
91   "us(altgr-intl)",
92   "us(intl)",
93 };
94
95
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()-_";
100
101   if (layout_name.empty()) {
102     DVLOG(1) << "Invalid layout_name: " << layout_name;
103     return false;
104   }
105
106   if (layout_name.find_first_not_of(kValidLayoutNameCharacters) !=
107       std::string::npos) {
108     DVLOG(1) << "Invalid layout_name: " << layout_name;
109     return false;
110   }
111
112   return true;
113 }
114
115 class XKeyboardImpl : public XKeyboard {
116  public:
117   XKeyboardImpl();
118   virtual ~XKeyboardImpl() {}
119
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;
132
133  private:
134   // Returns a mask for Num Lock (e.g. 1U << 4). Returns 0 on error.
135   unsigned int GetNumLockMask();
136
137   // Sets the caps-lock status. Note that calling this function always disables
138   // the num-lock.
139   void SetLockedModifiers(bool caps_lock_enabled);
140
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);
144
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();
149
150   // Polls to see setxkbmap process exits.
151   void PollUntilChildFinish(const base::ProcessHandle handle);
152
153   // Called when execve'd setxkbmap process exits.
154   void OnSetLayoutFinish();
155
156   const bool is_running_on_chrome_os_;
157   unsigned int num_lock_mask_;
158
159   // The current Caps Lock status. If true, enabled.
160   bool current_caps_lock_status_;
161
162   // The XKB layout name which we set last time like "us" and "us(dvorak)".
163   std::string current_layout_name_;
164
165   // A queue for executing setxkbmap one by one.
166   std::queue<std::string> execute_queue_;
167
168   base::ThreadChecker thread_checker_;
169
170   base::WeakPtrFactory<XKeyboardImpl> weak_factory_;
171
172   DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl);
173 };
174
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());
180
181   num_lock_mask_ = GetNumLockMask();
182
183   if (is_running_on_chrome_os_) {
184     // Some code seems to assume that Mod2Mask is always assigned to
185     // Num Lock.
186     //
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_;
191   }
192
193   current_caps_lock_status_ = CapsLockIsEnabled();
194 }
195
196 unsigned int XKeyboardImpl::GetNumLockMask() {
197   DCHECK(thread_checker_.CalledOnValidThread());
198   static const unsigned int kBadMask = 0;
199
200   unsigned int real_mask = kBadMask;
201   XkbDescPtr xkb_desc =
202       XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd);
203   if (!xkb_desc)
204     return kBadMask;
205
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)
213         continue;
214       const std::string virtual_mod_str = virtual_mod_str_raw_ptr;
215       XFree(virtual_mod_str_raw_ptr);
216
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.
221         }
222         break;
223       }
224     }
225   }
226   XkbFreeKeyboard(xkb_desc, 0, True /* free all components */);
227   return real_mask;
228 }
229
230 void XKeyboardImpl::SetLockedModifiers(bool caps_lock_enabled) {
231   DCHECK(thread_checker_.CalledOnValidThread());
232
233   // Always turn off num lock.
234   unsigned int affect_mask = num_lock_mask_;
235   unsigned int value_mask = 0;
236
237   affect_mask |= LockMask;
238   value_mask |= (caps_lock_enabled ? LockMask : 0);
239   current_caps_lock_status_ = caps_lock_enabled;
240
241   XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask);
242 }
243
244 bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name,
245                                       bool force) {
246   if (!is_running_on_chrome_os_) {
247     // We should not try to change a layout on Linux or inside ui_tests. Just
248     // return true.
249     return true;
250   }
251
252   if (!CheckLayoutName(layout_name))
253     return false;
254
255   if (!force && (current_layout_name_ == layout_name)) {
256     DVLOG(1) << "The requested layout is already set: " << layout_name;
257     return true;
258   }
259
260   DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name;
261
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);
269   if (start_execution)
270     MaybeExecuteSetLayoutCommand();
271
272   return true;
273 }
274
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())
280     return;
281   const std::string layout_to_set = execute_queue_.front();
282
283   std::vector<std::string> argv;
284   base::ProcessHandle handle = base::kNullProcessHandle;
285
286   argv.push_back(kSetxkbmapCommand);
287   argv.push_back("-layout");
288   argv.push_back(layout_to_set);
289   argv.push_back("-synch");
290
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.
294     return;
295   }
296
297   PollUntilChildFinish(handle);
298
299   DVLOG(1) << "ExecuteSetLayoutCommand: "
300            << layout_to_set << ": pid=" << base::GetProcId(handle);
301 }
302
303 // Delay and loop until child process finishes and call the callback.
304 void XKeyboardImpl::PollUntilChildFinish(const base::ProcessHandle handle) {
305   int exit_code;
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(
311           FROM_HERE,
312           base::Bind(&XKeyboardImpl::PollUntilChildFinish,
313                  weak_factory_.GetWeakPtr(), handle),
314           base::TimeDelta::FromMilliseconds(kSetLayoutCommandCheckDelayMs));
315       return;
316
317     case base::TERMINATION_STATUS_NORMAL_TERMINATION:
318       DVLOG(1) << "PollUntilChildFinish: Child process finished";
319       OnSetLayoutFinish();
320       return;
321
322     case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
323       DVLOG(1) << "PollUntilChildFinish: Abnormal exit code: " << exit_code;
324       OnSetLayoutFinish();
325       return;
326
327     default:
328       NOTIMPLEMENTED();
329       OnSetLayoutFinish();
330       return;
331   }
332 }
333
334 bool XKeyboardImpl::CapsLockIsEnabled() {
335   DCHECK(thread_checker_.CalledOnValidThread());
336   XkbStateRec status;
337   XkbGetState(GetXDisplay(), XkbUseCoreKbd, &status);
338   return (status.locked_mods & LockMask);
339 }
340
341 bool XKeyboardImpl::IsISOLevel5ShiftAvailable() const {
342   for (size_t i = 0; i < arraysize(kISOLevel5ShiftLayoutIds); ++i) {
343     if (current_layout_name_ == kISOLevel5ShiftLayoutIds[i])
344       return true;
345   }
346   return false;
347 }
348
349 bool XKeyboardImpl::IsAltGrAvailable() const {
350   for (size_t i = 0; i < arraysize(kAltGrLayoutIds); ++i) {
351     if (current_layout_name_ == kAltGrLayoutIds[i])
352       return true;
353   }
354   return false;
355 }
356
357
358 bool XKeyboardImpl::SetAutoRepeatEnabled(bool enabled) {
359   if (enabled)
360     XAutoRepeatOn(GetXDisplay());
361   else
362     XAutoRepeatOff(GetXDisplay());
363   DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off");
364   return true;
365 }
366
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";
375     return false;
376   }
377   return true;
378 }
379
380 void XKeyboardImpl::SetCapsLockEnabled(bool enable_caps_lock) {
381   SetLockedModifiers(enable_caps_lock);
382 }
383
384 bool XKeyboardImpl::SetCurrentKeyboardLayoutByName(
385     const std::string& layout_name) {
386   if (SetLayoutInternal(layout_name, false)) {
387     current_layout_name_ = layout_name;
388     return true;
389   }
390   return false;
391 }
392
393 bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() {
394   if (current_layout_name_.empty()) {
395     DVLOG(1) << "Can't reapply XKB layout: layout unknown";
396     return false;
397   }
398   return SetLayoutInternal(current_layout_name_, true /* force */);
399 }
400
401 void XKeyboardImpl::ReapplyCurrentModifierLockStatus() {
402   SetLockedModifiers(current_caps_lock_status_);
403 }
404
405 void XKeyboardImpl::DisableNumLock() {
406   SetCapsLockEnabled(current_caps_lock_status_);
407 }
408
409 void XKeyboardImpl::OnSetLayoutFinish() {
410   if (execute_queue_.empty()) {
411     DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. "
412              << "base::LaunchProcess failed?";
413     return;
414   }
415   execute_queue_.pop();
416   MaybeExecuteSetLayoutCommand();
417 }
418
419 }  // namespace
420
421 // static
422 bool XKeyboard::GetAutoRepeatEnabledForTesting() {
423   XKeyboardState state = {};
424   XGetKeyboardControl(GetXDisplay(), &state);
425   return state.global_auto_repeat != AutoRepeatModeOff;
426 }
427
428 // static
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;
433 }
434
435 // static
436 bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) {
437   return CheckLayoutName(layout_name);
438 }
439
440 // static
441 XKeyboard* XKeyboard::Create() {
442   return new XKeyboardImpl();
443 }
444
445 }  // namespace input_method
446 }  // namespace chromeos