[accerciser] Python 3 migration



commit b9bb2f48eebbf9f21ca633b6ecd6a58d6befe04a
Author: Joanmarie Diggs <jdiggs igalia com>
Date:   Sun Dec 9 03:50:14 2012 +0100

    Python 3 migration
    
    GNOME Goal: Python 3 Porting
    see: https://live.gnome.org/GnomeGoals/Python3Porting
         https://bugzilla.gnome.org/show_bug.cgi?id=678512

 configure.ac                                |    4 ++--
 macaroon/macaroon/record/script_factory.py  |    6 +++---
 plugindata/validate/basic.py                |   14 +++++++-------
 plugins/event_monitor.py                    |    4 ++--
 plugins/interface_view.py                   |   20 ++++++++++----------
 plugins/ipython_view.py                     |   17 +++++++++--------
 plugins/quick_select.py                     |    4 ++--
 plugins/validate.py                         |   16 ++++++++--------
 pyreqs.py                                   |   15 +++++++--------
 src/accerciser.in                           |    6 +++---
 src/lib/accerciser/__init__.py              |   12 ++++++------
 src/lib/accerciser/about_dialog.py          |    2 +-
 src/lib/accerciser/accerciser.py            |   26 +++++++++++++-------------
 src/lib/accerciser/accessible_treeview.py   |   20 ++++++++++----------
 src/lib/accerciser/bookmarks.py             |   15 +++++++--------
 src/lib/accerciser/hotkey_manager.py        |   10 +++++-----
 src/lib/accerciser/i18n.py.in               |    2 +-
 src/lib/accerciser/icons.py                 |    2 +-
 src/lib/accerciser/main_window.py           |   14 +++++++-------
 src/lib/accerciser/node.py                  |    4 ++--
 src/lib/accerciser/plugin/__init__.py       |    6 +++---
 src/lib/accerciser/plugin/base_plugin.py    |    6 +++---
 src/lib/accerciser/plugin/plugin_manager.py |   12 ++++++------
 src/lib/accerciser/plugin/view.py           |   25 ++++++++++++-------------
 src/lib/accerciser/prefs_dialog.py          |   12 ++++++------
 src/lib/accerciser/tools.py                 |   17 ++++++++---------
 src/lib/accerciser/ui_manager.py            |    2 +-
 27 files changed, 145 insertions(+), 148 deletions(-)
---
diff --git a/configure.ac b/configure.ac
index a1aa621..5140400 100644
--- a/configure.ac
+++ b/configure.ac
@@ -6,12 +6,12 @@ AM_MAINTAINER_MODE([enable])
 YELP_HELP_INIT
 
 dnl == check for python ==
-AM_PATH_PYTHON(2.7)
+AM_PATH_PYTHON(3.2)
 
 dnl == requeriments ==
 GTK_REQUIRED=3.1.13
 PYGOBJECT_REQUIRED=2.90.3
-ATSPI_REQUIRED=2.1.5
+ATSPI_REQUIRED=2.5.2
 GLIB_GSETTINGS
 
 dnl == check for requeriments ==
diff --git a/macaroon/macaroon/record/script_factory.py b/macaroon/macaroon/record/script_factory.py
index 58cc751..2877047 100644
--- a/macaroon/macaroon/record/script_factory.py
+++ b/macaroon/macaroon/record/script_factory.py
@@ -141,7 +141,7 @@ class Level2SequenceFactory(SequenceFactory):
       self._prependContext()
     if event.modifiers in (0, Gdk.ModifierType.SHIFT_MASK) and \
           Gdk.keyval_to_unicode(event.id):
-      self.typed_text += unichr(Gdk.keyval_to_unicode(event.id))
+      self.typed_text += chr(Gdk.keyval_to_unicode(event.id))
     else:
       if self.frame_name:
         if isinstance(event, pyatspi.deviceevent.DeviceEvent):
@@ -270,7 +270,7 @@ class DogtailFactory(ScriptFactory):
       return
     if event.modifiers in (0, Gdk.ModifierType.SHIFT_MASK) and \
           Gdk.keyval_to_unicode(event.id):
