File: validate.py

package info (click to toggle)
accerciser 3.22.0-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,392 kB
  • sloc: python: 8,322; sh: 839; makefile: 245
file content (607 lines) | stat: -rw-r--r-- 18,861 bytes parent folder | download | duplicates (3)
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
'''
AT-SPI validation plugin.

@author: Peter Parente
@organization: IBM Corporation
@copyright: Copyright (c) 2007 IBM Corporation
@license: BSD

All rights reserved. This program and the accompanying materials are made 
available under the terms of the BSD which accompanies this distribution, and 
is available at U{http://www.opensource.org/licenses/bsd-license.php}
'''
import gi

from gi.repository import Gtk as gtk
from gi.repository import GObject
from gi.repository import GLib

import os
import traceback
import sys
import glob
import imp
import webbrowser
from accerciser.plugin import ViewportPlugin
from accerciser.i18n import _, N_, DOMAIN
import pyatspi

UI_FILE = os.path.join(os.path.dirname(__file__), 'validate.ui')
USER_SCHEMA_PATH = os.path.join(GLib.get_user_data_dir(), 'accerciser',
                                'plugindata', 'validate')
SYS_SCHEMA_PATH = os.path.join(sys.prefix, 'share', 'accerciser', 
                               'plugindata', 'validate')
VALIDATORS = {}
SCHEMA_METADATA = {}

# method to make use of metaclasses on both python 2.x and 3.x
#
def with_metaclass(meta, *bases):
    class metaclass(meta):
        __call__ = type.__call__
        __init__ = type.__init__
        def __new__(cls, name, this_bases, d):
            if this_bases is None:
                return type.__new__(cls, name, (), d)
            return meta(name, bases, d)
    return metaclass('temporary_class', None, {})

class ValidatorManager(type):
  '''
  Metaclass that tracks all validator subclasses imported by the plug-in.
  Used to update a list of validator schemas at runtime.
  '''
  def __init__(cls, name, bases, dct):
    '''
    Build the class as usual, but keep track of its name and one instance.
    '''
    super(ValidatorManager, cls).__init__(name, bases, dct)
    if name != 'Validator':
      # don't count the base class
      names = cls.__module__.split('.')
      VALIDATORS.setdefault(names[-1], []).append(cls())

  @staticmethod
  def loadSchemas():
    '''
    Loads all schema files from well known locations.
    '''
    for path in [USER_SCHEMA_PATH, SYS_SCHEMA_PATH]:
      for fn in glob.glob(os.path.join(path, '*.py')):
        module = os.path.basename(fn)[:-3]
        params = imp.find_module(module, [path])
        schema = imp.load_module(module, *params)
        try:
          # try to get descriptive fields from the module
          SCHEMA_METADATA[module] = schema.__metadata__
        except AttributeError:
          # default to usinf file name as description
          SCHEMA_METADATA[module] = {'name' : module,
                                        'description' : _('No description')}
      
  @staticmethod
  def getValidators(name):
    '''
    Gets all validator classes within a schema.
    
    @param name: Name of a schema
    @return: List of Validator objects
    @raise KeyError: When the schema is not known
    '''
    return VALIDATORS[name]

  @staticmethod
  def listSchemas():
    '''
    Gets a list of all available schema names.

    @return: List of string names
    '''
    return list(VALIDATORS.keys())

  @staticmethod
  def getSchemaMetadata(name):
    '''
    Gets information about a schema.

    @param name: Name of the schema
    @return: Dictionary of 'name', 'description', etc.
    '''
    return SCHEMA_METADATA[name]

class Validator(with_metaclass(ValidatorManager, object)):
  '''
  Base class for all validators. Defines the public interface used by the 
  plug-in controller/view to generate validation reports.
  '''
  def __init__(self):
    pass
  
  def condition(self, acc):
    '''
    Checks if this validator is fit to test the given accessible. For instance,
    a test for table properties is not applicable to buttons.

    @param acc: Accessible to test
    @return: True to validate, False to avoid testing
    @raise Exception: Same as returning False
    '''
    return True
  
  def before(self, acc, state, view):
    '''
    Tests the accessible before testing its descendants.

    @param acc: Accessible to test
    @param state: Dictionary containing arbitrary state that will be passed
      among validators and be made available in both before and after passes
    @param view: View object to use to log test results
    '''
    pass
  
  def after(self, acc, state, view):
    '''
    Tests the accessible after testing its descendants.

    @param acc: Accessible to test
    @param state: Dictionary containing arbitrary state that will be passed
      among validators and be made available in both before and after passes
    @param view: View object to use to log test results
    '''
    pass

