
nc                 @   sW  d  Z  d d l m Z d Z d d l Z d d l Z d d l	 Z
 d d l m Z m Z d d l Z e e d d  pz e j e _ yB e e f d d   Z d	 d   Z d d l Z d d
 l m Z WnF e k
 r
d d   Z d d   Z d d l Z d d l m Z Yn Xd d   Z Gd d   d e   Z! Gd d   d e  Z d d l" Z# e# j$   d k rtd d l% m& Z' n~ e# j$   d k rd d l% m( Z' nY e# j$   d k ry d d l% m) Z' Wqe* k
 rYqXn e+ d j, e# j$      d d l- m. Z. m/ Z/ m0 Z0 d d l1 m2 Z3 d d l4 m5 Z5 m6 Z6 m7 Z7 e8   Z9 d d   Z: e   Z; i  Z< e< Z= i  Z> Gd  d!   d! e3  Z? e?   Z@ d" d# d$  ZA d% d&   ZB d" d" d' d(  ZC eC ZD d) d*   ZE d+ d,   ZF d- d.   ZG f  d/ d0 d1  ZH i  ZI d2 d3 d   d4 d5  ZJ d2 d6 d7  ZK d2 d8 d9  ZL d2 d: d;  ZM d2 d< d=  ZN d2 d> d?  ZO d@ dA   ZP eP ZQ dB dC   ZR dD dE   ZS eQ ZT dF dG   ZU eQ ZV dH dI   ZW dJ dK   ZX i  ZY f  d2 d d2 dL dM  ZZ eZ Z[ dN dO   Z\ e\ Z] Z^ dP dQ   Z_ e_ Z` Za Zb d" d2 dR dS  Zc e\ Zd dT dU   Ze dV dW   Zf dX dY   Zg d d" d dZ d[  Zh d d2 d2 d\ d]  Zi d d^ d_  Zj d2 d` da  Zk d2 db dc  Zl d" dd de  Zm d" df dg  Zn d ao d dh di  Zp dj dk   Zq dl d2 d2 dm dn  Zr do dp dq  Zs es Zt i  Zu dr g d2 ds dt du  Zv dv dw   Zw d2 ds dx dy  Zx ev Zy ex Zz ew Z{ d S)zu8  
keyboard
========

Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

## Features

- **Global event hook** on all keyboards (captures keys regardless of focus).
- **Listen** and **send** keyboard events.
- Works with **Windows** and **Linux** (requires sudo), with experimental **OS X** support (thanks @glitchassassin!).
- **Pure Python**, no C modules to be compiled.
- **Zero dependencies**. Trivial to install and deploy, just copy the files.
- **Python 2 and 3**.
- Complex hotkey support (e.g. `ctrl+shift+m, ctrl+space`) with controllable timeout.
- Includes **high level API** (e.g. [record](#keyboard.record) and [play](#keyboard.play), [add_abbreviation](#keyboard.add_abbreviation)).
- Maps keys as they actually are in your layout, with **full internationalization support** (e.g. `Ctrl+ç`).
- Events automatically captured in separate thread, doesn't block main program.
- Tested and documented.
- Doesn't break accented dead keys (I'm looking at you, pyHook).
- Mouse support available via project [mouse](https://github.com/boppreh/mouse) (`pip install mouse`).

## Usage

Install the [PyPI package](https://pypi.python.org/pypi/keyboard/):

    pip install keyboard

or clone the repository (no installation required, source files are sufficient):

    git clone https://github.com/boppreh/keyboard

or [download and extract the zip](https://github.com/boppreh/keyboard/archive/master.zip) into your project folder.

Then check the [API docs below](https://github.com/boppreh/keyboard#api) to see what features are available.


## Example

Use as library:

```py
import keyboard

keyboard.press_and_release('shift+s, space')

keyboard.write('The quick brown fox jumps over the lazy dog.')

keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey'))

# Press PAGE UP then PAGE DOWN to type "foobar".
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))

# Blocks until you press esc.
keyboard.wait('esc')

# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed.
keyboard.play(recorded, speed_factor=3)

# Type @@ then press space to replace with abbreviation.
keyboard.add_abbreviation('@@', 'my.long.email@example.com')

# Block forever, like `while True`.
keyboard.wait()
```

Use as standalone module:

```bash
# Save JSON events to a file until interrupted:
python -m keyboard > events.txt

cat events.txt
# {"event_type": "down", "scan_code": 25, "name": "p", "time": 1622447562.2994788, "is_keypad": false}
# {"event_type": "up", "scan_code": 25, "name": "p", "time": 1622447562.431007, "is_keypad": false}
# ...

# Replay events
python -m keyboard < events.txt
```

## Known limitations:

- Events generated under Windows don't report device id (`event.device == None`). [#21](https://github.com/boppreh/keyboard/issues/21)
- Media keys on Linux may appear nameless (scan-code only) or not at all. [#20](https://github.com/boppreh/keyboard/issues/20)
- Key suppression/blocking only available on Windows. [#22](https://github.com/boppreh/keyboard/issues/22)
- To avoid depending on X, the Linux parts reads raw device files (`/dev/input/input*`) but this requires root.
- Other applications, such as some games, may register hooks that swallow all key events. In this case `keyboard` will be unable to report events.
- This program makes no attempt to hide itself, so don't use it for keyloggers or online gaming bots. Be responsible.
- SSH connections forward only the text typed, not keyboard events. Therefore if you connect to a server or Raspberry PI that is running `keyboard` via SSH, the server will not detect your key events.

## Common patterns and mistakes

### Preventing the program from closing

```py
import keyboard
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
# If the program finishes, the hotkey is not in effect anymore.

# Don't do this! This will use 100% of your CPU.
#while True: pass

# Use this instead
keyboard.wait()

# or this
import time
while True:
    time.sleep(1000000)
```

### Waiting for a key press one time

```py
import keyboard

# Don't do this! This will use 100% of your CPU until you press the key.
#
#while not keyboard.is_pressed('space'):
#    continue
#print('space was pressed, continuing...')

# Do this instead
keyboard.wait('space')
print('space was pressed, continuing...')
```

### Repeatedly waiting for a key press

```py
import keyboard

# Don't do this!
#
#while True:
#    if keyboard.is_pressed('space'):
#        print('space was pressed!')
#
# This will use 100% of your CPU and print the message many times.

# Do this instead
while True:
    keyboard.wait('space')
    print('space was pressed! Waiting on it again...')

# or this
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
keyboard.wait()
```

### Invoking code when an event happens

```py
import keyboard

# Don't do this! This will call `print('space')` immediately then fail when the key is actually pressed.
#keyboard.add_hotkey('space', print('space was pressed'))

# Do this instead
keyboard.add_hotkey('space', lambda: print('space was pressed'))

# or this
def on_space():
    print('space was pressed')
keyboard.add_hotkey('space', on_space)

# or this
while True:
    # Wait for the next event.
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN and event.name == 'space':
        print('space was pressed')
```

### 'Press any key to continue'

```py
# Don't do this! The `keyboard` module is meant for global events, even when your program is not in focus.
#import keyboard
#print('Press any key to continue...')
#keyboard.get_event()

# Do this instead
input('Press enter to continue...')

# Or one of the suggestions from here
# https://stackoverflow.com/questions/983354/how-to-make-a-script-wait-for-a-pressed-key
```
    )print_functionz0.13.5N)ThreadLock	monotonicc             C   s   t  |  t  S)N)
isinstance
basestring)x r	   'C:\Python Projects\keyboard\__init__.py<lambda>   s    r   c             C   s   t  |  t t f  S)N)r   intlong)r   r	   r	   r
   r      s    )_Eventc             C   s   t  |  t  S)N)r   str)r   r	   r	   r
   r      s    c             C   s   t  |  t  S)N)r   r   )r   r	   r	   r
   r      s    )Eventc             C   s   t  |  t t f  S)N)r   listtuple)r   r	   r	   r
   r      s    c               @   s   e  Z d  Z d S)_StateN)__name__
