Refactor code to improve readability, try diff threads

This commit is contained in:
WorldTeacher
2024-02-09 13:17:15 +01:00
parent ae9bb40166
commit cbd3ae80c7

View File

@@ -123,7 +123,6 @@ class MessageCalendar(QtWidgets.QCalendarWidget):
) )
class Ui(Ui_Semesterapparat): class Ui(Ui_Semesterapparat):
# use the Ui_MainWindow class from mainwindow.py # use the Ui_MainWindow class from mainwindow.py
def __init__(self, MainWindow, username: str) -> None: def __init__(self, MainWindow, username: str) -> None:
@@ -161,7 +160,7 @@ class Ui(Ui_Semesterapparat):
) )
self.calendarWidget.setObjectName("MessageCalendar") self.calendarWidget.setObjectName("MessageCalendar")
self.calendarWidget.clicked.connect(self.open_reminder) self.calendarWidget.clicked.connect(self.open_reminder)
#assign a context menu to the calendar # assign a context menu to the calendar
self.calendarWidget.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu) self.calendarWidget.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.calendarWidget.customContextMenuRequested.connect(self.calendar_context_menu) self.calendarWidget.customContextMenuRequested.connect(self.calendar_context_menu)
@@ -214,7 +213,7 @@ class Ui(Ui_Semesterapparat):
self.tableWidget_apparat_media.customContextMenuRequested.connect( self.tableWidget_apparat_media.customContextMenuRequested.connect(
self.media_context_menu self.media_context_menu
) )
#enable automatic resizing of columns for book_search_result # enable automatic resizing of columns for book_search_result
self.book_search_result.horizontalHeader().setSectionResizeMode( self.book_search_result.horizontalHeader().setSectionResizeMode(
QtWidgets.QHeaderView.ResizeMode.Stretch QtWidgets.QHeaderView.ResizeMode.Stretch
) )
@@ -292,7 +291,7 @@ class Ui(Ui_Semesterapparat):
#!admin - create user #!admin - create user
#!admin - delete user #!admin - delete user
#!admin - change user #!admin - change user
#TODO:admin - change faculty # TODO:admin - change faculty
self.select_action_box.addItem("") self.select_action_box.addItem("")
self.select_action_box.setCurrentText("") self.select_action_box.setCurrentText("")
self.hide_all() self.hide_all()
@@ -300,9 +299,9 @@ class Ui(Ui_Semesterapparat):
self.edit_faculty_member_select_member.currentTextChanged.connect(self.edit_faculty_member_set_data) self.edit_faculty_member_select_member.currentTextChanged.connect(self.edit_faculty_member_set_data)
self.book_search.clicked.connect(self.search_book) self.book_search.clicked.connect(self.search_book)
#enable click functionality for the combobox to allow selection of roles # enable click functionality for the combobox to allow selection of roles
#admin buttons # admin buttons
self.user_frame_addUser.clicked.connect(self.add_user) self.user_frame_addUser.clicked.connect(self.add_user)
self.pushButton.clicked.connect(self.delete_user) self.pushButton.clicked.connect(self.delete_user)
self.update_user.clicked.connect(self.update_user_data) self.update_user.clicked.connect(self.update_user_data)
@@ -320,7 +319,6 @@ class Ui(Ui_Semesterapparat):
self.tabWidget_2.setCurrentIndex(1) self.tabWidget_2.setCurrentIndex(1)
self.tabWidget_2.setCurrentIndex(0) self.tabWidget_2.setCurrentIndex(0)
def search_book(self): def search_book(self):
self.book_search_result.setRowCount(0) self.book_search_result.setRowCount(0)
signature = self.seach_by_signature.text() signature = self.seach_by_signature.text()
@@ -342,15 +340,14 @@ class Ui(Ui_Semesterapparat):
print(book[1]) print(book[1])
self.book_search_result.setItem(0,2,QtWidgets.QTableWidgetItem(self.db.getApparatName(book[1],book[2]))) self.book_search_result.setItem(0,2,QtWidgets.QTableWidgetItem(self.db.getApparatName(book[1],book[2])))
def edit_faculty_member_set_data(self): def edit_faculty_member_set_data(self):
#get the selected member # get the selected member
name = self.edit_faculty_member_select_member.currentText() name = self.edit_faculty_member_select_member.currentText()
fullname = name.replace(",","") fullname = name.replace(",","")
print(fullname,name) print(fullname,name)
#get the data for the selected member # get the data for the selected member
data = self.db.getProfByName(fullname) data = self.db.getProfByName(fullname)
#set the data # set the data
print(data) print(data)
if data == None: if data == None:
self.edit_faculty_member_title.setText("") self.edit_faculty_member_title.setText("")
@@ -363,7 +360,6 @@ class Ui(Ui_Semesterapparat):
self.faculty_member_oldmail.setText(data[5]) self.faculty_member_oldmail.setText(data[5])
self.edit_faculty_member_title.setText(data[1]) if data[1] != None else self.edit_faculty_member_title.setText("") self.edit_faculty_member_title.setText(data[1]) if data[1] != None else self.edit_faculty_member_title.setText("")
# self.edit_faculty_member_name.setText(f"{data[3]} {data[2]}") # self.edit_faculty_member_name.setText(f"{data[3]} {data[2]}")
# self.edit_faculty_member_title.setCurrentText(data[1]) # self.edit_faculty_member_title.setCurrentText(data[1])
# self.edit_faculty_member_mail.setText(data[4]) # self.edit_faculty_member_mail.setText(data[4])
@@ -424,7 +420,7 @@ class Ui(Ui_Semesterapparat):
return f"{data[2]} {fname}" return f"{data[2]} {fname}"
if fname != "" and lname != "": if fname != "" and lname != "":
return f"{lname} {fname}" return f"{lname} {fname}"
#get the data and use new value if it is not none and does not mach the old value # get the data and use new value if it is not none and does not mach the old value
if self.edit_faculty_member_select_member.currentText() =="": if self.edit_faculty_member_select_member.currentText() =="":
return return
olddata = self.db.getFacultyMember(self.edit_faculty_member_select_member.currentText()) olddata = self.db.getFacultyMember(self.edit_faculty_member_select_member.currentText())
@@ -432,7 +428,7 @@ class Ui(Ui_Semesterapparat):
data = olddata[0] data = olddata[0]
oldlname = data[2] oldlname = data[2]
oldfname = data[1] oldfname = data[1]
#take data except first and last entry # take data except first and last entry
titel = self.edit_faculty_member_new_title.currentText() if self.edit_faculty_member_new_title.currentText() != "Kein Titel" else None titel = self.edit_faculty_member_new_title.currentText() if self.edit_faculty_member_new_title.currentText() != "Kein Titel" else None
fname = self.edit_faculty_member_new_surname.text() if self.edit_faculty_member_new_surname.text() != "" else self.edit_faculty_member_select_member.currentText().split(" ")[1].strip() fname = self.edit_faculty_member_new_surname.text() if self.edit_faculty_member_new_surname.text() != "" else self.edit_faculty_member_select_member.currentText().split(" ")[1].strip()
@@ -467,7 +463,7 @@ class Ui(Ui_Semesterapparat):
action = self.select_action_box.currentText() action = self.select_action_box.currentText()
roles = self.db.getRoles() roles = self.db.getRoles()
roles = [role[0] for role in roles] roles = [role[0] for role in roles]
#remove duplicates # remove duplicates
roles = list(dict.fromkeys(roles)) roles = list(dict.fromkeys(roles))
users = self.db.getUsers() users = self.db.getUsers()
users = [user[2] for user in users] users = [user[2] for user in users]
@@ -496,7 +492,6 @@ class Ui(Ui_Semesterapparat):
self.add_faculty_member_data() self.add_faculty_member_data()
self.edit_faculty_member_new_title.addItems(PROF_TITLES) self.edit_faculty_member_new_title.addItems(PROF_TITLES)
else: else:
self.hide_all() self.hide_all()
return return
@@ -571,18 +566,18 @@ class Ui(Ui_Semesterapparat):
def open_apparat(self, header:str, apparat:str, parent_depth:int): def open_apparat(self, header:str, apparat:str, parent_depth:int):
print(header) print(header)
if header == "deleted" and parent_depth == 2: if header == "deleted" and parent_depth == 2:
#TODO: warn message here # TODO: warn message here
print("warning") print("warning")
if parent_depth == 1: if parent_depth == 1:
print(apparat) print(apparat)
#person selected case - open all apparats from this person in the tableWidget # person selected case - open all apparats from this person in the tableWidget
self.tableWidget.setRowCount(0) self.tableWidget.setRowCount(0)
prof_id = self.db.getProfId(apparat.split("(")[0].strip()) prof_id = self.db.getProfId(apparat.split("(")[0].strip())
apparats = self.db.getApparatsByProf(prof_id) apparats = self.db.getApparatsByProf(prof_id)
for app in apparats: for app in apparats:
print(app) print(app)
#set the items 0 = clickable checkbox, 1 = appname, 2 = profname, 3 = fach # set the items 0 = clickable checkbox, 1 = appname, 2 = profname, 3 = fach
#insert new row # insert new row
self.tableWidget.insertRow(0) self.tableWidget.insertRow(0)
self.tableWidget.setItem(0,0, QtWidgets.QTableWidgetItem("")) self.tableWidget.setItem(0,0, QtWidgets.QTableWidgetItem(""))
self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem(app[1])) self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem(app[1]))
@@ -606,9 +601,9 @@ class Ui(Ui_Semesterapparat):
"Dieser Semesterapparat kann nicht gelöscht werden, da er bereits gelöscht wurde" "Dieser Semesterapparat kann nicht gelöscht werden, da er bereits gelöscht wurde"
) )
elif parent_depth == 2: elif parent_depth == 2:
#apparat selected case - open the apparat in the frame # apparat selected case - open the apparat in the frame
self.load_app_data(apparat) self.load_app_data(apparat)
#change tab focus to tab 0 # change tab focus to tab 0
self.tabWidget.setCurrentIndex(0) self.tabWidget.setCurrentIndex(0)
return return
@@ -636,7 +631,7 @@ class Ui(Ui_Semesterapparat):
self.tab_changed() self.tab_changed()
def populate_tab(self): def populate_tab(self):
#add default values to the dropdowns # add default values to the dropdowns
self.box_appnrs.clear() self.box_appnrs.clear()
self.box_appnrs.addItem("") self.box_appnrs.addItem("")
self.box_appnrs.setCurrentText("") self.box_appnrs.setCurrentText("")
@@ -655,7 +650,7 @@ class Ui(Ui_Semesterapparat):
self.box_dauerapp.clear() self.box_dauerapp.clear()
self.box_dauerapp.addItems(["Ja", "Nein", ""]) self.box_dauerapp.addItems(["Ja", "Nein", ""])
self.box_dauerapp.setCurrentText("") self.box_dauerapp.setCurrentText("")
#add custom vaules # add custom vaules
appnrs = self.db.getUnavailableApparatNumbers() appnrs = self.db.getUnavailableApparatNumbers()
apparats = natsorted(appnrs) apparats = natsorted(appnrs)
apparats = [str(apparat) for apparat in apparats] apparats = [str(apparat) for apparat in apparats]
@@ -669,7 +664,7 @@ class Ui(Ui_Semesterapparat):
self.box_erstellsemester.addItems(semester) self.box_erstellsemester.addItems(semester)
self.statistics_table.setRowCount(0) self.statistics_table.setRowCount(0)
#set data for table and graph in tab 2 tableWidget_3 # set data for table and graph in tab 2 tableWidget_3
data = self.db.getApparatCountBySemester() data = self.db.getApparatCountBySemester()
data = c_sort.custom_sort(data) data = c_sort.custom_sort(data)
# self.tabWidget_3.clear() # self.tabWidget_3.clear()
@@ -795,8 +790,6 @@ class Ui(Ui_Semesterapparat):
"Dieser Semesterapparat kann nicht gelöscht werden, da er bereits gelöscht wurde" "Dieser Semesterapparat kann nicht gelöscht werden, da er bereits gelöscht wurde"
) )
def populate_frame(self, appdata: ApparatData): def populate_frame(self, appdata: ApparatData):
# populate the frame with the data from the database # populate the frame with the data from the database
ic(appdata) ic(appdata)
@@ -870,8 +863,6 @@ class Ui(Ui_Semesterapparat):
self.update_app_media_list() self.update_app_media_list()
self.cancel_active_selection.click() self.cancel_active_selection.click()
def confirm_popup(self, message: str): def confirm_popup(self, message: str):
dial = QtWidgets.QDialog() dial = QtWidgets.QDialog()
popup = popus_confirm() popup = popus_confirm()
@@ -1029,9 +1020,9 @@ class Ui(Ui_Semesterapparat):
def load_app_data(self,app_id=None): def load_app_data(self,app_id=None):
print(type(app_id)) print(type(app_id))
if isinstance(app_id, str): if isinstance(app_id, str):
#double click the tableWidget_apparate row with the given app_id # double click the tableWidget_apparate row with the given app_id
row,column = self.get_index_of_value(self.tableWidget_apparate,app_id) row,column = self.get_index_of_value(self.tableWidget_apparate,app_id)
#set the current index to the row # set the current index to the row
self.tableWidget_apparate.setCurrentCell(row,0) self.tableWidget_apparate.setCurrentCell(row,0)
app_pos = self.tableWidget_apparate.currentIndex() app_pos = self.tableWidget_apparate.currentIndex()
appnr = self.tableWidget_apparate.item(app_pos.row(), 0).text() appnr = self.tableWidget_apparate.item(app_pos.row(), 0).text()
@@ -1109,12 +1100,14 @@ class Ui(Ui_Semesterapparat):
text = f"Medium {curr}/{total}" text = f"Medium {curr}/{total}"
self.logger.log_info(text) self.logger.log_info(text)
self.progress_label.setText(text) self.progress_label.setText(text)
self.MainWindow.setStatusTip(f"Medien werden hinzugefügt, bitte warten... {curr}/{total}")
# update tableWidget_apparat_media # update tableWidget_apparat_media
self.update_app_media_list() self.update_app_media_list()
def hide_progress_label(self): def hide_progress_label(self):
self.logger.log_info("Finished adding media, hiding progress label") self.logger.log_info("Finished adding media, hiding progress label")
self.progress_label.hide() self.progress_label.hide()
self.progress_label.setText("Bitte warten...")
self.line_2.hide() self.line_2.hide()
self.label_info.hide() self.label_info.hide()
@@ -1148,9 +1141,12 @@ class Ui(Ui_Semesterapparat):
# create apparat # create apparat
self.btn_save_apparat() self.btn_save_apparat()
# create a thread that updates the progress label after each medium # create a thread that updates the progress label after each medium
count = len(data)
thread = QThread() thread = QThread()
grabber = BookGrabber(mode, data, app_id, prof_id) grabber = BookGrabber(mode=mode, app_id=app_id, prof_id=prof_id, data=data)
# grabber.mode = mode
# grabber.data = data
# grabber.app_id = app_id
# grabber.prof_id = prof_id
grabber.moveToThread(thread) grabber.moveToThread(thread)
grabber.finished.connect(thread.quit) grabber.finished.connect(thread.quit)
grabber.finished.connect(grabber.deleteLater) grabber.finished.connect(grabber.deleteLater)
@@ -1354,7 +1350,7 @@ class Ui(Ui_Semesterapparat):
# set tooltip of row 3 to the file path for each row # set tooltip of row 3 to the file path for each row
self.dokument_list.item(0, 3).setToolTip(file) self.dokument_list.item(0, 3).setToolTip(file)
# self.db.insert_file(files, self.active_apparat(), self.db.get_prof_id(self.drpdwn_prof_name.currentText())) # self.db.insert_file(files, self.active_apparat(), self.db.get_prof_id(self.drpdwn_prof_name.currentText()))
def open_document(self): def open_document(self):
_selected_doc_name = "" _selected_doc_name = ""
@@ -1388,7 +1384,6 @@ class Ui(Ui_Semesterapparat):
# path = path.replace("~", str(Path.home())) # path = path.replace("~", str(Path.home()))
# path = Path(path) # path = Path(path)
def add_media_from_file(self): def add_media_from_file(self):
def __open_dialog(signatures): def __open_dialog(signatures):
dialog = QtWidgets.QDialog() dialog = QtWidgets.QDialog()
@@ -1492,7 +1487,7 @@ class Ui(Ui_Semesterapparat):
prof_id = self.db.getProfId(self.drpdwn_prof_name.currentText()) prof_id = self.db.getProfId(self.drpdwn_prof_name.currentText())
# check if apparat in database # check if apparat in database
#if app_id not in database, create apparat # if app_id not in database, create apparat
if not self.db.checkApparatExistsById(app_id): if not self.db.checkApparatExistsById(app_id):
# create apparat # create apparat
print("Creating apparat") print("Creating apparat")
@@ -1503,7 +1498,7 @@ class Ui(Ui_Semesterapparat):
self.tableWidget_apparate.setToolTip("") self.tableWidget_apparate.setToolTip("")
return return
else: else:
# if file is selected, check for books in the file # if file is selected, check for books in the file
print("File selected") print("File selected")
file = self.dokument_list.item(self.dokument_list.currentRow(), 3).text() file = self.dokument_list.item(self.dokument_list.currentRow(), 3).text()
@@ -1539,7 +1534,11 @@ class Ui(Ui_Semesterapparat):
ic(signatures) ic(signatures)
print("starting thread") print("starting thread")
thread = QThread() thread = QThread()
grabber = BookGrabber("ARRAY", signatures, app_id, prof_id) grabber = BookGrabber(mode = "ARRAY", app_id = app_id,prof_id = prof_id,data = signatures)
# grabber.mode = "ARRAY"
# grabber.data = signatures
# grabber.app_id = app_id
# grabber.prof_id = prof_id
grabber.moveToThread(thread) grabber.moveToThread(thread)
self.label_info.show() self.label_info.show()
self.progress_label.show() self.progress_label.show()
@@ -1685,7 +1684,7 @@ class Ui(Ui_Semesterapparat):
self.logger.log_info(f"Inserted apparat {apparat[4]}") self.logger.log_info(f"Inserted apparat {apparat[4]}")
def calendar_context_menu(self): def calendar_context_menu(self):
#create a context menu for the calendar # create a context menu for the calendar
menu = QtWidgets.QMenu() menu = QtWidgets.QMenu()
create_reminder = menu.addAction("Erinnerung erstellen") create_reminder = menu.addAction("Erinnerung erstellen")
create_reminder.triggered.connect(self.reminder(date=self.calendarWidget.selectedDate().toString("yyyy-MM-dd"))) create_reminder.triggered.connect(self.reminder(date=self.calendarWidget.selectedDate().toString("yyyy-MM-dd")))
@@ -1786,13 +1785,13 @@ class Ui(Ui_Semesterapparat):
data = settings.return_data() data = settings.return_data()
print(data) print(data)
OmegaConf.save(data, "config.yaml") OmegaConf.save(data, "config.yaml")
#re-load the config # re-load the config
config = OmegaConf.load("config.yaml") config = OmegaConf.load("config.yaml")
self.logger.log_info("Saved settings to config.yaml") self.logger.log_info("Saved settings to config.yaml")
self.reload() self.reload()
def reload(self): def reload(self):
#create a new connection to the database, refresh table data and replace the old connection # create a new connection to the database, refresh table data and replace the old connection
self.db = Database() self.db = Database()
self.apparats = self.db.getAllAparats(deleted=0) self.apparats = self.db.getAllAparats(deleted=0)
self.apparats = natsorted(self.apparats, key=lambda x: x[4], reverse=True) self.apparats = natsorted(self.apparats, key=lambda x: x[4], reverse=True)