summaryrefslogtreecommitdiffstats
path: root/Lib/idlelib/OutputWindow.py
blob: 12280ad4d70fd671c9b37c95e4a99d145a40414b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# changes by dscherer@cmu.edu
#   - OutputWindow and OnDemandOutputWindow have been hastily
#     extended to provide readline() support, an "iomark" separate
#     from the "insert" cursor, and scrolling to clear the window.
#     These changes are used by the ExecBinding module to provide
#     standard input and output for user programs.  Many of the new
#     features are very similar to features of PyShell, which is a
#     subclass of OutputWindow.  Someone should make some sense of
#     this.

from Tkinter import *
from EditorWindow import EditorWindow
import re
import tkMessageBox

from UndoDelegator import UndoDelegator

class OutputUndoDelegator(UndoDelegator):
    reading = 0
    # Forbid insert/delete before the I/O mark, in the blank lines after
    #   the output, or *anywhere* if we are not presently doing user input
    def insert(self, index, chars, tags=None):
        try:
            if (self.delegate.compare(index, "<", "iomark") or
                self.delegate.compare(index, ">", "endmark") or
                (index!="iomark" and not self.reading)):
                self.delegate.bell()
                return
        except TclError:
            pass
        UndoDelegator.insert(self, index, chars, tags)
    def delete(self, index1, index2=None):
        try:
            if (self.delegate.compare(index1, "<", "iomark") or
                self.delegate.compare(index1, ">", "endmark") or
                (index2 and self.delegate.compare(index2, ">=", "endmark")) or
                not self.reading):
                self.delegate.bell()
                return
        except TclError:
            pass
        UndoDelegator.delete(self, index1, index2)

class OutputWindow(EditorWindow):
    """An editor window that can serve as an input and output file.
       The input support has been rather hastily hacked in, and should
       not be trusted.
    """

    UndoDelegator = OutputUndoDelegator
    source_window = None

    def __init__(self, *args, **keywords):
        if keywords.has_key('source_window'):
            self.source_window = keywords['source_window']
        apply(EditorWindow.__init__, (self,) + args)
        self.text.bind("<<goto-file-line>>", self.goto_file_line)
        self.text.bind("<<newline-and-indent>>", self.enter_callback)
        self.text.mark_set("iomark","1.0")
        self.text.mark_gravity("iomark", LEFT)
        self.text.mark_set("endmark","1.0")

    # Customize EditorWindow

    def ispythonsource(self, filename):
        # No colorization needed
        return 0

    def short_title(self):
        return "Output"

    def long_title(self):
        return ""

    def maybesave(self):
        # Override base class method -- don't ask any questions
        if self.get_saved():
            return "yes"
        else:
            return "no"

    # Act as input file - incomplete

    def set_line_and_column(self, event=None):
        index = self.text.index(INSERT)
        if (self.text.compare(index, ">", "endmark")):
          self.text.mark_set("insert", "endmark")
        self.text.see("insert")
        EditorWindow.set_line_and_column(self)

    reading = 0
    canceled = 0
    endoffile = 0

    def readline(self):
        save = self.reading
        try:
            self.reading = self.undo.reading = 1
            self.text.mark_set("insert", "iomark")
            self.text.see("insert")
            self.top.mainloop()
        finally:
            self.reading = self.undo.reading = save
        line = self.text.get("input", "iomark")
        if self.canceled:
            self.canceled = 0
            raise KeyboardInterrupt
        if self.endoffile:
            self.endoffile = 0
            return ""
        return line or '\n'

    def close(self):
        self.interrupt()
        return EditorWindow.close(self)

    def interrupt(self):
        if self.reading:
            self.endoffile = 1
            self.top.quit()

    def enter_callback(self, event):
        if self.reading and self.text.compare("insert", ">=", "iomark"):
            self.text.mark_set("input", "iomark")
            self.text.mark_set("iomark", "insert")
            self.write('\n',"iomark")
            self.text.tag_add("stdin", "input", "iomark")
            self.text.update_idletasks()
            self.top.quit() # Break out of recursive mainloop() in raw_input()

        return "break"

    # Act as output file

    def write(self, s, tags=(), mark="iomark"):
        self.text.mark_gravity(mark, RIGHT)
        self.text.insert(mark, str(s), tags)
        self.text.mark_gravity(mark, LEFT)
        self.text.see(mark)
        self.text.update()

    def writelines(self, l):
        map(self.write, l)

    def flush(self):
        pass

    # Our own right-button menu

    rmenu_specs = [
        ("Go to file/line", "<<goto-file-line>>"),
    ]

    file_line_pats = [
        r'file "([^"]*)", line (\d+)',
        r'([^\s]+)\((\d+)\)',
        r'([^\s]+):\s*(\d+):',
    ]

    file_line_progs = None

    def goto_file_line(self, event=None):
        if self.file_line_progs is None:
            l = []
            for pat in self.file_line_pats:
                l.append(re.compile(pat, re.IGNORECASE))
            self.file_line_progs = l
        # x, y = self.event.x, self.event.y
        # self.text.mark_set("insert", "@%d,%d" % (x, y))
        line = self.text.get("insert linestart", "insert lineend")
        result = self._file_line_helper(line)
        if not result:
            # Try the previous line.  This is handy e.g. in tracebacks,
            # where you tend to right-click on the displayed source line
            line = self.text.get("insert -1line linestart",
                                 "insert -1line lineend")
            result = self._file_line_helper(line)
            if not result:
                tkMessageBox.showerror(
                    "No special line",
                    "The line you point at doesn't look like "
                    "a valid file name followed by a line number.",
                    master=self.text)
                return
        filename, lineno = result
        edit = self.untitled(filename) or self.flist.open(filename)
        edit.gotoline(lineno)
        edit.wakeup()

    def untitled(self, filename):
        if filename!='Untitled' or not self.source_window or self.source_window.io.filename:
            return None
        return self.source_window

    def _file_line_helper(self, line):
        for prog in self.file_line_progs:
            m = prog.search(line)
            if m:
                break
        else:
            return None
        filename, lineno = m.group(1, 2)
        if not self.untitled(filename):
            try:
                f = open(filename, "r")
                f.close()
            except IOError:
                return None
        try:
            return filename, int(lineno)
        except TypeError:
            return None

