[Idle-dev] [ idlefork-Patches-450716 ] Most Recently used files

noreply@sourceforge.net noreply@sourceforge.net
Sun, 07 Oct 2001 19:46:57 -0700


Patches item #450716, was opened at 2001-08-13 23:58
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=309579&aid=450716&group_id=9579

Category: None
Group: None
>Status: Pending
>Resolution: Postponed
Priority: 5
Submitted By: Chui Tey (teyc)
>Assigned to: Stephen M. Gava (elguavas)
Summary: Most Recently used files

Initial Comment:
*** old/EditorWindow.py	Sun Aug 12 22:06:16 2001
--- new/EditorWindow.py	Tue Aug 14 09:51:14 2001
***************
*** 15,20 ****
--- 15,21 ----
  
  import webbrowser
  import idlever
+ import MRUList
  import WindowList
  from IdleConf import idleconf
  
***************
*** 138,143 ****
--- 139,147 ----
          self.createmenubar()
          self.apply_bindings()
  
+         self.mrulist=MRUList.MRUList()
+         self.mrumenu=MRUList.MRUMenu(self.menudict
['file'], self.mrulist)
+ 
          self.top.protocol("WM_DELETE_WINDOW", 
self.close)
          self.top.bind("<<close-window>>", 
self.close_event)
          text.bind("<<center-insert>>", 
self.center_insert_event)
***************
*** 425,430 ****
--- 432,441 ----
              self.addcolorizer()
          else:
              self.rmcolorizer()
+         # update the MRU list, and the menu
+         if self.io.filename:
+             self.mrulist.add(self.io.filename)
+             self.mrumenu.update()
  
      def addcolorizer(self):
          if self.color:



#--------------------------------------------------
# MRUList.py
# Most Recently Used list of files
# 
# class MRUList - maintains a list of most recently 
used files
# class MRUMenu - creates a menu of most recently used 
files
#
import ConfigParser
from Tkinter import *

# Default section name
SECTION = 'MRUList'

class MRUList:
    """Maintains a most recently used file list.
       The list is stored in $HOME/.idle
       See also:
          MRUMenu (for presentational logic)
    """

    def __init__(self):        
        self.max  = 4
        self._list = []
        self._read()

    # PUBLIC Methods --------------------------------
    
    def add(self, filename):
        """Adds a new filename to the most recently 
used list
        """
        # maintain the MRU as a stack
        # with the most recent at the top of the stack
        # 
        self._read()   # get the latest from the 
config file
        if filename in self._list:
           self.delete(filename)
        self._list.append(filename)
        self._trim()
        self._write()  # write it back immediately, 
more crash-proof

    def delete(self, filename):
        """Removes a filename from the most recently 
used list.
        Should be called when the file no longer 
exists.
        """
        try:
           self._list.remove(filename)  
        except ValueError:
           # Just in case item doesn't exist
           pass

    def list(self):
        """List of most recently used files, newest at 
the end"""
        return self._list

    # PRIVATE Methods -------------------------------
    def __del__(self):
        #
        # Upon destruction, update the mrulist
        #
        self._trim()
        self._write()

    def __repr__(self):
        return ("max: %d\ncount: %d\n" % (self.max, len
(self._list)) \
                + `self._list`)

    def _getfilename(self):
        """Returns the file name of the config file"""
        # Copied from IdleConf.py
        import os
        try:
            homedir = os.environ['HOME']
        except KeyError:
            homedir = os.getcwd()
        return os.path.join(homedir, '.idle')

    def _trim(self):
        """Trims the MRU list to the maximum 
specified"""
        too_many = len(self._list) - self.max
        if too_many > 0:
           self._list = self._list[too_many:]  

    def _read(self):
        """Reads the config.txt for the list of MRU 
files"""
        self.conf = conf = ConfigParser.ConfigParser()
        conf.read(self._getfilename())
        if not conf.has_section(SECTION):
           conf.add_section(SECTION)
        try:
            self.max = max = conf.getint
(SECTION, 'max') 
            count = conf.getint(SECTION, 'count')
            for i in range(count):
                filename=conf.get(SECTION, "file%d" % 
(i+1))
                if not filename in self._list:
                    self._list.append(filename)
        except ConfigParser.NoOptionError:
            pass

    def _write(self):     
        """Writes the list of MRU files to .idle"""
        conf = self.conf
        conf.set(SECTION, 'enable', 0) # This is not 
an idle extension
        conf.set(SECTION, 'max', self.max)
        conf.set(SECTION, 'count', len(self._list))
        for i in range(len(self._list)):
            conf.set(SECTION, "file%d" % (i+1), 
self._list[i])
        conf.write(open(self._getfilename(),'wb'))
        
class MRUMenu(Menu):
    """Maintains a menu associated with an MRU List.
       When an item on the MRUList is selected, a 
callback
       function calls open() on the EditorWindow which 
owns the menu.
       See also:
           MRUList
    """

    def __init__(self, parent, mrulist):
        self.parent = parent     # parent window
        self.mrulist = mrulist   # instance of MRUList
        self.prev_mrumenus = {}  # previous mru list
        self.parent.add_separator()
        self.update()
         
    def update(self):
        """Updates the MRU menu"""
        #
        # Build a reversed list of MRU files
        #
        import copy
        list = copy.copy(self.mrulist.list())
        list.reverse()
        #
        # convert list to list of menu labels
        # 
        menulist = []
        for counter, filename in zip(range(len(list)), 
list):       
            label = "%d %s" % (counter+1, filename)
            menulist.append( (label, filename) )
        # 
        # replace invalid mru with valid ones
        #
        for index in range(len(menulist)):
          menulabel, filename = menulist[index]
          if self.prev_mrumenus.has_key( index ):
             menu_index = self.parent.index( 
self.prev_mrumenus[index] )
             self.parent.entryconfig(
                menu_index,             \
                label=menulabel,        \
                command=self._callback(filename))
             self.prev_mrumenus[index] = filename 
          else:
             self.parent.add_command(   \
                label=menulabel,        \
                underline=0,            \
                command = self._callback
(filename))        
             self.prev_mrumenus[index] = filename

    def _callback(self, filename):
        """Returns a callback function which opens a 
file with
        a given filename"""
        def open(filename=filename):
            #
            # XXX todo.
            open('test','a').write("Opening %s 
(MRUList.py)...\n" % filename)
        return open 

def test():
    mrulist = MRUList()
    mrulist.add('testMRU-1.py')
    mrulist.add('testMRU-2.py')
    mrulist.add('testMRU-3.py')
    mrulist.add('testMRU-4.py')
    mrulist.add('testMRU-5.py')
    mrulist.add('testMRU-6.py')
    print mrulist

if __name__ == '__main__':
    test()


----------------------------------------------------------------------

>Comment By: Stephen M. Gava (elguavas)
Date: 2001-10-07 19:46

Message:
Logged In: YES 
user_id=75867

an mru implementation is on our todo list, but it will have
to wait until after the new configuration handling is in
place

----------------------------------------------------------------------

You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=309579&aid=450716&group_id=9579