[Python-checkins] r65356 - in sandbox/trunk/ttk-gsoc/src/idlelib: EditorWindow.py FileList.py PyShell.py editorpage.py tabbedpages.py

guilherme.polo python-checkins at python.org
Fri Aug 1 04:14:30 CEST 2008


Author: guilherme.polo
Date: Fri Aug  1 04:14:29 2008
New Revision: 65356

Log:
FileList:
    canonize method is now just a function, and marked it as private;
    Changed filename_changed_edit signature, first step towards working with
     tabs.

EditorWindow:
    current_page method is now a read-only property;
    Marked several functions as private, since they are used nowhere else;
    Readded short_title method, which calls short_title in the current page;
    Moved open_module and find_module to editorpage;

editorpage:
    Moved some code at __init__ to a post_init() function to avoid troubles
     during page creation;

PyShell:
    Some better names, and other misc changes;

tabbedpages:
    Changed absolute imports to relative imports, following the rest of idlelib.


Modified:
   sandbox/trunk/ttk-gsoc/src/idlelib/EditorWindow.py
   sandbox/trunk/ttk-gsoc/src/idlelib/FileList.py
   sandbox/trunk/ttk-gsoc/src/idlelib/PyShell.py
   sandbox/trunk/ttk-gsoc/src/idlelib/editorpage.py
   sandbox/trunk/ttk-gsoc/src/idlelib/tabbedpages.py

Modified: sandbox/trunk/ttk-gsoc/src/idlelib/EditorWindow.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/src/idlelib/EditorWindow.py	(original)
+++ sandbox/trunk/ttk-gsoc/src/idlelib/EditorWindow.py	Fri Aug  1 04:14:29 2008
@@ -1,7 +1,6 @@
 import os
 import re
 import sys
-import imp
 import traceback
 import webbrowser
 import tkMessageBox
@@ -28,23 +27,6 @@
 # The default tab setting for a Text widget, in average-width characters.
 TK_TABWIDTH_DEFAULT = 8
 
-def _find_module(fullname, path=None):
-    """Version of imp.find_module() that handles hierarchical module names"""
-
-    file = None
-    for tgt in fullname.split('.'):
-        if file is not None:
-            file.close()            # close intermediate files
-        (file, filename, descr) = imp.find_module(tgt, path)
-        if descr[2] == imp.PY_SOURCE:
-            break                   # find but not load the source file
-        module = imp.load_module(tgt, file, filename, descr)
-        try:
-            path = module.__path__
-        except AttributeError:
-            raise ImportError, 'No source for module ' + module.__name__
-    return file, filename, descr
-
 class EditorWindow(object):
     from ColorDelegator import ColorDelegator # overridden by PyShell
     from UndoDelegator import UndoDelegator   # overridden by PyShell
@@ -126,18 +108,18 @@
         # reside
         self.text_notebook = TabbedPageSet(top)
         self.text_notebook.bind('<<NotebookTabChanged>>',
-            self.update_controls)
+            self._update_controls)
         self.new_tab(filename=filename)
-        self.text = text = self.current_page().text
+        self.text = text = self.current_page.text # XXX
         self.top.focused_widget = self.text
         self.text_notebook.pack(fill=BOTH, expand=True)
 
-        self.io = self.current_page().io
+        self.io = self.current_page.io
 
         # The following "width" attribute is used by PyShell, so keep it here
         self.width = idleConf.GetOption('main', 'EditorPage', 'width')
 
-        self.createmenubar()
+        self._createmenubar()
 
         self.top.protocol("WM_DELETE_WINDOW", self.close)
         self.top.bind("<<close-window>>", self.close_event)
@@ -147,12 +129,12 @@
             flist.inversedict[self] = key
             if key:
                 flist.dict[key] = self
-            text.bind("<<open-new-window>>", self.new_callback)
+            text.bind("<<open-new-window>>", self._new_callback)
             text.bind("<<close-all-windows>>", self.flist.close_all_callback)
-            text.bind("<<open-class-browser>>", self.open_class_browser)
-            text.bind("<<open-path-browser>>", self.open_path_browser)
+            text.bind("<<open-class-browser>>", self._open_class_browser)
+            text.bind("<<open-path-browser>>", self._open_path_browser)
 
-        self.create_statusbar()
+        self._create_statusbar()
         top.after_idle(self.set_line_and_column)
 
         # usetabs true  -> literal tab characters are used by indent and