# This classes now used by ExecBinding.py:

class OnDemandOutputWindow:
    source_window = None

    tagdefs = {
        # XXX Should use IdlePrefs.ColorPrefs
        "stdin":   {"foreground": "black"},
        "stdout":  {"foreground": "blue"},
        "stderr":  {"foreground": "red"},
    }   
    
    def __init__(self, flist):
        self.flist = flist
        self.owin = None
        self.title = "Output"
        self.close_hook = None
        self.old_close = None

    def owclose(self):
        if self.close_hook:
            self.close_hook()
        if self.old_close:
            self.old_close()

    def set_title(self, title):
        self.title = title
        if self.owin and self.owin.text:
          self.owin.saved_change_hook()

    def write(self, s, tags=(), mark="iomark"):
        if not self.owin or not self.owin.text:
            self.setup()
        self.owin.write(s, tags, mark)

    def readline(self):
        if not self.owin or not self.owin.text:
            self.setup()
        return self.owin.readline()

    def scroll_clear(self):
        if self.owin and self.owin.text:
           lineno = self.owin.getlineno("endmark")
           self.owin.text.mark_set("insert","endmark")
           self.owin.text.yview(float(lineno))
           self.owin.wakeup()
    
    def setup(self):
        self.owin = owin = OutputWindow(self.flist, source_window = self.source_window)
        owin.short_title = lambda self=self: self.title
        text = owin.text

        self.old_close = owin.close_hook
        owin.close_hook = self.owclose

        # xxx Bad hack: 50 blank lines at the bottom so that
        #     we can scroll the top of the window to the output
        #     cursor in scroll_clear().  There must be a better way...
        owin.text.mark_gravity('endmark', LEFT)
        owin.text.insert('iomark', '\n'*50)
        owin.text.mark_gravity('endmark', RIGHT)
        
        for tag, cnf in self.tagdefs.items():
            if cnf:
                apply(text.tag_configure, (tag,), cnf)
        text.tag_raise('sel')