File: DebugConsole.py

package info (click to toggle)
oolite 1.77.1-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 41,264 kB
  • ctags: 5,362
  • sloc: objc: 132,090; ansic: 10,457; python: 2,225; sh: 1,325; makefile: 332; perl: 259; xml: 125; php: 5
file content (431 lines) | stat: -rwxr-xr-x 11,909 bytes parent folder | download
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#! /usr/bin/python
#
#  DebugConsole.py
#  pythonDebugConsole
#
#  Created by Jens Ayton on 2007-11-29.
#  Copyright (c) 2007 Jens Ayton. All rights reserved.
#
#  GUI I/O stuff (c) 2008-2013 Kaks. CC-by-NC-SA 3
#

"""
A gui implementation of the Oolite JavaScript debug console interface.
"""

__author__	= "Jens Ayton <jens@ayton.se>, Kaks"
__version__	= "1.5"


from ooliteConsoleServer import *
from twisted.internet.protocol import Factory
from twisted.internet import stdio, reactor, tksupport
from OoliteDebugCLIProtocol import OoliteDebugCLIProtocol
from Tkinter import *

import string, os, ConfigParser, pickle


CFGFILE = 'DebugConsole.cfg'
# if we're using the compiled version, it's OoDebugConsole.cfg rather than DebugConsole.cfg
if hasattr (sys,'frozen'): CFGFILE = 'Oo' + CFGFILE

# use a corresponding cli history file.
HISTFILE = CFGFILE.replace('.cfg','.dat')

class SimpleConsoleDelegate:
	__active = Active = False
	
	def __init__(self, protocol):
		self.protocol = protocol
		self.identityString = "DebugConsole"
	
	def __del__(self):
		if self.__active: self.protocol.factory.activeCount -= 1
		if cliHandler.inputReceiver is self:  cliHandler.inputReceiver = None
	
	def acceptConnection(self):
		return self.protocol.factory.activeCount < 1
	
	def connectionOpened(self, ooliteVersionString):
		app.Print ("Opened connection with Oolite version "+ ooliteVersionString)
		self.protocol.factory.activeCount += 1
		self.__active = self.Active = True
		cliHandler.inputReceiver = self
	
	def connectionClosed(self, message):
		if message is None or isinstance(message, str):
			if message is not None and len(message) > 0:
				app.Print ('Connection closed:"' + message +'"')
			else:
				app.Print ("Connection closed with no message.")
		if self.__active:
			self.protocol.factory.activeCount -= 1
			self.__active = self.Active = False
		app.tried=0
	
	def writeToConsole(self, message, colorKey, emphasisRanges):
		app.colPrint(message, colorKey)
	
	def clearConsole(self):
		app.cClear(True)
		
	def showConsole(self):
		if (ENABLESHOW):
			if root.state() is not 'zoomed' and root.state() is not 'normal': root.state('normal')
			root.wm_attributes("-topmost", 1)
			root.wm_attributes("-topmost", 0)
			app.cli.focus_set()
	
	def send(string):
		receiveUserInput(string)
	
	def receiveUserInput(self, string):
		self.protocol.sendCommand(string)
	
	def closeConnection(self, message):
		self.protocol.closeConnection(message)

def getInputReceiver():
	return currentInputReceiver


