Moving GUI out of the TCP thread

This commit is contained in:
cidoku 2026-02-08 19:45:35 -03:00
parent e323bf47dc
commit 84f1af7ac1
5 changed files with 208 additions and 173 deletions

View File

@ -4,7 +4,7 @@ import platform
import websocket import websocket
import ssl import ssl
from constants import * from constants import GAME_VERSION
printPackets = False # Enable for debugging packets sent and received printPackets = False # Enable for debugging packets sent and received

View File

@ -320,12 +320,12 @@ class EmoteButton(QtGui.QLabel):
if self.pixmap(): if self.pixmap():
if self.pixmap().isNull(): if self.pixmap().isNull():
button_img = QtGui.QPixmap(self.path + '_off.png') buttonImg = QtGui.QPixmap(self.path + '_off.png')
painter.setOpacity(0.5) painter.setOpacity(0.5)
if not button_img.width() == 40: if buttonImg and not buttonImg.isNull() and not buttonImg.width() == 40:
painter.drawPixmap(0, 0, button_img.scaled(40, 40, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation)) painter.drawPixmap(0, 0, buttonImg.scaled(40, 40, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation))
else: else:
painter.drawPixmap(0, 0, button_img) painter.drawPixmap(0, 0, buttonImg)
else: else:
painter.drawPixmap(0, 0, self.pixmap()) painter.drawPixmap(0, 0, self.pixmap())
# else: # else:

View File

@ -4,6 +4,7 @@ from PyQt4 import QtCore, QtGui
from bisect import bisect_left from bisect import bisect_left
class DemoPlayer(QtCore.QObject): class DemoPlayer(QtCore.QObject):
connectionError = QtCore.pyqtSignal(str, str, str)
MS_Chat = QtCore.pyqtSignal(list) MS_Chat = QtCore.pyqtSignal(list)
newChar = QtCore.pyqtSignal(int) newChar = QtCore.pyqtSignal(int)
newBackground = QtCore.pyqtSignal(str, bool) newBackground = QtCore.pyqtSignal(str, bool)
@ -17,6 +18,8 @@ class DemoPlayer(QtCore.QObject):
authStatusChanged = QtCore.pyqtSignal(int) authStatusChanged = QtCore.pyqtSignal(int)
updateAreaList = QtCore.pyqtSignal(list) updateAreaList = QtCore.pyqtSignal(list)
setCharList = QtCore.pyqtSignal(list) setCharList = QtCore.pyqtSignal(list)
playMusicRequested = QtCore.pyqtSignal(str, int, str)
modCall = QtCore.pyqtSignal(str)
def __init__(self, parent): def __init__(self, parent):
super(DemoPlayer, self).__init__(parent) super(DemoPlayer, self).__init__(parent)

View File