__module____qualname__r	   r	   r	   r
   r      s    r   c               @   s   e  Z d  Z d d   Z d S)r   c             C   s!   x t  j |  d  r Pq q Wd  S)Ng      ?)_UninterruptibleEventwait)selfr	   r	   r
   r      s    z_Event.waitN)r   r   r   r   r	   r	   r	   r
   r      s   r   Windows   )_winkeyboardLinux)_nixkeyboardDarwin)_darwinkeyboardzUnsupported platform '{}')KEY_DOWNKEY_UPKeyboardEvent)GenericListener)all_modifierssided_modifiersnormalize_namec             C   sM   t  |   r |  t k St s? d d   t D } t j |   n  |  t k Sd S)zI
    Returns True if `key` is a scan code or name of a modifier key.
    c             s   s   |  ] } t  | d   Vq d S)FN)key_to_scan_codes).0namer	   r	   r
   	<genexpr>  s    zis_modifier.<locals>.<genexpr>N)_is_strr%   _modifier_scan_codesupdate)key
scan_codesr	   r	   r
   is_modifier   s    
r1   c               @   s  e  Z d  Z i d d e d f 6d d e d f 6d d e d f 6d d e d f 6d d e d f 6d d e d f 6d d e d f 6d d e d f 6d d e d	 f 6d d e d	 f 6d d e d	 f 6d d e d	 f 6d d e d	 f 6d  d e d	 f 6d! d e d	 f 6d" d e d	 f 6d# d e d
 f 6d$ d e d
 f 6d% d e d
 f 6d& d e d
 f 6d' d e d
 f 6d( d e d
 f 6d) d e d
 f 6d* d e d
 f 6Z d d   Z d d   Z d d   Z d d   Z	 d S)+_KeyboardListenerFTfreemodifierpendingallowed
suppressedNhotkeyotherc             C   s   t  j   t   |  _ g  |  _ t j t  |  _ t j t  |  _	 t j t  |  _
 t j t  |  _ t j   |  _ d |  _ i  |  _ d  S)NF)_os_keyboardinitsetactive_modifiersblocking_hooks_collectionsdefaultdictr   blocking_keysnonblocking_keysblocking_hotkeysnonblocking_hotkeysCounterfiltered_modifiersis_replayingmodifier_states)r   r	   r	   r
   r;   9  s    
		z_KeyboardListener.initc          
   C   s   x" |  j  | j D] } | |  q Wt  t t t   } Wd  QXx |  j | D] } | |  qR W| j p | j o | j d k S)Nunknown)rB   	scan_code_pressed_events_lockr   sorted_pressed_eventsrD   r*   )r   eventkey_hookr8   callbackr	   r	   r
   pre_process_eventI  s    z#_KeyboardListener.pre_process_eventc          
      sn  |  j  r d St   f d d   |  j D  s3 d S  j }   j } t  | t k r t |  rw |  j j	 |  n    t
 | <n  t t t
   } | t k r |  j j |  | t
 k r t
 | =q n  Wd QXx% |  j | D] } |    s d Sq Wd } |  j r|  j | r-d } t | g  } nf |  j } t |  rR| | h B} n    f d d   |  j | D }	 |	 rt |	  } d	 } n d
 } x t |  D]o }
 |  j j |
 d  | | f } |  j | \ } } } | rt |
  n  | d k	 r| } n  | |  j |
 <qWn  | rZ| t k r5  t | <qZ| t k rZ| t k rZt | =qZn  |  j j    | S)a  
        This function is called for every OS keyboard event and decides if the
        event should be blocked or not, and passes a copy of the event to
        other, non-blocking, listeners.

        There are two ways to block events: remapped keys, which translate
        events by suppressing and re-emitting; and blocked hotkeys, which
        suppress specific hotkeys.
        Tc             3   s   |  ] } |    Vq d  S)Nr	   )r)   hook)rN   r	   r
   r+   b  s    z4_KeyboardListener.direct_callback.<locals>.<genexpr>FNr4   c                s   g  |  ] } |     q Sr	   r	   )r)   rP   )rN   r	   r
   