@@ -219,12 +201,20 @@
         self.askinteger = tkSimpleDialog.askinteger
         self.showerror = tkMessageBox.showerror
 
-    def new_callback(self, event):
-        # XXX ??
-        current_page = self.current_page()
-        dirname, basename = current_page.io.defaultfilename()
-        self.flist.new(dirname)
-        return "break"
+    @property
+    def current_page(self):
+        """Return the active EditorPage in EditorWindow."""
+        curr_tab = self.text_notebook.select()
+        if TTK:
+            page = self.text_notebook.pages[self.text_notebook.tab(
+                curr_tab)['text']].editpage
+        else:
+            page = self.text_notebook.pages[curr_tab].editpage
+        return page
+
+    def short_title(self):
+        # overriden by PyShell
+        self.current_page.short_title()
 
     def next_tab(self, event):
         """Show next tab if not in the last tab already."""
@@ -245,14 +235,11 @@
         page_title = "#%d" % (len(self.text_notebook.pages) + 1)
         page = self.text_notebook.add_page(page_title)
 
-        if TTK:
-            parent = page.frame
-        else:
-            parent = page.frame
-
-        vbar = Scrollbar(parent, name='vbar')
-        page.editpage = EditorPage(parent, self, filename=filename, name='text',
+        vbar = Scrollbar(page.frame, name='vbar')
+        page.editpage = EditorPage(page.frame, self, name='text',
             padx=5, wrap='none')
+        page.editpage.post_init(filename=filename)
+
         text = page.editpage.text
 
         vbar['command'] = text.yview
@@ -272,43 +259,12 @@
 
         return "break"
 
-    def update_controls(self, event):
-        self.io = self.current_page().io
-        self.set_line_and_column()
-
-    def create_statusbar(self):
-        self.status_bar = MultiStatusBar(self.top)
-        if macosxSupport.runningAsOSXApp():
-            # Insert some padding to avoid obscuring some of the statusbar
-            # by the resize widget.
-            self.status_bar.set_label('_padding1', '    ', side=RIGHT)
-        self.status_bar.set_label('column', 'Col: ?', side=RIGHT)
-        self.status_bar.set_label('line', 'Ln: ?', side=RIGHT)
-        self.status_bar.pack(side=BOTTOM, fill=X)
-
     def set_line_and_column(self, event=None):
         # Used by PyShell too
-        line, column = self.current_page().text.index(INSERT).split('.')
+        line, column = self.current_page.text.index(INSERT).split('.')
         self.status_bar.set_label('column', 'Col: %s' % column)
         self.status_bar.set_label('line', 'Ln: %s' % line)
 
-    def createmenubar(self):
-        mbar = self.menubar
-        self.menudict = menudict = {}
-        for name, label in self.menu_specs:
-            underline, label = prepstr(label)
-            menudict[name] = menu = Menu(mbar, name=name, tearoff=0)
-            mbar.add_cascade(label=label, menu=menu, underline=underline)
-
-        if sys.platform == 'darwin' and '.framework' in sys.executable:
-            # Insert the application menu
-            menudict['application'] = menu = Menu(mbar, name='apple')
-            mbar.add_cascade(label='IDLE', menu=menu)
-
-        self.fill_menus()
-        self.base_helpmenu_length = self.menudict['help'].index(END)
-        self.reset_help_menu_entries()
-
     def postwindowsmenu(self):
         # Only called when Windows menu exists
         menu = self.menudict['windows']
@@ -319,79 +275,20 @@
             menu.delete(self.wmenu_end+1, end)
         WindowList.add_windows_to_menu(menu)
 
-    def open_module(self, event=None): # XXX depends on self.text
-        # XXX Shouldn't this be in IOBinding or in FileList?
-        try:
-            name = self.text.get("sel.first", "sel.last")
-        except TclError:
-            name = ""
-        else:
-            name = name.strip()
-        name = tkSimpleDialog.askstring("Module",
-                 "Enter the name of a Python module\n"
-                 "to search on sys.path and open:",
-                 parent=self.text, initialvalue=name)
-        if name:
-            name = name.strip()
-        if not name:
-            return
-        # XXX Ought to insert current file's directory in front of path
-        try:
-            (f, file, (suffix, mode, type)) = _find_module(name)
-        except (NameError, ImportError), msg:
-            tkMessageBox.showerror("Import error", str(msg), parent=self.text)
-            return
-        if type != imp.PY_SOURCE:
-            tkMessageBox.showerror("Unsupported type",
-                "%s is not a source module" % name, parent=self.text)
-            return
-        if f:
-            f.close()
-        if self.flist:
-            self.flist.open(file) # XXX change this to create a new tab instead
-        else:
-            self.io.loadfile(file)
-
-    def open_class_browser(self, event=None): # XXX depends on self.text
-        filename = self.io.filename
-        if not filename:
-            tkMessageBox.showerror(
-                "No filename",
-                "This buffer has no associated filename",
-                master=self.text)
-            self.text.focus_set()
-            return None
-        head, tail = os.path.split(filename)
-        base, ext = os.path.splitext(tail)
-        ClassBrowser.ClassBrowser(self.flist, base, [head])
-
-    def open_path_browser(self, event=None):
-        PathBrowser.PathBrowser(self.flist)
-
-    def current_page(self):
-        """Return the active EditorPage in EditorWindow."""
-        curr_tab = self.text_notebook.select()
-        if TTK:
-            page = self.text_notebook.pages[self.text_notebook.tab(
-                curr_tab)['text']].editpage
-        else:
-            page = self.text_notebook.pages[curr_tab].editpage
-        return page
-
     def newline_and_indent_event(self, event):
         """Call newline_and_indent_event on current EditorPage."""
-        self.current_page().newline_and_indent_event(event)
+        self.current_page.newline_and_indent_event(event)
 
     def get_selection_indices(self):
         """Call get_selection_indices on current EditorPage."""
-        return self.current_page().get_selection_indices()
+        return self.current_page.get_selection_indices()
 
     def build_char_in_string_func(self, startindex):
         """Call build_char_in_string_func on current EditorPage."""
-        return self.current_page().build_char_in_string_func(startindex)
+        return self.current_page.build_char_in_string_func(startindex)
 
     def gotoline(self, lineno):
-        page = self.current_page()
+        page = self.current_page
         text = page.text
 
         if lineno is not None and lineno > 0:
@@ -482,13 +379,6 @@
                             accel = get_accelerator(keydefs, event)
                             menu.entryconfig(index, accelerator=accel)
 
-    def set_notabs_indentwidth(self):
-        "Update the indentwidth if changed and not using tabs in this window"
-        # Called from configDialog.py
-        if not self.usetabs:
-            self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces',
-                                                  type='int')
-
     def reset_help_menu_entries(self):
         "Update the additional help entries on the Help menu"
         help_list = idleConf.GetAllExtraHelpSourcesList()
