Home | History | Annotate | Download | only in input_playback
      1 # Copyright 2017 The Chromium OS 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 import os
      6 
      7 from autotest_lib.client.common_lib import error
      8 from autotest_lib.client.cros.input_playback import input_playback
      9 
     10 _KEYBOARD = 'keyboard'
     11 _KEY_FILENAME = 'keyboard_%s'
     12 
     13 class Keyboard(object):
     14     """An emulated keyboard device used for UI automation."""
     15 
     16     def __init__(self):
     17         """Prepare an emulated keyboard device."""
     18         self.dirname = os.path.dirname(__file__)
     19         # Create an emulated keyboard device.
     20         self.keyboard = input_playback.InputPlayback()
     21         self.keyboard.emulate(input_type=_KEYBOARD)
     22         self.keyboard.find_connected_inputs()
     23 
     24     def press_key(self, key):
     25         """Replay the recorded key events if exists.
     26 
     27         @param key: the target key name, e.g. f1, f2, tab or combination of keys
     28                     'alt+shift+i', 'ctrl+f5', etc.
     29 
     30         """
     31         event_file = os.path.join(self.dirname, _KEY_FILENAME % key)
     32         if not os.path.exists(event_file):
     33             raise error.TestError('No such key file keyboard_%s in %s'
     34                                   % (key, self.dirname))
     35         self.keyboard.blocking_playback(filepath=event_file,
     36                                         input_type=_KEYBOARD)
     37 
     38     def playback(self, event_file):
     39         """Replay the specified key events file.
     40 
     41         @param event_file: the filename of the key events
     42 
     43         """
     44         self.keyboard.blocking_playback(filepath=event_file,
     45                                         input_type=_KEYBOARD)
     46 
     47     def close(self):
     48         """Clean up the files/handles created in the class."""
     49         if self.keyboard:
     50             self.keyboard.close()
     51