home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / gnome-orca / orca / bookmarks.py < prev    next >
Encoding:
Python Source  |  2009-04-13  |  9.4 KB  |  254 lines

  1. # Orca
  2. #
  3. # Copyright 2005-2008 Sun Microsystems Inc.
  4. #
  5. # This library is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU Library General Public
  7. # License as published by the Free Software Foundation; either
  8. # version 2 of the License, or (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13. # Library General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Library General Public
  16. # License along with this library; if not, write to the
  17. # Free Software Foundation, Inc., Franklin Street, Fifth Floor,
  18. # Boston MA  02110-1301 USA.
  19.  
  20. """Provides the default implementation for bookmarks in Orca."""
  21.  
  22. import pickle
  23. import os
  24.  
  25. import speech
  26. import settings
  27. import orca_state
  28.  
  29. from orca_i18n import _
  30.  
  31.  
  32. class Bookmarks:
  33.     """Represents a default bookmark handler."""
  34.     def __init__(self, script):
  35.         self._script = script
  36.         self._bookmarks = {} 
  37.         self._saveObservers = []
  38.         self._loadObservers = []
  39.         self._loadBookmarks() 
  40.         self._currentbookmarkindex = None
  41.  
  42.     def addSaveObserver(self, observer):
  43.         self._saveObservers.append(observer)
  44.  
  45.     def addLoadObserver(self, observer):
  46.         self._loadObservers.append(observer)
  47.  
  48.     def goToBookmark(self, inputEvent, index=None):
  49.         """ Go to the bookmark indexed by inputEvent.hw_code """
  50.         # establish the _bookmarks index
  51.         index = index or inputEvent.hw_code
  52.  
  53.         try:
  54.             context = self._script.getFlatReviewContext()
  55.             context_info = self._bookmarks[index]
  56.             context.setCurrent(context_info['line'], context_info['zone'], \
  57.                                 context_info['word'], context_info['char'])
  58.             self._bookmarks[index] = context_info
  59.         except KeyError:
  60.             self._script.systemBeep()
  61.             return
  62.  
  63.         self._script.flatReviewContext = context
  64.         self._script.reviewCurrentItem(inputEvent)
  65.  
  66.         # update the currentbookmark
  67.         self._currentbookmarkindex = index
  68.  
  69.     def addBookmark(self, inputEvent):
  70.         """ Add an in-page accessible object bookmark for this key. """
  71.         context = self._script.getFlatReviewContext()
  72.         self._bookmarks[inputEvent.hw_code] = self._contextToBookmark(context)
  73.         
  74.         # Translators: this announces that a bookmark has been entered.  
  75.         # Orca allows users to tell it to remember a particular spot in an 
  76.         # application window and provides keystrokes for the user to jump to 
  77.         # those spots.  These spots are known as 'bookmarks'. 
  78.         #
  79.         utterances = [_('bookmark entered')]
  80.         utterances.extend(self._script.speechGenerator.getSpeech( \
  81.                           context.getCurrentAccessible(), False))
  82.         speech.speakUtterances(utterances)
  83.  
  84.     def bookmarkCurrentWhereAmI(self, inputEvent):
  85.         """ Report "Where am I" information for this bookmark relative to the 
  86.         current pointer location."""
  87.         try:
  88.             context = self._bookmarkToContext( \
  89.                           self._bookmarks[inputEvent.hw_code])
  90.         except KeyError:
  91.             self._script.systemBeep()
  92.             return   
  93.  
  94.         obj = context.getCurrentAccessible()    
  95.         cur_obj = orca_state.locusOfFocus
  96.  
  97.         # Are they the same object?
  98.         if self._script.isSameObject(cur_obj, obj):
  99.             # Translators: this announces that the current object is the same
  100.             # object pointed to by the bookmark.
  101.             #
  102.             speech.speak(_('bookmark is current object'))
  103.             return
  104.         # Are their parents the same?
  105.         elif self._script.isSameObject(cur_obj.parent, obj.parent):
  106.             # Translators: this announces that the current object's parent and 
  107.             # the parent of the object pointed to by the bookmark are the same.
  108.             #
  109.             speech.speak(_('bookmark and current object have same parent'))
  110.             return
  111.  
  112.         # Do they share a common ancestor?
  113.         # bookmark's ancestors
  114.         bookmark_ancestors = []
  115.         p = obj.parent
  116.         while p:
  117.             bookmark_ancestors.append(p)
  118.             p = p.parent
  119.         # look at current object's ancestors to compare to bookmark's ancestors
  120.         p = cur_obj.parent
  121.         while p:
  122.             if bookmark_ancestors.count(p) > 0:
  123.                 # Translators: this announces that the bookmark and the current
  124.                 # object share a common ancestor
  125.                 #
  126.                 speech.speak(_('shared ancestor %s') %p.role)
  127.                 return
  128.             p = p.parent
  129.  
  130.         # Translators: This announces that a comparison between the bookmark
  131.         # and the current object can not be determined.
  132.         #
  133.         speech.speak(_('comparison unknown'))
  134.  
  135.     def saveBookmarks(self, inputEvent):
  136.         """ Save the bookmarks for this script. """        
  137.         try:
  138.             self.saveBookmarksToDisk(self._bookmarks)
  139.             # Translators: this announces that a bookmark has been saved to 
  140.             # disk
  141.             #
  142.             speech.speak(_('bookmarks saved'))
  143.         except IOError:
  144.             # Translators: this announces that a bookmark could not be saved to 
  145.             # disk
  146.             #
  147.             speech.speak(_('bookmarks could not be saved'))
  148.  
  149.         # Notify the observers
  150.         for o in self._saveObservers:
  151.             o()
  152.  
  153.     def goToNextBookmark(self, inputEvent):
  154.         """ Go to the next bookmark location.  If no bookmark has yet to be
  155.         selected, the first bookmark will be used.  """
  156.  
  157.         # get the hardware keys that have registered bookmarks
  158.         hwkeys = self._bookmarks.keys()
  159.         hwkeys.sort()
  160.  
  161.         # no bookmarks have been entered
  162.         if len(hwkeys) == 0:
  163.             self._script.systemBeep()
  164.             return
  165.         # only 1 bookmark or we are just starting out
  166.         elif len(hwkeys) == 1 or self._currentbookmarkindex is None:
  167.             self.goToBookmark(None, index=hwkeys[0])
  168.             return
  169.  
  170.         # find current bookmark hw_code in our sorted list.  
  171.         # Go to next one if possible
  172.         try:
  173.             index = hwkeys.index(self._currentbookmarkindex)
  174.             self.goToBookmark(None, index=hwkeys[index+1])
  175.         except (ValueError, KeyError, IndexError):
  176.             self.goToBookmark(None, index=hwkeys[0])
  177.  
  178.     def goToPrevBookmark(self, inputEvent):
  179.         # get the hardware keys that have registered bookmarks
  180.         hwkeys = self._bookmarks.keys()
  181.         hwkeys.sort()
  182.  
  183.         # no bookmarks have been entered
  184.         if len(hwkeys) == 0:
  185.             self._script.systemBeep()
  186.             return
  187.         # only 1 bookmark or we are just starting out
  188.         elif len(hwkeys) == 1 or self._currentbookmarkindex is None:
  189.             self.goToBookmark(None, index=hwkeys[0])
  190.             return
  191.  
  192.         # find current bookmark hw_code in our sorted list.  
  193.         # Go to previous one if possible
  194.         try:
  195.             index = hwkeys.index(self._currentbookmarkindex)
  196.             self.goToBookmark(None, index=hwkeys[index-1])
  197.         except (ValueError, KeyError, IndexError):
  198.             self.goToBookmark(None, index=hwkeys[0])
  199.  
  200.     def _loadBookmarks(self):
  201.         """ Load this scripts saved bookmarks."""
  202.         self._bookmarks = self.readBookmarksFromDisk() or {}
  203.  
  204.         # notify the observers
  205.         for o in self._loadObservers:
  206.             o()
  207.  
  208.     def readBookmarksFromDisk(self, filename=None):
  209.         """ Read saved bookmarks from disk.  Currently an unpickled object
  210.         that represents a bookmark """
  211.         filename = filename or self._script.name.split(' ')[0]
  212.         orcaDir = settings.userPrefsDir
  213.         orcaBookmarksDir = os.path.join(orcaDir, "bookmarks")
  214.         try:
  215.             inputFile = open( os.path.join( orcaBookmarksDir, \
  216.                         '%s.pkl' %filename), "r")
  217.             bookmarks = pickle.load(inputFile)
  218.             inputFile.close()
  219.             return bookmarks
  220.         except (IOError, EOFError, OSError):
  221.             return None
  222.  
  223.     def saveBookmarksToDisk(self, bookmarksObj, filename=None):
  224.         """ Write bookmarks to disk.  bookmarksObj must be a pickleable 
  225.         object. """
  226.         filename = filename or self._script.name.split(' ')[0]
  227.         orcaDir = settings.userPrefsDir
  228.         orcaBookmarksDir = os.path.join(orcaDir, "bookmarks")
  229.         # create directory if it does not exist.  correct place??
  230.         try:
  231.             os.stat(orcaBookmarksDir)
  232.         except OSError:
  233.             os.mkdir(orcaBookmarksDir)
  234.         output = open( os.path.join( orcaBookmarksDir, \
  235.                     '%s.pkl' %filename), "w", os.O_CREAT)
  236.         pickle.dump(bookmarksObj, output)
  237.         output.close()
  238.  
  239.     def _contextToBookmark(self, context):
  240.         """Converts a flat_review.Context object into a bookmark."""
  241.         context_info = {}
  242.         context_info['zone'] = context.zoneIndex
  243.         context_info['char'] = context.charIndex
  244.         context_info['word'] = context.wordIndex
  245.         context_info['line'] = context.lineIndex
  246.         return context_info
  247.  
  248.     def _bookmarkToContext(self, bookmark):
  249.         """Converts a bookmark into a flat_review.Context object."""
  250.         context = self._script.getFlatReviewContext()
  251.         context.setCurrent(bookmark['line'], bookmark['zone'], \
  252.                            bookmark['word'], bookmark['char'])
  253.         return context
  254.