@@ -506,19 +396,16 @@
         # and update the menu dictionary
         self.menudict['help'] = helpmenu
 
-    def __extra_help_callback(self, helpfile):
-        "Create a callback with the helpfile value frozen at definition time"
-        def display_extra_help(helpfile=helpfile):
-            if not helpfile.startswith(('www', 'http')):
-                url = os.path.normpath(helpfile)
-            if sys.platform[:3] == 'win':
-                os.startfile(helpfile)
-            else:
-                webbrowser.open(helpfile)
-        return display_extra_help
+    def set_notabs_indentwidth(self):
+        "Update the indentwidth if changed and not using tabs in this window"
+        # Called from configDialog.py
+        if not self.usetabs:
+            self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces',
+                                                  type='int')
 
     def update_recent_files_list(self, new_file=None):
         "Load and update the recent files list and menus"
+        # IOBinding calls this
         rf_list = []
         if os.path.exists(self.recent_files_path):
             rf_list_file = open(self.recent_files_path,'r')
@@ -557,13 +444,8 @@
                                  command=callback,
                                  underline=0)
 
-    def __recent_file_callback(self, file_name):
-        def open_recent_file(fn_closure=file_name):
-            self.io.open(editFile=fn_closure)
-        return open_recent_file
-
     def get_saved(self):
-        return self.current_page().undo.get_saved() # XXX Pretty wrong
+        return self.current_page.undo.get_saved() # XXX Pretty wrong
 
     def get_geometry(self):
         "Return (width, height, x, y)"
@@ -636,7 +518,7 @@
         cls = getattr(mod, name)
         keydefs = idleConf.GetExtensionBindings(name)
         if hasattr(cls, "menudefs"):