@ -478,7 +478,7 @@ class AOCharMovie(QtGui.QLabel):
return QtCore.Qt.KeepAspectRatio return QtCore.Qt.KeepAspectRatio
def getScaledImage(self, f_img): def getScaledImage(self, f_img):
if not f_img.isNull(): if f_img and not f_img.isNull():
transform = self.getTransform(f_img.size().height() > self.size().height()) transform = self.getTransform(f_img.size().height() > self.size().height())
aspect = self.getAspect(f_img.size()) aspect = self.getAspect(f_img.size())
return f_img.scaled(self.size(), aspect, transform) return f_img.scaled(self.size(), aspect, transform)
@ -489,6 +489,8 @@ class AOCharMovie(QtGui.QLabel):
f_img = self.getScaledImage(self.mMovie.currentImage().mirrored(self.mFlipped, False)) f_img = self.getScaledImage(self.mMovie.currentImage().mirrored(self.mFlipped, False))
fPixmap = QtGui.QPixmap.fromImage(f_img) fPixmap = QtGui.QPixmap.fromImage(f_img)
if not fPixmap or fPixmap.isNull():
return
self.setPixmap(fPixmap) self.setPixmap(fPixmap)
if self.mMovie.frameCount() - 1 == nFrame and self.playOnce: if self.mMovie.frameCount() - 1 == nFrame and self.playOnce:
@ -514,6 +516,8 @@ class AOCharMovie(QtGui.QLabel):
f_img = self.getScaledImage(self.pillowFrames[self.pillowFrame][0].mirrored(self.mFlipped, False)) f_img = self.getScaledImage(self.pillowFrames[self.pillowFrame][0].mirrored(self.mFlipped, False))
fPixmap = QtGui.QPixmap.fromImage(f_img) fPixmap = QtGui.QPixmap.fromImage(f_img)
if not fPixmap or fPixmap.isNull():
return
self.setPixmap(fPixmap) self.setPixmap(fPixmap)
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
@ -645,11 +649,13 @@ class AOMovie(QtGui.QLabel):
if not self.pillowFrames: return if not self.pillowFrames: return
f_img = self.pillowFrames[self.pillowFrame][0] f_img = self.pillowFrames[self.pillowFrame][0]
if not f_img.isNull() and (f_img.size().width() != self.size().width() or f_img.size().height() != self.size().height()): if not f_img or f_img.isNull():
return
if (f_img.size().width() != self.size().width() or f_img.size().height() != self.size().height()):
f_img = f_img.scaled(self.size().width(), self.size().height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation) f_img = f_img.scaled(self.size().width(), self.size().height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)
fPixmap = QtGui.QPixmap.fromImage(f_img) self.pillowLabel.setPixmap(QtGui.QPixmap.fromImage(f_img))
self.pillowLabel.setPixmap(fPixmap)
class ZoomLines(QtGui.QLabel): class ZoomLines(QtGui.QLabel):
def __init__(self, parent): def __init__(self, parent):
@ -697,7 +703,7 @@ class WTCEView(QtGui.QLabel):
return return
img = self.movie.currentImage() img = self.movie.currentImage()
pixmap = QtGui.QPixmap.fromImage(img) pixmap = QtGui.QPixmap.fromImage(img)
if not pixmap.isNull(): if pixmap and not pixmap.isNull():
self.setPixmap(pixmap.scaled(self.size().width(), self.size().height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)) self.setPixmap(pixmap.scaled(self.size().width(), self.size().height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))
if self.movie.currentFrameNumber() == self.movie.frameCount() - 1: if self.movie.currentFrameNumber() == self.movie.frameCount() - 1:
self.finalframeTimer.start(self.movie.nextFrameDelay()) self.finalframeTimer.start(self.movie.nextFrameDelay())
@ -877,98 +883,6 @@ class EditEvidenceDialog(QtGui.QDialog):
def setTitle(self): def setTitle(self):
self.setWindowTitle('Add evidence' if not self.gamegui.privateInventorySelected else "Add evidence to private inventory") self.setWindowTitle('Add evidence' if not self.gamegui.privateInventorySelected else "Add evidence to private inventory")
class TCPThread(QtCore.QThread):
connectionError = QtCore.pyqtSignal(str, str, str)
MS_Chat = QtCore.pyqtSignal(list)
newChar = QtCore.pyqtSignal(int)
newBackground = QtCore.pyqtSignal(str, bool)
IC_Log = QtCore.pyqtSignal(str)
OOC_Log = QtCore.pyqtSignal(str)
charSlots = QtCore.pyqtSignal(list)
showCharSelect = QtCore.pyqtSignal()
loadAllEvidence = QtCore.pyqtSignal(list)
rainbowColor = QtCore.pyqtSignal(str)
updatePlayerList = QtCore.pyqtSignal(str, int, int, str)
timerUpdate = QtCore.pyqtSignal(int, int, int)
authStatusChanged = QtCore.pyqtSignal(int)
updateAreaList = QtCore.pyqtSignal(list)
setCharList = QtCore.pyqtSignal(list)
send_attempts = 0
max_attempts = 5
stop_now = False
def __init__(self, parent):
super(TCPThread, self).__init__(parent)
self.parent = parent
def run(self):
pingtimer = 150
rainbow = 0
sendtick = 0
color = QtGui.QColor()
color.setHsv(rainbow, 255, 255)
while True:
if self.stop_now:
self.parent.tcp.close()
self.parent.tcp = None
self.quit()
return
if self.parent.disconnectNow:
self.parent.disconnectCommon()
self.quit()
return
pingtimer -= 1
if pingtimer == 0:
# pingbefore = time.time()
self.parent.tcp.send('CH#%')
pingtimer = 150
if self.parent.mChatMessage[TEXT_COLOR] == str(C_RAINBOW):
color.setHsv(rainbow, 255, 255)
rainbow += 5
if rainbow > 255:
rainbow = 0
#self.parent.text.setStyleSheet('color: rgb(' + str(color.red()) + ', ' + str(color.green()) + ', ' + str(color.blue()) + ')')
self.rainbowColor.emit('background-color: rgba(0, 0, 0, 0); color: rgb(' + str(color.red()) + ', ' + str(color.green()) + ', ' + str(color.blue()) + ')')
if sendtick:
sendtick -= 1
if self.parent.messageQueue and not sendtick:
self.parent.tcp.send(self.parent.messageQueue[0])
sendtick = 4
error, total = self.parent.tcp.recv()
if error == -2:
# if the message can't be sent, discard it
if sendtick == 4:
self.send_attempts += 1
if self.send_attempts >= self.max_attempts:
self.send_attempts = 0
#print "[warning] message discarded"
del self.parent.messageQueue[0]
self.parent.queueItems.takeItem(0)
continue
elif error == -1:
self.parent.emit(QtCore.SIGNAL('showMessage(QString, QString, QString)'), 'critical', 'Connection lost', "%s connection to server lost." % ("WebSocket" if self.parent.tcp.isWS else "TCP"))
self.parent.willDisconnect = True
self.quit()
return
elif error == -3:
self.parent.emit(QtCore.SIGNAL('showMessage(QString, QString, QString)'), 'critical', 'Connection lost', "There was a critical connection failure. Please check your internet connection.\n\nDetails: %s." % total)
self.parent.willDisconnect = True
self.quit()
return
else:
self.send_attempts = 0
packets.handlePackets(self, total)
def stop(self):
self.stop_now = True
class Chatbox(QtGui.QLabel): class Chatbox(QtGui.QLabel):
def __init__(self, parent): def __init__(self, parent):
QtGui.QLabel.__init__(self, parent) QtGui.QLabel.__init__(self, parent)
@ -1056,7 +970,7 @@ class GUI(QtGui.QWidget):
self.inboxTimer.setSingleShot(True) self.inboxTimer.setSingleShot(True)
self.inboxTimer.timeout.connect(self.inboxTimerTimeout) self.inboxTimer.timeout.connect(self.inboxTimerTimeout)
self.modcall = None self.sndModCall = None
self.healthbars.connect(self.netmsgHP) self.healthbars.connect(self.netmsgHP)
self.disconnectNow = False self.disconnectNow = False
@ -1943,6 +1857,7 @@ class GUI(QtGui.QWidget):
else: else:
self.chatboxWidth = self.chatbox.width() self.chatboxWidth = self.chatbox.width()
self.chatboxHeight = self.chatbox.height() self.chatboxHeight = self.chatbox.height()
if chatboxPixmap and not chatboxPixmap.isNull():
self.chatbox.setPixmap(chatboxPixmap.scaled(self.chatboxWidth, self.chatboxHeight, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)) self.chatbox.setPixmap(chatboxPixmap.scaled(self.chatboxWidth, self.chatboxHeight, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))
# Theme background # Theme background
@ -2254,8 +2169,8 @@ class GUI(QtGui.QWidget):
audio.setHandleAttr(self.wtceSfx, BASS_ATTRIB_VOL, value / 100.0) audio.setHandleAttr(self.wtceSfx, BASS_ATTRIB_VOL, value / 100.0)
audio.setHandleAttr(self.guiltySfx, BASS_ATTRIB_VOL, value / 100.0) audio.setHandleAttr(self.guiltySfx, BASS_ATTRIB_VOL, value / 100.0)
audio.setHandleAttr(self.notGuiltySfx, BASS_ATTRIB_VOL, value / 100.0) audio.setHandleAttr(self.notGuiltySfx, BASS_ATTRIB_VOL, value / 100.0)
if self.modcall: if self.sndModCall:
audio.setHandleAttr(self.modcall, BASS_ATTRIB_VOL, value / 100.0) audio.setHandleAttr(self.sndModCall, BASS_ATTRIB_VOL, value / 100.0)
def changeBlipVolume(self, value): def changeBlipVolume(self, value):
if self.blipSound: if self.blipSound:
@ -2419,13 +2334,17 @@ class GUI(QtGui.QWidget):
def setEvidenceImage(self, guiobj, image, scale=False): def setEvidenceImage(self, guiobj, image, scale=False):
if exists(BASE_PATH + 'evidence/' + image): if exists(BASE_PATH + 'evidence/' + image):
img = QtGui.QPixmap(BASE_PATH + "evidence/%s" % image) img = QtGui.QPixmap(BASE_PATH + "evidence/%s" % image)
if not img.isNull() and scale: if not img or img.isNull():
return
if scale:
guiobj.setPixmap(img.scaled(140, 140, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)) guiobj.setPixmap(img.scaled(140, 140, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))
else: else:
guiobj.setPixmap(img) guiobj.setPixmap(img)
else: else:
img = QtGui.QPixmap(AO2XPpath + 'themes/default/evidence_selected.png') img = QtGui.QPixmap(AO2XPpath + 'themes/default/evidence_selected.png')
if not img.isNull() and scale: if not img or img.isNull():
return
if scale:
guiobj.setPixmap(img.scaled(140, 140, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)) guiobj.setPixmap(img.scaled(140, 140, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))
else: else:
guiobj.setPixmap(img) guiobj.setPixmap(img)
@ -2639,14 +2558,17 @@ class GUI(QtGui.QWidget):
else: else:
image = QtGui.QPixmap(BASE_PATH + 'characters/' + self.charName + '/emotions/button' + str(nRealEmote + 1) + '_off.png') image = QtGui.QPixmap(BASE_PATH + 'characters/' + self.charName + '/emotions/button' + str(nRealEmote + 1) + '_off.png')
if not image.isNull() and not image.width() == 40: self.emoteButtons[nEmote].show()
self.emoteButtons[nEmote].setToolTip(self.charEmotes[nEmote + self.currentEmotePage * self.maxEmotesOnPage][0])
if not image or image.isNull():
return
if not image.width() == 40:
self.emoteButtons[nEmote].setPixmap(image.scaled(40, 40, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation)) self.emoteButtons[nEmote].setPixmap(image.scaled(40, 40, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation))
else: else:
self.emoteButtons[nEmote].setPixmap(image) self.emoteButtons[nEmote].setPixmap(image)
self.emoteButtons[nEmote].show()
self.emoteButtons[nEmote].setToolTip(self.charEmotes[nEmote + self.currentEmotePage * self.maxEmotesOnPage][0])
def iniSwapIndexChange(self, ind): def iniSwapIndexChange(self, ind):
self.iniSwapIndex = ind self.iniSwapIndex = ind
@ -2979,7 +2901,10 @@ class GUI(QtGui.QWidget):
else: else:
image = QtGui.QPixmap(BASE_PATH + 'characters/' + self.charName + '/emotions/button' + str(button.emoteid + self.currentEmotePage * self.maxEmotesOnPage + 1) + '_off.png') image = QtGui.QPixmap(BASE_PATH + 'characters/' + self.charName + '/emotions/button' + str(button.emoteid + self.currentEmotePage * self.maxEmotesOnPage + 1) + '_off.png')
if not image.isNull() and not image.width() == 40: if not image or image.isNull():
return
if not image.width() == 40:
button.setPixmap(image.scaled(40, 40, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation)) button.setPixmap(image.scaled(40, 40, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation))
else: else:
button.setPixmap(image) button.setPixmap(image)
@ -3283,8 +3208,9 @@ class GUI(QtGui.QWidget):
if bgimg.size().width() != self.viewport.width() or bgimg.size().height() != self.viewport.height(): if bgimg.size().width() != self.viewport.width() or bgimg.size().height() != self.viewport.height():
if "bench" in bgfile[0]: if "bench" in bgfile[0]:
_scale = self.viewport.height() / float(bgimg.size().height()) _scale = self.viewport.height() / float(bgimg.size().height())
if bgimg and not bgimg.isNull():
setattr(self, bgfile[0], QtGui.QPixmap.fromImage(bgimg.scaled(bgimg.size().width() * _scale, bgimg.size().height() * _scale, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))) setattr(self, bgfile[0], QtGui.QPixmap.fromImage(bgimg.scaled(bgimg.size().width() * _scale, bgimg.size().height() * _scale, QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)))
else: elif bgimg and not bgimg.isNull():
setattr(self, bgfile[0], QtGui.QPixmap.fromImage(bgimg.scaled(self.viewport.width(), self.viewport.height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))) setattr(self, bgfile[0], QtGui.QPixmap.fromImage(bgimg.scaled(self.viewport.width(), self.viewport.height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)))
else: else:
setattr(self, bgfile[0], QtGui.QPixmap.fromImage(bgimg)) setattr(self, bgfile[0], QtGui.QPixmap.fromImage(bgimg))
@ -3296,15 +3222,17 @@ class GUI(QtGui.QWidget):
if self.slideAvailable: if self.slideAvailable:
slide = QtGui.QPixmap(court) slide = QtGui.QPixmap(court)
slide_width = slide.width() * 2 slideWidth = slide.width() * 2
self.slideBg.resize(slide_width, self.viewport.height()) self.slideBg.resize(slideWidth, self.viewport.height())
if slide and not slide.isNull():
self.slideBg.setPixmap(slide.scaled(slide.width() * 2, self.viewport.height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)) self.slideBg.setPixmap(slide.scaled(slide.width() * 2, self.viewport.height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))
courtOverlay = BASE_PATH + 'background/' + bg + '/courtOverlay.png' courtOverlay = BASE_PATH + 'background/' + bg + '/courtOverlay.png'
if exists(courtOverlay): if exists(courtOverlay):
slideOverlay = QtGui.QPixmap(courtOverlay) slideOverlay = QtGui.QPixmap(courtOverlay)
self.slideOverlay.resize(slide_width, self.viewport.height()) self.slideOverlay.resize(slideWidth, self.viewport.height())
if slideOverlay and not slideOverlay.isNull():
self.slideOverlay.setPixmap(slideOverlay.scaled(slide.width() * 2, self.viewport.height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation)) self.slideOverlay.setPixmap(slideOverlay.scaled(slide.width() * 2, self.viewport.height(), QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.FastTransformation))
self.slideHasOverlay = True self.slideHasOverlay = True
else: else:
@ -4703,7 +4631,8 @@ class GUI(QtGui.QWidget):
self.onImportEvidence(True) self.onImportEvidence(True)
self.tcpThread = TCPThread(self) self.tcpThread = packets.TCPThread(self)
self.tcpThread.connectionError.connect(self.showMessage)
self.tcpThread.MS_Chat.connect(self.netmsgMS) self.tcpThread.MS_Chat.connect(self.netmsgMS)
self.tcpThread.newChar.connect(self.onPVPacket) self.tcpThread.newChar.connect(self.onPVPacket)
self.tcpThread.newBackground.connect(self.setBackground) self.tcpThread.newBackground.connect(self.setBackground)
@ -4717,6 +4646,8 @@ class GUI(QtGui.QWidget):
self.tcpThread.rainbowColor.connect(self.text.setStyleSheet) self.tcpThread.rainbowColor.connect(self.text.setStyleSheet)
self.tcpThread.timerUpdate.connect(self.startPauseOnscreenTimers) self.tcpThread.timerUpdate.connect(self.startPauseOnscreenTimers)
self.tcpThread.updateAreaList.connect(self.updateAreaList) self.tcpThread.updateAreaList.connect(self.updateAreaList)
self.tcpThread.playMusicRequested.connect(self.playMusicRequested)
self.tcpThread.discardMessageFromQueue.connect(self.discardMessageFromQueue)
self.tcpThread.start() self.tcpThread.start()
self.demoPlaying = False self.demoPlaying = False
@ -4737,6 +4668,7 @@ class GUI(QtGui.QWidget):
self.demoPlayer.rainbowColor.connect(self.text.setStyleSheet) self.demoPlayer.rainbowColor.connect(self.text.setStyleSheet)
self.demoPlayer.timerUpdate.connect(self.startPauseOnscreenTimers) self.demoPlayer.timerUpdate.connect(self.startPauseOnscreenTimers)
self.demoPlayer.setCharList.connect(self.onSCPacket) self.demoPlayer.setCharList.connect(self.onSCPacket)
self.demoPlayer.playMusicRequested.connect(self.playMusicRequested)
def startDemo(self, fname): def startDemo(self, fname):
self.playerList = [] self.playerList = []
@ -4890,5 +4822,39 @@ class GUI(QtGui.QWidget):
self.OOCLogin.setText("Lo&gin") self.OOCLogin.setText("Lo&gin")
self.OOCLog.append("<b>%s</b>" % (statusStrings[status+1])) self.OOCLog.append("<b>%s</b>" % (statusStrings[status+1]))
def playMusicRequested(self, music, charid, showname):
t = time.localtime()
timestamp = "[%d:%.2d] " % (t[3], t[4]) if not self.demoPlaying else ""
music = str(music)
if charid != -1:
try:
name = self.charList[charid][0]
except:
name = 'char id %d' % charid
if showname:
name += " (" + showname.decode("utf-8") + ")"
self.ICLog.append(timestamp + '%s changed the music to %s' % (name, music))
else:
self.ICLog.append(timestamp + 'The music was changed to %s' % music)
self.playMusic(music)
def onModCallReceived(self, reason):
if self.sndModCall:
audio.freeHandle(self.sndModCall)
self.sndModCall = audio.loadHandle(0, "mod_call.wav", 0, 0, 0)
audio.setHandleAttr(self.sndModCall, BASS_ATTRIB_VOL, self.sliSoundVolume.value() / 100.0)
audio.playHandle(self.sndModCall, False)
if len(network) > 1:
caller.OOC_Log.emit('<b>[MOD CALL] ' + reason + '</b>')
else:
caller.OOC_Log.emit('<b>[MOD CALL] But there was no extra information. (old server?)</b>')
def onSCPacket(self, data): def onSCPacket(self, data):
self.charList = data self.charList = data
def discardMessageFromQueue(self):
del self.messageQueue[0]
self.queueItems.takeItem(0)

