Upstream version 7.35.144.0
[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   // Adds/removes observer.
121   virtual void AddObserver(Observer* observer) OVERRIDE;
122   virtual void RemoveObserver(Observer* observer) OVERRIDE;
123
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;
136
137  private:
138   // Returns a mask for Num Lock (e.g. 1U << 4). Returns 0 on error.
139   unsigned int GetNumLockMask();
140
141   // Sets the caps-lock status. Note that calling this function always disables
142   // the num-lock.
143   void SetLockedModifiers(bool caps_lock_enabled);
144
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);
148
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();
153
154   // Polls to see setxkbmap process exits.
155   void PollUntilChildFinish(const base::ProcessHandle handle);
156
157   // Called when execve'd setxkbmap process exits.
158   void OnSetLayoutFinish();
159
160   const bool is_running_on_chrome_os_;
161   unsigned int num_lock_mask_;
162
163   // The current Caps Lock status. If true, enabled.
164   bool current_caps_lock_status_;
165
166   // The XKB layout name which we set last time like "us" and "us(dvorak)".
167   std::string current_layout_name_;
168
169   // A queue for executing setxkbmap one by one.
170   std::queue<std::string> execute_queue_;
171
172   base::ThreadChecker thread_checker_;
173
174   base::WeakPtrFactory<XKeyboardImpl> weak_factory_;
175
176   ObserverList<Observer> observers_;
177
178   DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl);
179 };
180
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());
186
187   num_lock_mask_ = GetNumLockMask();
188
189   if (is_running_on_chrome_os_) {
190     // Some code seems to assume that Mod2Mask is always assigned to
191     // Num Lock.
192     //
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_;
197   }
198
199   current_caps_lock_status_ = CapsLockIsEnabled();
200 }
201
202 void XKeyboardImpl::AddObserver(XKeyboard::Observer* observer) {
203   observers_.AddObserver(observer);
204 }
205
206 void XKeyboardImpl::RemoveObserver(XKeyboard::Observer* observer) {
207   observers_.RemoveObserver(observer);
208 }
209
210 unsigned int XKeyboardImpl::GetNumLockMask() {
211   DCHECK(thread_checker_.CalledOnValidThread());
212   static const unsigned int kBadMask = 0;
213
214   unsigned int real_mask = kBadMask;
215   XkbDescPtr xkb_desc =
216       XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd);
217   if (!xkb_desc)
218     return kBadMask;
219
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)
227         continue;
228       const std::string virtual_mod_str = virtual_mod_str_raw_ptr;
229       XFree(virtual_mod_str_raw_ptr);
230
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.
235         }
236         break;
237       }
238     }
239   }
240   XkbFreeKeyboard(xkb_desc, 0, True /* free all components */);
241   return real_mask;
242 }
243
244 void XKeyboardImpl::SetLockedModifiers(bool caps_lock_enabled) {
245   DCHECK(thread_checker_.CalledOnValidThread());
246
247   // Always turn off num lock.
248   unsigned int affect_mask = num_lock_mask_;
249   unsigned int value_mask = 0;
250
251   affect_mask |= LockMask;
252   value_mask |= (caps_lock_enabled ? LockMask : 0);
253   current_caps_lock_status_ = caps_lock_enabled;
254
255   XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask);
256 }
257
258 bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name,
259                                       bool force) {
260   if (!is_running_on_chrome_os_) {
261     // We should not try to change a layout on Linux or inside ui_tests. Just
262     // return true.
263     return true;
264   }
265
266   if (!CheckLayoutName(layout_name))
267     return false;
268
269   if (!force && (current_layout_name_ == layout_name)) {
270     DVLOG(1) << "The requested layout is already set: " << layout_name;
271     return true;
272   }
273
274   DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name;
275
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);
283   if (start_execution)
284     MaybeExecuteSetLayoutCommand();
285
286   return true;
287 }
288
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())
294     return;
295   const std::string layout_to_set = execute_queue_.front();
296
297   std::vector<std::string> argv;
298   base::ProcessHandle handle = base::kNullProcessHandle;
299
300   argv.push_back(kSetxkbmapCommand);
301   argv.push_back("-layout");
302   argv.push_back(layout_to_set);
303   argv.push_back("-synch");
304
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.
308     return;
309   }
310
311   PollUntilChildFinish(handle);
312
313   DVLOG(1) << "ExecuteSetLayoutCommand: "
314            << layout_to_set << ": pid=" << base::GetProcId(handle);
315 }
316
317 // Delay and loop until child process finishes and call the callback.
318 void XKeyboardImpl::PollUntilChildFinish(const base::ProcessHandle handle) {
319   int exit_code;
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(
325           FROM_HERE,
326           base::Bind(&XKeyboardImpl::PollUntilChildFinish,
327                  weak_factory_.GetWeakPtr(), 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
348 bool XKeyboardImpl::CapsLockIsEnabled() {
349   DCHECK(thread_checker_.CalledOnValidThread());
350   XkbStateRec status;
351   XkbGetState(GetXDisplay(), XkbUseCoreKbd, &status);
352   return (status.locked_mods & LockMask);
353 }
354
355 bool XKeyboardImpl::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
363 bool XKeyboardImpl::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
371
372 bool XKeyboardImpl::SetAutoRepeatEnabled(bool enabled) {
373   if (enabled)
374     XAutoRepeatOn(GetXDisplay());
375   else
376     XAutoRepeatOff(GetXDisplay());
377   DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off");
378   return true;
379 }
380
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";
389     return false;
390   }
391   return true;
392 }
393
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));
400   }
401 }
402
403 bool XKeyboardImpl::SetCurrentKeyboardLayoutByName(
404     const std::string& layout_name) {
405   if (SetLayoutInternal(layout_name, false)) {
406     current_layout_name_ = layout_name;
407     return true;
408   }
409   return false;
410 }
411
412 bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() {
413   if (current_layout_name_.empty()) {
414     DVLOG(1) << "Can't reapply XKB layout: layout unknown";
415     return false;
416   }
417   return SetLayoutInternal(current_layout_name_, true /* force */);
418 }
419
420 void XKeyboardImpl::ReapplyCurrentModifierLockStatus() {
421   SetLockedModifiers(current_caps_lock_status_);
422 }
423
424 void XKeyboardImpl::DisableNumLock() {
425   SetCapsLockEnabled(current_caps_lock_status_);
426 }
427
428 void XKeyboardImpl::OnSetLayoutFinish() {
429   if (execute_queue_.empty()) {
430     DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. "
431              << "base::LaunchProcess failed?";
432     return;
433   }
434   execute_queue_.pop();
435   MaybeExecuteSetLayoutCommand();
436 }
437
438 }  // namespace
439
440 // static
441 bool XKeyboard::GetAutoRepeatEnabledForTesting() {
442   XKeyboardState state = {};
443   XGetKeyboardControl(GetXDisplay(), &state);
444   return state.global_auto_repeat != AutoRepeatModeOff;
445 }
446
447 // static
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;
452 }
453
454 // static
455 bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) {
456   return CheckLayoutName(layout_name);
457 }
458
459 // static
460 XKeyboard* XKeyboard::Create() {
461   return new XKeyboardImpl();
462 }
463
464 }  // namespace input_method
465 }  // namespace chromeos