-            self.fill_menus(cls.menudefs, keydefs)
+            self._fill_menus(cls.menudefs, keydefs)
         ins = cls(self)
         self.extensions[name] = ins
         if keydefs:
@@ -662,43 +544,6 @@
                 if keylist:
                     text.event_add(event, *keylist)
 
-    def fill_menus(self, menudefs=None, keydefs=None):# XXX depends on self.text
-        """Add appropriate entries to the menus and submenus
-
-        Menus that are absent or None in self.menudict are ignored.
-        """
-        if menudefs is None:
-            menudefs = Bindings.menudefs
-        if keydefs is None:
-            keydefs = Bindings.default_keydefs
-        menudict = self.menudict
-        text = self.text
-        for mname, entrylist in menudefs:
-            menu = menudict.get(mname)
-            if not menu:
-                continue
-            for entry in entrylist:
-                if not entry:
-                    menu.add_separator()
-                else:
-                    label, eventname = entry
-                    checkbutton = (label[:1] == '!')
-                    if checkbutton:
-                        label = label[1:]
-                    underline, label = prepstr(label)
-                    accelerator = get_accelerator(keydefs, eventname)
-                    def command(text=text, eventname=eventname):
-                        text.event_generate(eventname)
-                    if checkbutton:
-                        var = self.get_var_obj(eventname, BooleanVar)
-                        menu.add_checkbutton(label=label, underline=underline,
-                            command=command, accelerator=accelerator,
-                            variable=var)
-                    else:
-                        menu.add_command(label=label, underline=underline,
-                                         command=command,
-                                         accelerator=accelerator)
-
     def getvar(self, name):
         var = self.get_var_obj(name)
         if var:
@@ -767,6 +612,114 @@
             indentsmall = indentlarge = 0
         return indentlarge - indentsmall
 
+    # Private methods
+
+    def _update_controls(self, event):
+        self.io = self.current_page.io
+        self.set_line_and_column()
+
+    def _create_statusbar(self):
+        self.status_bar = MultiStatusBar(self.top)
+        if macosxSupport.runningAsOSXApp():
+            # Insert some padding to avoid obscuring some of the statusbar
+            # by the resize widget.
+            self.status_bar.set_label('_padding1', '    ', side=RIGHT)
+        self.status_bar.set_label('column', 'Col: ?', side=RIGHT)
+        self.status_bar.set_label('line', 'Ln: ?', side=RIGHT)
+        self.status_bar.pack(side=BOTTOM, fill=X)
+
+    def _createmenubar(self):
+        mbar = self.menubar
+        self.menudict = menudict = {}
+        for name, label in self.menu_specs:
+            underline, label = prepstr(label)
+            menudict[name] = menu = Menu(mbar, name=name, tearoff=0)
+            mbar.add_cascade(label=label, menu=menu, underline=underline)
+
+        if sys.platform == 'darwin' and '.framework' in sys.executable:
+            # Insert the application menu
+            menudict['application'] = menu = Menu(mbar, name='apple')
+            mbar.add_cascade(label='IDLE', menu=menu)
+
+        self._fill_menus()
+        self.base_helpmenu_length = self.menudict['help'].index(END)
+        self.reset_help_menu_entries()
+
+    def _fill_menus(self, menudefs=None, keydefs=None):
+        # XXX depends on self.text
+        """Add appropriate entries to the menus and submenus
+
+        Menus that are absent or None in self.menudict are ignored.
+        """
+        if menudefs is None:
+            menudefs = Bindings.menudefs
+        if keydefs is None:
+            keydefs = Bindings.default_keydefs
+        menudict = self.menudict
+        text = self.text
+        for mname, entrylist in menudefs:
+            menu = menudict.get(mname)
+            if not menu:
+                continue
+            for entry in entrylist:
+                if not entry:
+                    menu.add_separator()
+                else:
+                    label, eventname = entry
+                    checkbutton = (label[:1] == '!')
+                    if checkbutton:
+                        label = label[1:]
+                    underline, label = prepstr(label)
+                    accelerator = get_accelerator(keydefs, eventname)
+                    def command(text=text, eventname=eventname):
+                        text.event_generate(eventname)
+                    if checkbutton:
+                        var = self.get_var_obj(eventname, BooleanVar)
+                        menu.add_checkbutton(label=label, underline=underline,
+                            command=command, accelerator=accelerator,
+                            variable=var)
+                    else:
+                        menu.add_command(label=label, underline=underline,
+                                         command=command,
+                                         accelerator=accelerator)
+
+    def _new_callback(self, event):
+        dirname, basename = self.current_page.io.defaultfilename()
+        self.flist.new(dirname)
+        return "break"
+
+    def _open_class_browser(self, event=None):
+        filename = self.io.filename
+        if not filename:
+            tkMessageBox.showerror(
+                "No filename",
+                "This buffer has no associated filename",
+                master=self.text_notebook)
+            self.current_page.text.focus_set()
+            return None
+        head, tail = os.path.split(filename)
+        base, ext = os.path.splitext(tail)
+        ClassBrowser.ClassBrowser(self.flist, base, [head])
+
+    def _open_path_browser(self, event=None):
+        PathBrowser.PathBrowser(self.flist)
+
+    def __recent_file_callback(self, file_name):
+        def open_recent_file(fn_closure=file_name):
+            self.io.open(editFile=fn_closure)
+        return open_recent_file
+
+    def __extra_help_callback(self, helpfile):
+        "Create a callback with the helpfile value frozen at definition time"
+        def display_extra_help(helpfile=helpfile):
+            if not helpfile.startswith(('www', 'http')):
+                url = os.path.normpath(helpfile)
+            if sys.platform[:3] == 'win':
+                os.startfile(helpfile)
+            else:
+                webbrowser.open(helpfile)
+        return display_extra_help
+
 # Look at the leading whitespace in s.
 # Return pair (# of leading ws characters,
 #              effective # of leading blanks after expanding

Modified: sandbox/trunk/ttk-gsoc/src/idlelib/FileList.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/src/idlelib/FileList.py	(original)
+++ sandbox/trunk/ttk-gsoc/src/idlelib/FileList.py	Fri Aug  1 04:14:29 2008
@@ -1,6 +1,15 @@
 import os
 import tkMessageBox
 
+def _canonize(filename):
+    if not os.path.isabs(filename):
+        try:
+            pwd = os.getcwd()
+        except os.error:
+            pass
+        else:
+            filename = os.path.join(pwd, filename)
+    return os.path.normpath(filename)
 
 class FileList:
 
@@ -15,7 +24,7 @@
 
     def open(self, filename, action=None):
         assert filename
-        filename = self.canonize(filename)
+        filename = _canonize(filename)
         if os.path.isdir(filename):
             # This can happen when bad filename is passed on command line:
             tkMessageBox.showerror(
@@ -61,20 +70,20 @@
         if not self.inversedict:
             self.root.quit()
 
-    def filename_changed_edit(self, edit):
-        edit.saved_change_hook()
+    def filename_changed_edit(self, page, editwin):
+        page.saved_change_hook()
         try:
-            key = self.inversedict[edit]
+            key = self.inversedict[editwin]
         except KeyError:
             print "Don't know this EditorWindow object.  (rename)"
             return
-        filename = edit.io.filename
+        filename = page.io.filename
         if not filename:
             if key:
                 del self.dict[key]
             self.inversedict[edit] = None
             return
-        filename = self.canonize(filename)
+        filename = _canonize(filename)
         newkey = os.path.normcase(filename)
         if newkey == key:
             return
@@ -93,16 +102,6 @@
             except KeyError:
                 pass
 
-    def canonize(self, filename):
-        if not os.path.isabs(filename):
-            try:
-                pwd = os.getcwd()
-            except os.error:
-                pass
-            else:
-                filename = os.path.join(pwd, filename)
-        return os.path.normpath(filename)
-
 
 def _test():
     import sys

Modified: sandbox/trunk/ttk-gsoc/src/idlelib/PyShell.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/src/idlelib/PyShell.py	(original)
+++ sandbox/trunk/ttk-gsoc/src/idlelib/PyShell.py	Fri Aug  1 04:14:29 2008
@@ -122,11 +122,10 @@
         #self.breakpoints = []
         EditorWindow.__init__(self, *args)
 
-        self.top.bind('<<tab-created>>', self._configure_new_tab)
-        self._configure_new_tab()
-
         self.breakpointPath = os.path.join(idleConf.GetUserCfgDir(),
             'breakpoints.lst')
+        self.top.bind('<<tab-created>>', self._configure_new_tab)
+        self._configure_new_tab()
 
     def _configure_new_tab(self, event=None):
         page = self.text_notebook.last_page().editpage
@@ -140,7 +139,9 @@
         text.bind("<<open-python-shell>>", self.flist.open_shell)
 
         # whenever a file is changed, restore breakpoints
-        if page.io.filename: self.restore_file_breaks(text, page)
+        if page.io.filename:
+            self.restore_file_breaks(text, page)
+
         def filename_changed_hook(old_hook=page.io.filename_change_hook,
                                   self=self):
             self.restore_file_breaks(text, page)
@@ -1228,7 +1229,7 @@
             s = ""
         self.console.write(s)
 
-        curr_page = self.current_page()
+        curr_page = self.current_page
         curr_page.text.mark_set("insert", "end-1c")
         self.set_line_and_column()
         curr_page.io.reset_undo()
@@ -1412,13 +1413,13 @@
         # create base styles used along idle files
         style = Style()
 
-        x = style.map('.')
-        r = {'background': []}
-        for sspec in x.get('background', []):
+        rootbg = style.map('.', 'background')
+        fstyle = {'background': []}
+        for sspec in rootbg:
             if 'active' in sspec[:-1]:
-                r['background'].append(('!disabled', sspec[-1]))
+                fstyle['background'].append(('!disabled', sspec[-1]))
                 break
-        style.map('RootColor.TFrame', **r)
+        style.map('RootColor.TFrame', **fstyle)
         # end styles
 
     fixwordbreaks(root)

Modified: sandbox/trunk/ttk-gsoc/src/idlelib/editorpage.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/src/idlelib/editorpage.py	(original)
+++ sandbox/trunk/ttk-gsoc/src/idlelib/editorpage.py	Fri Aug  1 04:14:29 2008
@@ -1,6 +1,8 @@
 import os
 import sys
+import imp
 import webbrowser
+import tkMessageBox
 import tkSimpleDialog
 from Tkinter import Text, Menu, TclError
 
@@ -49,8 +51,26 @@
                 # byte-to-byte conversion
                 return filename.decode('iso8859-1')
 
-class EditorPage:
-    def __init__(self, parent_frame, editwin, filename=None, **kwargs):
+def _find_module(fullname, path=None):
+    """Version of imp.find_module() that handles hierarchical module names"""
+    file = None
+
+    for tgt in fullname.split('.'):
+        if file is not None:
+            file.close()            # close intermediate files
+        (file, filename, descr) = imp.find_module(tgt, path)
+        if descr[2] == imp.PY_SOURCE:
+            break                   # find but not load the source file
+        module = imp.load_module(tgt, file, filename, descr)
+        try:
+            path = module.__path__
+        except AttributeError:
+            raise ImportError('No source for module %s' % module.__name__)
+
+    return file, filename, descr
+
+class EditorPage(object):
+    def __init__(self, parent_frame, editwin, **kwargs):
         self.editwin = editwin
         kwargs.setdefault('width', idleConf.GetOption('main', 'EditorPage',
             'width'))
@@ -58,18 +78,20 @@
             'height'))
 
         self.text = MultiCallCreator(Text)(parent_frame, **kwargs)
