summaryrefslogtreecommitdiff
path: root/portato/gui/qt/terminal.py
blob: eabe467abba98d60b91d1065031d2f6201e825b2 (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
# -*- coding: utf-8 -*-
#
# File: portato/gui/qt/terminal.py
# This file is part of the Portato-Project, a graphical portage-frontend.
#
# Copyright (C) 2007 René 'Necoro' Neumann
# This is free software.  You may redistribute copies of it under the terms of
# the GNU General Public License version 2.
# There is NO WARRANTY, to the extent permitted by law.
#
# Written by René 'Necoro' Neumann <necoro@necoro.net>

from PyQt4 import QtGui, QtCore

from threading import Thread, Lock
from os import read

from portato.gui.wrapper import Console
from portato.helper import debug

class BoldFormat (QtGui.QTextCharFormat):

	def __init__(self):
		QtGui.QTextCharFormat.__init__(self)
		self.setFontWeight(QtGui.QFont.Bold)

class UnderlineFormat (QtGui.QTextCharFormat):

	def __init__(self):
		QtGui.QTextCharFormat.__init__(self)
		self.setFontUnderline(True)

class ColorFormat (QtGui.QTextCharFormat):

	def __init__(self, color):
		QtGui.QTextCharFormat.__init__(self)

		self.setForeground(QtGui.QBrush(QtGui.QColor(color)))

# we only support a subset of the commands
esc_seq = ("\x1b", "[")
reset_seq = "39;49;00"
seq_end = "m"
seq_sep = ";"
backspace = 8
title_seq = ("\x1b", "]")
title_end = "\x07"

attr = {}
attr[0]			=  	None 				# normal
attr[1]			=  	BoldFormat()	 	# bold
attr[4]    		=  	UnderlineFormat()	# underline
attr[30]        =  	ColorFormat("black")
attr[31]        =	ColorFormat("red")
attr[32]        = 	ColorFormat("green")
attr[33]       	= 	ColorFormat("yellow")
attr[34]        = 	ColorFormat("blue")
attr[35]      	= 	ColorFormat("magenta")
attr[36]        = 	ColorFormat("cyan")
attr[37]        = 	ColorFormat("white")
attr[39]      	= 	None				# default

class QtConsole (Console, QtGui.QTextEdit):

	def __init__ (self, parent):
		QtGui.QTextEdit.__init__(self, parent)

		self.pty = None
		self.running = False
		self.stdFormat = self.currentCharFormat()
		self.formatQueue = []
		self.formatLock = Lock()
		self.title = None

		self.setReadOnly(True)

		QtCore.QObject.connect(self, QtCore.SIGNAL("doSomeWriting"), self._write)
		QtCore.QObject.connect(self, QtCore.SIGNAL("deletePrevChar()"), self._deletePrev)

	def _deletePrev (self):
		self.textCursor().deletePreviousChar()

	def _write (self, text):
		if text == esc_seq[0]:
			self.setCurrentCharFormat(self.get_format())
		else:
			
			if not self.textCursor().atEnd(): # move cursor and re-set format
				f = self.currentCharFormat()
				self.moveCursor(QtGui.QTextCursor.End)
				self.setCurrentCharFormat(f)
			
			# insert the text
			self.textCursor().insertText(text)
			
			# scroll down if needed
			self.ensureCursorVisible()

	def write(self, text):
		self.emit(QtCore.SIGNAL("doSomeWriting"), text)

	def start_new_thread (self):
			self.run = True
			self.current = Thread(target=self.__run)
			self.current.setDaemon(True) # close application even if this thread is running
			self.current.start()

	def set_pty (self, pty):
		if not self.running:
			self.pty = pty
			self.start_new_thread()
			self.running = True
		
		else:
			# quit current thread
			self.run = False
	#		self.current.join()
			self.clear()

			self.pty = pty # set this after clearing to lose no chars :)
			self.start_new_thread()

	def __run (self):
		while self.run:
			s = read(self.pty, 1)
			if s == "": break

			if ord(s) == backspace:
				self.emit(QtCore.SIGNAL("deletePrevChar()"))
				continue

			if s == esc_seq[0]: # -> 0x27
				s = read(self.pty, 1)
				if s == esc_seq[1]: # -> [
					while True:
						_s = read(self.pty, 1)
						s += _s
						if _s == seq_end: break
					self.parse_seq(s[1:-1])
					continue

				elif s == title_seq[1]: # -> ]
					while True:
						_s = read(self.pty, 1)
						s += _s
						if _s == title_end: break
					
					self.parse_title(s[1:-1])
					continue
				else:
					self.write(esc_seq[0]+s)
			
			if s == "\r": continue
			self.write(s)

	def parse_seq (self, seq):
		global attr

		format = self.virgin_format()

		if seq != reset_seq: # resettet -> done
			seq = seq.split(seq_sep)
			for s in seq:
				try:
					s = int(s)
				except ValueError:
					format = self.virgin_format()
					break

				if attr[s] is not None:
					format.merge(attr[s])
				else:
					format = self.virgin_format()
					break

		self.add_format(format)
		self.write(esc_seq[0])

	def parse_title (self, seq):

		if not seq.startswith("0;"):
			return

		self.title = seq[2:]

	def get_window_title (self):
		return self.title

	def add_format (self, format):
		self.formatLock.acquire()
		self.formatQueue.append(format)
		self.formatLock.release()

	def get_format (self):
		self.formatLock.acquire()
		f = self.formatQueue.pop(0)
		self.formatLock.release()
		return f

	def virgin_format (self):
		return QtGui.QTextCharFormat(self.stdFormat)