a34413862bfa3ae535251437fb69ff9df42ee4dc
[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 // Returns false if |layout_name| contains a bad character.
49 bool CheckLayoutName(const std::string& layout_name) {
50   static const char kValidLayoutNameCharacters[] =
51       "abcdefghijklmnopqrstuvwxyz0123456789()-_";
52
53   if (layout_name.empty()) {
54     DVLOG(1) << "Invalid layout_name: " << layout_name;
55     return false;
56   }
57
58   if (layout_name.find_first_not_of(kValidLayoutNameCharacters) !=
59       std::string::npos) {
60     DVLOG(1) << "Invalid layout_name: " << layout_name;
61     return false;
62   }
63
64   return true;
65 }
66
67 class XKeyboardImpl : public XKeyboard {
68  public:
69   XKeyboardImpl();
70   virtual ~XKeyboardImpl() {}
71
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;
89
90  private:
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);
94
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();
99
100   // Polls to see setxkbmap process exits.
101   void PollUntilChildFinish(const base::ProcessHandle handle);
102
103   // Called when execve'd setxkbmap process exits.
104   void OnSetLayoutFinish();
105
106   const bool is_running_on_chrome_os_;
107   unsigned int num_lock_mask_;
108
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_;
114
115   // A queue for executing setxkbmap one by one.
116   std::queue<std::string> execute_queue_;
117
118   base::ThreadChecker thread_checker_;
119
120   base::WeakPtrFactory<XKeyboardImpl> weak_factory_;
121
122   DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl);
123 };
124
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());
130
131   num_lock_mask_ = GetNumLockMask();
132
133   if (is_running_on_chrome_os_) {
134     // Some code seems to assume that Mod2Mask is always assigned to
135     // Num Lock.
136     //
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_;
141   }
142   GetLockedModifiers(&current_caps_lock_status_, &current_num_lock_status_);
143 }
144
145 bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name,
146                                       bool force) {
147   if (!is_running_on_chrome_os_) {
148     // We should not try to change a layout on Linux or inside ui_tests. Just
149     // return true.
150     return true;
151   }
152
153   if (!CheckLayoutName(layout_name))
154     return false;
155
156   if (!force && (current_layout_name_ == layout_name)) {
157     DVLOG(1) << "The requested layout is already set: " << layout_name;
158     return true;
159   }
160
161   DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name;
162
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);
170   if (start_execution)
171     MaybeExecuteSetLayoutCommand();
172
173   return true;
174 }
175
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())
181     return;
182   const std::string layout_to_set = execute_queue_.front();
183
184   std::vector<std::string> argv;
185   base::ProcessHandle handle = base::kNullProcessHandle;
186
187   argv.push_back(kSetxkbmapCommand);
188   argv.push_back("-layout");
189   argv.push_back(layout_to_set);
190   argv.push_back("-synch");
191
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.
195     return;
196   }
197
198   PollUntilChildFinish(handle);
199
200   DVLOG(1) << "ExecuteSetLayoutCommand: "
201            << layout_to_set << ": pid=" << base::GetProcId(handle);
202 }
203
204 // Delay and loop until child process finishes and call the callback.
205 void XKeyboardImpl::PollUntilChildFinish(const base::ProcessHandle handle) {
206   int exit_code;
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(
212           FROM_HERE,
213           base::Bind(&XKeyboardImpl::PollUntilChildFinish,
214                  weak_factory_.GetWeakPtr(), handle),
215           base::TimeDelta::FromMilliseconds(kSetLayoutCommandCheckDelayMs));
216       return;
217
218     case base::TERMINATION_STATUS_NORMAL_TERMINATION:
219       DVLOG(1) << "PollUntilChildFinish: Child process finished";
220       OnSetLayoutFinish();
221       return;
222
223     case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
224       DVLOG(1) << "PollUntilChildFinish: Abnormal exit code: " << exit_code;
225       OnSetLayoutFinish();
226       return;
227
228     default:
229       NOTIMPLEMENTED();
230       OnSetLayoutFinish();
231       return;
232   }
233 }
234
235 bool XKeyboardImpl::NumLockIsEnabled() {
236   bool num_lock_enabled = false;
237   GetLockedModifiers(NULL /* Caps Lock */, &num_lock_enabled);
238   return num_lock_enabled;
239 }
240
241 bool XKeyboardImpl::CapsLockIsEnabled() {
242   bool caps_lock_enabled = false;
243   GetLockedModifiers(&caps_lock_enabled, NULL /* Num Lock */);
244   return caps_lock_enabled;
245 }
246
247 unsigned int XKeyboardImpl::GetNumLockMask() {
248   DCHECK(thread_checker_.CalledOnValidThread());
249   static const unsigned int kBadMask = 0;
250
251   unsigned int real_mask = kBadMask;
252   XkbDescPtr xkb_desc =
253       XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd);
254   if (!xkb_desc)
255     return kBadMask;
256
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)
264         continue;
265       const std::string virtual_mod_str = virtual_mod_str_raw_ptr;
266       XFree(virtual_mod_str_raw_ptr);
267
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.
272         }
273         break;
274       }
275     }
276   }
277   XkbFreeKeyboard(xkb_desc, 0, True /* free all components */);
278   return real_mask;
279 }
280
281 void XKeyboardImpl::GetLockedModifiers(bool* out_caps_lock_enabled,
282                                        bool* out_num_lock_enabled) {
283   DCHECK(thread_checker_.CalledOnValidThread());
284
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;
291     return;
292   }
293
294   XkbStateRec status;
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_;
300 }
301
302 bool XKeyboardImpl::SetAutoRepeatEnabled(bool enabled) {
303   if (enabled)
304     XAutoRepeatOn(GetXDisplay());
305   else
306     XAutoRepeatOff(GetXDisplay());
307   DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off");
308   return true;
309 }
310
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";
319     return false;
320   }
321   return true;
322 }
323
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.";
329     return;
330   }
331
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);
338   }
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);
343   }
344
345   if (affect_mask)
346     XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask);
347 }
348
349 void XKeyboardImpl::SetNumLockEnabled(bool enable_num_lock) {
350   SetLockedModifiers(
351       kDontChange, enable_num_lock ? kEnableLock : kDisableLock);
352 }
353
354 void XKeyboardImpl::SetCapsLockEnabled(bool enable_caps_lock) {
355   SetLockedModifiers(
356       enable_caps_lock ? kEnableLock : kDisableLock, kDontChange);
357 }
358
359 bool XKeyboardImpl::SetCurrentKeyboardLayoutByName(
360     const std::string& layout_name) {
361   if (SetLayoutInternal(layout_name, false)) {
362     current_layout_name_ = layout_name;
363     return true;
364   }
365   return false;
366 }
367
368 bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() {
369   if (current_layout_name_.empty()) {
370     DVLOG(1) << "Can't reapply XKB layout: layout unknown";
371     return false;
372   }
373   return SetLayoutInternal(current_layout_name_, true /* force */);
374 }
375
376 void XKeyboardImpl::ReapplyCurrentModifierLockStatus() {
377   SetLockedModifiers(current_caps_lock_status_ ? kEnableLock : kDisableLock,
378                      current_num_lock_status_ ? kEnableLock : kDisableLock);
379 }
380
381 void XKeyboardImpl::OnSetLayoutFinish() {
382   if (execute_queue_.empty()) {
383     DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. "
384              << "base::LaunchProcess failed?";
385     return;
386   }
387   execute_queue_.pop();
388   MaybeExecuteSetLayoutCommand();
389 }
390
391 }  // namespace
392
393 // static
394 bool XKeyboard::GetAutoRepeatEnabledForTesting() {
395   XKeyboardState state = {};
396   XGetKeyboardControl(GetXDisplay(), &state);
397   return state.global_auto_repeat != AutoRepeatModeOff;
398 }
399
400 // static
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;
405 }
406
407 // static
408 bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) {
409   return CheckLayoutName(layout_name);
410 }
411
412 // static
413 XKeyboard* XKeyboard::Create() {
414   return new XKeyboardImpl();
415 }
416
417 }  // namespace input_method
418 }  // namespace chromeos