-      self.typed_text += unichr(Gdk.keyval_to_unicode(event.id))
+      self.typed_text += chr(Gdk.keyval_to_unicode(event.id))
     else:
       if self.app_name:
         self.commands_queue.put_nowait('focus.application("%s")\n' % \
@@ -323,7 +323,7 @@ class LDTPFactory(DogtailFactory):
       return
     if event.modifiers in (0, Gdk.ModifierType.SHIFT_MASK) and \
           Gdk.keyval_to_unicode(event.id):
-      self.typed_text += unichr(Gdk.keyval_to_unicode(event.id))
+      self.typed_text += chr(Gdk.keyval_to_unicode(event.id))
     else:
       if self.frame_name:
         self.commands_queue.put_nowait('waittillguiexist("%s")\n' % \
diff --git a/plugindata/validate/basic.py b/plugindata/validate/basic.py
index a3e9c6b..161a7a9 100644
--- a/plugindata/validate/basic.py
+++ b/plugindata/validate/basic.py
@@ -55,7 +55,7 @@ class OneFocus(Validator):
   def before(self, acc, state, view):
     s = acc.getState()
     if s.contains(STATE_FOCUSED):
-      if not state.has_key('focus'):
+      if 'focus' not in state:
         state['focus'] = acc
       else:
         view.error(_('more than one focused widget'), acc, self.URL)
@@ -133,7 +133,7 @@ class ReciprocalRelations(Validator):
       rec = rel.getRelationType()
       if kind != rec:
         continue
-      for i in xrange(rel.getNTargets()):
+      for i in range(rel.getNTargets()):
         if rel.getTarget(i) == acc:
           return True
     return False
@@ -142,7 +142,7 @@ class ReciprocalRelations(Validator):
     s = acc.getRelationSet()
     for rel in s:
       kind = rel.getRelationType()
-      for i in xrange(rel.getNTargets()):
+      for i in range(rel.getNTargets()):
         target = rel.getTarget(i)
         ts = target.getRelationSet()
         rec = self._getReciprocal(kind)
@@ -189,7 +189,7 @@ class HasLabelName(Validator):
     for rel in acc.getRelationSet():
       if rel.getRelationType() != RELATION_LABELLED_BY:
         continue
-      for i in xrange(rel.getNTargets()):
+      for i in range(rel.getNTargets()):
         target = rel.getTarget(i)
         if self._checkForReadable(target):
           return
@@ -260,7 +260,7 @@ class RadioInSet(Validator):
   def before(self, acc, state, view):
     attrs = acc.getAttributes()
     m = dict([attr.split(':', 1) for attr in attrs])
-    if m.has_key('posinset'):
+    if 'posinset' in m:
       return
     rels = acc.getRelationSet()
     for rel in rels:
@@ -293,7 +293,7 @@ class TableRowColIndex(Validator):
   def before(self, acc, state, view):
     t = acc.queryTable()
     samples = max(t.nRows * t.nColumns, self.MAX_SAMPLES)
-    for i in xrange(samples):
+    for i in range(samples):
       r, c = _randomRowCol(t)
       i = t.getIndexAt(r, c)
       ir = t.getRowAtIndex(i)
@@ -324,7 +324,7 @@ class TableRowColParentIndex(Validator):
   def before(self, acc, state, view):
     t = acc.queryTable()
     samples = max(t.nRows * t.nColumns, self.MAX_SAMPLES)
-    for i in xrange(samples):
+    for i in range(samples):
       r, c = _randomRowCol(t)
       child = t.getAccessibleAt(r, c)
       ip = child.getIndexInParent()
diff --git a/plugins/event_monitor.py b/plugins/event_monitor.py
index 73e071b..2a86fdf 100644
--- a/plugins/event_monitor.py
+++ b/plugins/event_monitor.py
@@ -117,8 +117,8 @@ class EventMonitor(ViewportPlugin):
     Populate the model for the event types tree view. Uses a constant
     from pyatspi for the listing of all event types.
     '''
-    events = pyatspi.EVENT_TREE.keys()
-    for sub_events in pyatspi.EVENT_TREE.itervalues():
+    events = list(pyatspi.EVENT_TREE.keys())
+    for sub_events in pyatspi.EVENT_TREE.values():
       events.extend(sub_events)
     events = list(set([event.strip(':') for event in events]))
     events.sort()
diff --git a/plugins/interface_view.py b/plugins/interface_view.py
index 86592e5..f69e257 100644
--- a/plugins/interface_view.py
+++ b/plugins/interface_view.py
@@ -233,12 +233,12 @@ class _InterfaceSection(object):
     label = expander.get_label_widget()
     label_text = label.get_label()
 
-    if isinstance(label_text, unicode):
+    if isinstance(label_text, str):
         label_text = label_text.decode('UTF-8')
 
     not_implemented_str = _('(not implemented)')
 
-    if isinstance(not_implemented_str, unicode):
+    if isinstance(not_implemented_str, str):
         not_implemented_str = not_implemented_str.encode('UTF-8')
 
     if sensitive:
@@ -351,7 +351,7 @@ class _SectionAccessible(_InterfaceSection):
 
     states = [pyatspi.stateToString(s) for s in acc.getState().getStates()]
     states.sort()
-    map(self.states_model.append, [[state] for state in states])
+    list(map(self.states_model.append, [[state] for state in states]))
     
     try:
       attribs = acc.getAttributes()
@@ -436,7 +436,7 @@ class _SectionAccessible(_InterfaceSection):
         # Maybe we got a defunct state, in which case the object is diseased.
         states = []
       states.sort()
-      map(self.states_model.append, [[state] for state in states])        
+      list(map(self.states_model.append, [[state] for state in states]))        
 
 
 class _SectionAction(_InterfaceSection):
@@ -604,7 +604,7 @@ class _SectionComponent(_InterfaceSection):
     bbox = ci.getExtents(pyatspi.WINDOW_COORDS)
     self.label_posrel.set_text('%d, %d' % (bbox.x, bbox.y))
     layer = ci.getLayer()
-    self.label_layer.set_text(repr(ci.getLayer()).replace('LAYER_',''))
+    self.label_layer.set_text(repr(ci.getLayer()).replace('LAYER_', ''))
     self.label_zorder.set_text(repr(ci.getMDIZOrder()))
     self.label_alpha.set_text(repr(ci.getAlpha()))
     self.registerEventListener(self._accEventComponent, 
@@ -782,14 +782,14 @@ class _SectionHypertext(_InterfaceSection):
     '''
     hti = acc.queryHypertext()
 
-    for link_index in xrange(hti.getNLinks()):
+    for link_index in range(hti.getNLinks()):
       link = hti.getLink(link_index)
       iter = self.links_model.append(None,
                                      [link_index, 
                                       '', '', '',
                                       link.startIndex, 
                                       link.endIndex, None])
-      for anchor_index in xrange(link.nAnchors):
+      for anchor_index in range(link.nAnchors):
         acc_obj = link.getObject(anchor_index)
         self.links_model.append(iter,
                                 [link_index, acc_obj.name, acc_obj.description,
@@ -933,7 +933,7 @@ class _SectionSelection(_InterfaceSection):
       if child is not None:
         state = child.getState()
         if state.contains(pyatspi.STATE_SELECTABLE):
-          self.sel_model.append([getIcon(child),child.name, child])
+          self.sel_model.append([getIcon(child), child.name, child])
     
     state = acc.getState()
     multiple_selections = state.contains(pyatspi.STATE_MULTISELECTABLE)
@@ -1266,7 +1266,7 @@ class _SectionText(_InterfaceSection):
 
     expander_label = self.expander.get_label_widget()
     label_text = expander_label.get_label()
-    label_text = label_text.replace(_('<i>(Editable)</i>'),'')
+    label_text = label_text.replace(_('<i>(Editable)</i>'), '')
     label_text = label_text.strip(' ')
     if eti and acc.getState().contains(pyatspi.STATE_EDITABLE):
       label_text += ' ' + _('<i>(Editable)</i>')
@@ -1394,7 +1394,7 @@ class _SectionText(_InterfaceSection):
     else:
       attr_dict = self._attrStringToDict(attr)
 
-    attr_list = attr_dict.keys()
+    attr_list = list(attr_dict.keys())
     attr_list.sort()
 
     self.attr_model.clear()
diff --git a/plugins/ipython_view.py b/plugins/ipython_view.py
index df8df60..1e65bb0 100755
--- a/plugins/ipython_view.py
+++ b/plugins/ipython_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 '''
 Provides IPython console widget.
 
@@ -23,7 +23,8 @@ import re
 import sys
 import os
 
-from StringIO import StringIO
+from io import StringIO
+from functools import reduce
 
 try:
   import IPython
@@ -124,7 +125,7 @@ class IterableIPShell:
     '''
     Update self.IP namespace for autocompletion with sys.modules
     '''
-    for k,v in sys.modules.items():
+    for k, v in list(sys.modules.items()):
         if not '.' in k:
           self.IP.user_ns.update({k:v})
 
@@ -265,7 +266,7 @@ class IterableIPShell:
       possibilities = self.IP.complete(split_line[-1])
     else:
       completed = line
-      possibilities = ['',[]]
+      possibilities = ['', []]
     if possibilities:
       def _commonPrefix(str1, str2):
         '''
@@ -307,11 +308,11 @@ class IterableIPShell:
     @type header: string
     '''
     stat = 0
-    if verbose or debug: print header+cmd
+    if verbose or debug: print(header+cmd)
     # flush stdout so we don't mangle python's buffering
     if not debug:
       input, output = os.popen4(cmd)
-      print output.read()
+      print(output.read())
       output.close()
       input.close()
 
@@ -458,7 +459,7 @@ class ConsoleView(gtk.TextView):
     if text:
       self._write('\n')
     self._showPrompt(self.prompt)
-    self.text_buffer.move_mark(self.line_start,self.text_buffer.get_end_iter())
+    self.text_buffer.move_mark(self.line_start, self.text_buffer.get_end_iter())
     self.text_buffer.place_cursor(self.text_buffer.get_end_iter())
 
   def onKeyPress(self, widget, event):
@@ -526,7 +527,7 @@ class IPythonView(ConsoleView, IterableIPShell):
     '''
     ConsoleView.__init__(self)
     self.cout = StringIO()
-    IterableIPShell.__init__(self, cout=self.cout,cerr=self.cout, 
+    IterableIPShell.__init__(self, cout=self.cout, cerr=self.cout,
                              input_func=self.raw_input)
 #    self.connect('key_press_event', self.keyPress)
     self.interrupt = False
diff --git a/plugins/quick_select.py b/plugins/quick_select.py
index 751af40..3b1e1b9 100644
--- a/plugins/quick_select.py
+++ b/plugins/quick_select.py
@@ -80,7 +80,7 @@ class QuickSelect(Plugin):
     # First check if the currently selected accessible has the pointer over it.
     # This is an optimization: Instead of searching for 
     # STATE_SELECTED and ROLE_MENU and LAYER_POPUP in the entire tree.
-    item = self._getPopupItem(x,y)
+    item = self._getPopupItem(x, y)
     if item:
       self.node.update(item)
       return
@@ -140,7 +140,7 @@ class QuickSelect(Plugin):
         except NotImplementedError:
           continue
 
-        if ci.contains(x,y, pyatspi.DESKTOP_COORDS) and \
+        if ci.contains(x, y, pyatspi.DESKTOP_COORDS) and \
               ci.getLayer() == pyatspi.LAYER_POPUP:
           return child
 
diff --git a/plugins/validate.py b/plugins/validate.py
index 6412ac2..cbf1ce1 100644
--- a/plugins/validate.py
+++ b/plugins/validate.py
@@ -85,7 +85,7 @@ class ValidatorManager(type):
 
     @return: List of string names
     '''
-    return VALIDATORS.keys()
+    return list(VALIDATORS.keys())
 
   @staticmethod
   def getSchemaMetadata(name):
@@ -261,7 +261,7 @@ class ValidatorViewport(ViewportPlugin):
       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.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
 
@@ -429,7 +429,7 @@ class ValidatorViewport(ViewportPlugin):
     '''
     try:
       # generate the next accessible to validate
-      self.walk.next()
+      next(self.walk)
     except StopIteration:
       # nothing left to validate, so stop
       self._stopValidate()
@@ -454,8 +454,8 @@ class ValidatorViewport(ViewportPlugin):
     while 1:
       try:
         # get one child
-        child = gen_child.next()
-      except StopIteration, e:
+        child = next(gen_child)
+      except StopIteration as e:
         break
       # recurse
       gen_traverse = self._traverse(child, state)
@@ -464,7 +464,7 @@ class ValidatorViewport(ViewportPlugin):
         yield None
         try:
           # get one descendant
-          gen_traverse.next()
+          next(gen_traverse)
         except StopIteration:
           break
     
@@ -481,7 +481,7 @@ class ValidatorViewport(ViewportPlugin):
     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 xrange(acc.childCount):
+      for i in range(acc.childCount):
         child = acc.getChildAtIndex(i)
         yield child
     # run after methods on all validators
@@ -509,7 +509,7 @@ class ValidatorViewport(ViewportPlugin):
               val.before(acc, state, self)
             else:
               val.after(acc, state, self)
-          except Exception, e:
+          except Exception as e:
             self._exceptionError(acc, e)
 
   def _onCursorChanged(self, report):
diff --git a/pyreqs.py b/pyreqs.py
index f2906c6..1052a34 100644
--- a/pyreqs.py
+++ b/pyreqs.py
@@ -14,7 +14,7 @@ U{http://www.opensource.org/licenses/bsd-license.php}
 import sys, os, imp
 
 PYGTK_REQ = '2.0'
-PYATSPI_REQ = (2,23,3)
+PYATSPI_REQ = (2, 23, 3)
 GTK_VERSION = (2, 8, 0)
 
 try:
@@ -33,22 +33,21 @@ modules = ['pyatspi', 'cairo', 'rsvg', 'gi', 'gi.repository.Gtk', \
 for name in modules:
   try:
     m = __import__(name)
-    print name, 
-  except ImportError, e:
-    print name, '*MISSING*'
+    print(name)
+  except ImportError as e:
+    print(name, '*MISSING*')
     sys.exit(1)
   except RuntimeError:
     # ignore other errors which might be from lack of a display
     continue
   if name =='pyatspi':
     try:
-      compared = map(lambda x: cmp(*x),  zip(PYATSPI_REQ, m.__version__))
+      compared = [cmp(*x) for x in zip(PYATSPI_REQ, m.__version__)]
     except AttributeError:
       # Installed pyatspi does not support __version__, too old.
       compared = [-1, 0, 0]
     if -1 in compared and 1 not in compared[:compared.index(-1)]:
       # A -1 without a 1 preceding it means an older version.
-      print
-      print "Need pyatspi 1.23.4 or higher (or SVN trunk)"
+      print("\nNeed pyatspi 1.23.4 or higher (or SVN trunk)")
       sys.exit(1)
-print
+print()
diff --git a/src/accerciser.in b/src/accerciser.in
index 2cbe3df..4160b17 100755
--- a/src/accerciser.in
+++ b/src/accerciser.in
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#! PYTHON@
 '''
 Creates an instance of the program GUI and starts the main event loop.
 
@@ -21,11 +21,11 @@ import sys, os
 
 def migrate_data (old_path, new_path):
   if os.path.exists(old_path) and not os.path.exists(new_path):
-    mask = os.umask(077)
+    mask = os.umask(0o77)
     try:
       os.renames(old_path, new_path)
     except:
-      print "Unable to migrate ", old_path
+      print("Unable to migrate ", old_path)
     os.umask(mask)
 
 # Load gail module no matter what the desktop-wide settings are.
diff --git a/src/lib/accerciser/__init__.py b/src/lib/accerciser/__init__.py
index 1b189c4..7a6930f 100644
--- a/src/lib/accerciser/__init__.py
+++ b/src/lib/accerciser/__init__.py
@@ -12,13 +12,13 @@ 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 sys, os
-from i18n import _
+from .i18n import _
 import signal
 def signal_handler(signal, frame):
-  print _(
-    'You pressed Ctrl+Z. This would normally freeze your keyboard')
-  print _(
-    'Ctrl+Z has been disabled; use "accerciser &" instead from the command line')
+  print(_(
+    'You pressed Ctrl+Z. This would normally freeze your keyboard'))
+  print(_(
+    'Ctrl+Z has been disabled; use "accerciser &" instead from the command line'))
 signal.signal(signal.SIGTSTP, signal_handler)
 
 # If pyatspi not installed seperately, add pyatspi zip file to the path
@@ -31,6 +31,6 @@ def main():
   '''
   Run program.
   '''
-  from accerciser import Main
+  from .accerciser import Main
   main = Main()
   main.run()
diff --git a/src/lib/accerciser/about_dialog.py b/src/lib/accerciser/about_dialog.py
index caa7797..b174cee 100644
--- a/src/lib/accerciser/about_dialog.py
+++ b/src/lib/accerciser/about_dialog.py
@@ -16,7 +16,7 @@ is available at U{http://www.opensource.org/licenses/bsd-license.php}
 import gi
 
 from gi.repository import Gtk as gtk
-from i18n import _
+from .i18n import _
 
 class AccerciserAboutDialog(gtk.AboutDialog):
   '''
diff --git a/src/lib/accerciser/accerciser.py b/src/lib/accerciser/accerciser.py
index ec703a5..ea08c4c 100644
--- a/src/lib/accerciser/accerciser.py
+++ b/src/lib/accerciser/accerciser.py
@@ -21,20 +21,20 @@ from gi.repository import GObject
 from gi.repository import Atk as atk
 
 import os, sys, locale
-from icons import getIcon
+from .icons import getIcon
 import os
-from bookmarks import BookmarkStore
-from accessible_treeview import *
-from node import Node
-from plugin import PluginManager
-from plugin import PluginView
-from tools import Tools
-from i18n import _, N_
-from hotkey_manager import HotkeyManager, HotkeyTreeView
-from about_dialog import AccerciserAboutDialog
-from prefs_dialog import AccerciserPreferencesDialog
-from main_window import AccerciserMainWindow
-import ui_manager
+from .bookmarks import BookmarkStore
+from .accessible_treeview import *
+from .node import Node
+from .plugin import PluginManager
+from .plugin import PluginView
+from .tools import Tools
+from .i18n import _, N_
+from .hotkey_manager import HotkeyManager, HotkeyTreeView
+from .about_dialog import AccerciserAboutDialog
+from .prefs_dialog import AccerciserPreferencesDialog
+from .main_window import AccerciserMainWindow
+from . import ui_manager
 
 class Main(Tools):
   '''
diff --git a/src/lib/accerciser/accessible_treeview.py b/src/lib/accerciser/accessible_treeview.py
index ac34bbc..9f29215 100644
--- a/src/lib/accerciser/accessible_treeview.py
+++ b/src/lib/accerciser/accessible_treeview.py
@@ -19,12 +19,12 @@ from gi.repository import GObject
 
 import pyatspi
 import os
-import ui_manager
+from . import ui_manager
 from time import sleep
-from icons import getIcon
-from node import Node
-from tools import Tools, getTreePathBoundingBox
-from i18n import _
+from .icons import getIcon
+from .node import Node
+from .tools import Tools, getTreePathBoundingBox
+from .i18n import _
 
 COL_ICON = 0
 COL_NAME = 1
@@ -236,10 +236,10 @@ class AccessibleModel(gtk.TreeStore, Tools):
     '''
 
     if not self._hide_leaves:
-      return [i for i in xrange(accessible.childCount)]
+      return [i for i in range(accessible.childCount)]
     else:
       children_ids = []
-      for i in xrange(accessible.childCount):
+      for i in range(accessible.childCount):
         child = accessible.getChildAtIndex(i)
         if child.childCount > 0 or child.getRoleName() != 'application':
           children_ids.append(i)
@@ -361,7 +361,7 @@ class AccessibleModel(gtk.TreeStore, Tools):
     @return: True if entire path is populated.
     @rtype: boolean
     '''
-    for i in xrange(1, len(path)):
+    for i in range(1, len(path)):
       if not self[path[:i]][COL_FILLED]:
         self.popLevel(self.get_iter(path[:i]))
         return False
@@ -425,13 +425,13 @@ class AccessibleModel(gtk.TreeStore, Tools):
         if index_in_parent < 0:
           break
         path = (index_in_parent,) + path
-      except Exception, e:
+      except Exception as e:
         return None
       child = child.get_parent()
     if not self._hide_leaves:
       try:
         path = (list(self.desktop).index(child),) + path
-      except Exception, e:
+      except Exception as e:
         return None
 
     return path
diff --git a/src/lib/accerciser/bookmarks.py b/src/lib/accerciser/bookmarks.py
index 11724f1..e2aff5c 100644
--- a/src/lib/accerciser/bookmarks.py
+++ b/src/lib/accerciser/bookmarks.py
@@ -4,11 +4,11 @@ from gi.repository import Atk as atk
 
 import os
 from xml.dom.minidom import getDOMImplementation, parse, Element
-from i18n import _
+from .i18n import _
 from pyatspi import getPath
 from random import random
 import random
-import ui_manager
+from . import ui_manager
 
 COL_NAME = 0
 COL_APP = 1
@@ -188,8 +188,7 @@ class BookmarkStore(gtk.ListStore):
     @return: list of elements.
     @rtype: list of Element
     '''
-    return filter(lambda x: isinstance(x, Element),
-                  self._xmldoc.documentElement.childNodes)
+    return [x for x in self._xmldoc.documentElement.childNodes if isinstance(x, Element)]
 
   def _onRowChanged(self, model, tree_path, iter):
     '''
@@ -273,7 +272,7 @@ class BookmarkStore(gtk.ListStore):
     if '' == bookmark.path: 
       path = ()
     else: 
-      path = map(int, bookmark.path.split(','))
+      path = list(map(int, bookmark.path.split(',')))
     self.node.updateToPath(bookmark.app, path)
 
   def bookmarkCurrent(self):
@@ -327,7 +326,7 @@ class BookmarkStore(gtk.ListStore):
       '''
       gtk.Dialog.__init__(self, _('Edit Bookmarks...'), 
                           buttons=(gtk.STOCK_CLOSE, gtk.ResponseType.CLOSE))
-      self.set_default_size(480,240)
+      self.set_default_size(480, 240)
       self.connect('response', self._onResponse)
       vbox = self.get_children()[0]
       hbox = gtk.HBox()
@@ -472,7 +471,7 @@ class BookmarkStore(gtk.ListStore):
         return
       if col_id == COL_PATH:
         try:
-          int_path = map(int, new_text.split(','))
+          int_path = list(map(int, new_text.split(',')))
         except ValueError:
           return
       bookmark = model[path][0]
@@ -542,7 +541,7 @@ class BookmarkStore(gtk.ListStore):
         entry.set_text(value)
         entry.connect('activate', self._onEnter, ok_button)
         label_widget = gtk.Label(label)
-        label_widget.set_alignment(0.0,0.5)
+        label_widget.set_alignment(0.0, 0.5)
         label_acc = label_widget.get_accessible()
         entry_acc = entry.get_accessible()
         label_acc.add_relationship(atk.RelationType.LABEL_FOR, entry_acc)
diff --git a/src/lib/accerciser/hotkey_manager.py b/src/lib/accerciser/hotkey_manager.py
index eef9b9a..272c8f2 100644
--- a/src/lib/accerciser/hotkey_manager.py
+++ b/src/lib/accerciser/hotkey_manager.py
@@ -14,7 +14,7 @@ from gi.repository import Gtk as gtk
 from gi.repository import Gdk as gdk
 from gi.repository.Gio import Settings as GSettings
 
-from i18n import _
+from .i18n import _
 import pyatspi
 
 HOTKEYS_GSCHEMA = 'org.a11y.Accerciser.hotkeys'
@@ -123,14 +123,14 @@ class HotkeyManager(gtk.ListStore):
     be perfomed.
     @type modifiers: int
     '''
-    component_desc_pairs = zip([row[COL_COMPONENT] for row in self],
-                               [row[COL_DESC] for row in self])
+    component_desc_pairs = list(zip([row[COL_COMPONENT] for row in self],
+                               [row[COL_DESC] for row in self]))
     if (component, description) in component_desc_pairs:
       path = component_desc_pairs.index((component, description))
       self[path][COL_CALLBACK] = callback
     else:
       gspath = self._getComboGSettingsPath(component, description)
-      gsettings = GSettings(schema=HOTKEYS_GSCHEMA , path=gspath)
+      gsettings = GSettings(schema=HOTKEYS_GSCHEMA, path=gspath)
       if gsettings.get_string('hotkey-combo'):
         final_keypress, final_modifiers = gtk.accelerator_parse(
           gsettings.get_string('hotkey-combo'))
@@ -181,7 +181,7 @@ class HotkeyManager(gtk.ListStore):
 
     gspath = self._getComboGSettingsPath(model[iter][COL_COMPONENT], 
                                          model[iter][COL_DESC])
-    gsettings = GSettings(schema=HOTKEYS_GSCHEMA , path=gspath)
+    gsettings = GSettings(schema=HOTKEYS_GSCHEMA, path=gspath)
     combo_name = gtk.accelerator_name(model[iter][COL_KEYPRESS], 
                                       gdk.ModifierType(model[iter][COL_MOD]))
 
diff --git a/src/lib/accerciser/i18n.py.in b/src/lib/accerciser/i18n.py.in
index fbbee2a..e175362 100644
--- a/src/lib/accerciser/i18n.py.in
+++ b/src/lib/accerciser/i18n.py.in
@@ -50,7 +50,7 @@ def bind(domain, locale_dir):
   except IOError:
     # no translation file, so just return the unicode version of the given 
     # string
-    return lambda x: unicode(x)
+    return lambda x: str(x)
 
 # use the current system locale
 locale.setlocale(locale.LC_ALL, '')
diff --git a/src/lib/accerciser/icons.py b/src/lib/accerciser/icons.py
index 76d26c5..a9bc42f 100644
--- a/src/lib/accerciser/icons.py
+++ b/src/lib/accerciser/icons.py
@@ -61,7 +61,7 @@ def getIcon(acc):
         return GdkPixbuf.Pixbuf.new_from_file(fn)
       except GObject.GError:
         pass
-  except Exception, e:
+  except Exception as e:
     pass
   fn = os.path.join(ICONS_PATH, 'filler.png')
   return GdkPixbuf.Pixbuf.new_from_file(fn)
diff --git a/src/lib/accerciser/main_window.py b/src/lib/accerciser/main_window.py
index 43f5053..343f5db 100644
--- a/src/lib/accerciser/main_window.py
+++ b/src/lib/accerciser/main_window.py
@@ -2,11 +2,11 @@ from gi.repository import Gtk as gtk
 from gi.repository import Gdk as gdk
 from gi.repository.Gio import Settings as GSettings
 
-from plugin import PluginView
-from i18n import _, N_
-from accessible_treeview import *
-import ui_manager
-from ui_manager import uimanager
+from .plugin import PluginView
+from .i18n import _, N_
+from .accessible_treeview import *
+from . import ui_manager
+from .ui_manager import uimanager
 
 GSCHEMA = 'org.a11y.Accerciser'
 
@@ -147,7 +147,7 @@ class AccerciserMainWindow(gtk.Window):
     @type event: L{gtk.gdk.Event}
     '''
     if event.state & gdk.ModifierType.MOD1_MASK and \
-          event.keyval in xrange(gdk.keyval_from_name('0'), 
+          event.keyval in range(gdk.keyval_from_name('0'),
                                  gdk.keyval_from_name('9')):
       tab_num = event.keyval - gdk.keyval_from_name('0') or 10
       pages_count1 = self.pluginview1.getNVisiblePages()
@@ -197,7 +197,7 @@ class AccerciserMainWindow(gtk.Window):
     tree_path = model.get_path(iter)
     path_tuple = tuple(tree_path.get_indices())
 
-    path = map(str, path_tuple)
+    path = list(map(str, path_tuple))
     self.statusbar.pop(context_id)
     if len(path) > 1:
       self.statusbar.push(context_id, 'Path: '+' '.join(path[1:]))
diff --git a/src/lib/accerciser/node.py b/src/lib/accerciser/node.py
index c670c36..c514d93 100644
--- a/src/lib/accerciser/node.py
+++ b/src/lib/accerciser/node.py
@@ -21,7 +21,7 @@ from gi.repository.Gio import Settings as GSettings
 import cairo
 import pyatspi
 import string
-from tools import Tools, parseColorString
+from .tools import Tools, parseColorString
 
 MAX_BLINKS = 6
 
@@ -42,7 +42,7 @@ class Bag(object):
     self.__dict__.update(kwargs)
     
   def __str__(self):
-    return ', '.join(vars(self).keys())
+    return ', '.join(list(vars(self).keys()))
 
 class Node(GObject.GObject, Tools):
   '''
diff --git a/src/lib/accerciser/plugin/__init__.py b/src/lib/accerciser/plugin/__init__.py
index 51ae04c..0e6e998 100644
--- a/src/lib/accerciser/plugin/__init__.py
+++ b/src/lib/accerciser/plugin/__init__.py
@@ -11,7 +11,7 @@ available under the terms of the BSD which accompanies this distribution, and
 is available at U{http://www.opensource.org/licenses/bsd-license.php}
 '''
 
-from base_plugin import Plugin, ViewportPlugin, ConsolePlugin
-from plugin_manager import PluginManager
-from view import PluginView
+from .base_plugin import Plugin, ViewportPlugin, ConsolePlugin
+from .plugin_manager import PluginManager
+from .view import PluginView
 
diff --git a/src/lib/accerciser/plugin/base_plugin.py b/src/lib/accerciser/plugin/base_plugin.py
index a13784e..ed47ef5 100644
--- a/src/lib/accerciser/plugin/base_plugin.py
+++ b/src/lib/accerciser/plugin/base_plugin.py
@@ -155,13 +155,13 @@ class Plugin(Tools):
       '''
       try:
         return self.func(*args, **kwargs)
-      except Exception, e:
+      except Exception as e:
         if hasattr(self.func, 'im_self') and hasattr(self.func, 'im_class'):
-          message_manager = getattr(self.func.im_self, '_message_manager', None)
+          message_manager = getattr(self.func.__self__, '_message_manager', None)
           if not message_manager:
             raise e
           message_manager.newPluginError(
-            self.func.im_self, self.func.im_class,
+            self.func.__self__, self.func.__self__.__class__,
             traceback.format_exception_only(e.__class__, e)[0].strip(),
             traceback.format_exc())
 
diff --git a/src/lib/accerciser/plugin/plugin_manager.py b/src/lib/accerciser/plugin/plugin_manager.py
index f0b9e96..cea804a 100644
--- a/src/lib/accerciser/plugin/plugin_manager.py
+++ b/src/lib/accerciser/plugin/plugin_manager.py
@@ -17,10 +17,10 @@ from gi.repository import GLib
 from gi.repository import Gtk as gtk
 from gi.repository.Gio import Settings as GSettings
 
-from base_plugin import Plugin
-from view import ViewManager
+from .base_plugin import Plugin
+from .view import ViewManager
 from accerciser.tools import Tools, getTreePathBoundingBox
-from message import MessageManager
+from .message import MessageManager
 import os
 import sys
 import imp
@@ -139,7 +139,7 @@ class PluginManager(gtk.ListStore, Tools):
       params = imp.find_module(plugin_fn, [plugin_dir])
       plugin = imp.load_module(plugin_fn, *params)
       plugin_locals = plugin.__dict__
-    except Exception, e:
+    except Exception as e:
       self.message_manager.newModuleError(plugin_fn, plugin_dir,
         traceback.format_exception_only(e.__class__, e)[0].strip(),
         traceback.format_exc())
@@ -158,7 +158,7 @@ class PluginManager(gtk.ListStore, Tools):
     '''
     plugin_locals = self._getPluginLocals(plugin_dir, plugin_fn)
     # use keys list to avoid size changes during iteration
-    for symbol in plugin_locals.keys():
+    for symbol in list(plugin_locals.keys()):
       try:
         is_plugin = \
             issubclass(plugin_locals[symbol], Plugin) and \
@@ -195,7 +195,7 @@ class PluginManager(gtk.ListStore, Tools):
           plugin_class.plugin_name, 
           plugin_class.plugin_name_localized or plugin_class.plugin_name
           , *key_combo)
-    except Exception, e:
+    except Exception as e:
       self.message_manager.newPluginError(
         plugin_instance, plugin_class,
         traceback.format_exception_only(e.__class__, e)[0].strip(),
diff --git a/src/lib/accerciser/plugin/view.py b/src/lib/accerciser/plugin/view.py
index 4555c44..47739ae 100644
--- a/src/lib/accerciser/plugin/view.py
+++ b/src/lib/accerciser/plugin/view.py
@@ -15,9 +15,9 @@ from gi.repository import Gdk as gdk
 from gi.repository.Gio import Settings as GSettings
 from gi.repository import GObject
 
-from base_plugin import Plugin
+from .base_plugin import Plugin
 from accerciser.tools import *
-from message import MessageManager
+from .message import MessageManager
 import os
 import sys
 import imp
@@ -193,7 +193,7 @@ class PluginView(gtk.Notebook):
     @return: Plugins in given view.
     @rtype: List of {Plugin}
     '''
-    return filter(lambda x: isinstance(x, Plugin), self.get_children())
+    return [x for x in self.get_children() if isinstance(x, Plugin)]
 
   def insert_page(self, child, tab_label=None, position=-1):
     '''
@@ -213,7 +213,7 @@ class PluginView(gtk.Notebook):
     if tab_label:
       name = tab_label
     elif isinstance(child, Plugin):
-      name = getattr(child,'plugin_name_localized', None) or child.plugin_name
+      name = getattr(child, 'plugin_name_localized', None) or child.plugin_name
     elif child.get_name():
       name = child.get_name()
     gtk.Notebook.append_page(self, child, None)
@@ -252,7 +252,7 @@ class PluginView(gtk.Notebook):
     @type tab_num: integer
     '''
     children = self.get_children()
-    shown_children = filter(lambda x: x.get_property('visible'), children)
+    shown_children = [x for x in children if x.get_property('visible')]
     try:
       child = shown_children[tab_num]
     except IndexError:
@@ -267,8 +267,7 @@ class PluginView(gtk.Notebook):
     @return: Number of visible children.
     @rtype: integer
     '''
-    shown_children = filter(lambda x: x.get_property('visible'), 
-                            self.get_children())
+    shown_children = [x for x in self.get_children() if x.get_property('visible')]
     return len(shown_children)
 
 class PluginViewWindow(gtk.Window, Tools):
@@ -342,7 +341,7 @@ class PluginViewWindow(gtk.Window, Tools):
     @type event: gtk.gdk.Event
     '''
     if event.state & gdk.ModifierType.MOD1_MASK and \
-          event.keyval in xrange(gdk.keyval_from_name('0'), 
+          event.keyval in range(gdk.keyval_from_name('0'),
                                  gdk.keyval_from_name('9')):
       tab_num = event.keyval - gdk.keyval_from_name('0') or 10
       pages_count = self.plugin_view.get_n_pages()
@@ -871,7 +870,7 @@ class MultiViewModel(list, BaseViewModel):
     if (view.view_name, plugin.plugin_name) in self._ignore_insertion:
       self._ignore_insertion.remove((view.view_name, plugin.plugin_name))
       return
-    if self._placement_cache.has_key(plugin.plugin_name):
+    if plugin.plugin_name in self._placement_cache:
       self._placement_cache.pop(plugin.plugin_name)
 
     plugin_layouts = self._getPluginLayouts()
@@ -896,8 +895,8 @@ class MultiViewModel(list, BaseViewModel):
     self.plugviews.set_strv('top-panel-layout', plugin_layouts.pop('Top panel'))
     self.plugviews.set_strv('bottom-panel-layout', plugin_layouts.pop('Bottom panel'))
 
-    for plugview in plugin_layouts.keys():
-      gspath = NEWPLUGVIEWS_PATH + plugview.lower().replace(' ','-') + '/'
+    for plugview in list(plugin_layouts.keys()):
+      gspath = NEWPLUGVIEWS_PATH + plugview.lower().replace(' ', '-') + '/'
       newview = GSettings(schema=NEWPLUGVIEWS_GSCHEMA, path=gspath)
       newview.set_strv('layout', plugin_layouts[plugview])
       l = self.plugviews.get_strv('available-newviews')
@@ -911,7 +910,7 @@ class MultiViewModel(list, BaseViewModel):
     plugin_layouts['Bottom panel'] = self.plugviews.get_strv('bottom-panel-layout')
 
     for plugview in self.plugviews.get_strv('available-newviews'):
-      gspath = NEWPLUGVIEWS_PATH + plugview.lower().replace(' ','-') + '/'
+      gspath = NEWPLUGVIEWS_PATH + plugview.lower().replace(' ', '-') + '/'
       newview = GSettings(schema=NEWPLUGVIEWS_GSCHEMA, path=gspath)
       layout = newview.get_strv('layout')
       if layout:
@@ -932,7 +931,7 @@ class MultiViewModel(list, BaseViewModel):
     @param plugin: Plugin to add.
     @type plugin: L{Plugin}
     '''
-    if self._placement_cache.has_key(plugin.plugin_name):
+    if plugin.plugin_name in self._placement_cache:
       view_name, index = self._placement_cache.pop(plugin.plugin_name)
       view = self._getViewOrNewView(view_name)
     else:
diff --git a/src/lib/accerciser/prefs_dialog.py b/src/lib/accerciser/prefs_dialog.py
index ee0ef40..a73f9ad 100644
--- a/src/lib/accerciser/prefs_dialog.py
+++ b/src/lib/accerciser/prefs_dialog.py
@@ -18,9 +18,9 @@ from gi.repository import Gdk as gdk
 from gi.repository import Atk as atk
 from gi.repository.Gio import Settings as GSettings
 
-from i18n import _
-import node
-from tools import parseColorString
+from .i18n import _
+from . import node
+from .tools import parseColorString
 
 class AccerciserPreferencesDialog(gtk.Dialog):
   '''
@@ -38,7 +38,7 @@ class AccerciserPreferencesDialog(gtk.Dialog):
     gtk.Dialog.__init__(self, _('accerciser Preferences'), 
                         buttons=(gtk.STOCK_CLOSE, gtk.ResponseType.CLOSE))
     self.connect('response', self._onResponse)
-    self.set_default_size(500,250)
+    self.set_default_size(500, 250)
     notebook = gtk.Notebook()
     vbox = self.get_children()[0]
     vbox.add(notebook)
@@ -105,8 +105,8 @@ class _HighlighterView(gtk.Alignment):
       table.attach(label, 0, 1, row, row + 1, gtk.AttachOptions.FILL)
       table.attach(control, 1, 2, row, row + 1, gtk.AttachOptions.FILL)
 
-    for label, control in zip(map(lambda x: x.get_accessible(),labels),
-                              map(lambda x: x.get_accessible(),controls)):
+    for label, control in zip([x.get_accessible() for x in labels],
+                              [x.get_accessible() for x in controls]):
       label.add_relationship(atk.RelationType.LABEL_FOR, control)
       control.add_relationship(atk.RelationType.LABELLED_BY, label)
 
diff --git a/src/lib/accerciser/tools.py b/src/lib/accerciser/tools.py
index 07f7109..2cb6b6f 100644
--- a/src/lib/accerciser/tools.py
+++ b/src/lib/accerciser/tools.py
@@ -13,7 +13,6 @@ is available at U{http://www.opensource.org/licenses/bsd-license.php}
 import os
 import pickle
 import weakref
-import new
 
 class Tools(object):
   '''
@@ -43,13 +42,13 @@ class Tools(object):
       return False
     try:
       app = acc.getApplication()
-    except Exception, e:
+    except Exception as e:
       return False
     try:
       app_id = app.id
     except:
       return False
-    if hasattr(self,'my_app_id'):
+    if hasattr(self, 'my_app_id'):
       if self.my_app_id == app_id:
         return True
     else:
@@ -69,14 +68,14 @@ class Proxy(object):
   def __init__(self, cb):
     try:
       try:
-        self.inst = weakref.ref(cb.im_self)
+        self.inst = weakref.ref(cb.__self__)
       except TypeError:
         self.inst = None
-      self.func = cb.im_func
-      self.klass = cb.im_class
+      self.func = cb.__func__
+      self.klass = cb.__self__.__class__
     except AttributeError:
       self.inst = None
-      self.func = cb.im_func
+      self.func = cb.__func__
       self.klass = None
      
   def __call__(self, *args, **kwargs):
@@ -90,7 +89,7 @@ class Proxy(object):
       return
     elif self.inst is not None:
       # build a new instance method with a strong reference to the instance
-      mtd = new.instancemethod(self.func, self.inst(), self.klass)
+      mtd = self.func.__get__(self.inst(), self.klass)
     else:
       # not a bound method, just return the func
       mtd = self.func
@@ -129,7 +128,7 @@ def parseColorString(color_string):
   of 0.0 to 1.0
   @rtype: tuple of string and float.
   '''
-  return color_string[:-2], long(color_string[-2:], 16)/255.0
+  return color_string[:-2], int(color_string[-2:], 16)/255.0
 
 def getTreePathBoundingBox(treeview, path, col):
   '''
diff --git a/src/lib/accerciser/ui_manager.py b/src/lib/accerciser/ui_manager.py
index 4c68259..c3310f0 100644
--- a/src/lib/accerciser/ui_manager.py
+++ b/src/lib/accerciser/ui_manager.py
@@ -15,7 +15,7 @@ import gi
 
 from gi.repository import Gtk as gtk
 
-from i18n import _, N_, C_
+from .i18n import _, N_, C_
 
 menu_actions = gtk.ActionGroup('MenuActions')
 



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]