<listcomp>  s   	 z5_KeyboardListener.direct_callback.<locals>.<listcomp>r8   r9   r3   )rG   allr>   
event_typerJ   rK   r!   r1   r=   addrM   r   rL   r"   discardrA   rC   rF   r<   rH   gettransition_tablepress_logically_pressed_keysqueueput)r   rN   rU   rJ   r8   rO   acceptoriginZmodifiers_to_updateZcallback_resultsr/   Ztransition_tupleZshould_pressZ
new_acceptZ	new_stater	   )rN   r
   direct_callbackT  s^    	"		  		 	  	z!_KeyboardListener.direct_callbackc             C   s   t  j |  j  d  S)N)r:   listenr`   )r   r	   r	   r
   ra     s    z_KeyboardListener.listen)FTfree)FFzpending)TTrb   )FTr6   )FFrb   )FFr7   )FTrb   )FTr6   )FNrb   )FNrb   )FNr7   )FNr7   )FNr7   )FNr7   )FNr6   )FNr6   )FTrb   )FTrb   )TTr6   )TTr6   )FFr6   )TTr6   )FTr6   )FTr6   )
r   r   r   r"   r!   rY   r;   rQ   r`   ra   r	   r	   r	   r
   r2     s:   Gr2   Tc                sz  t  |   r |  f St |   r9 t d d   |  D f   St |   sv t d t t |    d t |   d   n  t |   } | t	 k r t
 d | d    t
 d | d  }   t   f d	 d   | D  Sy5 t t j d
 d   t j |  D   } d } Wn7 t t f k
 rC} z f  } | } WYd d } ~ Xn X| rr| rrt d j t |    |   n | Sd S)zT
    Returns a list of scan codes associated with this key (name or scan code).
    c             s   s   |  ] } t  |  Vq d  S)N)r(   )r)   ir	   r	   r
   r+     s    z$key_to_scan_codes.<locals>.<genexpr>zUnexpected key type z	, value ()zleft Fzright c             3   s!   |  ] } |   k r | Vq d  S)Nr	   )r)   c)left_scan_codesr	   r
   r+     s    c             s   s!   |  ] \ } } | d  f Vq d S)TNr	   )r)   rJ   r4   r	   r	   r
   r+     s    Nz&Key {} is not mapped to any known key.)
_is_number_is_listsumr,   
ValueErrorr   typereprr'   r&   r(   r   r?   OrderedDictr:   map_nameKeyErrorformat)r/   Zerror_if_missingZ
normalizedZright_scan_codeste	exceptionr	   )rf   r
   r(     s(    1!+
!r(   c             C   s   t  |   s t |   d k r@ t |   } | f } | f } | St |   r t t t |    s t d d   |  D  } | f } | S|  Sg  } xL t j d |   D]8 } t j d |  } | j	 t d d   | D   q Wt |  S)a  
    Parses a user-provided hotkey into nested tuples representing the
    parsed structure, with the bottom values being lists of scan codes.
    Also accepts raw scan codes, which are then wrapped in the required
    number of nestings.

    Example:

        parse_hotkey("alt+shift+a, alt+b, c")
        #    Keys:    ^~^ ^~~~^ ^  ^~^ ^  ^
        #    Steps:   ^~~~~~~~~~^  ^~~~^  ^

        # ((alt_codes, shift_codes, a_codes), (alt_codes, b_codes), (c_codes,))
    r   c             s   s   |  ] } t  |  Vq d  S)N)r(   )r)   kr	   r	   r
   r+     s    zparse_hotkey.<locals>.<genexpr>z,\s?z\s?\+\s?c             s   s   |  ] } t  |  Vq d  S)N)r(   )r)   r/   r	   r	   r
   r+     s    )
rg   lenr(   rh   anymapr   _resplitappend)r8   r0   stepstepskeysr	   r	   r
   parse_hotkey  s     			$r~   c             C   s   d t  _ t |   } xj | D]b } | rM x" | D] } t j | d  q/ Wn  | r x( t |  D] } t j | d  q` Wq q Wd t  _ d S)a  
    Sends OS events that perform the given *hotkey* hotkey.

    - `hotkey` can be either a scan code (e.g. 57 for space), single key
    (e.g. 'space') or multi-key, multi-step hotkey (e.g. 'alt+F4, enter').
    - `do_press` if true then press events are sent. Defaults to True.
    - `do_release` if true then release events are sent. Defaults to True.

        send(57)
        send('ctrl+alt+del')
        send('alt+F4, enter')
        send('shift+s')

    Note: keys are released in the opposite order they were pressed.
    Tr   FN)	_listenerrG   r~   r:   rZ   reversedrelease)r8   Zdo_pressZ
