Commit 06080577 authored by Zheng Yile's avatar Zheng Yile
Browse files

Merge branch 'gui-feature-thread' into gui-master

parents f9b0ff8c 9df3bda3
......@@ -5,7 +5,7 @@ from PyQt5.QtCore import Qt, QSize, QThread, pyqtSignal
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout
from PyQt5.QtWidgets import QListWidgetItem, QWidget, QListWidget
from PyQt5.QtWidgets import QListWidgetItem, QWidget
from PyQt5.QtWidgets import QMessageBox, QMainWindow, QApplication
from codiaclient import net_var
......@@ -13,7 +13,7 @@ from codiaclient.network import get_pack, show_pack, start_pack, logined, get_ex
from codiaclient.network import submit,get_data
from codiaclient.report import Error as codiaError, error_translate
from codiaclient.requests import variables as requests_var
from codiaclientgui.utils import QPalette, Font, Palette, Style, Color, ErrorDisplay
from codiaclientgui.utils import QPalette, Font, Palette, Style, Color, ErrorDisplay, NewListWidget
from mainWindow import Ui_windowMain
variables = {
......@@ -24,10 +24,14 @@ variables = {
"hasNext": True,
"packInfo": {},
"currentPackRow": None,
"exerciseInfo": None
"exerciseInfo": None,
"workingStatus": {
"frameExerciseInit": False,
"frameQuestionInit": False,
}
}
displayLanguage = {
toDisplay = {
'CPP': 'C++',
'C': 'C',
'JAVA': 'Java',
......@@ -41,17 +45,16 @@ displayLanguage = {
'time limit exceeds': "超时",
"": '正在评测'
}
dataLanguage = {val: key for key, val in displayLanguage.items()}
toData = {val: key for key, val in toDisplay.items()}
# 获取题包内容信息的网络通信
class _ShowPack(QThread):
class MyThread(QThread):
infoSignal = pyqtSignal(dict)
errorSignal = pyqtSignal(codiaError)
def __init__(self, *args, pid, **kargs):
super(_ShowPack, self).__init__(*args, **kargs)
def __init__(self, *args, RunMethod, **kargs):
super(MyThread, self).__init__(*args, **kargs)
self.working = True
self.pid = pid
self.RunMethod = RunMethod
def __del__(self):
self.working = False
......@@ -59,17 +62,17 @@ class _ShowPack(QThread):
def run(self):
try:
self.packInfo = show_pack(pid=self.pid)
self.Info = self.RunMethod()
except codiaError as e:
self.errorSignal.emit(e)
else:
self.infoSignal.emit(self.packInfo)
self.infoSignal.emit(self.Info)
# 获取题包内容信息的多线程准备
# 获取题包内容信息的多线程
def ShowPack(pid, InfoRecv=lambda: None, ErrorRecv=lambda: None):
global threadShowPack # extremely essential!
threadShowPack = _ShowPack(pid=pid)
threadShowPack = MyThread(RunMethod=lambda: show_pack(pid=pid))
threadShowPack.infoSignal.connect(InfoRecv)
threadShowPack.errorSignal.connect(ErrorRecv)
uiMain.progressBarPack.setValue(90)
......@@ -77,27 +80,23 @@ def ShowPack(pid, InfoRecv=lambda: None, ErrorRecv=lambda: None):
def frameExerciseInit():
global frameExerciseInitWorking
try:
if frameExerciseInitWorking:
return
except:
pass
if variables["workingStatus"]["frameExerciseInit"]:
return
if not uiMain.listWidgetPack.selectedIndexes():
QMessageBox.information(None, "提示", "请选择一个题包", QMessageBox.Ok)
QMessageBox.information(None, "提示", "请选择一个题包", QMessageBox.Ok)
return
getSelectedPid()
uiMain.progressBarPack.setValue(0)
uiMain.progressBarPack.show()
frameExerciseInitWorking = True
variables["workingStatus"]["frameExerciseInit"] = True
def ErrorRecv(e: codiaError):
global frameExerciseInitWorking
ErrorDisplay(e, error_translate, "获取失败")
uiMain.progressBarPack.hide()
frameExerciseInitWorking = False
variables["workingStatus"]["frameExerciseInit"] = False
def exerciseListInfoRecv(exerciseListInfo):
global frameExerciseInitWorking
presentTime = datetime.now()
if exerciseListInfo["due"]:
endTime = datetime.strptime(search(r"^[^.]*", exerciseListInfo["due"].replace("T", " ")).group(),
......@@ -126,7 +125,7 @@ def frameExerciseInit():
for exercise in variables['exerciseListInfo']:
AddItemToQuestionList(exercise)
uiMain.progressBarPack.hide()
frameExerciseInitWorking = False
variables["workingStatus"]["frameExerciseInit"] = False
uiMain.framePack.hide()
uiMain.frameExercise.show()
......@@ -179,6 +178,8 @@ def getSelectedPid():
def getSelectedEid():
if variables['workingStatus']['frameQuestionInit']:
return
selected = uiMain.listWidgetExercise.currentIndex().row()
variables['currentExerciseRow'] = selected
requests_var['e'] = variables['exerciseListInfo'][selected]['id']
......@@ -214,35 +215,10 @@ def MainInit(callback=None):
GetPage()
# 获取题目信息的网络通信
class _GetExercise(QThread):
infoSignal = pyqtSignal(dict)
errorSignal = pyqtSignal(codiaError)
def __init__(self, *args, pid, eid, lang, **kargs):
super(_GetExercise, self).__init__(*args, **kargs)
self.working = True
self.pid = pid
self.eid = eid
self.lang = lang
def __del__(self):
self.working = False
self.wait()
def run(self):
try:
self.exerciseInfo = get_exercise(eid=self.eid, pid=self.pid, lang=self.lang)
except codiaError as e:
self.errorSignal.emit(e)
else:
self.infoSignal.emit(self.exerciseInfo)
# 获取题目信息的多线程准备
# 获取题目信息的多线程
def GetExercise(pid, eid, lang, InfoRecv=lambda: None, ErrorRecv=lambda: None):
global threadGetExercise # extremely essential!
threadGetExercise = _GetExercise(eid=eid, pid=pid, lang=lang)
threadGetExercise = MyThread(RunMethod=lambda: get_exercise(eid=eid, pid=pid, lang=lang))
threadGetExercise.infoSignal.connect(InfoRecv)
threadGetExercise.errorSignal.connect(ErrorRecv)
uiMain.progressBarExercise.setValue(90)
......@@ -250,23 +226,18 @@ def GetExercise(pid, eid, lang, InfoRecv=lambda: None, ErrorRecv=lambda: None):
def frameQuestionInit():
global frameQuestionInitWorking
try:
if frameQuestionInitWorking:
return
except:
pass
if variables["workingStatus"]["frameQuestionInit"]:
return
if not uiMain.listWidgetExercise.selectedIndexes():
QMessageBox.information(None, '消息', '请选择一个题目', QMessageBox.Ok)
return
frameQuestionInitWorking = True
getSelectedEid()
variables["workingStatus"]["frameQuestionInit"] = True
uiMain.progressBarExercise.setValue(0)
uiMain.progressBarExercise.show()
def ExerciseInfoRecv(questionInfo):
global frameQuestionInitWorking
variables['exerciseInfo'] = questionInfo
windowMain.setWindowTitle(questionInfo['title'])
uiMain.statusbar.clearMessage()
......@@ -299,20 +270,19 @@ def frameQuestionInit():
str(questionInfo['viewerStatus']['totalCount']))
uiMain.comboBoxLanguage.clear()
uiMain.comboBoxLanguage.addItem('请选择提交语言')
languages = [displayLanguage[lan] for lan in variables['exerciseInfo']['supportedLanguages']]
languages = [toDisplay[lang] for lang in variables['exerciseInfo']['supportedLanguages']]
uiMain.comboBoxLanguage.addItems(languages)
uiMain.labelSubmitStatus.setText(uiMain.labelQuestionStatus.text())
uiMain.textEditSubmit.setText(variables['exerciseInfo']['codeSnippet'])
uiMain.progressBarExercise.hide()
frameQuestionInitWorking = False
variables["workingStatus"]["frameQuestionInit"] = False
uiMain.frameExercise.hide()
uiMain.frameQuestion.show()
def ErrorRecv(e: codiaError):
global frameQuestionInitWorking
ErrorDisplay(e, error_translate, "获取失败")
uiMain.progressBarExercise.hide()
frameQuestionInitWorking = False
variables["workingStatus"]["frameQuestionInit"] = False
GetExercise(pid=requests_var['p'], eid=requests_var['e'],
lang='CPP', InfoRecv=ExerciseInfoRecv,
......@@ -330,29 +300,31 @@ def BeginMain(callback=None):
uiMain.statusbar.showMessage(f"当前用户: {nickname}", 0)
else:
uiMain.statusbar.showMessage(f"当前用户: {nickname}(未验证)", 0)
QMessageBox.information(None, "消息", "当前账号功能受限,请尽快完成联系方式验证", QMessageBox.Ok)
QMessageBox.information(None, "消息", "当前账号功能受限,请尽快完成联系方式验证", QMessageBox.Ok)
uiMain.statusbar.setFont(Font["status"])
uiMain.pushButtonPackNext.clicked.connect(lambda: GetPage(before=variables["lastPid"]))
uiMain.pushButtonPackPrevious.clicked.connect(lambda: GetPage(after=variables["firstPid"]))
uiMain.progressBarPack.hide()
uiMain.progressBarExercise.hide()
uiMain.progressBarSubmit.hide()
uiMain.frameQuestion.hide()
uiMain.frameHistory.hide()
uiMain.frameSubmit.hide()
uiMain.progressBarPack.setStyleSheet(Style["progressBar"])
uiMain.progressBarExercise.setStyleSheet(Style["progressBar"])
uiMain.progressBarSubmit.setStyleSheet(Style["progressBar"])
uiMain.textEditSubmit.setTabStopWidth(uiMain.textEditSubmit.font().pointSize() * 2)
codeFont = QFont()
codeFont.setFamily('Consolas')
uiMain.textEditSubmit.setFont(codeFont)
uiMain.listWidgetPack.itemClicked.connect(getSelectedPid)
# uiMain.listWidgetPack.itemClicked.connect(getSelectedPid)
uiMain.listWidgetPack.itemDoubleClicked.connect(frameExerciseInit)
uiMain.pushButtonPackOK.clicked.connect(frameExerciseInit)
uiMain.pushButtonExerciseReturn.clicked.connect(ExerciseReturn)
uiMain.pushButtonExerciseBegin.clicked.connect(BeginPack)
uiMain.listWidgetExercise.itemClicked.connect(getSelectedEid)
# uiMain.listWidgetExercise.itemClicked.connect(getSelectedEid)
uiMain.listWidgetExercise.itemDoubleClicked.connect(frameQuestionInit)
uiMain.pushButtonExerciseOK.clicked.connect(frameQuestionInit)
uiMain.pushButtonQuestionReturn.clicked.connect(QuestionReturn)
......@@ -369,7 +341,7 @@ def BeginMain(callback=None):
uiMain.pushButtonHistoryBack.clicked.connect(HistoryReturn)
for i in range(0, variables['packPerPage']):
AddItemToPackList(uiMain.listWidgetPack, colorName=['white', 'lightgray'][i % 2])
AddItemToPackList(uiMain.listWidgetPack)
uiMain.frameExercise.hide()
uiMain.framePack.show()
......@@ -402,20 +374,13 @@ def AddItemToHistoryList(data: dict):
item = QListWidgetItem()
item.setSizeHint(QSize(960, 65))
widget = GetHistoryWidget(data)
if not widget.isEnabled():
item.setFlags(item.flags() & ~Qt.ItemIsSelectable)
uiMain.listWidgetPackHistory.addItem(item)
uiMain.listWidgetPackHistory.setItemWidget(item, widget)
def GetHistoryWidget(data: dict):
if not data:
widget = QWidget()
layout = QHBoxLayout()
labelStatus = QLabel('评测中')
labelStatus.setAlignment(Qt.AlignCenter)
layout.addWidget(labelStatus)
widget.setLayout(layout)
return widget
mainLayout = QHBoxLayout()
elapseLayout = QVBoxLayout()
statusLabel = QLabel()
......@@ -435,13 +400,13 @@ def GetHistoryWidget(data: dict):
errorType = i['value']
if not errorType:
for i in data['submission']['reports']:
if (i['value'] != 'passed' and i['value'] != 'memory consumed'
and i['value'] != 'time elapsed' and i['value'] != 'score'):
if (i['value'] != 'passed' and i['key'] != 'memory consumed'
and i['key'] != 'time elapsed' and i['key'] != 'score'):
errorType = i['value']
break
statusLabel.setText(displayLanguage[errorType])
statusLabel.setText(toDisplay[errorType])
SetErrorColor(statusLabel)
languageLabel.setText(displayLanguage[data['solution']['lang']])
languageLabel.setText(toDisplay[data['solution']['lang']])
timeLabel.setText('提交时间:' +
(datetime.strptime(search(r"^[^.]*", data["time"].replace("T", " ")).group(),
"%Y-%m-%d %H:%M:%S") + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"))
......@@ -470,6 +435,8 @@ def GetHistoryWidget(data: dict):
widget = QWidget()
widget.setLayout(mainLayout)
widget.setCursor(Qt.PointingHandCursor)
if not data['submission']['reports']:
widget.setEnabled(False)
return widget
......@@ -485,7 +452,7 @@ def SetErrorColor(statusLabel: QLabel):
def ReadFromFile(lang: str):
if uiMain.comboBoxLanguage.currentText() == '请选择提交语言':
if lang == '请选择提交语言':
QMessageBox.information(None, '提示', '请选择一种提交语言。', QMessageBox.Ok)
return
fileWindow = QFileDialog()
......@@ -504,12 +471,12 @@ def ReadFromFile(lang: str):
elif lang == 'Rust':
fileWindow.setNameFilter('Rust 源文件(*.rs)')
else:
QMessageBox.critical(None, '错误', '未知错误', QMessageBox.Ok)
fileWindow.setDirectory('./')
QMessageBox.critical(None, '错误', '未知错误', QMessageBox.Ok)
# fileWindow.setDirectory('./')
if fileWindow.exec_():
fileChosen = fileWindow.selectedFiles()[0]
else:
QMessageBox.information(None, '提示', '请选择一个文件', QMessageBox.Ok)
QMessageBox.information(None, '提示', '请选择一个文件', QMessageBox.Ok)
return None
with open(fileChosen, "r") as inputCode:
codeSubmit = inputCode.read()
......@@ -530,26 +497,41 @@ def SubmitReturn():
uiMain.frameSubmit.hide()
uiMain.frameQuestion.show()
def Submit(pid, eid, lang, code, InfoRecv=lambda: None, ErrorRecv=lambda: None):
global threadSubmit # extremely essential!
threadSubmit = MyThread(RunMethod=lambda: submit(eid=eid, pid=pid, lang=lang, solutioncode=code))
threadSubmit.infoSignal.connect(InfoRecv)
threadSubmit.errorSignal.connect(ErrorRecv)
uiMain.progressBarSubmit.setValue(90)
threadSubmit.start()
def SubmitCode(lang: str, code: str):
if lang == '请选择提交语言':
QMessageBox.information(None, '提示', '请选择一种提交语言。', QMessageBox.Ok)
return
try:
submit_result = submit(requests_var['e'], requests_var['p'], dataLanguage[lang], code)
except codiaError as e:
ErrorDisplay(e, error_translate, "提交失败")
else:
if submit_result:
uiMain.progressBarSubmit.setValue(0)
uiMain.progressBarSubmit.show()
def ErrorRecv(e: codiaError):
ErrorDisplay(e, error_translate, "获取失败")
uiMain.progressBarSubmit.hide()
def submitInfoRecv(submitInfo):
if submitInfo:
QMessageBox.information(None, '提交成功', '提交成功,请在历史记录中查看评测结果', QMessageBox.Ok)
variables['exerciseListInfo'][variables['currentExerciseRow']]['viewerStatus']['totalCount']
uiMain.frameSubmit.hide()
uiMain.frameQuestion.show()
else:
QMessageBox.critical(None, '提交失败', '请检查语言选择是否正确。', QMessageBox.Ok)
QMessageBox.critical(None, '提交失败', '请检查语言选择是否正确', QMessageBox.Ok)
uiMain.progressBarSubmit.hide()
Submit(pid=requests_var['p'], eid=requests_var['e'], lang=toData[lang], code=code, InfoRecv=submitInfoRecv, ErrorRecv=ErrorRecv)
def SubmitInit():
languages = [displayLanguage[lang] for lang in variables['exerciseInfo']['supportedLanguages']]
languages = [toDisplay[lang] for lang in variables['exerciseInfo']['supportedLanguages']]
uiMain.comboBoxLanguageSubmit.clear()
uiMain.comboBoxLanguageSubmit.addItem('请选择提交语言')
uiMain.comboBoxLanguageSubmit.addItems(languages)
......@@ -579,37 +561,13 @@ def UpdatePage():
packList.reverse()
packList += [None] * (variables['packPerPage'] - len(packList))
for i in range(0, len(packList)):
AddItemToPackList(uiMain.listWidgetPack, packList[i], colorName=['white', 'lightgray'][i % 2])
# 获取题包信息的网络通信
class _GetPack(QThread):
infoSignal = pyqtSignal(dict)
errorSignal = pyqtSignal(codiaError)
def __init__(self, *args, before=None, after=None, **kargs):
super(_GetPack, self).__init__(*args, **kargs)
self.working = True
self.before = before
self.after = after
def __del__(self):
self.working = False
self.wait()
def run(self):
try:
self.packInfo = get_pack(cnt=variables['packPerPage'], before=self.before, after=self.after)
except codiaError as e:
self.errorSignal.emit(e)
else:
self.infoSignal.emit(self.packInfo)
AddItemToPackList(uiMain.listWidgetPack, packList[i])
# 获取题包信息的多线程准备
# 获取题包信息的多线程
def GetPack(before=None, after=None, InfoRecv=lambda: None, ErrorRecv=lambda: None):
global threadGetPack # extremely essential!
threadGetPack = _GetPack(before=before, after=after)
threadGetPack = MyThread(RunMethod=lambda: get_pack(cnt=variables['packPerPage'], before=before, after=after))
threadGetPack.infoSignal.connect(InfoRecv)
threadGetPack.errorSignal.connect(ErrorRecv)
uiMain.progressBarPack.setValue(90)
......@@ -722,10 +680,9 @@ def GetPackWidget(data: dict):
return widget
def AddItemToPackList(packList: QListWidget, data: dict = {}, colorName: str = "white"):
def AddItemToPackList(packList: NewListWidget, data: dict = {}):
item = QListWidgetItem()
item.setSizeHint(QSize(960, 65))
item.setBackground(Color[colorName])
if not data:
widget = QWidget()
widget.setEnabled(False)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment