aboutsummaryrefslogtreecommitdiffstats
path: root/build/lib.linux-x86_64-2.7/dogtail/rawinput.py
blob: 7100b29bfae41b5bf543af05b6026790a802b057 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# -*- coding: utf-8 -*-
"""
Handles raw input using AT-SPI event generation.

Note: Think of keyvals as keysyms, and keynames as keystrings.

Authors: David Malcolm <dmalcolm@redhat.com>, Zack Cerza <zcerza@redhat.com>
"""

__author__ = """
David Malcolm <dmalcolm@redhat.com>,
Zack Cerza <zcerza@redhat.com>
"""
import gi

gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')

from gi.repository import Gdk
from config import config
from utils import doDelay
from logging import debugLogger as logger
from pyatspi import Registry as registry
from pyatspi import (KEY_SYM, KEY_PRESS, KEY_PRESSRELEASE, KEY_RELEASE)
from exceptions import ValueError
from __builtin__ import unicode, unichr


def doTypingDelay():
    doDelay(config.typingDelay)


def checkCoordinates(x, y):
    if x < 0 or y < 0:
        raise ValueError(
            "Attempting to generate a mouse event at negative coordinates: (%s,%s)" % (x, y))


def click(x, y, button=1, check=True):
    """
    Synthesize a mouse button click at (x,y)
    """
    if check:
        checkCoordinates(x, y)
    logger.log("Mouse button %s click at (%s,%s)" % (button, x, y))
    registry.generateMouseEvent(x, y, 'b%sc' % button)
    doDelay(config.actionDelay)


def doubleClick(x, y, button=1, check=True):
    """
    Synthesize a mouse button double-click at (x,y)
    """
    if check:
        checkCoordinates(x, y)
    logger.log("Mouse button %s doubleclick at (%s,%s)" % (button, x, y))
    registry.generateMouseEvent(x, y, 'b%sd' % button)
    doDelay()


def press(x, y, button=1, check=True):
    """
    Synthesize a mouse button press at (x,y)
    """
    if check:
        checkCoordinates(x, y)
    logger.log("Mouse button %s press at (%s,%s)" % (button, x, y))
    registry.generateMouseEvent(x, y, 'b%sp' % button)
    doDelay()


def release(x, y, button=1, check=True):
    """
    Synthesize a mouse button release at (x,y)
    """
    if check:
        checkCoordinates(x, y)
    logger.log("Mouse button %s release at (%s,%s)" % (button, x, y))
    registry.generateMouseEvent(x, y, 'b%sr' % button)
    doDelay()


def absoluteMotion(x, y, mouseDelay=None, check=True):
    """
    Synthesize mouse absolute motion to (x,y)
    """
    if check:
        checkCoordinates(x, y)
    logger.log("Mouse absolute motion to (%s,%s)" % (x, y))
    registry.generateMouseEvent(x, y, 'abs')
    if mouseDelay:
        doDelay(mouseDelay)
    else:
        doDelay()


def relativeMotion(x, y, mouseDelay=None):
    logger.log("Mouse relative motion of (%s,%s)" % (x, y))
    registry.generateMouseEvent(x, y, 'rel')
    if mouseDelay:
        doDelay(mouseDelay)
    else:
        doDelay()


def drag(fromXY, toXY, button=1, check=True):
    """
    Synthesize a mouse press, drag, and release on the screen.
    """
    logger.log("Mouse button %s drag from %s to %s" % (button, fromXY, toXY))

    (x, y) = fromXY
    press(x, y, button, check)
    # doDelay()

    (x, y) = toXY
    absoluteMotion(x, y, check=check)
    doDelay()

    release(x, y, button, check)
    doDelay()


def typeText(string):
    """
    Types the specified string, one character at a time.
    Please note, you may have to set a higher typing delay,
    if your machine misses/switches the characters typed.
    Needed sometimes on slow setups/VMs typing non-ASCII utf8 chars.
    """
    if not isinstance(string, unicode):
        string = string.decode('utf-8')
    for char in string:
        pressKey(char)