do_releaseZparsedr{   r0   r	   r	   r
   send  s    	r   c             C   s   t  |  d d  d S)z/ Presses and holds down a hotkey (see `send`). TFN)r   )r8   r	   r	   r
   rZ      s    rZ   c             C   s   t  |  d d  d S)z! Releases a hotkey (see `send`). FTN)r   )r8   r	   r	   r
   r     s    r   c                s   t  j   t |   r0 t  |  t k SWd QXn  t |   } t |  d k r] t d   n  t  t t    Wd QXx5 | d D]) } t	   f d d   | D  s d Sq Wd S)	z
    Returns True if the key is pressed.

        is_pressed(57) #-> True
        is_pressed('space') #-> True
        is_pressed('ctrl+space') #-> True
    Nr   zRImpossible to check if multi-step hotkeys are pressed (`a+b` is ok, `a, b` isn't).r   c             3   s   |  ] } |   k Vq d  S)Nr	   )r)   rJ   )pressed_scan_codesr	   r
   r+     s    zis_pressed.<locals>.<genexpr>FT)
r   start_if_necessaryrg   rK   rM   r~   ru   rj   r<   rv   )r8   r|   r0   r	   )r   r
   
is_pressed  s    
r   gMbP?c                s/   t  d     f d d    } | j   d S)z
    Calls the provided function in a new thread after waiting some time.
    Useful for giving the system some time to process an event, without blocking
    the current execution flow.
    targetc                  s   t  j        f S)N)_timesleepr	   )argsdelayfnr	   r
   r   )  s    zcall_later.<locals>.<lambda>N)_Threadstart)r   r   r   threadr	   )r   r   r   r
   
call_later#  s    !r   Fc               C   s   d  S)Nr	   r	   r	   r	   r
   r   -  s    c                sz   | r, t  j   t  j j t  j j }  n t  j t  j }  |         f d d     t   <t  < S)a[  
    Installs a global listener on all available keyboards, invoking `callback`
    each time a key is pressed or released.
    
    The event passed to the callback is of type `keyboard.KeyboardEvent`,
    with the following attributes:

    - `name`: an Unicode representation of the character (e.g. "&") or
    description (e.g.  "space"). The name is always lower-case.
    - `scan_code`: number representing the physical key, e.g. 55.
    - `time`: timestamp of the time the event occurred, with as much precision
    as given by the OS.

    Returns the given callback for easier development.
    c                  s5   t  j   d   t  j  d          d  S)N)_hookspopr	   )rP   	on_removeremoveremove_r	   r
   r   D  s    
zhook.<locals>.remove_)r   r   r>   rz   r   Zadd_handlerZremove_handlerr   )rP   suppressr   rz   r	   )rP   r   r   r   r
   rR   -  s    

rR   c                s   t    f d d   d | S)zN
    Invokes `callback` for every KEY_DOWN event. For details see `hook`.
    c                s   |  j  t k p   |   S)N)rU   r"   )rr   )rP   r	   r
   r   P  s    zon_press.<locals>.<lambda>r   )rR   )rP   r   r	   )rP   r
   on_pressL  s    r   c                s   t    f d d   d | S)zL
    Invokes `callback` for every KEY_UP event. For details see `hook`.
    c                s   |  j  t k p   |   S)N)rU   r!   )rr   )rP   r	   r
   r   V  s    zon_release.<locals>.<lambda>r   )rR   )rP   r   r	   )rP   r
   
on_releaseR  s    r   c                s   t  j   | r t  j n t  j  t    x  D] }  | j    q5 W      f d d     t   <t  <t  < S)a  
    Hooks key up and key down events for a single key. Returns the event handler
    created. To remove a hooked key use `unhook_key(key)` or
    `unhook_key(handler)`.

    Note: this function shares state with hotkeys, so `clear_all_hotkeys`
    affects it as well.
    c                 sV   t  j   d   t  j  d   t  j  d   x  D] }   |  j    q7 Wd  S)N)r   r   r   )rJ   )rP   r/   r   r0   storer	   r
   r   g  s
    zhook_key.<locals>.remove_)r   r   rA   rB   r(   rz   r   )r/   rP   r   rJ   r	   )rP   r/   r   r0   r   r
   hook_keyX  s    	
r   c                s   t  |    f d d   d | S)za
    Invokes `callback` for KEY_DOWN event related to the given key. For details see `hook`.
    c                s   |  j  t k p   |   S)N)rU   r"   )rr   )rP   r	   r
   r   t  s    zon_press_key.<locals>.<lambda>r   )r   )r/   rP   r   r	   )rP   r
   on_press_keyp  s    r   c                s   t  |    f d d   d | S)z_
    Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
    c                s   |  j  t k p   |   S)N)rU   r!   )rr   )rP   r	   r
   r   z  s    z on_release_key.<locals>.<lambda>r   )r   )r/   rP   r   r	   )rP   r
   on_release_keyv  s    r   c             C   s   t  |    d S)zc
    Removes a previously added hook, either by callback or by the return value
    of `hook`.
    N)r   )r   r	   r	   r
   unhook|  s    r   c               C   sO   t  j   t  j j   t  j j   t  j d d  =t  j d d  =t   d S)z{
    Removes all keyboard hooks in use, including hotkeys, abbreviations, word
    listeners, `record`ers and `wait`s.
    N)r   r   rA   clearrB   r>   Zhandlersunhook_all_hotkeysr	   r	   r	   r
   
