<commit_before>'''
AT-SPI validation plugin.

@author: <NAME>
@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 = {}

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(object):
  '''
  Base class for all validators. Defines the public interface used by the 
  plug-in controller/view to generate validation reports.
  '''
  __metaclass__ = ValidatorManager
  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.
<commit_msg>validate plugin: Make use of metaclasses compatible on python 2.x & 3.x<commit_after>'''
AT-SPI validation plugin.

@author: <NAME>
@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.

{'fraction_non_alphanumeric': 0.09638386648122392, 'fraction_numerical': 0.0027816411682892906, 'mean_word_length': 2.9972206781545303, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2805657', 'n_tokens_mistral': 2146, 'n_tokens_neox': 2098, 'n_words': 716}