class Window:
	def __init__(self,master):
		self.tried=0
		
		self.frame = Frame(master)
		self.frame.place(relwidth=1, relheight=1, height=-60)
		
		self.yScroll = Scrollbar (self.frame, orient=VERTICAL, width=16)
		self.yScroll.pack(side=LEFT, anchor=E, fill=Y, expand=YES)
		
		self.BodyText = Text(self.frame,bg="#dadddd", bd=0, padx=2, font=('arial', 10, 'normal'), wrap=WORD, yscrollcommand=self.yScroll.set)
		
		self.BodyText.tag_config('dbg')
		self.BodyText.place(relwidth=1, relheight=1, width=-16)
		
		self.yScroll.config(command=self.BodyText.yview)
		
		self.cliBox = Frame(master)
		self.cliBox.place(rely=1,anchor=SW, relwidth=1, height=60)
		
		self.cli = Text(self.cliBox, bd=2, relief=FLAT, bg="#fff",font=('arial', 10, 'normal'))
		self.cli.place(relwidth=1,relheight=1,width=-50)
		self.cli.bind('<Return>', self.cRet)
		self.cli.bind("<Up>", self.cHistoryBack)
		self.cli.bind("<Down>", self.cHistoryForward)
		
		self.cli.focus_set()
		
		self.btnRun = Button(self.cliBox, text=" Run", bg='#ccc', command=self.cRun)
		self.btnRun.place(anchor=NE, relx=1, height=38, width=50)
		self.btnExit = Button(self.cliBox, bg='#ddd', text=" Clear", command=self.cClear)
		self.btnExit.place(anchor=NE, relx=1, y=38, height=22, width=50)
		
		# Command history
		
		self.history = []
		self.historyIdx = None
		self.current = ""
		
	def cRet(self,event):
		self.cRun()
		return 'break'
	
	def cRun(self):
		if '/quit' == self.cli.get( '1.0', END)[:5]:
			self.cExit()
		else:
			self.historyIdx = None
			self.CMD = self.cli.get( '1.0', END)
			idx = len(self.history) - 1;
			if string.strip(self.CMD) and (idx < 0 or self.CMD != self.history[idx]):
				self.history.append(self.CMD)		
			if hasattr (cliHandler.inputReceiver,'receiveUserInput') and cliHandler.inputReceiver.Active:
				self.tried = 0
				cliHandler.inputReceiver.receiveUserInput(self.CMD)
				self.cli.delete( '1.0', END) 
			else:
				if self.tried == 0:
					self.Print("\n"+CONNECTINFO+"\nYou can only use the console after you're connected.")
				elif self.tried == 1:
					self.Print(' * Please connect to Oolite first! * ')
				self.tried=self.tried+1
		
	def Print(self,s):
		self.colPrint(s,'dbg')
	
	def colPrint(self,s,colkey):
		colkey = colkey.lower()
		isDbg = True
		if colkey != 'dbg':
			isDbg = False
			s = s.strip(' \t\n\r')
			if len(s) >0: s = s + '\n'
		
		txt = self.BodyText
		try:
			if not isDbg: tmp = COLORS[colkey]
		except Exception:
			if (DEBUGCOLS): s = '['+colkey+'] ' + s
			colkey = 'dbg'
			isDbg = True
		
		txt.config(state=NORMAL)
		txt.insert(END,s,colkey)
		if len(s) < 1 or isDbg: txt.insert(END,'\n','dbg')
		txt.config(state=DISABLED)
		txt.see(END)
		txt.tag_raise('sel')
	
	def cClear(self,body=False):
		if body or OLDCLEAR:
			self.tried = 0
			self.BodyText.config(state=NORMAL)
			self.BodyText.delete('1.0', END)
			self.BodyText.config(state=DISABLED)
		else:
			self.cli.delete('1.0', END)
	
	def cHistoryBack(self, event):
		if self.history:
			if self.historyIdx is None:
				self.current = self.cli.get( '1.0', END)
				self.historyIdx = len(self.history) - 1
			elif self.historyIdx > 0:
				self.historyIdx -= 1
			self.cHistoryShow()
		return 'break'
	
	def cHistoryForward(self, event):
		if self.history and self.historyIdx is not None:
			self.historyIdx += 1
			if self.historyIdx < len(self.history):
				self.cHistoryShow()
			else:
				self.historyIdx = None
				self.cHistoryShow(self.current)
		return 'break'
	
	def cHistoryShow(self, cmd=None):
		if cmd is None:
			cmd = self.history[self.historyIdx]
		self.cli.delete('1.0', END)
		self.cli.insert(END,cmd.rstrip())
	
	def cExit(self_):
		saveConfig = True
		saveHistory = True
		config = ConfigParser.RawConfigParser()
		config.optionxform = str
		try:
			fp = open(CFGFILE)
			config.readfp(fp)
			try:
				saveConfig = config.getboolean('Settings','SaveConfigOnExit')
			except:
				pass
			try:
				saveHistory = config.getboolean('Settings','SaveHistoryOnExit')
			except:
				pass
			fp.close()
		except Exception: 
			pass
		
		if saveConfig:
			try:
				if not config.has_section('Settings'):
					config.add_section('Settings')
				config.set('Settings', 'SaveConfigOnExit', 'Yes')
				config.set('Settings', 'Geometry', root.geometry())
				cfg = open(CFGFILE, 'w')
				config.write(cfg)
				cfg.close()
			except Exception:
				pass
		if saveHistory:
			try:
				hfile = open(HISTFILE, 'wb')
				pickle.dump(app.history[-200:], hfile, -1)
				hfile.close()
			except Exception:
				pass
		
		reactor.stop()


root = Tk()
app = Window(root)
root.minsize(320, 300)
root.resizable(YES, YES)
root.title("Oolite - Javascript Debug Console")
root.protocol("WM_DELETE_WINDOW", app.cExit)


# Load initial settings
consolePort = None
DEBUGCOLS = False
ENABLESHOW = True
OLDCLEAR = False
CONNECTINFO = "Please (re)start Oolite in order to connect."
initConfig = ConfigParser.RawConfigParser()
try:
	fp = open(CFGFILE)
	initConfig.readfp(fp)
	fp.close()
	try:
		settings = initConfig.get('Settings','Geometry')
	except:
		pass
	try:
		consolePort = initConfig.get('Settings','Port')
	except:
		pass
	try:
		DEBUGCOLS = initConfig.getboolean('Settings','DebugColors')
	except:
		pass
	try:
		ENABLESHOW = initConfig.getboolean('Settings','EnableShowConsole')
	except:
		pass
	try:
		OLDCLEAR = initConfig.getboolean('Settings','OldClearBehaviour')
	except:
		pass
	try:
		CONNECTINFO = initConfig.get('Settings','ConnectInfo')
	except:
		pass