class ValidatorViewport(ViewportPlugin):
  '''
  Validator UI. Key feature is a table showing the results of a validation
  run on some accessible and its descendants.

  @ivar main_xml: gtk builder parsed XML definition
  @ivar report: Report table
  @ivar progress: Activity bar
  @ivar validate: Validation button
  @ivar save: Save report button
  @ivar schema: Schema combobox
  @ivar vals: All validators for the selected schema
  @ivar walk: Generator for the current validation walk through the hierarchy
  '''
  plugin_name = N_('AT-SPI Validator')
  plugin_name_localized = _(plugin_name)
  plugin_description = N_('Validates application accessibility')

  # keep track of when a file is being written
  write_in_progress = False

  def init(self):
    '''
    Loads the glade UI definition and initializes it.
    '''
    # load all schemas
    ValidatorManager.loadSchemas()

    # validators and walk generator
    self.vals = None
    self.walk = None
    # help url for last selected
    self.url = None

    self.main_xml = gtk.Builder()
    self.main_xml.set_translation_domain(DOMAIN)
    self.main_xml.add_from_file(UI_FILE)
    frame = self.main_xml.get_object('main vbox')
    self.plugin_area.add(frame)
    self.report = self.main_xml.get_object('report table')
    self.progress = self.main_xml.get_object('progress bar')
    self.validate = self.main_xml.get_object('validate button')
    self.help = self.main_xml.get_object('help button')
    self.save = self.main_xml.get_object('save button')
    self.clear = self.main_xml.get_object('clear button')
    self.schema = self.main_xml.get_object('schema combo')
    self.validator_buffer = gtk.TextBuffer()

    # model for the combobox
    model = gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING)
    self.schema.set_model(model)

    # append all schema names/descriptions
    vm = ValidatorManager
    for name in vm.listSchemas():
      d = vm.getSchemaMetadata(name)
      model.append(['%s - %s' % (d['name'], d['description']), name])
    self.schema.set_active(0)
    
    # model for the report
    model = gtk.ListStore(str, str, object, str)
    self.report.set_model(model)

    # schema cell renderer
    cell = gtk.CellRendererText()
    self.schema.pack_start(cell, True)
    self.schema.add_attribute(cell, 'text', 0)
    
    # log level column
    col = gtk.TreeViewColumn(_('Level'))
    rend = gtk.CellRendererText()
    col.pack_start(rend, True)
    col.add_attribute(rend, 'text', 0)
    self.report.append_column(col)
    # description column
    rend = gtk.CellRendererText()
    col = gtk.TreeViewColumn(_('Description'), rend, text=1)
    self.report.append_column(col)

    # set progress bar to zero initially
    self.progress.set_fraction(0.0)
        
    self.main_xml.connect_signals(self)
    self.show_all()
    
  def onAccChanged(self, acc):
    '''
    Stops validation if the accessible hierarchy changes.

    @param acc: The accessible that changed
    '''
    if self.walk is not None:
      self._stopValidate()
    
  def _onValidate(self, widget):
    '''
    Starts or stops a validation run.

    @param widget: The validate button
    '''
    if widget.get_active():
      self._startValidate()
    else:
      self._stopValidate()

  def _writeFile(self):
    '''
    Save the report from the report model to disk in a temporary location.
    Close the file when finished.
    '''
    if self.write_in_progress:
      # if we have finished writing to the file
      if self.curr_file_row == self.n_report_rows:
        self.save_to.close()
        self._stopSave()
        return False
    else:
      # set up the file to be written
      self._startSave()
      self.save.set_sensitive(False)
      report_store = self.report.get_model()
      # create list of lists containing column values
      self.row_values = [[row[0], row[1], row[2], row[3]] for row in report_store]
      self.n_report_rows = len(self.row_values)
      return True

    remaining_rows = self.n_report_rows - self.curr_file_row
    n_rows_to_write = 5
    if n_rows_to_write > remaining_rows:
      n_rows_to_write = remaining_rows
  
    file_str_list = [] # list to store strings to be written to file
    start = self.curr_file_row
    end = (self.curr_file_row + n_rows_to_write)
    for i in range(start, end):
      val = self.row_values[i]
      # add level to buffer
      file_str_list.append("%s: %s\n" % (_('Level'), val[0]))
      # add description to buffer
      file_str_list.append("%s: %s\n" % (_('Description'), val[1]))
      # add accessible's name to buffer
      file_str_list.append("%s: %s\n" % (_('Name'), val[2].name))
      # add accessible's role to buffer
      file_str_list.append("%s: %s\n" % (_('Role'), val[2].getRoleName()))
      # add url role to buffer
      file_str_list.append("%s: %s\n\n" % (_('Hyperlink'), val[3]))
      self.curr_file_row += 1
  
    self.save_to.write(''.join(file_str_list))

    return True

  def _onSave(self, button):
    '''
    Save the report from the report model to disk

    @param button: Save button
    '''
    save_dialog = gtk.FileChooserDialog(
      'Save validator output',
      action=gtk.FileChooserAction.SAVE,
      buttons=(gtk.STOCK_CANCEL, gtk.ResponseType.CANCEL,
               gtk.STOCK_OK, gtk.ResponseType.OK))
    #save_dialog.connect("response", self._savedDiagResponse)
    save_dialog.set_do_overwrite_confirmation(True)
    save_dialog.set_default_response(gtk.ResponseType.OK)
    response = save_dialog.run()
    if response == gtk.ResponseType.OK:
      self.save_to = open(save_dialog.get_filename(), 'w')
      GLib.idle_add(self._writeFile)
    save_dialog.destroy()

  def _onClear(self, button):
    '''
    Clear the report from the report model

    @param button: Clear button
    '''
    self.report.get_model().clear()
    self.validator_buffer.set_text('')
    self.save.set_sensitive(False)
    self.clear.set_sensitive(False)

  def _onHelp(self, button):
    '''
    Open a help URL in the system web browser.

    @param button: Help button
    '''
    webbrowser.open(self.url)

  def _onSaveIdle(self):
    '''
    Move the progress bar
    '''
    self.progress.pulse()
    return True

  def _startSave(self):
    '''
    Starts a save by settting up an idle callback after initializing progress
    bar.
    '''
    # set variables for writing report to file
    self.write_in_progress = True
    self._setDefaultSaveVars()
    # register an idle callback
    self.idle_save_id = GLib.idle_add(self._onSaveIdle)
    self.progress.set_text(_('Saving'))
    # disable controls
    self.validate.set_sensitive(False)
    self.save.set_sensitive(False)

  def _stopSave(self):
    '''
    Stops a save by disabling the idle callback and restoring the various UI
    components to their enabled states.
    '''
    # stop callbacks
    GLib.source_remove(self.idle_save_id)
    # reset progress
    self.progress.set_fraction(0.0)
    self.progress.set_text(_('Idle'))
    # enable other controls
    self.validate.set_sensitive(True)
    self.save.set_sensitive(True)
    self.save.set_sensitive(True)
    # reset variables for writing report to file
    self._setDefaultSaveVars()
    self.write_in_progress = False

  def _setDefaultSaveVars(self):
    '''
    Ready appropriate variables for a save
    '''
    self.curr_file_row = 0
    self.n_report_rows = 0 
    self.row_values = [] 

  def _startValidate(self):
    '''
    Starts a validation by settting up an idle callback after initializing the
    report table and progress bar. Gets all validators for the selected schema.
    '''
    # clear the report
    self.report.get_model().clear()
    # get the validators
    index = self.schema.get_active()
    row = self.schema.get_model()[index]
    self.vals = ValidatorManager.getValidators(row[1])
    # build a new state dict
    state = {}
    # build our walk generator
    self.walk = self._traverse(self.acc, state)
    # register an idle callback
    self.idle_validate_id = GLib.idle_add(self._onValidateIdle)
    self.progress.set_text(_('Validating'))
    # disable controls
    self.schema.set_sensitive(False)
    self.help.set_sensitive(False)
    self.save.set_sensitive(False)
    self.clear.set_sensitive(False)

  def _stopValidate(self):
    '''
    Stops a validation run by disabling the idle callback and restoring the
    various UI components to their enabled states.
    '''
    # stop callbacks
    GLib.source_remove(self.idle_validate_id)
    # destroy generator
    self.walk = None
    # reset progress
    self.progress.set_fraction(0.0)
    self.progress.set_text(_('Idle'))
    # depress validate
    self.validate.set_active(False)
    # enable other controls
    self.schema.set_sensitive(True)
    self.help.set_sensitive(True)
    self.save.set_sensitive(True)
    self.clear.set_sensitive(True)
     
  def _onValidateIdle(self):
    '''
    Tests one accessible at a time on each idle callback by advancing the
    walk generator.
    '''
    try:
      # generate the next accessible to validate
      next(self.walk)
    except StopIteration:
      # nothing left to validate, so stop
      self._stopValidate()
      return False
    # pule the progress bar
    self.progress.pulse()
    # yes, we want more callbacks
    return True

  def _traverse(self, acc, state):
    '''
    Generates accessibles in a two-pass traversal of the subtree rooted at
    the accessible selected at the time the validation starts. Accessibles are
    tested first before their descendants (before pass) and then after all of
    their descendants (after pass).

    @param acc: Accessible root of some subtree in the walk
    @param state: State object used by validators to share information
    '''
    # start the walk generator
    gen_child = self._genAccessible(acc, state)
    while 1:
      try:
        # get one child
        child = next(gen_child)
      except StopIteration as e:
        break
      # recurse
      gen_traverse = self._traverse(child, state)
      while 1:
        # yield before continuing processing 
        yield None
        try:
          # get one descendant
          next(gen_traverse)
        except StopIteration:
          break
    
  def _genAccessible(self, acc, state):
    '''
    Tests the given accessible in the before pass if its test condition is
    satisfied. Then generates all of its children. Finally, tests the original
    accessible in the after pass if its test condition is satisfied.

    @param acc: Accessible to test
    @param state: State object used by validators to share information
    '''
    # run before() methods on all validators
    self._runValidators(acc, state, True)
    # generate all children, but only if acc doesn't manage descendants
    if not acc.getState().contains(pyatspi.constants.STATE_MANAGES_DESCENDANTS):
      for i in range(acc.childCount):
        child = acc.getChildAtIndex(i)
        yield child
    # run after methods on all validators
    self._runValidators(acc, state, False)

  def _runValidators(self, acc, state, before):
    '''
    Runs all validators on a single accessible. If the validator condition is
    true, either executes the before() or after() method on the validator
    depending on the param 'before' passed to this method.

    @param acc: Accessible to test
    @param state: State object used by validators to share information
    @param before: True to execute before method, false to execute after
    '''
    for val in self.vals:
      try:
        ok = val.condition(acc)
      except Exception:
        pass
      else:
        if ok:
          try:
            if before:
              val.before(acc, state, self)
            else:
              val.after(acc, state, self)
          except Exception as e:
            self._exceptionError(acc, e)

  def _onCursorChanged(self, report):
    '''
    Enables or disables the help button based on whether an item has help or
    not.

    @param report: Report table
    '''
    selection = report.get_selection()
    model, iter = selection.get_selected()
    if iter:
      url = model[iter][3]
      self.help.set_sensitive(len(url))
      self.url = url

  def _onActivateRow(self, report, iter, col):
    '''
    Updates the Accerciser tree to show an accessible when a report entry is
    selected.

    @param report: Report table
    @param iter: Tree table iterator
    @param col: Tree table column
    '''
    selection = report.get_selection()
    model, iter = selection.get_selected()
    if iter:
      acc = model[iter][2]
      if acc:
        self.node.update(acc)
                             
  def _exceptionError(self, acc, ex):
    '''
    Logs an unexpected exception that occurred during execution of a validator.
    
    @param acc: Accessible under test when the exception occurred
    @param ex: The exception
    '''
    info = traceback.extract_tb(sys.exc_info()[2])
    text = '%s (%d): %s' % (os.path.basename(info[-1][0]), info[-1][1], ex)
    self.report.get_model().append([_('EXCEPT'), text, acc, ''])

  def error(self, text, acc, url=''):
    '''
    Used by validators to log messages for accessibility problems that have to
    be fixed.
    '''
    level = _('ERROR')
    self.report.get_model().append([level, text, acc, url])
    
  def warn(self, text, acc, url=''):
    '''
    Used by validators to log warning messages for accessibility problems that
    should be fixed, but are not critical.
    '''
    level = _('WARN')
    self.report.get_model().append([level, text, acc, url])
  
  def info(self, text, acc, url=''):
    '''
    Used by validators to log informational messages.
    '''
    level = _('INFO')
    self.report.get_model().append([level, text, acc, url])
    
  def debug(self, text, acc, url=''):
    '''
    Used by validators to log debug messages.
    '''
    level = _('DEBUG')
    self.report.get_model().append([level, text, acc, url])

  def close(self):
    '''
    Things to do before the plugin closes.
    '''
    # don't close the plugin until we have finished writing
    while True:
      if not self.write_in_progress:
        break
      gtk.main_iteration_do(True)