keyNameAliases = {
    'enter': 'Return',
    'esc': 'Escape',
    'alt': 'Alt_L',
    'control': 'Control_L',
    'ctrl': 'Control_L',
    'shift': 'Shift_L',
    'del': 'Delete',
    'ins': 'Insert',
    'pageup': 'Page_Up',
    'pagedown': 'Page_Down',
    ' ': 'space',
    '\t': 'Tab',
    '\n': 'Return'
}


# TODO: Dead code
def keySymToUniChar(keySym):  # pragma: no cover
    i = Gdk.keyval_to_unicode(keySym)
    if i:
        UniChar = unichr(i)
    else:
        UniChar = ''
    return UniChar


def uniCharToKeySym(uniChar):
    # OK, if it's not actually unicode we can fix that, right?
    if not isinstance(uniChar, unicode):
        uniChar = unicode(uniChar, 'utf-8')
    i = ord(uniChar)
    keySym = Gdk.unicode_to_keyval(i)
    return keySym


# dead code
def keySymToKeyName(keySym):  # pragma: no cover
    return Gdk.keyval_name(keySym)


def keyNameToKeySym(keyName):
    keyName = keyNameAliases.get(keyName.lower(), keyName)
    keySym = Gdk.keyval_from_name(keyName)
    # various error 'codes' returned for non-recognized chars in versions of GTK3.X
    if keySym == 0xffffff or keySym == 0x0 or keySym is None:
        try:
            keySym = uniCharToKeySym(keyName)
        except: # not even valid utf-8 char
            try: # Last attempt run at a keyName ('Meta_L', 'Dash' ...)
                keySym = getattr(Gdk, 'KEY_' + keyName)
            except AttributeError:
                raise KeyError(keyName)
    return keySym


def keyNameToKeyCode(keyName):
    """
    Use GDK to get the keycode for a given keystring.

    Note that the keycode returned by this function is often incorrect when
    the requested keystring is obtained by holding down the Shift key.

    Generally you should use uniCharToKeySym() and should only need this
    function for nonprintable keys anyway.
    """
    keymap = Gdk.Keymap.get_for_display(Gdk.Display.get_default())
    entries = keymap.get_entries_for_keyval(
        Gdk.keyval_from_name(keyName))
    try:
        return entries[1][0].keycode
    except TypeError:
        pass


def pressKey(keyName):
    """
    Presses (and releases) the key specified by keyName.
    keyName is the English name of the key as seen on the keyboard. Ex: 'enter'
    Names are looked up in Gdk.KEY_ If they are not found there, they are
    looked up by uniCharToKeySym().
    """
    keySym = keyNameToKeySym(keyName)
    registry.generateKeyboardEvent(keySym, None, KEY_SYM)
    doTypingDelay()


def keyCombo(comboString):
    """
    Generates the appropriate keyboard events to simulate a user pressing the
    specified key combination.

    comboString is the representation of the key combo to be generated.
    e.g. '<Control><Alt>p' or '<Control><Shift>PageUp' or '<Control>q'
    """
    strings = []
    for s in comboString.split('<'):
        if s:
            for S in s.split('>'):
                if S:
                    S = keyNameAliases.get(S.lower(), S)
                    strings.append(S)
    for s in strings:
        if not hasattr(Gdk, s):
            if not hasattr(Gdk, 'KEY_' + s):
                raise ValueError("Cannot find key %s" % s)
    modifiers = strings[:-1]
    finalKey = strings[-1]
    for modifier in modifiers:
        code = keyNameToKeyCode(modifier)
        registry.generateKeyboardEvent(code, None, KEY_PRESS)
    code = keyNameToKeyCode(finalKey)
    registry.generateKeyboardEvent(code, None, KEY_PRESSRELEASE)
    for modifier in modifiers:
        code = keyNameToKeyCode(modifier)
        registry.generateKeyboardEvent(code, None, KEY_RELEASE)
    doDelay()