aboutsummaryrefslogtreecommitdiffstats
path: root/dogtail/procedural.py
blob: c87ae86181c33c82887e69ba6ead5e92a0b739d5 (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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
"""
Dogtail's procedural UI
All the classes here are intended to be single-instance, except for Action.
"""
__author__ = 'Zack Cerza <zcerza@redhat.com>'
#
#
# WARNING: Here There Be Dragons (TM)                                        #
#
# If you don't understand how to use this API, you almost certainly don't    #
# want to read the code first. We make use of some very non-intuitive        #
# features of Python in order to make the API very simplistic. Therefore,    #
# you should probably only read this code if you're already familiar with    #
# some of Python's advanced features. You have been warned. ;)               #
#
#

import tree
import predicate
from config import config
from utils import Lock
import rawinput

#FocusError = "FocusError: %s not found"


class FocusError(Exception):
    pass

import errors


def focusFailed(pred):
    errors.warn('The requested widget could not be focused: %s' %
                pred.debugName)

ENOARGS = "At least one argument is needed"


class FocusBase(object):

    """
    The base for every class in the module. Does nothing special, really.
    """
    node = None

    def __getattr__(self, name):
        # Fold all the Node's AT-SPI properties into the Focus object.
        try:
            return getattr(self.node, name)
        except AttributeError:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        # Fold all the Node's AT-SPI properties into the Focus object.
        if name == 'node':
            setattr(self.__class__, name, value)
        else:
            try:
                setattr(self.node, name, value)
            except AttributeError:
                raise AttributeError(name)


class FocusApplication (FocusBase):

    """
    Keeps track of which application is currently focused.
    """
    desktop = tree.root

    def __call__(self, name):
        """
        Search for an application that matches and refocus on the given name.
        """
        try:
            pred = predicate.IsAnApplicationNamed(name)
            app = self.desktop.findChild(
                pred, recursive=False, retry=False)
        except tree.SearchError:
            if config.fatalErrors:
                raise FocusError(name)
            else:
                focusFailed(pred)
                return False
        if app:
            FocusApplication.node = app
            FocusDialog.node = None
            FocusWindow.node = None
            FocusWidget.node = None
        return True


class FocusDesktop (FocusBase):

    """
    This isn't used yet, and may never be used.
    """
    pass


class FocusWindow (FocusBase):

    """
    Keeps track of which window is currently focused.
    """

    def __call__(self, name):
        """
        Search for a dialog that matches the given name and refocus on it.
        """
        result = None
        pred = predicate.IsAWindowNamed(name)
        try:
            result = FocusApplication.node.findChild(
                pred, requireResult=False, recursive=False)
        except AttributeError:
            pass
        if result:
            FocusWindow.node = result
            FocusDialog.node = None
            FocusWidget.node = None
        else:
            if config.fatalErrors:
                raise FocusError(pred.debugName)
            else:
                focusFailed(pred)
                return False
        return True


class FocusDialog (FocusBase):

    """
    Keeps track of which dialog is currently focused.
    """

    def __call__(self, name):
        """
        Search for a dialog that matches the given name and refocus on it.
        """
        result = None
        pred = predicate.IsADialogNamed(name)
        try:
            result = FocusApplication.node.findChild(
                pred, requireResult=False, recursive=False)
        except AttributeError:
            pass
        if result:
            FocusDialog.node = result
            FocusWidget.node = None
        else:
            if config.fatalErrors:
                raise FocusError(pred.debugName)
            else:
                focusFailed(pred)
                return False
        return True


class FocusWidget (FocusBase):

    """
    Keeps track of which widget is currently focused.
    """

    def findByPredicate(self, pred):
        result = None
        try:
            result = FocusWidget.node.findChild(
                pred, requireResult=False, retry=False)
        except AttributeError:
            pass
        if result:
            FocusWidget.node = result
        else:
            try:
                result = FocusDialog.node.findChild(
                    pred, requireResult=False, retry=False)
            except AttributeError:
                pass
        if result:
            FocusWidget.node = result
        else:
            try:
                result = FocusWindow.node.findChild(
                    pred, requireResult=False, retry=False)
            except AttributeError:
                pass
        if result:
            FocusWidget.node = result
        else:
            try:
                result = FocusApplication.node.findChild(
                    pred, requireResult=False, retry=False)
                if result:
                    FocusWidget.node = result
            except AttributeError:
                if config.fatalErrors:
                    raise FocusError(pred)
                else:
                    focusFailed(pred)
                    return False

        if result is None:
            FocusWidget.node = result
            if config.fatalErrors:
                raise FocusError(pred.debugName)
            else:
                focusFailed(pred)
                return False
        return True

    def __call__(self, name='', roleName='', description=''):
        """
        If name, roleName or description are specified, search for a widget that matches and refocus on it.
        """
        if not name and not roleName and not description:
            raise TypeError(ENOARGS)

        # search for a widget.
        pred = predicate.GenericPredicate(name=name,
                                          roleName=roleName, description=description)
        return self.findByPredicate(pred)


class Focus (FocusBase):

    """
    The container class for the focused application, dialog and widget.
    """

    def __getattr__(self, name):
        raise AttributeError(name)

    def __setattr__(self, name, value):
        if name in ('application', 'dialog', 'widget', 'window'):
            self.__dict__[name] = value
        else:
            raise AttributeError(name)

    desktop = tree.root
    application = FocusApplication()
    app = application  # shortcut :)
    dialog = FocusDialog()
    window = FocusWindow()
    frame = window
    widget = FocusWidget()

    def button(self, name):
        """
        A shortcut to self.widget.findByPredicate(predicate.IsAButtonNamed(name))
        """
        return self.widget.findByPredicate(predicate.IsAButtonNamed(name))

    def icon(self, name):
        """
        A shortcut to self.widget(name, roleName = 'icon')
        """
        return self.widget(name=name, roleName='icon')

    def menu(self, name):
        """
        A shortcut to self.widget.findByPredicate(predicate.IsAMenuNamed(name))
        """
        return self.widget.findByPredicate(predicate.IsAMenuNamed(name))

    def menuItem(self, name):
        """
        A shortcut to self.widget.findByPredicate(predicate.IsAMenuItemNamed(name))
        """
        return self.widget.findByPredicate(predicate.IsAMenuItemNamed(name))

    def table(self, name=''):
        """
        A shortcut to self.widget(name, roleName 'table')
        """
        return self.widget(name=name, roleName='table')

    def tableCell(self, name=''):
        """
        A shortcut to self.widget(name, roleName 'table cell')
        """
        return self.widget(name=name, roleName='table cell')

    def text(self, name=''):
        """
        A shortcut to self.widget.findByPredicate(IsATextEntryNamed(name))
        """
        return self.widget.findByPredicate(predicate.IsATextEntryNamed(name))


class Action (FocusWidget):

    """
    Aids in executing AT-SPI actions, refocusing the widget if necessary.
    """

    def __init__(self, action):
        """
        action is a string with the same name as the AT-SPI action you wish to execute using this class.
        """
        self.action = action

    def __call__(self, name='', roleName='', description='', delay=config.actionDelay):
        """
        If name, roleName or description are specified, first search for a widget that matches and refocus on it.
        Then execute the action.
        """
        if name or roleName or description:
            FocusWidget.__call__(
                self, name=name, roleName=roleName, description=description)
        self.node.doActionNamed(self.action)

    def __getattr__(self, attr):
        return getattr(FocusWidget.node, attr)

    def __setattr__(self, attr, value):
        if attr == 'action':
            self.__dict__[attr] = value
        else:
            setattr(FocusWidget, attr, value)

    def button(self, name):
        """
        A shortcut to self(name, roleName = 'push button')
        """
        self.__call__(name=name, roleName='push button')

    def menu(self, name):
        """
        A shortcut to self(name, roleName = 'menu')
        """
        self.__call__(name=name, roleName='menu')

    def menuItem(self, name):
        """
        A shortcut to self(name, roleName = 'menu item')
        """
        self.__call__(name=name, roleName='menu item')

    def table(self, name=''):
        """
        A shortcut to self(name, roleName 'table')
        """
        self.__call__(name=name, roleName='table')

    def tableCell(self, name=''):
        """
        A shortcut to self(name, roleName 'table cell')
        """
        self.__call__(name=name, roleName='table cell')

    def text(self, name=''):
        """
        A shortcut to self(name, roleName = 'text')
        """
        self.__call__(name=name, roleName='text')


class Click (Action):

    """
    A special case of Action, Click will eventually handle raw mouse events.
    """
    primary = 1
    middle = 2
    secondary = 3

    def __init__(self):
        Action.__init__(self, 'click')

    def __call__(self, name='', roleName='', description='', raw=True, button=primary, delay=config.actionDelay):
        """
        By default, execute a raw mouse event.
        If raw is False or if button evaluates to False, just pass the rest of
        the arguments to Action.
        """
        if name or roleName or description:
            FocusWidget.__call__(
                self, name=name, roleName=roleName, description=description)
        if raw and button:
            # We're doing a raw mouse click
            Click.node.click(button)
        else:
            Action.__call__(
                self, name=name, roleName=roleName, description=description, delay=delay)


class Select (Action):

    """
    Aids in selecting and deselecting widgets, i.e. page tabs
    """
    select = 'select'
    deselect = 'deselect'

    def __init__(self, action):
        """
        action must be 'select' or 'deselect'.
        """
        if action not in (self.select, self.deselect):
            raise ValueError(action)
        Action.__init__(self, action)

    def __call__(self, name='', roleName='', description='', delay=config.actionDelay):
        """
        If name, roleName or description are specified, first search for a widget that matches and refocus on it.
        Then execute the action.
        """
        if name or roleName or description:
            FocusWidget.__call__(
                self, name=name, roleName=roleName, description=description)
        func = getattr(self.node, self.action)
        func()


def type(text):
    if focus.widget.node:
        focus.widget.node.typeText(text)
    else:
        rawinput.typeText(text)


def keyCombo(combo):
    if focus.widget.node:
        focus.widget.node.keyCombo(combo)
    else:
        rawinput.keyCombo(combo)


def run(application, arguments='', appName=''):
    from utils import run as utilsRun
    pid = utilsRun(application + ' ' + arguments, appName=appName)
    focus.application(application)
    return pid

import os
# tell sniff not to use auto-refresh while script using this module is running
# may have already been locked by dogtail.tree
if not os.path.exists('/tmp/sniff_refresh.lock'):  # pragma: no cover
    sniff_lock = Lock(lockname='sniff_refresh.lock', randomize=False)
    try:
        sniff_lock.lock()
    except OSError:
        pass  # lock was already present from other script instance or leftover from killed instance
    # lock should unlock automatically on script exit.

focus = Focus()
click = Click()
activate = Action('activate')
openItem = Action('open')
menu = Action('menu')
select = Select(Select.select)
deselect = Select(Select.deselect)