except Exception: 
	pass
# if size & position settings are not valid, revert to default
try:
	root.geometry(settings)
except Exception:
	root.geometry("500x380")


# Set up icon if possible
try:
#	windows compiled runtime (pyInstall)
	root.iconbitmap(os.path.join(os.environ['_MEIPASS2'], "OoJSC.ico"))
except Exception:
	try: 
# 	normal windows runtime
		root.iconbitmap("OoJSC.ico")
	except Exception:
#	other runtimes, try not to use the tk icon
		try:
			root.iconbitmap('@block.xbm')
		except Exception:
			pass

# Set up the console's port using the Port setting inside the .cfg file.
# All dynamic, private, or ephemeral ports 'should' be between 49152-65535. However, the default port is 8563.
connectPort = defaultOoliteConsolePort
if consolePort is not None:
	try:
		consolePort = int(consolePort)
	except:
		pass
	if consolePort > 1 and consolePort < 65536:
		connectPort = consolePort
		app.Print ("Listening on port " + str(connectPort) +".")
		root.title("Oolite - Javascript Debug Console:" + str(connectPort))
	else:
		app.Print ("Invalid port specified. Using default port (" + str(connectPort) +").")

# Set up Colors:
COLORS = {'general':'#000','command':'#006','warning':'#660','error':'#800','exception':'#808'}

COLORS['command-result'] = '#050'
COLORS['command-error'] = '#600'

COLORS['macro-expansion'] = '#999'
COLORS['macro-warning'] = '#aa5'
COLORS['macro-list'] = '#5a5'

COLORS['unknown-macro'] = '#aa5'
COLORS['macro-error'] = '#a55'
COLORS['macro-info'] = '#5a5'
COLORS['command-exception'] = '#606'

txt = app.BodyText
txt.tag_configure('sel', foreground ='#dcecf2', background='#5c6070')

if initConfig.has_section('Colors'):
	cols = initConfig.options('Colors')
	for col in cols:
		try:
			tmp = initConfig.get('Colors', col)
			txt.tag_configure('tmp', foreground=tmp)
			COLORS[col.lower()] = tmp
		except:
			if DEBUGCOLS: app.Print(" CFG Error: "+col+" = "+tmp+" -  wrong value '"+tmp+"'")
if float(txt.index(END)) > 2: app.Print('')
			
for col,val in COLORS.items():
	txt.tag_configure(col, foreground=val)
	if col is 'command': txt.tag_configure(col, font=('arial',9,'bold'), background='#e8ebeb')

#app.Print(COLORS)

# Restore CLI history from its savefile
try:
	hfile = open(HISTFILE, 'rb')
	app.history = pickle.load(hfile)
	hfile.close()
	if not isinstance(app.history, list):
		app.history = []
except:
	pass

# Set up console server protocol
factory = Factory()
factory.delegateClass = SimpleConsoleDelegate
factory.activeCount = 0
factory.protocol = OoliteDebugConsoleProtocol

# Set up command line I/O protocol
cliHandler = OoliteDebugCLIProtocol()
cliHandler.getInputReceiver = getInputReceiver
stdio.StandardIO(cliHandler)

# Install the Reactor support
tksupport.install(root)

try:
	app.listener=reactor.listenTCP(connectPort, factory)
	app.Print ("Use Up and Down arrows to scroll through the command history.")
	app.Print ("Type /quit to quit.")
	app.Print ("Waiting for connection...")
except Exception, e:
	oops = str(e)
#	oops = "\nAnother process is already listening on "
#	oops += "\nthe default port." if (connectPort == defaultOoliteConsolePort) else "port " + str(connectPort) +"."
	oops += "\n\nThis debug console will close now."
	root.minsize(1, 1)
	root.resizable(NO, NO)
	root.geometry("320x166")
	root.protocol("WM_DELETE_WINDOW", reactor.stop)
	app.yScroll.pack_forget()
	app.btnOK = Button(app.cliBox, text="OK", bg='#eee', font=('arial', 17, 'bold'), command=reactor.stop)
	app.btnOK.place(relwidth=1,relheight=1)

	txt.place(width=0)
	txt.configure(bg="#fffdfd")
	txt.config(state=NORMAL)
	txt.delete('1.0', END)
	txt.tag_configure('header', justify=CENTER, font=('arial', 11, 'bold'), foreground='#600')
	txt.tag_configure('center', justify=CENTER)
	txt.insert(END,'\nInitialisation Error\n\n','header')
	txt.insert(END,oops,'center')
	root.geometry("320x" + str(int((float(txt.index(END))-5)*16 + 166)))
	txt.config(state=DISABLED)

# Wait for user input.
reactor.run()