unhook_all  s    
r   c             C   s   t  |  d d   d d S)zN
    Suppresses all key events of the given key, regardless of modifiers.
    c             S   s   d S)NFr	   )rr   r	   r	   r
   r     s    zblock_key.<locals>.<lambda>r   T)r   )r/   r	   r	   r
   	block_key  s    r   c                s%     f d d   } t  |  | d d S)z
    Whenever the key `src` is pressed or released, regardless of modifiers,
    press or release the hotkey `dst` instead.
    c                s*   |  j  t k r t    n
 t    d S)NF)rU   r!   rZ   r   )rN   )dstr	   r
   handler  s    
zremap_key.<locals>.handlerr   T)r   )srcr   r   r	   )r   r
   	remap_key  s    r   c                s/   d d     t    f d d   t |   D  S)z
    Parses a user-provided hotkey. Differently from `parse_hotkey`,
    instead of each step being a list of the different scan codes for each key,
    each step is a list of all possible combinations of those scan codes.
    c             S   s   d d   t  j |    D S)Nc             s   s!   |  ] } t  t |   Vq d  S)N)r   rL   )r)   r0   r	   r	   r
   r+     s    zBparse_hotkey_combinations.<locals>.combine_step.<locals>.<genexpr>)
_itertoolsproduct)r{   r	   r	   r
   combine_step  s    z/parse_hotkey_combinations.<locals>.combine_stepc             3   s!   |  ] } t    |   Vq d  S)N)r   )r)   r{   )r   r	   r
   r+     s    z,parse_hotkey_combinations.<locals>.<genexpr>)r   r~   )r8   r	   )r   r
   parse_hotkey_combinations  s    r   c                s   | r t  j n t  j  xP   D]H } x. | D]& } t |  r, t  j | d 7<q, q, W | j   q W    f d d   } | S)z6
    Hooks a single-step hotkey (e.g. 'shift+a').
    r   c                 sW   xP   D]H }  x. |  D]& } t  |  r t j | d 8<q q W |  j   q Wd  S)Nr   )r1   r   rF   r   )r0   rJ   )combinations	containerr   r	   r
   r     s
    z _add_hotkey_step.<locals>.remove)r   rC   rD   r1   rF   rz   )r   r   r   r0   rJ   r   r	   )r   r   r   r
   _add_hotkey_step  s    r   c                s   r   f d d   n  t  j   t   
 | r@ t n t  t 
  d k r   f d d   } t | 
 d        f d d     t  <t  <t  < St   	 d d   	 _	 d	 	 _
 g  	 _ t d
  	 _ d     	  f d d       	 
  f d d     d  d d   
 D      	 f d d     t  <t  <t  < S)a  
    Invokes a callback every time a hotkey is pressed. The hotkey must
    be in the format `ctrl+shift+a, s`. This would trigger when the user holds
    ctrl, shift and "a" at once, releases, and then presses "s". To represent
    literal commas, pluses, and spaces, use their names ('comma', 'plus',
    'space').

    - `args` is an optional list of arguments to passed to the callback during
    each invocation.
    - `suppress` defines if successful triggers should block the keys from being
    sent to other programs.
    - `timeout` is the amount of seconds allowed to pass between key presses.
    - `trigger_on_release` if true, the callback is invoked on key release instead
    of key press.

    The event handler function is returned. To remove a hotkey call
    `remove_hotkey(hotkey)` or `remove_hotkey(handler)`.
    before the hotkey state is reset.

    Note: hotkeys are activated when the last key is *pressed*, not released.
    Note: the callback is executed in a separate thread, asynchronously. For an
    example of how to use a callback synchronously, see `wait`.

    Examples:

        # Different but equivalent ways to listen for a spacebar key press.
        add_hotkey(' ', print, args=['space was pressed'])
        add_hotkey('space', print, args=['space was pressed'])
        add_hotkey('Space', print, args=['space was pressed'])
        # Here 57 represents the keyboard code for spacebar; so you will be
        # pressing 'spacebar', not '57' to activate the print function.
        add_hotkey(57, print, args=['space was pressed'])

        add_hotkey('ctrl+q', quit)
        add_hotkey('ctrl+alt+enter, space', some_callback)
    c                s
   |      S)Nr	   )rP   )r   r	   r
   r     s    zadd_hotkey.<locals>.<lambda>r   c                s@    t  k r* |  j t k r* |  j t k p?  |  j k o?     S)N)r!   rU   r"   rJ   r[   )rr   )rP   rU   r	   r
   r     s    r   c                  s;      t  j  d   t  j  d   t  j   d   d  S)N)_hotkeysr   r	   )rP   r8   r   remove_stepr	   r
   r     s    zadd_hotkey.<locals>.remove_c               S   s   d  S)Nr	   r	   r	   r	   r
   r     s    Nz-infFc                s   |  j   k r.  j r. |  j    j k sS  rM t j    j  k sS | r  j   x=  j D]2 }  |  j  t k r t	 |  j  qg t
 |  j  qg W j d  d   =d }  d  n  d S)Nr   T)rU   indexrJ   r   r   last_updateremove_last_stepsuppressed_eventsr!   rZ   r   )rN   
force_failr   )allowed_keys_by_steprU   	set_indexstatetimeoutr	   r
   catch_misses  s    	