-
         self.color = None # initialized in reset_colorizer
-
         self.per = Percolator(self.text)
         self.undo = self.editwin.UndoDelegator()
         self.per.insertfilter(self.undo)
         self.text.undo_block_start = self.undo.undo_block_start
         self.text.undo_block_stop = self.undo.undo_block_stop
-        self.undo.set_saved_change_hook(self.saved_change_hook)
-
         self.io = IOBinding.IOBinding(self)
+
+        self.undo.set_saved_change_hook(self.saved_change_hook)
         self.io.set_filename_change_hook(self.filename_change_hook)
+        self.reset_colorizer()
+        self._setup_bindings()
+
+    def post_init(self, filename=None):
         if filename:
             if os.path.exists(filename) and not os.path.isdir(filename):
                 self.io.loadfile(filename)
@@ -77,10 +99,6 @@
                 self.io.set_filename(filename)
         self.saved_change_hook()
 
-        self.reset_colorizer()
-
-        self._setup_bindings()
-
     def close(self):
         """Perform necessary cleanup for this page before closing it."""
         self.io.close()
@@ -97,7 +115,7 @@
 
     # XXX (1) mark where these functions are used
     def saved_change_hook(self):
-        short = self.short_title()
+        short = self.editwin.short_title()
         long = self.long_title()
 
         if short and long:
