aboutsummaryrefslogtreecommitdiffstats
path: root/build/lib/dogtail/config.py
blob: 82e197cf523550a008fe6a9f4d16edd27106ab13 (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
"""
The configuration module.
"""
__author__ = "Zack Cerza <zcerza@redhat.com>, David Malcolm <dmalcolm@redhat.com>"

import os
import sys
import locale


def _userTmpDir(baseName):
    # i.e. /tmp/dogtail-foo
    return '-'.join(('/'.join(('/tmp', baseName)), os.environ['USER']))


class _Config(object):

    """
    Contains configuration parameters for the dogtail run.

    scratchDir(str):
    Directory where things like screenshots are stored.

    dataDir(str):
    Directory where related data files are located.

    logDir(str):
    Directory where dogtail.tc.TC*-generated logs are stored.

    scriptName(str) [Read-Only]:
    The name of the script being run.

    encoding(str)
    The encoding for text, used by dogtail.tc.TCString .

    actionDelay(float):
    The delay after an action is executed.

    typingDelay(float):
    The delay after a character is typed on the keyboard.

    runInterval(float):
    The interval at which dogtail.utils.run() and dogtail.procedural.run()
    check to see if the application has started up.

    runTimeout(int):
    The timeout after which dogtail.utils.run() and dogtail.procedural.run()
    give up on looking for the newly-started application.

    searchBackoffDuration (float):
    Time in seconds for which to delay when a search fails.

    searchWarningThreshold (int):
    Number of retries before logging the individual attempts at a search.

    searchCutoffCount (int):
    Number of times to retry when a search fails.

    defaultDelay (float):
    Default time in seconds to sleep when delaying.

    childrenLimit (int):
    When there are a very large number of children of a node, only return
    this many, starting with the first.

    debugSearching (boolean):
    Whether to write info on search backoff and retry to the debug log.

    debugSleep (boolean):
    Whether to log whenever we sleep to the debug log.

    debugSearchPaths (boolean):
    Whether we should write out debug info when running the SearchPath
    routines.

    absoluteNodePaths (boolean):
    Whether we should identify nodes in the logs with long 'abcolute paths', or
    merely with a short 'relative path'. FIXME: give examples

    ensureSensitivity (boolean):
    Should we check that ui nodes are sensitive (not 'greyed out') before
    performing actions on them? If this is True (the default) it will raise
    an exception if this happens. Can set to False as a workaround for apps
    and toolkits that don't report sensitivity properly.

    debugTranslation (boolean):
    Whether we should write out debug information from the translation/i18n
    subsystem.

    blinkOnActions (boolean):
    Whether we should blink a rectangle around a Node when an action is
    performed on it.

    fatalErrors (boolean):
    Whether errors encountered in dogtail.procedural should be considered
    fatal. If True, exceptions will be raised. If False, warnings will be
    passed to the debug logger.

    checkForA11y (boolean):
    Whether to check if accessibility is enabled. If not, just assume it is
    (default True).

    logDebugToFile (boolean):
    Whether to write debug output to a log file.

    logDebugToStdOut (boolean):
    Whether to print log output to console or not (default True).
    """
    @property
    def scriptName(self):
        return os.path.basename(sys.argv[0]).replace('.py', '')

    @property
    def encoding(self):
        return locale.getpreferredencoding().lower()

    defaults = {
        # Storage
        'scratchDir': '/'.join((_userTmpDir('dogtail'), '')),
        'dataDir': '/'.join((_userTmpDir('dogtail'), 'data', '')),
        'logDir': '/'.join((_userTmpDir('dogtail'), 'logs', '')),
        'scriptName': scriptName.fget(None),
        'encoding': encoding.fget(None),
        'configFile': None,
        'baseFile': None,

        # Timing and Limits
        'actionDelay': 1.0,
        'typingDelay': 0.1,
        'runInterval': 0.5,
        'runTimeout': 30,
        'searchBackoffDuration': 0.5,
        'searchWarningThreshold': 3,
        'searchCutoffCount': 20,
        'defaultDelay': 0.5,
        'childrenLimit': 100,

        # Debug
        'debugSearching': False,
        'debugSleep': False,
        'debugSearchPaths': False,
        'logDebugToStdOut': True,
        'absoluteNodePaths': False,
        'ensureSensitivity': False,
        'debugTranslation': False,
        'blinkOnActions': False,
        'fatalErrors': False,
        'checkForA11y': True,

        # Logging
        'logDebugToFile': True
    }

    options = {}

    invalidValue = "__INVALID__"

    def __init__(self):
        _Config.__createDir(_Config.defaults['scratchDir'])
        _Config.__createDir(_Config.defaults['logDir'])
        _Config.__createDir(_Config.defaults['dataDir'])

    def __setattr__(self, name, value):
        if name not in config.defaults:
            raise AttributeError(name + " is not a valid option.")

        elif _Config.defaults[name] != value or \
                _Config.options.get(name, _Config.invalidValue) != value:
            if 'Dir' in name:
                _Config.__createDir(value)
                if value[-1] != os.path.sep:
                    value = value + os.path.sep
            elif name == 'logDebugToFile':
                import logging
                logging.debugLogger = logging.Logger('debug', value)
            _Config.options[name] = value

    def __getattr__(self, name):
        try:
            return _Config.options[name]
        except KeyError:
            try:
                return _Config.defaults[name]
            except KeyError:
                raise AttributeError("%s is not a valid option." % name)

    def __createDir(cls, dirName, perms=0o777):
        """
        Creates a directory (if it doesn't currently exist), creating any
        parent directories it needs.

        If perms is None, create with python's default permissions.
        """
        dirName = os.path.abspath(dirName)
        # print "Checking for %s ..." % dirName,
        if not os.path.isdir(dirName):
            if perms:
                umask = os.umask(0)
                os.makedirs(dirName, perms)
                os.umask(umask)
            else:
                # This is probably a dead code - no other functions call this without the permissions set
                os.makedirs(dirName)  # pragma: no cover
    __createDir = classmethod(__createDir)

    def load(self, dict):
        """
        Loads values from dict, preserving any options already set that are not overridden.
        """
        _Config.options.update(dict)

    def reset(self):
        """
        Resets all settings to their defaults.
        """
        _Config.options = {}


config = _Config()