summaryrefslogtreecommitdiffstats
path: root/Mac/Contrib/PyIDE-src/IDELib/Widgets/PyConsole.py
blob: 8cb2e4bf16537f46e1ed6f33fb0de45bdea92af7 (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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import W
import Fm
from WASTEconst import *
from SpecialKeys import *
from types import *
import Events
import string
import sys,os
import traceback
import MacOS
import MacPrefs
import PyInteractive

if not hasattr(sys, 'ps1'):
	sys.ps1 = '>>> '
if not hasattr(sys, 'ps2'):
	sys.ps2 = '... '


class ConsoleTextWidget(W.EditText):
	
	def __init__(self, *args, **kwargs):
		apply(W.EditText.__init__, (self,) + args, kwargs)
		self._inputstart = 0
		self._buf = ''
		self.pyinteractive = PyInteractive.PyInteractive()
	
		import __main__
		self._namespace = __main__.__dict__
	
	def insert(self, text):
		self.checkselection()
		self.ted.WEInsert(text, None, None)
		self.changed = 1
		self.selchanged = 1
	
	def set_namespace(self, dict):
		if type(dict) <> DictionaryType:
			raise TypeError, "The namespace needs to be a dictionary"
		self._namespace = dict
	
	def open(self):
		W.EditText.open(self)
		self.write('Python ' + sys.version + '\n' + sys.copyright + '\n')
		self.write(sys.ps1)
		self.flush()
	
	def key(self, char, event):
		(what, message, when, where, modifiers) = event
		if self._enabled and not modifiers & Events.cmdKey or char in arrowkeys:
			if char not in navigationkeys:
				self.checkselection()
			if char == enterkey:
				char = returnkey
			selstart, selend = self.getselection()
			if char == backspacekey:
				if selstart <= (self._inputstart - (selstart <> selend)):
					return
			self.ted.WEKey(ord(char), modifiers)
			if char not in navigationkeys:
				self.changed = 1
			if char not in scrollkeys:
				self.selchanged = 1
			self.updatescrollbars()
			if char == returnkey:
				text = self.get()[self._inputstart:selstart]
				saveyield = MacOS.EnableAppswitch(0)
				self.pyinteractive.executeline(text, self, self._namespace)
				MacOS.EnableAppswitch(saveyield)
				selstart, selend = self.getselection()
				self._inputstart = selstart
	
	def domenu_save_as(self, *args):
		import macfs
		fss, ok = macfs.StandardPutFile('Save console text as:', 'console.txt')
		if not ok:
			return
		f = open(fss.as_pathname(), 'wb')
		f.write(self.get())
		f.close()
		fss.SetCreatorType(W._signature, 'TEXT')
	
	def write(self, text):
		self._buf = self._buf + text
		if '\n' in self._buf:
			self.flush()
	
	def flush(self):
		stuff = string.split(self._buf, '\n')
		stuff = string.join(stuff, '\r')
		self.setselection_at_end()
		self.ted.WEInsert(stuff, None, None)
		selstart, selend = self.getselection()
		self._inputstart = selstart
		self._buf = ""
		self.ted.WEClearUndo()
		self.updatescrollbars()
	
	def selection_ok(self):
		selstart, selend = self.getselection()
		return not (selstart < self._inputstart or selend < self._inputstart)
	
	def checkselection(self):
		if not self.selection_ok():
			self.setselection_at_end()
	
	def setselection_at_end(self):
		end = self.ted.WEGetTextLength()
		self.setselection(end, end)
		self.updatescrollbars()
		
	def domenu_cut(self, *args):
		if not self.selection_ok():
			return
		W.EditText.domenu_cut(self)
	
	def domenu_paste(self, *args):
		if not self.selection_ok():
			self.setselection_at_end()
		W.EditText.domenu_paste(self)
	
	def domenu_clear(self, *args):
		if not self.selection_ok():
			return
		W.EditText.domenu_clear(self)


class PyConsole(W.Window):
	
	def __init__(self, bounds, show = 1, fontsettings = ("Monaco", 0, 9, (0, 0, 0)), unclosable = 0):
		W.Window.__init__(self,
					bounds, 
					"Python Interactive", 
					minsize = (200, 100), 
					tabbable = 0, 
					show = show)
		
		self._unclosable = unclosable
		consoletext = ConsoleTextWidget((-1, -1, -14, 1), inset = (6, 5), fontsettings = fontsettings)
		self._bary = W.Scrollbar((-15, 14, 16, -14), consoletext.vscroll, max = 32767)
		self.consoletext = consoletext
		self.namespacemenu = W.PopupMenu((-15, -1, 16, 16), [], self.consoletext.set_namespace)
		self.namespacemenu.bind('<click>', self.makenamespacemenu)
		self.open()
	
	def makenamespacemenu(self, *args):
		W.SetCursor('watch')
		namespacelist = self.getnamespacelist()
		self.namespacemenu.set([("Font settingsŠ", self.dofontsettings), 
				["Namespace"] + namespacelist, ("Clear buffer", self.clearbuffer), ("Browse namespaceŠ", self.browsenamespace)])
		currentname = self.consoletext._namespace["__name__"]
		for i in range(len(namespacelist)):
			if namespacelist[i][0] == currentname:
				break
		else:
			return
		# XXX this functionality should be generally available in Wmenus
		submenuid = self.namespacemenu.menu.menu.GetItemMark(2)
		menu = self.namespacemenu.menu.bar.menus[submenuid]
		menu.menu.CheckItem(i + 1, 1)
	
	def browsenamespace(self):
		import PyBrowser, W
		W.SetCursor('watch')
		PyBrowser.Browser(self.consoletext._namespace, self.consoletext._namespace["__name__"])
	
	def clearbuffer(self):
		import Res
		self.consoletext.ted.WEUseText(Res.Resource(''))
		self.consoletext.write(sys.ps1)
		self.consoletext.flush()
	
	def getnamespacelist(self):
		import __main__
		editors = filter(lambda x: x.__class__.__name__ == "Editor", self.parent._windows.values())
		
		namespaces = [ ("__main__",__main__.__dict__) ]
		for ed in editors:
			modname = os.path.splitext(ed.title)[0]
			if sys.modules.has_key(modname):
				module = sys.modules[modname] 
				namespaces.append((modname, module.__dict__))
			else:
				if ed.title[-3:] == '.py':
					modname = ed.title[:-3]
				else:
					modname = ed.title
				ed.globals["__name__"] = modname
				namespaces.append((modname, ed.globals))
		return namespaces
	
	def dofontsettings(self):
		import FontSettings
		fontsettings = FontSettings.FontDialog(self.consoletext.getfontsettings())
		if fontsettings:
			self.consoletext.setfontsettings(fontsettings)
	
	def show(self, onoff = 1):
		W.Window.show(self, onoff)
		if onoff:
			self.select()
	
	def close(self):
		if self._unclosable:
			self.show(0)
			return -1
		W.Window.close(self)
	
	def writeprefs(self):
		prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
		prefs.console.show = self.isvisible()
		prefs.console.windowbounds = self.getbounds()
		prefs.console.fontsettings = self.consoletext.getfontsettings()
		prefs.save()


class OutputTextWidget(W.EditText):
	
	def _getflags(self):
		import WASTEconst
		return WASTEconst.weDoAutoScroll | WASTEconst.weDoMonoStyled | \
				WASTEconst.weDoUndo

class PyOutput:
	
	def __init__(self):
		self.w = None
		self.closed = 1
		self._buf = ''
		# should be able to set this
		self.savestdout, self.savestderr = sys.stdout, sys.stderr
		sys.stderr = sys.stdout = self
	
	def write(self, text):
		self._buf = self._buf + text
		if '\n' in self._buf:
			self.flush()
	
	def flush(self):
		self.show()
		stuff = string.split(self._buf, '\n')
		stuff = string.join(stuff, '\r')
		end = self.w.outputtext.ted.WEGetTextLength()
		self.w.outputtext.setselection(end, end)
		self.w.outputtext.ted.WEInsert(stuff, None, None)
		self._buf = ""
		self.w.outputtext.ted.WEClearUndo()
		self.w.outputtext.updatescrollbars()
	
	def show(self):
		if self.closed:
			if not self.w:
				self.setupwidgets()
				self.w.open()
				self.closed = 0
			else:
				self.w.show(1)
				self.closed = 0
				self.w.select()
	
	def setupwidgets(self): 
		self.w = W.Window((450, 200), "Output", minsize = (200, 100), tabbable = 0)
		self.w.outputtext = OutputTextWidget((-1, -1, -14, 1), inset = (6, 5))
		self.w._bary = W.Scrollbar((-15, -1, 16, -14), self.w.outputtext.vscroll, max = 32767)
		self.w.bind("<close>", self.close)
		self.w.bind("<activate>", self.activate)
	
	def activate(self, onoff):
		if onoff:
			self.closed = 0
	
	def close(self):
		self.w.show(0)
		self.closed = 1
		return -1


def installconsole(defaultshow = 1):
	global console
	prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
	if not prefs.console or not hasattr(prefs.console, 'show'):
		prefs.console.show = defaultshow
	if not hasattr(prefs.console, "windowbounds"):
		prefs.console.windowbounds = (450, 250)
	if not hasattr(prefs.console, "fontsettings"):
		prefs.console.fontsettings = ("Monaco", 0, 9, (0, 0, 0))
	console = PyConsole(prefs.console.windowbounds, prefs.console.show, prefs.console.fontsettings, 1)

def installoutput():
	global output
	output = PyOutput()