View File

@ -1,8 +1,98 @@
import time import time
from constants import * from constants import decodeAOString, CHATMSG, TEXT_COLOR, C_RAINBOW
from PyQt4 import QtGui
from os.path import exists from os.path import exists
from pybass_constants import * from PyQt4 import QtCore
class TCPThread(QtCore.QThread):
connectionError = QtCore.pyqtSignal(str, str, str)
MS_Chat = QtCore.pyqtSignal(list)
newChar = QtCore.pyqtSignal(int)
newBackground = QtCore.pyqtSignal(str, bool)
IC_Log = QtCore.pyqtSignal(str)
OOC_Log = QtCore.pyqtSignal(str)
charSlots = QtCore.pyqtSignal(list)
showCharSelect = QtCore.pyqtSignal()
loadAllEvidence = QtCore.pyqtSignal(list)
rainbowColor = QtCore.pyqtSignal(str)
updatePlayerList = QtCore.pyqtSignal(str, int, int, str)
timerUpdate = QtCore.pyqtSignal(int, int, int)
authStatusChanged = QtCore.pyqtSignal(int)
updateAreaList = QtCore.pyqtSignal(list)
setCharList = QtCore.pyqtSignal(list)
playMusicRequested = QtCore.pyqtSignal(str, int, str)
modCall = QtCore.pyqtSignal(str)
discardMessageFromQueue = QtCore.pyqtSignal()
send_attempts = 0
max_attempts = 5
stop_now = False
def __init__(self, parent):
super(TCPThread, self).__init__(parent)
self.parent = parent
def run(self):
pingtimer = 150
rainbow = 0
sendtick = 0
while True:
if self.stop_now:
self.parent.tcp.close()
self.parent.tcp = None
self.quit()
return
if self.parent.disconnectNow:
self.parent.disconnectCommon()
self.quit()
return
pingtimer -= 1
if pingtimer == 0:
# pingbefore = time.time()
self.parent.tcp.send('CH#%')
pingtimer = 150
if self.parent.mChatMessage[TEXT_COLOR] == str(C_RAINBOW):
rainbow += 5
if rainbow > 255:
rainbow = 0
self.rainbowColor.emit('background-color: rgba(0, 0, 0, 0); color: hsv(%s,255,255)' % rainbow)
if sendtick:
sendtick -= 1
if self.parent.messageQueue and not sendtick:
self.parent.tcp.send(self.parent.messageQueue[0])
sendtick = 4
error, total = self.parent.tcp.recv()
if error == -2:
# if the message can't be sent, discard it
if sendtick == 4:
self.send_attempts += 1
if self.send_attempts >= self.max_attempts:
self.send_attempts = 0
#print "[warning] message discarded"
self.discardMessageFromQueue.emit()
continue
elif error == -1:
self.parent.willDisconnect = True
self.connectionError.emit('critical', 'Connection lost', "%s connection to server lost." % ("WebSocket" if self.parent.tcp.isWS else "TCP"))
self.quit()
return
elif error == -3:
self.parent.willDisconnect = True
self.connectionError.emit('critical', 'Connection lost', "There was a critical connection failure. Please check your internet connection.\n\nDetails: %s." % total)
self.quit()
return
else:
self.send_attempts = 0
handlePackets(self, total)
self.msleep(5)
def stop(self):
self.stop_now = True
def handlePackets(caller, total, record=True): def handlePackets(caller, total, record=True):
# Record the packet if demos enabled # Record the packet if demos enabled
@ -13,7 +103,7 @@ def handlePackets(caller, total, record=True):
header = network[0] header = network[0]
if header == 'MS': if header == 'MS':
if len(network) < 15: if len(network) < 15:
print '[warning]', 'Malformed/incomplete MS packet was received' print '[warning]', 'Malformed or incomplete MS packet was received'
continue continue
if isinstance(network[CHATMSG], unicode): if isinstance(network[CHATMSG], unicode):
@ -24,22 +114,12 @@ def handlePackets(caller, total, record=True):
caller.MS_Chat.emit(network) caller.MS_Chat.emit(network)
elif header == 'MC': elif header == 'MC':
music = decodeAOString(network[1]) del network[0]
charid = int(network[2]) music = decodeAOString(network[0])
t = time.localtime() if not music: return
timestamp = "[%d:%.2d] " % (t[3], t[4]) if not caller.parent.demoPlaying else "" charid = int(network[1])
if charid != -1: showname = decodeAOString(network[2]) if len(network) > 2 else None
try: caller.playMusicRequested.emit(music, charid, showname)
name = caller.parent.charList[charid][0]
except:
name = 'char id %d' % charid
if len(network) > 3 and network[3]:
name += " ("+network[3].decode("utf-8")+")"
caller.IC_Log.emit(timestamp + '%s changed the music to %s' % (name, music))
else:
caller.IC_Log.emit(timestamp + 'The music was changed to %s' % music)
caller.parent.playMusic(music)
elif header == 'BN': elif header == 'BN':
caller.newBackground.emit(network[1].lower(), True) caller.newBackground.emit(network[1].lower(), True)
@ -56,19 +136,6 @@ def handlePackets(caller, total, record=True):
del network[0] del network[0]
caller.loadAllEvidence.emit([evi.split('&') for evi in network]) caller.loadAllEvidence.emit([evi.split('&') for evi in network])
elif header == 'ZZ':
# TODO: Remove from tcp thread
if caller.parent.modcall:
audio.freeHandle(caller.parent.modcall)
caller.parent.modcall = audio.loadHandle(0, "mod_call.wav", 0, 0, 0)
audio.setHandleAttr(caller.parent.modcall, BASS_ATTRIB_VOL, caller.parent.sliSoundVolume.value() / 100.0)
audio.playHandle(caller.parent.modcall, False)
if len(network) > 1:
caller.OOC_Log.emit('<b>[MOD CALL] ' + network[1].replace("\n", "<br />") + '</b>')
else:
caller.OOC_Log.emit('<b>[MOD CALL] But there was no extra information. (old server?)</b>')
elif header == 'CharsCheck': elif header == 'CharsCheck':
del network[0] del network[0]
caller.charSlots.emit(network) caller.charSlots.emit(network)
@ -83,21 +150,6 @@ def handlePackets(caller, total, record=True):
health = int(network[2]) health = int(network[2])
caller.parent.healthbars.emit(kind, health) caller.parent.healthbars.emit(kind, health)
elif header == 'KK':
# TODO: Show message from GUI thread
reason = network[1]
caller.parent.emit(QtCore.SIGNAL('showMessage(QString, QString, QString)'), 'critical', 'Connection lost', 'You were kicked from the server. (%s)' % reason)
elif header == 'KB':
# TODO: Show message from GUI thread
reason = network[1]
caller.parent.emit(QtCore.SIGNAL('showMessage(QString, QString, QString)'), 'critical', 'Connection lost', 'You have been banned from the server. (%s)' % reason)
elif header == 'BB': # message popup (AO 2.9)
# TODO: Show message from GUI thread
message = network[1]
caller.parent.emit(QtCore.SIGNAL('showMessage(QString, QString, QString)'), 'information', 'Message from server', message)
elif header == 'AUTH': # login status (AO 2.9) elif header == 'AUTH': # login status (AO 2.9)
caller.authStatusChanged.emit(int(network[1])) caller.authStatusChanged.emit(int(network[1]))
@ -127,10 +179,24 @@ def handlePackets(caller, total, record=True):
time_ms = 0 time_ms = 0
if len(network) == 3: if len(network) == 3:
time_ms = int(network[2]) time_ms = int(network[2])
caller.timerUpdate.emit(command, timer_id, time_ms) caller.timerUpdate.emit(command, timer_id, time_ms)
# For demos
elif header == 'SC': elif header == 'SC':
# Used in demos
del network[0] del network[0]
caller.setCharList.emit([ [char.split('&')[0].decode('utf-8'), 0, "male", True ] for char in network ]) caller.setCharList.emit([[char.split('&')[0].decode('utf-8'), 0, "male", True] for char in network])
elif header == 'KK':
reason = network[1]
caller.connectionError.emit('critical', 'Connection lost', 'You were kicked from the server. (%s)' % reason)
elif header == 'KB':
reason = network[1]
caller.connectionError.emit('critical', 'Connection lost', 'You have been banned from the server. (%s)' % reason)
elif header == 'BB': # message popup (AO 2.9)
message = network[1]
caller.connectionError.emit('information', 'Message from server', message)
elif header == 'ZZ':
caller.modCall.emit(network[1].replace("\n", "<br />"))