z add_hotkey.<locals>.catch_missesc                s	  |   _  |  d k r1  j   d d    _ n. |  d k r_  j   t  d d  _ n  |  t   d k r        f d d   } t |   j      n;  j  d     f d	 d  } t |   j         _ t j    _ d
 S)Nr   c               S   s   d  S)Nr	   r	   r	   r	   r
   r   /  s    z/add_hotkey.<locals>.set_index.<locals>.<lambda>r   r   Tc                so   |  j  t k r#     d  n  |  j   k o8     } | rQ  |  d d S|  g  j d  d   <d Sd  S)Nr   r   TF)rU   r"   r   )rN   r^   )rP   r   rU   r   r   r   r	   r
   r   6  s    z.add_hotkey.<locals>.set_index.<locals>.handlerc                s7   |  j  t k r#      |  n   j j |   d S)NF)rU   r"   r   rz   )rN   	new_index)r   r   r   r	   r
   r   C  s
    F)	r   remove_catch_missesrR   ru   r   r   r   r   r   )r   r   )rP   r   rU   r   r   r|   r   )r   r
   r   (  s    	

!
"	zadd_hotkey.<locals>.set_indexc             S   s"   g  |  ] } t    j |    q Sr	   )r<   union)r)   r{   r	   r	   r
   rS   P  s   	zadd_hotkey.<locals>.<listcomp>c                  sH    j     j   t j  d   t j  d   t j   d   d  S)N)r   r   r   r   r	   )rP   r8   r   r   r	   r
   r   T  s
    

)r   r   r   r"   r!   ru   r   r   r   r   r   r   floatr   )r8   rP   r   r   r   trigger_on_releaser   r	   )r   r   rP   r   rU   r8   r   r   r   r   r|   r   r   r
   
add_hotkey  s0    %
			!$%
	