@@ -123,10 +141,15 @@
         self.undo.set_saved(flag)
 
     def filename_change_hook(self):
+        try:
+            print self, self.editwin, self.editwin.inversedict
+        except AttributeError: # PyShell
+            pass
+
         if self.editwin.flist:
-            self.editwin.flist.filename_changed_edit(self)
+            self.editwin.flist.filename_changed_edit(self, self.editwin)
         self.saved_change_hook()
-        self.editwin.top.update_windowlist_registry(self)
+        self.editwin.top.update_windowlist_registry(self.editwin)
         self.reset_colorizer()
 
     def reset_undo(self):
@@ -206,6 +229,7 @@
             # adjust indentation for continuations and block
             # open/close first need to find the last stmt
             lno = index2line(text.index('insert'))
+            #print self.editwin.indentwidth, self.editwin.tabwidth
             y = PyParse.Parser(self.editwin.indentwidth, self.editwin.tabwidth)
             if not self.editwin.context_use_ps1:
                 for context in self.editwin.num_context_lines:
@@ -300,7 +324,7 @@
     def _setup_bindings(self):
         text = self.text
         actions = ('<<close-tab>>', '<<help>>', '<<python-docs>>',
-            '<<about-idle>>', '<<open-config-dialog>>',
+            '<<about-idle>>', '<<open-config-dialog>>', '<<open-module>>',
             '<<cut>>', '<<copy>>', '<<paste>>', '<<select-all>>',
             '<<remove-selection>>', '<<del-word-left>>', '<<del-word-right>>',
             '<<beginning-of-line>>')
@@ -322,8 +346,7 @@
             method_name = event[prefix_size:-prefix_size].replace('-', '_')
             text.bind(event, getattr(self, "_%s_event" % method_name.lower()))
 
-        parent_actions = ('<<new-tab>>', '<<next-tab>>', '<<prev-tab>>',
-            '<<open-module>>')
+        parent_actions = ('<<new-tab>>', '<<next-tab>>', '<<prev-tab>>')
 
         for action in parent_actions:
             prefix_size = action.count('<')
@@ -368,6 +391,42 @@
         # parent
         configDialog.ConfigDialog(self.editwin.top, 'Settings')
 
+     def _open_module(self, event=None):
+        try:
+            name = self.text.get("sel.first", "sel.last")
+        except TclError:
+            name = ""
+        else:
+            name = name.strip()
+
+        name = tkSimpleDialog.askstring("Module",
+            "Enter the name of a Python module\n"
+            "to search on sys.path and open:",
+            parent=self.text, initialvalue=name)
+
+        if name:
+            name = name.strip()
+        if not name:
+            return
+        # XXX Ought to insert current file's directory in front of path
+        try:
+            (f, file, (suffix, mode, type)) = _find_module(name)
+        except (NameError, ImportError), msg:
+            tkMessageBox.showerror("Import error", str(msg), parent=self.text)
+            return
+
+        if type != imp.PY_SOURCE:
+            tkMessageBox.showerror("Unsupported type",
+                "%s is not a source module" % name, parent=self.text)
+            return
+        if f:
+            f.close()
+        if self.editwin.flist: # XXX
+            # XXX change this to create a new tab instead
+            self.editwin.flist.open(file)
+        else:
+            self.io.loadfile(file)
+
     def _find_event(self, event):
         SearchDialog.find(self.text)
         return "break"

Modified: sandbox/trunk/ttk-gsoc/src/idlelib/tabbedpages.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/src/idlelib/tabbedpages.py	(original)
+++ sandbox/trunk/ttk-gsoc/src/idlelib/tabbedpages.py	Fri Aug  1 04:14:29 2008
@@ -5,8 +5,8 @@
 def get_tabbedpage():
     """Returns the TabbedPageSet available for use."""
     try:
-        from idlelib.tabbedpages_new import TabbedPageSet
+        from tabbedpages_new import TabbedPageSet
     except ImportError:
-        from idlelib.tabbedpages_old import TabbedPageSet
+        from tabbedpages_old import TabbedPageSet
 
     return TabbedPageSet


More information about the Python-checkins mailing list