/
channel.py
476 lines (373 loc) · 18.6 KB
/
channel.py
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
from fa.replay import replay
import util
from PyQt4 import QtGui, QtCore
import time
from chat import user2name, logger
from chat.chatter import Chatter
import re
import fa
import json
import unicodedata
QUERY_BLINK_SPEED = 250
CHAT_TEXT_LIMIT = 350
CHAT_REMOVEBLOCK = 50
FormClass, BaseClass = util.loadUiType("chat/channel.ui")
class Channel(FormClass, BaseClass):
'''
This is an actual chat channel object, representing an IRC chat room and the users currently present.
'''
def __init__(self, lobby, name, private=False, *args, **kwargs):
BaseClass.__init__(self, lobby, *args, **kwargs)
self.setupUi(self)
#Special HTML formatter used to layout the chat lines written by people
self.FORMATTER_ANNOUNCEMENT = unicode(util.readfile("chat/formatters/announcement.qthtml"))
self.FORMATTER_MESSAGE = unicode(util.readfile("chat/formatters/message.qthtml"))
self.FORMATTER_MESSAGE_AVATAR = unicode(util.readfile("chat/formatters/messageAvatar.qthtml"))
self.FORMATTER_ACTION = unicode(util.readfile("chat/formatters/action.qthtml"))
self.FORMATTER_ACTION_AVATAR = unicode(util.readfile("chat/formatters/actionAvatar.qthtml"))
self.FORMATTER_RAW = unicode(util.readfile("chat/formatters/raw.qthtml"))
self.NICKLIST_COLUMNS = json.loads(util.readfile("chat/formatters/nicklist_columns.json"))
self.lobby = lobby
self.chatters = {}
self.lasttimestamp= None
# Query flasher
self.blinker = QtCore.QTimer()
self.blinker.timeout.connect(self.blink)
self.blinked = False
# Table width of each chatter's name cell...
self.maxChatterWidth = 100 # TODO: This might / should auto-adapt
#count the number of line currently in the chat
self.lines = 0
# Clear window menu action
self.lobby.client.actionClearWindow.triggered.connect(self.clearWindow)
# Perform special setup for public channels as opposed to private ones
self.name = name
self.private = private
self.setup()
def setup(self):
if not self.private:
# Non-query channels have a sorted nicklist
self.nickList.sortItems(Chatter.SORT_COLUMN)
#Properly and snugly snap all the columns
self.nickList.horizontalHeader().setResizeMode(Chatter.RANK_COLUMN, QtGui.QHeaderView.Fixed)
self.nickList.horizontalHeader().resizeSection(Chatter.RANK_COLUMN, self.NICKLIST_COLUMNS['RANK'])
self.nickList.horizontalHeader().setResizeMode(Chatter.AVATAR_COLUMN, QtGui.QHeaderView.Fixed)
self.nickList.horizontalHeader().resizeSection(Chatter.AVATAR_COLUMN, self.NICKLIST_COLUMNS['AVATAR'])
self.nickList.horizontalHeader().setResizeMode(Chatter.STATUS_COLUMN, QtGui.QHeaderView.Fixed)
self.nickList.horizontalHeader().resizeSection(Chatter.STATUS_COLUMN, self.NICKLIST_COLUMNS['STATUS'])
self.nickList.horizontalHeader().setResizeMode(Chatter.SORT_COLUMN, QtGui.QHeaderView.Stretch)
self.nickList.itemDoubleClicked.connect(self.nickDoubleClicked)
self.nickList.itemPressed.connect(self.nickPressed)
self.nickFilter.textChanged.connect(self.filterNicks)
self.lobby.client.usersUpdated.connect(self.updateChatters)
else:
self.nickFrame.hide()
self.announceLine.hide()
self.chatArea.anchorClicked.connect(self.openUrl)
self.chatEdit.returnPressed.connect(self.sendLine)
self.chatEdit.setChatters(self.chatters)
self.lobby.client.doneresize.connect(self.resizing)
self.resizeTimer = QtCore.QTimer(self)
self.resizeTimer.timeout.connect(self.canresize)
def joinChannel(self, index):
''' join another channel'''
channel = self.channelsComboBox.itemText(index)
if channel.startswith('#'):
self.lobby.autoJoin([channel])
def keyReleaseEvent(self, keyevent):
'''
Allow the ctrl-C event.
'''
if keyevent.key() == 67 :
self.chatArea.copy()
def canresize(self):
if self.isVisible() :
self.chatArea.setLineWrapColumnOrWidth(self.chatArea.size().width() - 20) #Hardcoded, but seems to be enough (tabstop was a bit large)
self.resizeTimer.stop()
def resizing(self):
self.resizeTimer.start(10)
def showEvent(self, event):
self.stopBlink()
return BaseClass.showEvent(self, event)
@QtCore.pyqtSlot()
def clearWindow(self):
if self.isVisible():
self.chatArea.setPlainText("")
self.lasttimestamp = 0
@QtCore.pyqtSlot()
def filterNicks(self):
for chatter in self.chatters.keys():
self.chatters[chatter].setVisible(self.chatters[chatter].isFiltered(self.nickFilter.text().lower()))
def updateUserCount(self):
count = len(self.chatters.keys())
self.nickFilter.setPlaceholderText(str(count) + " users... (type to filter)")
if self.nickFilter.text():
self.filterNicks()
@QtCore.pyqtSlot()
def blink(self):
if (self.blinked):
self.blinked = False
self.lobby.tabBar().setTabText(self.lobby.indexOf(self), self.name)
else:
self.blinked = True
self.lobby.tabBar().setTabText(self.lobby.indexOf(self), "")
@QtCore.pyqtSlot()
def stopBlink(self):
self.blinker.stop()
self.lobby.tabBar().setTabText(self.lobby.indexOf(self), self.name)
@QtCore.pyqtSlot()
def startBlink(self):
self.blinker.start(QUERY_BLINK_SPEED)
@QtCore.pyqtSlot()
def pingWindow(self):
QtGui.QApplication.alert(self.lobby.client)
if not self.isVisible() or QtGui.QApplication.activeWindow() != self.lobby.client:
if self.oneMinuteOrOlder():
if self.lobby.client.soundeffects:
util.sound("chat/sfx/query.wav")
if not self.isVisible():
if not self.blinker.isActive() and not self == self.lobby.currentWidget():
self.startBlink()
@QtCore.pyqtSlot(QtCore.QUrl)
def openUrl(self, url):
logger.debug("Clicked on URL: " + url.toString())
if url.scheme() == "faflive":
replay(url)
elif url.scheme() == "fafgame":
self.lobby.client.joinGameFromURL(url)
else :
QtGui.QDesktopServices.openUrl(url)
@QtCore.pyqtSlot(str, str)
def printAnnouncement(self, text, color, size, scroll_forced = True):
'''
Print an actual message in the chatArea of the channel
'''
# scroll if close to the last line of the log
scroll_current = self.chatArea.verticalScrollBar().value()
scroll_needed = scroll_forced or ((self.chatArea.verticalScrollBar().maximum() - scroll_current) < 20)
cursor = self.chatArea.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.chatArea.setTextCursor(cursor)
formatter = self.FORMATTER_ANNOUNCEMENT
line = formatter.format(size=size, color=color, text=util.irc_escape(text, self.lobby.a_style))
self.chatArea.insertHtml(line)
if scroll_needed:
self.chatArea.verticalScrollBar().setValue(self.chatArea.verticalScrollBar().maximum())
else:
self.chatArea.verticalScrollBar().setValue(scroll_current)
def printLine(self, name, text, color, scroll_forced=False, server_action=False):
if self.lines > CHAT_TEXT_LIMIT :
cursor = self.chatArea.textCursor()
cursor.movePosition(QtGui.QTextCursor.Start)
cursor.movePosition(QtGui.QTextCursor.Down, QtGui.QTextCursor.KeepAnchor, CHAT_REMOVEBLOCK)
cursor.removeSelectedText()
self.lines = self.lines - CHAT_REMOVEBLOCK
player = self.lobby.players[name]
displayName = name
if player.clan is not None:
displayName = "<b>[%s]</b>%s" % (player.clan, name)
# Play a ping sound and flash the title under certain circumstances
mentioned = text.find(self.lobby.client.login) != -1
if self.private or mentioned:
self.pingWindow()
avatar = None
# Default colour behaviour
if name.lower() in self.lobby.specialUserColors:
color = self.lobby.specialUserColors[name.lower()]
else:
if name in self.chatters:
chatter = self.chatters[name]
color = chatter.textColor().name()
if chatter.avatar:
avatar = chatter.avatar["url"]
avatarTip = chatter.avatarTip or ""
else:
# Fallback and ask the client. We have no Idea who this is.
color = self.lobby.client.getUserColor(name)
# Overrides for special cases.
if mentioned:
color = self.lobby.client.getColor("tous")
if server_action:
color = self.lobby.client.getColor("server")
# scroll if close to the last line of the log
scroll_current = self.chatArea.verticalScrollBar().value()
scroll_needed = scroll_forced or ((self.chatArea.verticalScrollBar().maximum() - scroll_current) < 20)
cursor = self.chatArea.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.chatArea.setTextCursor(cursor)
# This whole block seems to be duplicated further up.
# For fucks sake.
if avatar:
pix = util.respix(avatar)
if pix:
if not self.chatArea.document().resource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(avatar)) :
self.chatArea.document().addResource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(avatar), pix)
formatter = self.FORMATTER_ACTION_AVATAR
line = formatter.format(time=self.timestamp(), avatar=avatar, avatarTip=avatarTip, name=displayName, color=color, width=self.maxChatterWidth, text=util.irc_escape(text, self.lobby.a_style))
else:
formatter = self.FORMATTER_ACTION
line = formatter.format(time=self.timestamp(), name=displayName, color=color, width=self.maxChatterWidth, text=util.irc_escape(text, self.lobby.a_style))
else:
formatter = self.FORMATTER_ACTION
line = formatter.format(time=self.timestamp(), name=displayName, color=color, width=self.maxChatterWidth, text=util.irc_escape(text, self.lobby.a_style))
self.chatArea.insertHtml(line)
self.lines = self.lines + 1
if scroll_needed:
self.chatArea.verticalScrollBar().setValue(self.chatArea.verticalScrollBar().maximum())
else:
self.chatArea.verticalScrollBar().setValue(scroll_current)
@QtCore.pyqtSlot(str, str)
def printMsg(self, name, text, scroll_forced=False):
if self.lobby.client.isFoe(name):
return
self.printLine(name, text, scroll_forced)
@QtCore.pyqtSlot(str, str)
def printAction(self, name, text, scroll_forced=False, server_action=False):
self.printLine(name, text, scroll_forced, server_action)
@QtCore.pyqtSlot(str, str)
def printRaw(self, name, text, scroll_forced=False):
'''
Print an raw message in the chatArea of the channel
'''
try:
if name in self.lobby.specialUserColors:
color = self.lobby.specialUserColors[name]
else:
color = self.lobby.client.getUserColor(name)
# Play a ping sound
if self.private and name != self.lobby.client.login:
self.pingWindow()
# scroll if close to the last line of the log
scroll_current = self.chatArea.verticalScrollBar().value()
scroll_needed = scroll_forced or ((self.chatArea.verticalScrollBar().maximum() - scroll_current) < 20)
cursor = self.chatArea.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.chatArea.setTextCursor(cursor)
formatter = self.FORMATTER_RAW
line = formatter.format(time=self.timestamp(), name=name, color=color, width=self.maxChatterWidth, text=text)
self.chatArea.insertHtml(line)
if scroll_needed:
self.chatArea.verticalScrollBar().setValue(self.chatArea.verticalScrollBar().maximum())
else:
self.chatArea.verticalScrollBar().setValue(scroll_current)
except:
pass
def timestamp(self):
'''returns a fresh timestamp string once every minute, and an empty string otherwise'''
timestamp = time.strftime("%H:%M")
if self.lasttimestamp != timestamp:
self.lasttimestamp = timestamp
return timestamp
else:
return ""
def oneMinuteOrOlder(self):
timestamp = time.strftime("%H:%M")
return self.lasttimestamp != timestamp
@QtCore.pyqtSlot(QtGui.QTableWidgetItem)
def nickDoubleClicked(self, item):
chatter = self.nickList.item(item.row(), Chatter.SORT_COLUMN) #Look up the associated chatter object
chatter.doubleClicked(item)
@QtCore.pyqtSlot(QtGui.QTableWidgetItem)
def nickPressed(self, item):
if QtGui.QApplication.mouseButtons() == QtCore.Qt.RightButton:
#Look up the associated chatter object
chatter = self.nickList.item(item.row(), Chatter.SORT_COLUMN)
chatter.pressed(item)
@QtCore.pyqtSlot(list)
def updateChatters(self, updated_chatters):
'''
Updates the status, icon and color of an IRC user depending on its known state in the FAF client
Takes a list of users.
'''
for name in updated_chatters:
if name in self.chatters:
self.chatters[name].update() #only update chatters that are in this channel
self.updateUserCount()
def elevateChatter(self, name, modes):
add = re.compile(".*\+([a-z]+)")
remove = re.compile(".*\-([a-z]+)")
if name in self.chatters:
addmatch = re.search(add, modes)
if addmatch:
modes = addmatch.group(1)
mode = ""
if "v" in modes:
mode = "+"
if "o" in modes:
mode = "@"
if "q" in modes:
mode = "~"
if mode in self.lobby.OPERATOR_COLORS:
self.chatters[name].elevation = mode
self.chatters[name].update()
removematch = re.search(remove, modes)
if removematch:
modes = removematch.group(1)
mode = ""
if "o" in modes and self.chatters[name].elevation == "@":
self.chatters[name].elevation = None
self.chatters[name].update()
if "q" in modes and self.chatters[name].elevation == "~":
self.chatters[name].elevation = None
self.chatters[name].update()
if "v" in modes and self.chatters[name].elevation == "+":
self.chatters[name].elevation = None
self.chatters[name].update()
def addChatter(self, user, join = False):
'''
Adds an user to this chat channel, and assigns an appropriate icon depending on friendship and FAF player status
'''
name = user2name(user)
if name not in self.chatters:
item = Chatter(self.nickList, user, self.lobby, None)
self.chatters[name] = item
self.chatters[name].update()
self.updateUserCount()
if join and self.lobby.client.joinsparts:
self.printAction(name, "joined the channel.", server_action=True)
def removeChatter(self, name, action = None):
if name in self.chatters:
self.nickList.removeRow(self.chatters[name].row())
del self.chatters[name]
if action and (self.lobby.client.joinsparts or self.private):
self.printAction(name, action, server_action=True)
self.stopBlink()
self.updateUserCount()
def setAnnounceText(self,text):
self.announceLine.clear()
self.announceLine.setText("<style>a{color:cornflowerblue}</style><b><font color=white>" + util.irc_escape(text) + "</font></b>")
@QtCore.pyqtSlot()
def sendLine(self, target=None):
self.stopBlink()
if not target:
target = self.name #pubmsg in channel
line = self.chatEdit.text()
#Split into lines if newlines are present
fragments = line.split("\n")
for text in fragments:
# Compound wacky Whitespace
text = re.sub('\s', ' ', text)
text = text.strip()
# Reject empty messages
if not text:
continue
# System commands
if text.startswith("/"):
if text.startswith(("/join ")):
self.lobby.join(text[6:])
elif text.startswith(("/topic ")):
self.lobby.setTopic(self.name, text[7:])
elif text.startswith(("/me ")):
if self.lobby.sendAction(target, text[4:]):
self.printAction(self.lobby.client.login, text[4:], True)
else:
self.printAction("IRC", "action not supported", True)
elif text.startswith(("/seen ")):
if self.lobby.sendMsg("nickserv", "info %s" % (text[6:])):
self.printAction("IRC", "info requested on %s" % (text[6:]), True)
else:
self.printAction("IRC", "not connected", True)
else:
if self.lobby.sendMsg(target, text):
self.printMsg(self.lobby.client.login, text, True)
self.chatEdit.clear()