r   c             C   s   t  |    d S)zi
    Removes a previously hooked hotkey. Must be called with the value returned
    by `add_hotkey`.
    N)r   )Zhotkey_or_callbackr	   r	   r
   remove_hotkey`  s    r   c               C   s   t  j j   t  j j   d S)zt
    Removes all keyboard hotkeys in use, including abbreviations, word listeners,
    `record`ers and `wait`s.
    N)r   rC   r   rD   r	   r	   r	   r
   r   h  s    r   c                s+     f d d   } t  |  | d | d | S)z
    Whenever the hotkey `src` is pressed, suppress it and send
    `dst` instead.

    Example:

        remap('alt+w', 'ctrl+up')
    c                 sl   t  d d   t j j   D  }  x |  D] } t |  q) Wt    x t |   D] } t |  qT Wd S)Nc             s   s'   |  ] \ } } | d  k r | Vq d S)r6   Nr	   )r)   r4   r   r	   r	   r
   r+   }  s    z0remap_hotkey.<locals>.handler.<locals>.<genexpr>F)rL   r   rH   itemsr   r   r   rZ   )r=   r4   )r   r	   r
   r   |  s    "
zremap_hotkey.<locals>.handlerr   r   )r   )r   r   r   r   r   r	   )r   r
   remap_hotkeys  s    	r   c           	   C   s;   t   t t  }  Wd QXx |  D] } t j |  q  W|  S)z
    Builds a list of all currently pressed scan codes, releases them and returns
    the list. Pairs well with `restore_state` and `restore_modifiers`.
    N)rK   rL   rM   r:   r   )r   rJ   r	   r	   r
   stash_state  s
    r   c          	   C   s   d t  _ t  t t  } Wd QXt |   } x | | D] } t j |  q9 Wx | | D] } t j |  q[ Wd t  _ d S)z
    Given a list of scan_codes ensures these keys, and only these keys, are
    pressed. Pairs well with `stash_state`, alternative to `restore_modifiers`.
    TNF)r   rG   rK   r<   rM   r:   r   rZ   )r0   currentr   rJ   r	   r	   r
   restore_state  s    	r   c             C   s   t  d d   |  D  d S)z@
    Like `restore_state`, but only restores modifier keys.
    c             s   s!   |  ] } t  |  r | Vq d  S)N)r1   )r)   rJ   r	   r	   r
   r+     s    z$restore_modifiers.<locals>.<genexpr>N)r   )r0   r	   r	   r
   restore_modifiers  s    r   c       
      C   sm  | d k r! t  j   d k } n  t   } | r x#|  D]B } | d k rV t |  n t j |  | r7 t j |  q7 q7 Wn x |  D] } y1 t j t	 |   } t
 t |   \ } } Wn+ t t t f k
 r t j |  w Yn Xx | D] }	 t |	  q Wt j |  t j |  x | D] }	 t |	  q(W| r t j |  q q W| rit |  n  d S)a3  
    Sends artificial keyboard events to the OS, simulating the typing of a given
    text. Characters not available on the keyboard are typed as explicit unicode
    characters using OS-specific functionality, such as alt+codepoint.

    To ensure text integrity, all currently pressed keys are released before
    the text is typed, and modifiers are restored afterwards.

    - `delay` is the number of seconds to wait between keypresses, defaults to
    no delay.
    - `restore_state_after` can be used to restore the state of pressed keys
    after the text is typed, i.e. presses the keys that were released at the
    beginning. Defaults to True.
    - `exact` forces typing all characters as explicit unicode (e.g.
    alt+codepoint or special events). If None, uses platform-specific suggested
    value.
    Nr   z
)	_platformsystemr   r   r:   Ztype_unicoder   r   rn   r'   nextiterro   rj   StopIterationrZ   r   r   )
textr   Zrestore_state_afterexactr   ZletterZentriesrJ   	modifiersr4   r	   r	   r
   write  s6    	 r   c                se   |  rM t      t |    f d d   d | d | }   j   t |  n x t j d  qP Wd S)zx
    Blocks the program execution until the given hotkey is pressed or,
    if given no parameters, blocks forever.
    c                  s
     j    S)N)r<   r	   )lockr	   r
   r     s    zwait.<locals>.<lambda>r   r   g    .AN)r   r   r   r   r   r   )r8   r   r   r   r	   )r   r
   r     s    	'
r   c                s   |  d k r? t  j   t  d d   t j   D }  Wd QXn d d   |  D }  t d d   |  D  } d d d	 d
 g     f d d   } d j t | d |  S)a  
    Returns a string representation of hotkey from the given key names, or
    the currently pressed keys if not given.  This function:

    - normalizes names;
    - removes "left" and "right" prefixes;
    - replaces the "+" key name with "plus" to avoid ambiguity;
    - puts modifier keys first, in a standardized order;
    - sort remaining keys;
    - finally, joins everything with "+".

    Example:

        get_hotkey_name(['+', 'left ctrl', 'shift'])
        # "ctrl+shift+plus"
    Nc             S   s   g  |  ] } | j   q Sr	   )r*   )r)   rr   r	   r	   r
   rS     s   	 z#get_hotkey_name.<locals>.<listcomp>c             S   s   g  |  ] } t  |   q Sr	   )r'   )r)   r*   r	   r	   r
   rS     s   	 c             s   s9   |  ]/ } | j  d  d  j  d d  j  d d  Vq d S)zleft  zright +plusN)replace)r)   rr   r	   r	   r
   r+     s    z"get_hotkey_name.<locals>.<genexpr>ZctrlZaltshiftwindowsc                s+   |    k r   j  |   n d t |   f S)N   )r   r   )rt   )r   r	   r
   r     s    z!get_hotkey_name.<locals>.<lambda>r   r/   )r   r   rK   rM   valuesr<   joinrL   )namesZclean_namesZsorting_keyr	   )r   r
   get_hotkey_name  s    
"r   c             C   sI   t  j d d  } t | j d |  } x | j   } t |  | SWd S)zI
    Blocks until a keyboard event happens, then returns that event.
    maxsizer   r   N)_queueQueuerR   r]   rX   r   )r   r\   hookedrN   r	   r	   r
   
read_event  s    
r   c             C   s   t  |   } | j p | j S)zr
    Blocks until a keyboard event happens, then returns that event's name or,
    if missing, its scan code.
    )r   r*   rJ   )r   rN   r	   r	   r
   read_key  s    r   c          	      s   t  j       f d d   } t | d |  } xc   j   } | j t k r3 t |  t ( d d   t j	   D | j
 g } Wd QXt |  Sq3 Wd S)z
    Similar to `read_key()`, but blocks until the user presses and releases a
    hotkey (or single key), then returns a string representing the hotkey
    pressed.

    Example:

        read_hotkey()
        # "ctrl+shift+p"
    c                s     j  |   p |  j t k S)N)r]   rU   r!   )rr   )r\   r	   r
   r   -  s    zread_hotkey.<locals>.<lambda>r   c             S   s   g  |  ] } | j   q Sr	   )r*   )r)   rr   r	   r	   r
   rS   4  s   	 zread_hotkey.<locals>.<listcomp>N)r   r   rR   rX   rU   r"   r   rK   rM   r   r*   r   )r   r   r   rN   r   r	   )r\   r
   read_hotkey!  s    
)r   c             c   s@  t  j   d k r d n d } d } d } d } x|  D] } | j } | j d k r^ d } n  d | j k r | j d	 k } q7 | j d
 k r | j d	 k r | } q7 | r | j | k r | j d	 k r | d d  } q7 | j d	 k r7 t |  d k r%| | Ar| j   } n  | | } q3| Vd } q7 q7 W| Vd S)a  
    Given a sequence of events, tries to deduce what strings were typed.
    Strings are separated when a non-textual key is pressed (such as tab or
    enter). Characters are converted to uppercase according to shift and
    capslock status. If `allow_backspace` is True, backspaces remove the last
    character typed.

    This function is a generator, so you can pass an infinite stream of events
    and convert them to strings in real time.

    Note this functions is merely an heuristic. Windows for example keeps per-
    process keyboard state such as keyboard layout, and this information is not
    available for our hooks.

        get_type_strings(record()) #-> ['This is what', 'I recorded', '']
    r   deleteZ	backspaceFr   space r   Zdownz	caps lockNr   )r   r   r*   rU   ru   upper)eventsZallow_backspaceZbackspace_nameZshift_pressedZcapslock_pressedstringrN   r*   r	   r	   r
   get_typed_strings7  s,    		
$
r   c             C   s+   |  p t  j   }  |  t |  j  f a t S)z
    Starts recording all keyboard events into a global variable, or the given
    queue if any. Returns the queue of events and the hooked function.

    Use `stop_recording()` or `unhook(hooked_function)` to stop.
    )r   r   rR   r]   
_recording)recorded_events_queuer	   r	   r
   start_recordingf  s    r   c              C   s8   t  s t d   n  t  \ }  } t |  t |  j  S)z]
    Stops the global recording of events and returns a list of the events
    captured.
    z#Must call "start_recording" before.)r   rj   r   r   r\   )r   r   r	   r	   r
   stop_recordingr  s
    
r   escapec             C   s$   t    t |  d | d | t   S)aH  
    Records all keyboard events from all keyboards until the user presses the
    given hotkey. Then returns the list of events recorded, of type
    `keyboard.KeyboardEvent`. Pairs well with
    `play(events)`.

    Note: this is a blocking function.
    Note: for more details on the keyboard hook and events see `hook`.
    r   r   )r   r   r   )Zuntilr   r   r	   r	   r
   record~  s    
r   g      ?c             C   s   t    } d } x |  D]y } | d k rO | d k	 rO t j | j | |  n  | j } | j pg | j } | j t k r t |  n	 t	 |  q Wt
 |  d S)a:  
    Plays a sequence of recorded events, maintaining the relative time
    intervals. If speed_factor is <= 0 then the actions are replayed as fast
    as the OS allows. Pairs well with `record()`.

    Note: the current keyboard state is cleared at the beginning and restored at
    the end of the function.
    Nr   )r   r   r   timerJ   r*   rU   r!   rZ   r   r   )r   Zspeed_factorr   Z	last_timerN   r/   r	   r	   r
   play  s    			)r   r      c                s   t     d  _ d  _        f d d    t        f d d     t  <t  <t  < S)a  
    Invokes a callback every time a sequence of characters is typed (e.g. 'pet')
    and followed by a trigger key (e.g. space). Modifiers (e.g. alt, ctrl,
    shift) are ignored.

    - `word` the typed text to be matched. E.g. 'pet'.
    - `callback` is an argument-less function to be invoked each time the word
    is typed.
    - `triggers` is the list of keys that will cause a match to be checked. If
    the user presses some key that is not a character (len>1) and not in
    triggers, the characters so far will be discarded. By default the trigger
    is only `space`.
    - `match_suffix` defines if endings of words should also be checked instead
    of only whole words. E.g. if true, typing 'carpet'+space will trigger the
    listener for 'pet'. Defaults to false, only whole words are checked.
    - `timeout` is the maximum number of seconds between typed characters before
    the current word is discarded. Defaults to 2 seconds.

    Returns the event handler created. To remove a word listener use
    `remove_word_listener(word)` or `remove_word_listener(handler)`.

    Note: all actions are performed on key down. Key up events are ignored.
    Note: word matches are **case sensitive**.
    r   r   c                s   |  j  } |  j t k s$ | t k r( d  S rP |  j  j  k rP d  _ n  |  j  _  j  k p  o  j j   } |  k r | r     d  _ n- t |  d k r d  _ n  j | 7_ d  S)Nr   r   )r*   rU   r"   r%   r   r   endswithru   )rN   r*   Zmatched)rP   match_suffixr   r   triggerswordr	   r
   r     s    	 'z"add_word_listener.<locals>.handlerc                  sM       t  k r t   =n    t  k r3 t    =n   t  k rI t   =n  d  S)N)_word_listenersr	   )r   r   r   r   r	   r
   r     s    

z!add_word_listener.<locals>.remover   )r   r   r   rR   r   )r   rP   r   r   r   r	   )	rP   r   r   r   r   r   r   r   r   r
   add_word_listener  s    			!r   c             C   s   t  |    d S)z
    Removes a previously registered word listener. Accepts either the word used
    during registration (exact string) or the event handler returned by the
    `add_word_listener` or `add_abbreviation` functions.
    N)r   )Zword_or_handlerr	   r	   r
   remove_word_listener  s    r   c                sC   d t  |   d |     f d d   } t |  | d | d | S)u  
    Registers a hotkey that replaces one typed text with another. For example

        add_abbreviation('tm', u'™')

    Replaces every "tm" followed by a space with a ™ symbol (and no space). The
    replacement is done by sending backspace events.

    - `match_suffix` defines if endings of words should also be checked instead
    of only whole words. E.g. if true, typing 'carpet'+space will trigger the
    listener for 'pet'. Defaults to false, only whole words are checked.
    - `timeout` is the maximum number of seconds between typed characters before
    the current word is discarded. Defaults to 2 seconds.
    
    For more details see `add_word_listener`.
    r   c                  s
   t     S)N)r   r	   )replacementr	   r
   r     s    z"add_abbreviation.<locals>.<lambda>r   r   )ru   r   )Zsource_textZreplacement_textr   r   rP   r	   )r   r
   add_abbreviation  s    r   )|__doc__
__future__r   Z_print_functionversionrerx   	itertoolsr   collectionsr?   	threadingr   r   r   Z_Lockr   r   getattrr   r   r   r,   rg   r   r   r   r   	NameErrorr\   r   rh   objectr   platformr   r   r   r   r:   r   r    ImportErrorOSErrorrp   Z_keyboard_eventr!   r"   r#   Z_genericr$   Z_GenericListenerZ_canonical_namesr%   r&   r'   r<   r-   r1   rK   rM   Z_physically_pressed_keysr[   r2   r   r(   r~   r   Zpress_and_releaserZ   r   r   r   r   rR   r   r   r   r   r   r   Z
unhook_keyr   r   Zunblock_keyr   Zunremap_keyr   r   r   r   Zregister_hotkeyr   Zunregister_hotkeyZclear_hotkeyr   Zunregister_all_hotkeysZremove_all_hotkeysZclear_all_hotkeysr   Zunremap_hotkeyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zreplayr   r   r   r   Zregister_word_listenerZregister_abbreviationZremove_abbreviationr	   r	   r	   r
   <module>   s   
			!	
	7.;