tirilane
/
egon
Archived
1
0
Fork 0
This repository has been archived on 2024-07-04. You can view files and clone it, but cannot push or open issues or pull requests.
egon/egon.py

2065 lines
66 KiB
Python
Executable File

#!/usr/bin/env python
#coding: utf-8
# Copyright 2008, Tiril Anette Langfeldt Rødland
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import platform
import sys
import string
import datetime
import time
import random
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#from PyQt4 import QtGui
#from PyQt4 import QtCore
from pysqlite2 import dbapi2 as sqlite
#import qrc_resources
from qrc_resources import *
__version__ = "0.0.2"
main = None
semesters = []
semester = None
courses = []
coursesString = []
books = []
booksString = []
chosenDay = QDate()
colors = []
termList = None
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
# The program name
self.title = "Egon"
# The days
self.days = [self.trUtf8("Monday"), self.trUtf8("Tuesday"), self.trUtf8("Wednesday"), self.trUtf8("Thursday"), self.trUtf8("Friday")]
# The tabs
self.assignment = AssignmentTab()
self.reading = ReadingTab()
self.schedule = ScheduleTab()
# Set the tabs in the middle
self.tabs = QTabWidget()
self.tabs.addTab(self.assignment, "&Assignments")
self.tabs.addTab(self.reading, "&Reading List")
self.tabs.addTab(self.schedule, "&Schedule")
self.tabs.setTabShape(QTabWidget.Rounded)
self.tabs.setTabPosition(QTabWidget.North)
self.setCentralWidget(self.tabs)
# Set the title
self.setWindowTitle(self.title)
# The calendar
self.calendarFrame = QFrame()
self.calendarFrame.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
self.calendarDockWidget = QDockWidget("Calendar", self)
self.calendarDockWidget.setVisible(False)
self.calendarDockWidget.setObjectName("CalendarDockWidget")
self.calendarDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea|Qt.RightDockWidgetArea|Qt.BottomDockWidgetArea)
self.calendar = QCalendarWidget()
self.calendar.setFirstDayOfWeek(Qt.Monday)
self.calendarLayout = QVBoxLayout()
self.calendarLayout.addWidget(self.calendar)
self.calendarFrame.setLayout(self.calendarLayout)
self.calendarFrame.hide()
self.calendarDockWidget.setWidget(self.calendarFrame)
# The semesters
global semester, semesters, termList
termList = QStringList()
termList.append(self.trUtf8("Spring"))
termList.append(self.trUtf8("Autumn"))
semesters = getSemestersFromDB()
semester = self.getLatestSemester(semesters)
if semester:
print semester.getTerm(), semester.getYear()
self.load(semester)
# Actions
fileNewAction = self.createAction("&New", self.fileNew, QKeySequence.New, "filenew", "Create a new semester plan")
fileOpenAction = self.createAction("&Open", self.fileOpen, QKeySequence.Open, "fileopen", "Open an existing semester plan")
filePrintAction = self.createAction("&Print", self.filePrint, QKeySequence.Print, "fileprint", "Print plan")
fileQuitAction = self.createAction("&Quit", self.close, "Ctrl+Q", "filequit", "Quit program")
editAddCourse = self.createAction("Add &course", self.addCourse, "Ctrl+C", None, "Add a new course")
editAddBook = self.createAction("Add &book", self.addBook, "Ctrl+B", None, "Add a new book")
editAddAssignment = self.createAction("Add &assignment", self.addAssignment, "Ctrl+A", None, "Add a new assignment")
editAddReading = self.createAction("Add &reading", self.addReading, "Ctrl+R", None, "Add a new reading")
editAddLesson = self.createAction("Add &lesson", self.addLesson, "Ctrl+L", None, "Add a new lesson")
editShowCalendar = self.createAction("Cal&endar", self.showCalendar, "Ctrl+E", None, "Show the calendar")
helpAboutScheduler = self.createAction("&About %s" % self.title)
# Menus
self.fileMenu = self.menuBar().addMenu("&File")
self.editMenu = self.menuBar().addMenu("&Edit")
self.helpMenu = self.menuBar().addMenu("&Help")
# Add actions to the menus
self.addActions(self.fileMenu, (fileNewAction, fileOpenAction, None, filePrintAction, None, fileQuitAction))
self.addActions(self.editMenu, (editAddCourse, editAddBook, None, editAddAssignment, None, editAddReading, None, editAddLesson, None, editShowCalendar))
self.addActions(self.helpMenu, (helpAboutScheduler, None))
# Connect statements
self.connect(editAddCourse, SIGNAL("triggered()"), self.addCourse)
self.connect(editAddBook, SIGNAL("triggered()"), self.addBook)
self.connect(editAddAssignment, SIGNAL("triggered()"), self.addAssignment)
self.connect(editAddReading, SIGNAL("triggered()"), self.addReading)
self.connect(editAddLesson, SIGNAL("triggered()"), self.addLesson)
self.connect(editShowCalendar, SIGNAL("pressed()"), self.showCalendar)
self.connect(helpAboutScheduler, SIGNAL("triggered()"), self.helpAbout)
self.connect(self.assignment.addAssignmentButton, SIGNAL("pressed()"), self.addAssignment)
self.connect(self.assignment.deleteAssignmentButton, SIGNAL("pressed()"), self.deleteAssignment)
self.connect(self.assignment.completeAssignmentBox, SIGNAL("currentIndexChanged(QString)"), self.completeAssignment)
self.connect(self.reading.addReadingButton, SIGNAL("pressed()"), self.addReading)
self.connect(self.reading.deleteReadingButton, SIGNAL("pressed()"), self.deleteReading)
self.connect(self.reading.readingDoneButton, SIGNAL("pressed()"), self.doneReading)
self.connect(self.schedule.addScheduleButton, SIGNAL("pressed()"), self.addLesson)
self.connect(self.schedule.deleteScheduleButton, SIGNAL("pressed()"), self.deleteLesson)
self.connect(self.calendar, SIGNAL("selectionChanged()"), self.changeDay)
# The toolbars
fileToolbar = self.addToolBar("File")
fileToolbar.setObjectName("FileToolBar")
self.addActions(fileToolbar, (fileNewAction, fileOpenAction, None, filePrintAction, None, fileQuitAction))
editToolbar = self.addToolBar("Edit")
editToolbar.setObjectName("EditToolBar")
self.addActions(editToolbar, (editAddCourse, editAddBook, None, editShowCalendar))
courses = getCourses()
makeCoursesString()
global main
main = self
def addCourse(self):##, code, title, short):
self.acdlg = AddCourseDlg()
self.acdlg.show()
def addBook(self):##, isbn, title, author, edition, course):
self.abdlg = AddBookDlg()
self.abdlg.show()
def addAssignment(self):
self.aadlg = AddAssignmentDlg()
self.aadlg.show()
def deleteAssignment(self):
course, number = self.getCourseAndNumber()
table, row = self.getAssignmentTableAndRow()
global semester
removeAssignmentFromDB(course, number)
table.removeRow(row)
table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
def completeAssignment(self, completionLevel):
course, number = self.getCourseAndNumber()
table, row = self.getAssignmentTableAndRow()
updateAssignmentCompletion(course, number, completionLevel)
item = QTableWidgetItem(QString(completionLevel))
item.setBackground(self.assignment.makeBrush(completionLevel))
table.setItem(row, 4, item)
table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
def getAssignmentTableAndRow(self):
table = self.assignment.assignmentTable
row = table.currentRow()
return table, row
def getCourseAndNumber(self):
table, row = self.getAssignmentTableAndRow()
courseItem = table.item(row, 1)
numberItem = table.item(row, 2)
courseFull = courseItem.text()
number = numberItem.text()
course = getCourseCode(courseFull)
return course, number
def addReading(self):
self.ardlg = AddReadingDlg()
self.ardlg.show()
def deleteReading(self):
week, course, book = self.getWeekCourseAndBook()
table, row = self.getReadingTableAndRow()
global semester
removeReadingFromDB(week, course, book)
table.removeRow(row)
table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
def doneReading(self):
table, row = self.getReadingTableAndRow()
if table.item(row, 6).text().compare(QString(self.trUtf8("Not done"))) == 0:
done = True
item = QTableWidgetItem(self.trUtf8("Done"))
item.setBackground(QBrush(Qt.green, Qt.SolidPattern))
else:
done = False
item = QTableWidgetItem(self.trUtf8("Not done"))
item.setBackground(QBrush(Qt.red, Qt.SolidPattern))
table.setItem(row, 6, item)
table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
week = (table.item(row, 0).text().toInt())[0]
courseFull = table.item(row, 1).text()
courseCode = QString(getCourseCode(courseFull))
bookTitle = table.item(row, 2).text()
book = getBookWithTitleFromDB(bookTitle)
bookIsbn = book.getIsbn()
updateReadingDone(week, courseCode, bookIsbn, True)
def getReadingTableAndRow(self):
table = self.reading.readingTable
row = table.currentRow()
return table, row
def getWeekCourseAndBook(self):
table, row = self.getReadingTableAndRow()
weekItem = table.item(row, 0)
courseItem = table.item(row, 1)
bookItem = table.item(row, 2)
week = (weekItem.text().toInt())[0]
courseFull = courseItem.text()
courseCode = getCourseCode(courseFull)
book = getBookWithTitleFromDB(bookItem.text())
return week, courseCode, book.getIsbn()
def addLesson(self):
self.asdlg = AddScheduleDlg()
self.asdlg.show()
def deleteLesson(self):
table, row, column = self.getScheduleTableRowAndColumn()
day, course, time = self.getDayCourseAndTime()
global semester
removeLessonFromDB(day, course, time)
table.setItem(row, column, QTableWidgetItem())
def getDayCourseAndTime(self):
table, row, column = self.getScheduleTableRowAndColumn()
item = table.item(row, column)
text = item.text()
textlist = text.split('\n')
courseFull = textlist[0]
coursecode = getCourseCode(courseFull)
day = self.getDayFromTable(column)
time = row + 8
return day, coursecode, time
def getScheduleTableRowAndColumn(self):
table = self.schedule.scheduleTable
row = table.currentRow()
column = table.currentColumn()
return table, row, column
def getDayFromTable(self, column):
return self.days[column]
def getLatestSemester(self, semesters):
if len(semesters) == 0:
return None
global termList
max = semesters[0]
for s in semesters:
if s.getYear() > max.getYear():
max = s
if s.getYear() == max.getYear():
if s.getTerm() == self.trUtf8("Autumn"):
max = s
return max
def getTermList(self):
global termList
return termList
def helpAbout(self):
QMessageBox.about(self, "About %s" % self.title, u"""
<b>%s</b> v %s
<p>Copyright &copy; 2008 Tiril Anette Langfeldt Rødland. No rights reserved.
<p>You may modify and redistribute the program under the terms of the GPL. The license can be found here: http://www.gnu.org/licenses/gpl.html
<p>This application is mainly for use by students, and can be used to keep track of assignments, planned readings and the schedule.
<p>Python %s - Qt %s - PyQt %s on %s
<p>Developer: Tiril Anette Langfeldt Rødland, tirilane@pvv.ntnu.no
""" % (self.title, __version__, platform.python_version(), QT_VERSION_STR, PYQT_VERSION_STR, platform.system()))
def addActions(self, target, actions):
for action in actions:
if action is None:
target.addSeparator()
else:
target.addAction(action)
def changeDay(self):
global chosenDay
chosenDay = self.calendar
def fileNew(self):
self.nsdlg = NewSemesterDlg()
self.nsdlg.show()
def fileOpen(self):
self.osdlg = OpenSemesterDlg()
self.osdlg.show()
def filePrint(self):
pass
def updateFileMenu(self):
self.fileMenu.clear()
self.addActions(self.fileMenu, self.fileMenuActions[:-1])
current = QString(self.filename) if self.filename is not None else None
def createAction(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered()"):
action = QAction(text, self)
if icon is not None:
iconfile = ":/%s.png" % icon
action.setIcon(QIcon(iconfile))
if shortcut is not None:
action.setShortcut(shortcut)
if tip is not None:
action.setToolTip(tip)
action.setStatusTip(tip)
if slot is not None:
self.connect(action, SIGNAL(signal), slot)
if checkable:
action.setCheckable(True)
return action
def showCalendar(self):
if self.calendarDockWidget.isVisible():
self.removeDockWidget(self.calendarDockWidget)
else:
self.addDockWidget(Qt.BottomDockWidgetArea, self.calendarDockWidget)
self.calendarDockWidget.setVisible(True)
def load(self, semester):
self.assignment.updateTable(semester)
self.reading.updateTable(semester)
self.schedule.updateTable(semester)
class AssignmentTab(QWidget):
def __init__(self, parent=None):
super(AssignmentTab, self).__init__(parent)
self.addAssignmentButton = QPushButton("Add assignment")
self.completeAssignmentBox = QComboBox()
self.deleteAssignmentButton = QPushButton("Delete assignment")
completeTypes = [self.trUtf8("Not available"), self.trUtf8("Available"), self.trUtf8("Begun"), self.trUtf8("Finished"), self.trUtf8("Delivered"), self.trUtf8("Approved"), self.trUtf8("Not approved")]
self.completeAssignmentBox.addItems(completeTypes)
self.makeTable()
self.vlayout = QVBoxLayout()
self.hlayout = QHBoxLayout()
self.hlayout.addWidget(self.addAssignmentButton)
self.hlayout.addWidget(self.deleteAssignmentButton)
self.hlayout.addWidget(self.completeAssignmentBox)
self.hlayout.addStretch()
self.vlayout.addWidget(self.assignmentTable)
self.vlayout.addLayout(self.hlayout)
self.setLayout(self.vlayout)
def makeTable(self, current=None):
self.assignmentTable = QTableWidget(0, 5, self)
self.assignmentTable.clear()
self.assignmentHeaderList = QStringList()
self.assignmentHeaderList.append(self.trUtf8("Date"))
self.assignmentHeaderList.append(self.trUtf8("Course"))
self.assignmentHeaderList.append(self.trUtf8("Number"))
self.assignmentHeaderList.append(self.trUtf8("Description"))
self.assignmentHeaderList.append(self.trUtf8("Complete"))
self.assignmentTable.setHorizontalHeaderLabels(self.assignmentHeaderList)
self.assignmentTable.setAlternatingRowColors(True)
self.assignmentTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.assignmentTable.setSelectionBehavior(QAbstractItemView.SelectRows)
self.assignmentTable.setSelectionMode(QAbstractItemView.SingleSelection)
selected = None
def updateTable(self, semester, current=None):
self.assignments = getAssignmentsFromDB(semester)
rows = len(self.assignments)
self.assignmentTable.setRowCount(rows)
for row in range(rows):
self.addAssignmentToTable(row)
self.assignmentTable.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
self.assignmentTable.sortItems(0, Qt.AscendingOrder)
def addAssignmentToTable(self, row, assignment=None):
if assignment == None:
assignment = self.assignments[row]
complete = QString(assignment.getComplete())
brush = self.makeBrush(complete)
self.assignmentTable.setItem(row, 0, QTableWidgetItem(QString(assignment.getDate().toString("yyyy-MM-dd hh:mm, ddd"))))
self.assignmentTable.setItem(row, 1, QTableWidgetItem(QString(assignment.getCourse().getFull())))
self.assignmentTable.setItem(row, 2, QTableWidgetItem(QString("%i" % assignment.getNumber())))
self.assignmentTable.setItem(row, 3, QTableWidgetItem(QString("%s" % assignment.getDescription())))
completeItem = QTableWidgetItem(complete)
completeItem.setBackground(brush)
self.assignmentTable.setItem(row, 4, completeItem)
def makeBrush(self, complete):
brush = QBrush(Qt.NoBrush)
if complete.compare(QString(self.trUtf8("Available"))) == 0:
brush.setStyle(Qt.Dense7Pattern)
brush.setColor(QColor(Qt.cyan))
elif complete.compare(QString(self.trUtf8("Begun"))) == 0:
brush.setStyle(Qt.Dense5Pattern)
brush.setColor(QColor(Qt.cyan))
elif complete.compare(QString(self.trUtf8("Finished"))) == 0:
brush.setStyle(Qt.Dense3Pattern)
brush.setColor(QColor(Qt.cyan))
elif complete.compare(QString(self.trUtf8("Delivered"))) == 0:
brush.setStyle(Qt.Dense1Pattern)
brush.setColor(QColor(Qt.cyan))
elif complete.compare(QString(self.trUtf8("Approved"))) == 0:
brush.setStyle(Qt.SolidPattern)
brush.setColor(QColor(Qt.green))
elif complete.compare(QString(self.trUtf8("Not approved"))) == 0:
brush.setStyle(Qt.SolidPattern)
brush.setColor(QColor(Qt.red))
else:
brush.setStyle(Qt.NoBrush)
return brush
class AssignmentDlg(QDialog):
def __init__(self, parent=None):
super(AssignmentDlg, self).__init__(parent)
self.dateLabel = QLabel(self.trUtf8("&Date"))
self.courseLabel = QLabel(self.trUtf8("&Course"))
self.numberLabel = QLabel(self.trUtf8("&Number"))
self.descriptionLabel = QLabel(self.trUtf8("De&scription"))
self.completeLabel = QLabel(self.trUtf8("&Complete"))
self.dateEdit = QLineEdit("DD.MM.YYYY HH:MM")
self.dateEdit.setSelection(0, 16)
self.courseEdit = QComboBox()
self.courseEdit.addItems(makeCoursesString())
self.numberEdit = QSpinBox()
self.numberEdit.setRange(1, 20)
self.descriptionEdit = QLineEdit()
self.completeEdit = QComboBox()
completeTypes = [self.trUtf8("Not available"), self.trUtf8("Available"), self.trUtf8("Begun"), self.trUtf8("Finished"), self.trUtf8("Delivered"), self.trUtf8("Approved"), self.trUtf8("Not approved")]
self.completeEdit.addItems(completeTypes)
self.dateLabel.setBuddy(self.dateEdit)
self.courseLabel.setBuddy(self.courseEdit)
self.numberLabel.setBuddy(self.numberEdit)
self.descriptionLabel.setBuddy(self.descriptionEdit)
self.completeLabel.setBuddy(self.completeEdit)
self.layout = QGridLayout()
self.layout.addWidget(self.dateLabel, 0, 0)
self.layout.addWidget(self.courseLabel, 1, 0)
self.layout.addWidget(self.numberLabel, 2, 0)
self.layout.addWidget(self.descriptionLabel, 3, 0)
self.layout.addWidget(self.completeLabel, 4, 0)
self.layout.addWidget(self.dateEdit, 0, 1)
self.layout.addWidget(self.courseEdit, 1, 1)
self.layout.addWidget(self.numberEdit, 2, 1)
self.layout.addWidget(self.descriptionEdit, 3, 1)
self.layout.addWidget(self.completeEdit, 4, 1)
self.setLayout(self.layout)
def getValues(self):
assignment = []
assignment.append(unicode(self.dateEdit.text()))
assignment.append(unicode(self.courseEdit.currentText()))
assignment.append(self.numberEdit.value())
assignment.append(unicode(self.descriptionEdit.text()))
assignment.append(unicode(self.completeEdit.currentText()))
return assignment
class AddAssignmentDlg(AssignmentDlg):
def __init__(self, parent=None):
super(AddAssignmentDlg, self).__init__(parent)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.layout.addWidget(buttonBox, 5, 0, 1, 2)
self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Add new assignment"))
def accept(self):
assignmentList = self.getValues()
dateString = assignmentList[0]
courseFull = assignmentList[1]
number = assignmentList[2]
description = assignmentList[3]
complete = assignmentList[4]
if len(dateString) <= 11:
dateList = dateString.split('.')
timeList = ['00', '00']
else:
dateTime = dateString.split()
dateList = dateTime[0].split('.')
timeList = dateTime[1].split(':')
date = QDate(string.atoi(dateList[2]), string.atoi(dateList[1]), string.atoi(dateList[0]))
time = QTime(string.atoi(timeList[0]), string.atoi(timeList[1]))
datetime = QDateTime(date, time)
course = getCourseFromDB(getCourseCode(courseFull))
global semester
addNewAssignmentToDB(semester, datetime, course, number, description, complete)
assignment = AssignmentModel(datetime, course, number, description, complete)
table = getMain().assignment.assignmentTable
row = table.rowCount()
table.insertRow(row)
getMain().assignment.addAssignmentToTable(row, assignment)
table.sortItems(0, Qt.AscendingOrder)
self.close()
class EditAssignmentDlg(AssignmentDlg):
def __init__(self, parent=None):
super(EditAssignmentDlg, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Close)
self.layout.addWidget(buttonBox, 8, 0, 1, 2)
self.connect(buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.apply)
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Edit assignment"))
assignment = self.getValues()
self.dateEdit.setText(assignment[0])
# self.courseEdit.setText(assignment[1])
self.numberEdit.setValue(assignment[2])
self.descriptionEdit.setText(assignment[3])
# self.completeEdit.setText(assignment[4])
def apply(self):
assignmentList = self.getValues()
# updateAssignment(assignment, assignmentList[0], assignmentList[1], assignmentList[2], assignmentList[3], assignmentList[4])
class AssignmentModel():
date = None
course = None
number = 0
description = ""
complete = ""
def __init__(self, date, course, number, description, complete):
self.date = date
self.course = course
self.number = number
self.description = description
self.complete = complete
def getDate(self):
return self.date
def setDate(self, date):
self.date = date
def getCourse(self):
return self.course
def setCourse(self, course):
self.course = course
def getNumber(self):
return self.number
def setNumber(self, number):
self.number = number
def getDescription(self):
return self.description
def setDescription(self, description):
self.description = description
def getComplete(self):
return self.complete
def setComplete(self, complete):
self.complete = complete
class ReadingTab(QWidget):
def __init__(self, parent=None):
super(ReadingTab, self).__init__(parent)
self.addReadingButton = QPushButton(self.trUtf8("Add pages to read"))
self.deleteReadingButton = QPushButton(self.trUtf8("Delete pages"))
self.readingDoneButton = QPushButton(self.trUtf8("Done"))
self.makeTable()
self.vlayout = QVBoxLayout()
self.hlayout = QHBoxLayout()
self.hlayout.addWidget(self.addReadingButton)
self.hlayout.addWidget(self.deleteReadingButton)
self.hlayout.addWidget(self.readingDoneButton)
self.hlayout.addStretch()
self.vlayout.addWidget(self.readingTable)
self.vlayout.addLayout(self.hlayout)
self.setLayout(self.vlayout)
def makeTable(self, current=None):
self.readingTable = QTableWidget(0, 7, self)
self.readingTable.clear()
self.readingHeaderList = QStringList()
self.readingHeaderList.append(self.trUtf8("Week"))
self.readingHeaderList.append(self.trUtf8("Course"))
self.readingHeaderList.append(self.trUtf8("Book"))
self.readingHeaderList.append(self.trUtf8("Chapter"))
self.readingHeaderList.append(self.trUtf8("Pages"))
self.readingHeaderList.append(self.trUtf8("Number of pages"))
self.readingHeaderList.append(self.trUtf8("Done"))
self.readingTable.setHorizontalHeaderLabels(self.readingHeaderList)
self.readingTable.setAlternatingRowColors(True)
self.readingTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.readingTable.setSelectionBehavior(QAbstractItemView.SelectRows)
self.readingTable.setSelectionMode(QAbstractItemView.SingleSelection)
selected = None
def updateTable(self, semester):
self.readings = getReadingsFromDB(semester)
rows = len(self.readings)
self.readingTable.setRowCount(rows)
for row in range(rows):
self.addReadingToTable(row)
self.readingTable.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
self.readingTable.sortItems(0, Qt.AscendingOrder)
def addReadingToTable(self, row, reading=None):
if reading == None:
reading = self.readings[row]
brush = QBrush(Qt.NoBrush)
brush.setStyle(Qt.SolidPattern)
if reading.getDone():
doneString = self.trUtf8("Done")
brush.setColor(Qt.green)
else:
doneString = self.trUtf8("Not done")
brush.setColor(Qt.red)
self.readingTable.setItem(row, 0, QTableWidgetItem(QString("%02s" % reading.getWeek())))
self.readingTable.setItem(row, 1, QTableWidgetItem(QString(reading.getCourse().getFull())))
self.readingTable.setItem(row, 2, QTableWidgetItem(QString(reading.getBook().getTitle())))
self.readingTable.setItem(row, 3, QTableWidgetItem(QString(reading.getChapter())))
self.readingTable.setItem(row, 4, QTableWidgetItem(QString(reading.getPages())))
self.readingTable.setItem(row, 5, QTableWidgetItem(QString("%i" % reading.getNumberOfPages())))
item = QTableWidgetItem(QString(doneString))
item.setBackground(brush)
self.readingTable.setItem(row, 6, item)
class ReadingDlg(QDialog):
def __init__(self, parent=None):
super(ReadingDlg, self).__init__(parent)
self.weekLabel = QLabel(self.trUtf8("&Week"))
self.courseLabel = QLabel(self.trUtf8("&Course"))
self.bookLabel = QLabel(self.trUtf8("&Book"))
self.chapterLabel = QLabel(self.trUtf8("Cha&pter"))
self.pagesLabel = QLabel(self.trUtf8("&Pages"))
self.weekEdit = QSpinBox()
self.weekEdit.setRange(1, 52)
self.courseEdit = QComboBox()
coursesStringList = QStringList()
courses = makeCoursesString()
for course in courses:
coursesStringList.append(course)
self.courseEdit.addItems(coursesStringList)
self.bookEdit = QComboBox()
booksStringList = QStringList()
books = makeBooksString()
for book in books:
booksStringList.append(book)
self.bookEdit.addItems(booksStringList)
self.chapterEdit = QLineEdit()
self.pagesEdit = QLineEdit()
self.weekLabel.setBuddy(self.weekEdit)
self.courseLabel.setBuddy(self.courseEdit)
self.bookLabel.setBuddy(self.bookEdit)
self.chapterLabel.setBuddy(self.chapterEdit)
self.pagesLabel.setBuddy(self.pagesEdit)
self.layout = QGridLayout()
self.layout.addWidget(self.weekLabel, 0, 0)
self.layout.addWidget(self.courseLabel, 1, 0)
self.layout.addWidget(self.bookLabel, 2, 0)
self.layout.addWidget(self.chapterLabel, 3, 0)
self.layout.addWidget(self.pagesLabel, 4, 0)
self.layout.addWidget(self.weekEdit, 0, 1)
self.layout.addWidget(self.courseEdit, 1, 1)
self.layout.addWidget(self.bookEdit, 2, 1)
self.layout.addWidget(self.chapterEdit, 3, 1)
self.layout.addWidget(self.pagesEdit, 4, 1)
self.setLayout(self.layout)
class AddReadingDlg(ReadingDlg):
def __init__(self, parent=None):
super(AddReadingDlg, self).__init__(parent)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.layout.addWidget(buttonBox, 5, 0, 1, 2)
self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Add new reading"))
def accept(self):
week = unicode(self.weekEdit.value())
courseFull = unicode(self.courseEdit.currentText())
bookTitle = unicode(self.bookEdit.currentText())
chapter = unicode(self.chapterEdit.text())
pages = unicode(self.pagesEdit.text())
self.close()
course = getCourseFromDB(getCourseCode(courseFull))
book = getBookWithTitleFromDB(bookTitle)
global semester
addNewReadingToDB(semester, week, course, book, chapter, pages, False)
reading = ReadingModel(week, course, book, chapter, pages, False)
table = getMain().reading.readingTable
row = table.rowCount()
table.insertRow(row)
getMain().reading.addReadingToTable(row, reading)
table.sortItems(0, Qt.AscendingOrder)
class EditReadingDlg(ReadingDlg):
def __init__(self, parent=None):
super(EditReadingDlg, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Close)
self.layout.addWidget(buttonBox, 5, 0, 1, 2)
self.connect(buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.apply)
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Edit reading"))
def apply(self):
pass
class ReadingModel():
week = 0
course = None
book = None
chapter = ""
pages = ""
numberOfPages = 0
done = False
def __init__(self, week, course, book, chapter, pages, done=False):
self.week = week
self.course = course
self.book = book
self.chapter = chapter
self.pages = pages
self.numberOfPages = self.getNumberOfPages()
self.done = done
def getWeek(self):
return self.week
def setWeek(self, week):
self.week = week
def getCourse(self):
return self.course
def setCourse(self, course):
self.course = course
def getBook(self):
return self.book
def setBook(self, book):
self.book = book
def getChapter(self):
return self.chapter
def setChapter(self, chapter):
self.chapter = chapter
def getPages(self):
return self.pages
def setPages(self, pages):
self.pages = pages
def getNumberOfPages(self):
pages = self.getPages()
pagesArray = pages.split(",")
nextArray = []
sum = 0
for p in pagesArray:
p.strip()
nextArray.append(p.split("-"))
for n in nextArray:
sum += int(n[1]) - int(n[0])
return sum
def getDone(self):
return self.done
def setDone(self, done):
self.done = done
class ScheduleTab(QWidget):
def __init__(self, parent=None):
super(ScheduleTab, self).__init__(parent)
self.addScheduleButton = QPushButton("Add lesson")
self.deleteScheduleButton = QPushButton("Delete lesson")
self.makeTable()
self.vlayout = QVBoxLayout()
self.hlayout = QHBoxLayout()
self.hlayout.addWidget(self.addScheduleButton)
self.hlayout.addWidget(self.deleteScheduleButton)
self.hlayout.addStretch()
self.vlayout.addWidget(self.scheduleTable)
self.vlayout.addLayout(self.hlayout)
self.setLayout(self.vlayout)
def makeTable(self, current=None):
self.scheduleTable = QTableWidget(12, 5, self)
self.scheduleTable.clear()
self.scheduleHorizontalHeaderList = QStringList()
self.scheduleHorizontalHeaderList.append(self.trUtf8("Monday"))
self.scheduleHorizontalHeaderList.append(self.trUtf8("Tuesday"))
self.scheduleHorizontalHeaderList.append(self.trUtf8("Wednesday"))
self.scheduleHorizontalHeaderList.append(self.trUtf8("Thursday"))
self.scheduleHorizontalHeaderList.append(self.trUtf8("Friday"))
self.scheduleVerticalHeaderList = QStringList()
for i in range(8, 20):
self.scheduleVerticalHeaderList.append(self.trUtf8("%i" % i))
self.scheduleTable.setHorizontalHeaderLabels(self.scheduleHorizontalHeaderList)
self.scheduleTable.setVerticalHeaderLabels(self.scheduleVerticalHeaderList)
self.scheduleTable.setAlternatingRowColors(True)
self.scheduleTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.scheduleTable.setSelectionBehavior(QAbstractItemView.SelectItems)
self.scheduleTable.setSelectionMode(QAbstractItemView.SingleSelection)
selected = None
def updateTable(self, semester):
self.schedule = getLessonsFromDB(semester)
rows = len(self.schedule)
self.scheduleTable.setRowCount(rows)
for l in range(rows):
self.addLessonToTable(self.schedule[l])
self.scheduleTable.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
self.scheduleTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
def addLessonToTable(self, lesson):
row = lesson.getTime() - 8
column = self.getColumn(lesson.getDay())
course = lesson.getCourse().getFull()
type = lesson.getType()
room = lesson.getRoom()
item = QTableWidgetItem(QString("%s\n%s\n%s" % (course, type, room)))
item.setBackground(self.getBackground(QString("%s" % type), lesson.getCourse()))
self.scheduleTable.setItem(row, column, item)
def getColumn(self, dayString):
day = QString("%s" % dayString)
if day.compare(QString(self.trUtf8("Monday"))) == 0:
return 0
elif day.compare(QString(self.trUtf8("Tuesday"))) == 0:
return 1
elif day.compare(QString(self.trUtf8("Wednesday"))) == 0:
return 2
elif day.compare(QString(self.trUtf8("Thursday"))) == 0:
return 3
elif day.compare(QString(self.trUtf8("Friday"))) == 0:
return 4
else:
return -1
def getBackground(self, type, course):
if type.compare(QString(self.trUtf8("Lecture"))) == 0:
brush = QBrush(Qt.HorPattern)
elif type.compare(QString(self.trUtf8("Assignment lecture"))) == 0:
brush = QBrush(Qt.CrossPattern)
elif type.compare(QString(self.trUtf8("Assignment help"))) == 0:
brush = QBrush(Qt.VerPattern)
elif type.compare(QString(self.trUtf8("Lab"))) == 0:
brush = QBrush(Qt.BDiagPattern)
elif type.compare(QString(self.trUtf8("Seminar"))) == 0:
brush = QBrush(Qt.FDiagPattern)
elif type.compare(QString(self.trUtf8("Other"))) == 0:
brush = QBrush(Qt.DiagCrossPattern)
else:
brush = QBrush(Qt.NoBrush)
brush.setColor(course.getColor())
return brush
class ScheduleDlg(QDialog):
def __init__(self, parent=None):
super(ScheduleDlg, self).__init__(parent)
self.dayLabel = QLabel(self.trUtf8("&Day"))
self.fromLabel = QLabel(self.trUtf8("&From"))
self.toLabel = QLabel(self.trUtf8("&To"))
self.courseLabel = QLabel(self.trUtf8("&Course"))
self.typeLabel = QLabel(self.trUtf8("Ty&pe"))
self.roomLabel = QLabel(self.trUtf8("&Room"))
self.dayEdit = QComboBox()
self.dayEdit.addItems(getMain().days)
self.fromEdit = QSpinBox()
self.fromEdit.setRange(08.15, 18.15)
self.fromEdit.setSingleStep(01.00)
self.toEdit = QSpinBox()
self.toEdit.setRange(09.00, 19.00)
self.toEdit.setSingleStep(01.00)
self.courseEdit = QComboBox()
courses = makeCoursesString()
coursesStringList = QStringList()
for course in courses:
coursesStringList.append(course)
self.courseEdit.addItems(coursesStringList)
self.typeEdit = QComboBox()
types = [self.trUtf8("Lecture"), self.trUtf8("Assignment lecture"), self.trUtf8("Assignment help"), self.trUtf8("Lab"), self.trUtf8("Seminar"), self.trUtf8("Other")]
self.typeEdit.addItems(types)
self.roomEdit = QLineEdit()
self.dayLabel.setBuddy(self.dayEdit)
self.fromLabel.setBuddy(self.fromEdit)
self.toLabel.setBuddy(self.toEdit)
self.courseLabel.setBuddy(self.courseEdit)
self.typeLabel.setBuddy(self.typeEdit)
self.roomLabel.setBuddy(self.roomEdit)
self.layout = QGridLayout()
self.layout.addWidget(self.dayLabel, 0, 0)
self.layout.addWidget(self.fromLabel, 1, 0)
self.layout.addWidget(self.toLabel, 2, 0)
self.layout.addWidget(self.courseLabel, 3, 0)
self.layout.addWidget(self.typeLabel, 4, 0)
self.layout.addWidget(self.roomLabel, 5, 0)
self.layout.addWidget(self.dayEdit, 0, 1)
self.layout.addWidget(self.fromEdit, 1, 1)
self.layout.addWidget(self.toEdit, 2, 1)
self.layout.addWidget(self.courseEdit, 3, 1)
self.layout.addWidget(self.typeEdit, 4, 1)
self.layout.addWidget(self.roomEdit, 5, 1)
self.setLayout(self.layout)
class AddScheduleDlg(ScheduleDlg):
def __init__(self, parent=None):
super(AddScheduleDlg, self).__init__(parent)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.layout.addWidget(buttonBox, 6, 0, 1, 2)
self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Add new lesson"))
def accept(self):
day = unicode(self.dayEdit.currentText())
fromtime = self.fromEdit.value()
totime = self.toEdit.value()
courseFull = unicode(self.courseEdit.currentText())
type = unicode(self.typeEdit.currentText())
room = unicode(self.roomEdit.text())
course = getCourseFromDB(getCourseCode(courseFull))
global semester
for t in range(fromtime, totime):
addNewLessonToDB(semester, day, t, course, type, room)
getMain().schedule.addLessonToTable(ScheduleModel(day, t, course, type, room))
self.close()
class EditScheduleDlg(ScheduleDlg):
def __init__(self, parent=None):
super(EditScheduleDlg, self).__init__(parent)
buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Close)
self.layout.addWidget(buttonBox, 6, 0, 1, 2)
self.connect(buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.apply)
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Edit lesson"))
def apply(self):
pass
class ScheduleModel():
day = ""
time = 0
course = None
type = ""
room = ""
def __init__(self, day, time, course, type, room):
self.day = day
self.time = time
self.course = course
self.type = type
self.room = room
def getDay(self):
return self.day
def setDay(self, day):
self.day = day
def getTime(self):
return self.time
def setTime(self, fromTime):
self.time = time
def getCourse(self):
return self.course
def setCourse(self, course):
self.course = course
def getType(self):
return self.type
def setType(self, type):
self.type = type
def getRoom(self):
return self.room
def setRoom(self, room):
self.room = room
class CourseDlg(QDialog):
def __init__(self, parent=None):
super(CourseDlg, self).__init__(parent)
self.books = []
self.codeLabel = QLabel(self.trUtf8("&Code"))
self.titleLabel = QLabel(self.trUtf8("&Title"))
self.shortLabel = QLabel(self.trUtf8("&Short form"))
self.booksLabel = QLabel(self.trUtf8("&Books"))
self.codeEdit = QLineEdit()
self.titleEdit = QLineEdit()
self.shortEdit = QLineEdit()
self.booksEdit = QListWidget()
self.updateList()
self.booksEdit.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.newBook = QPushButton("Add new book")
self.connect(self.newBook, SIGNAL("pressed()"), getMain().addBook)
self.connect(getMain(), SIGNAL("newBook"), self.updateList)
self.codeLabel.setBuddy(self.codeEdit)
self.titleLabel.setBuddy(self.titleEdit)
self.shortLabel.setBuddy(self.shortEdit)
self.booksLabel.setBuddy(self.booksEdit)
self.layout = QGridLayout()
self.layout.addWidget(self.codeLabel, 0, 0)
self.layout.addWidget(self.titleLabel, 1, 0)
self.layout.addWidget(self.shortLabel, 2, 0)
self.layout.addWidget(self.booksLabel, 3, 0)
self.layout.addWidget(self.codeEdit, 0, 1)
self.layout.addWidget(self.titleEdit, 1, 1)
self.layout.addWidget(self.shortEdit, 2, 1)
self.layout.addWidget(self.booksEdit, 3, 1)
self.layout.addWidget(self.newBook, 4, 0)
self.setLayout(self.layout)
def updateList(self):
self.booksEdit.clear()
booksDB = getBooksFromDB()
booksStringList = QStringList()
for book in booksDB:
booksStringList.append(book.getTitle())
self.booksEdit.addItems(booksStringList)
self.booksEdit.sortItems()
def addNewBookToCourse(self):
book = getBookWithTitleFromDB(booktitle)
self.books.append(book)
class AddCourseDlg(CourseDlg):
def __init__(self, parent=None):
super(AddCourseDlg, self).__init__(parent)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.layout.addWidget(buttonBox, 4, 1, 1, 2)
self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Add new course"))
def accept(self):
courseCode = unicode(self.codeEdit.text())
courseTitle = unicode(self.titleEdit.text())
courseShort = unicode(self.shortEdit.text())
courseBooks = self.booksEdit.selectedItems()
color = getRandomColor()
global colors
while color in colors:
color = getRandomColor()
colors.append(color)
books = []
for book in courseBooks:
books.append(getBookWithTitleFromDB("%s" % book.text()))
course = CourseModel(courseCode, courseTitle, courseShort, color, books)
addNewCourseToDB(courseCode, courseTitle, courseShort, color, books)
self.close()
class CourseModel():
code = ""
title = ""
short = ""
full = ""
books = []
def __init__(self, code, title, short, color, books):
self.code = code
self.title = title
self.short = short
self.setFull(code, title)
self.color = color
self.books = books
def getCode(self):
return self.code
def getTitle(self):
return self.title
def getShort(self):
return self.short
def setFull(self, code, title):
self.full = code + ' ' + title
def getFull(self):
return self.full
def getColor(self):
return self.color
def addBook(self, book):
books.append(book)
def getBooks(self):
return self.books
class BookDlg(QDialog):
def __init__(self, parent=None):
super(BookDlg, self).__init__(parent)
self.titleLabel = QLabel(self.trUtf8("&Title"))
self.authorLabel = QLabel(self.trUtf8("&Author"))
self.editionLabel = QLabel(self.trUtf8("&Edition"))
self.isbnLabel = QLabel(self.trUtf8("&ISBN"))
self.titleEdit = QLineEdit()
self.authorEdit = QLineEdit()
self.editionEdit = QSpinBox()
self.editionEdit.setRange(1, 50)
self.isbnEdit = QLineEdit()
self.titleLabel.setBuddy(self.titleEdit)
self.authorLabel.setBuddy(self.authorEdit)
self.editionLabel.setBuddy(self.editionEdit)
self.isbnLabel.setBuddy(self.isbnEdit)
self.layout = QGridLayout()
self.layout.addWidget(self.titleLabel, 0, 0)
self.layout.addWidget(self.authorLabel, 1, 0)
self.layout.addWidget(self.editionLabel, 2, 0)
self.layout.addWidget(self.isbnLabel, 3, 0)
self.layout.addWidget(self.titleEdit, 0, 1)
self.layout.addWidget(self.authorEdit, 1, 1)
self.layout.addWidget(self.editionEdit, 2, 1)
self.layout.addWidget(self.isbnEdit, 3, 1)
self.setLayout(self.layout)
class AddBookDlg(BookDlg):
def __init__(self, parent=None):
super(AddBookDlg, self).__init__(parent)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.layout.addWidget(buttonBox, 4, 0, 1, 2)
self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Add new book"))
def accept(self):
bookTitle = unicode(self.titleEdit.text())
bookAuthor = unicode(self.authorEdit.text())
bookEdition = self.editionEdit.value()
bookIsbn = unicode(self.isbnEdit.text())
addNewBookToDB(bookIsbn, bookTitle, bookAuthor, bookEdition)
getMain().emit(SIGNAL("newBook"))
self.close()
class BookModel():
title = ""
author = ""
edition = 0
isbn = ""
def __init__(self, isbn, title, author, edition):
self.isbn = isbn
self.title = title
self.author = author
self.edition = edition
def getIsbn(self):
return self.isbn
def getTitle(self):
return self.title
def getAuthor(self):
return self.author
def getEdition(self):
return self.edition
class SemesterDlg(QDialog):
def __init__(self, parent=None):
super(SemesterDlg, self).__init__(parent)
self.oldLabel = QLabel(self.trUtf8("Earlier semesters:"))
self.newLabel = QLabel(self.trUtf8("New semester:"))
self.newTermLabel = QLabel(self.trUtf8("Term:"))
self.newYearLabel = QLabel(self.trUtf8("Year:"))
global semester, semesters, main
self.oldEdit = QListWidget()
self.oldEdit.addItems(semesters)
self.newTermEdit = QComboBox()
self.newTermEdit.addItems(getMain().getTermList())
self.newYearEdit = QSpinBox()
self.newYearEdit.setRange(2000, 2050)
self.newYearEdit.setSingleStep(1)
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
layout = QGridLayout()
layout.addWidget(self.oldLabel, 0, 0)
layout.addWidget(self.oldEdit, 0, 1, 1, 2)
layout.addWidget(self.newLabel, 1, 0)
layout.addWidget(self.newTermLabel, 1, 1)
layout.addWidget(self.newTermEdit, 2, 1)
layout.addWidget(self.newYearLabel, 1, 2)
layout.addWidget(self.newYearEdit, 2, 2)
layout.addWidget(self.buttonBox, 3, 0, 1, 3)
layout.setColumnStretch(0, 0)
layout.setColumnStretch(1, 1)
layout.setColumnStretch(2, 1)
self.setLayout(layout)
self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Choose a semester or create a new"))
def accept(self):
pass
class NewSemesterDlg(QDialog):
def __init__(self, parent=None):
super(NewSemesterDlg, self).__init__(parent)
self.termLabel = QLabel(self.trUtf8("Term"))
self.yearLabel = QLabel(self.trUtf8("Year"))
self.termEdit = QComboBox()
self.yearEdit = QSpinBox()
self.termEdit.addItems(getMain().getTermList())
self.yearEdit.setRange(2000, 2050)
self.yearEdit.setSingleStep(1)
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
layout = QGridLayout()
layout.addWidget(self.termLabel, 0, 0)
layout.addWidget(self.termEdit, 0, 1)
layout.addWidget(self.yearLabel, 1, 0)
layout.addWidget(self.yearEdit, 1, 1)
layout.addWidget(self.buttonBox, 2, 1)
self.setLayout(layout)
self.connect(self.buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(self.buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("New semester"))
def accept(self):
term = unicode(self.termEdit.currentText())
year = self.yearEdit.value()
global semester
semester = SemesterModel(term, year)
addNewSemesterToDB(term, year)
getMain().load(semester)
self.close()
class OpenSemesterDlg(QDialog):
def __init__(self, parent=None):
super(OpenSemesterDlg, self).__init__(parent)
self.semesterList = QListWidget()
semesters = getSemestersFromDB()
semesterlist = QStringList()
for semester in semesters:
semesterlist.append("%s %i" % (semester.getTerm(), semester.getYear()))
self.semesterList.addItems(semesterlist)
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
layout = QVBoxLayout()
layout.addWidget(self.semesterList)
layout.addStretch()
layout.addWidget(self.buttonBox)
self.setLayout(layout)
self.connect(self.buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"))
self.connect(self.buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"))
self.setWindowTitle(self.trUtf8("Open semester"))
def accept(self):
text = self.semesterList.currentItem().text()
textlist = text.split(' ')
term = textlist[0]
year = textlist[1].toInt()[0]
global semester
semester = SemesterModel(term, year)
semester.setAssignments(getAssignmentsFromDB(semester))
semester.setReadings(getReadingsFromDB(semester))
semester.setLessons(getLessonsFromDB(semester))
print semester.getAssignments()
print semester.getReadings()
print semester.getLessons()
getMain().load(semester)
self.close()
class SemesterModel():
term = ""
year = 0
assignments = []
readings = []
lessons = []
def __init__(self, term, year):
self.term = term
self.year = year
def getTerm(self):
return self.term
def getYear(self):
return self.year
def addAssignment(self, assignment):
self.assignments.append(assignment)
def setAssignments(self, assignments):
self.assignments = assignments
def getAssignments(self):
return self.assignments
def addReading(self, reading):
self.readings.append(reading)
def setReadings(self, readings):
self.readings = readings
def getReadings(self):
return self.readings
def addLesson(self, lesson):
self.lessons.append(lesson)
def setLessons(self, lessons):
self.lessons = lessons
def getLessons(self):
return self.lessons
class CalendarTab(QWidget):
def __init__(self, parent=None):
super(CalendarTab, self).__init__(parent)
calendar = QCalendarWidget()
calendar.setFirstDayOfWeek(Qt.Monday)
layout = QVBoxLayout()
layout.addWidget(calendar)
self.setLayout(layout)
def initDB():
conn = sqlite.connect('egon.db')
curs = conn.cursor()
return curs, conn
def initNewDB():
cursor, conn = initDB()
initSemesterDB(cursor)
initAssignmentDB(cursor)
initReadingDB(cursor)
initScheduleDB(cursor)
initBookDB(cursor)
initCourseDB(cursor)
initCourseUsesBook(cursor)
exitDB(conn)
def initSemesterDB(cursor):
cursor.execute('''
CREATE TABLE Semester (
term TEXT,
year INT,
PRIMARY KEY (term, year)
)
''')
def initAssignmentDB(cursor):
cursor.execute('''
CREATE TABLE Assignment (
date DATETIME,
course TEXT,
number INT,
description TEXT,
complete TEXT,
term TEXT,
year INT,
PRIMARY KEY (course, number)
)
''')
def initReadingDB(cursor):
cursor.execute('''
CREATE TABLE Reading (
week INT,
course TEXT,
book INT,
chapter TEXT,
pages TEXT,
done BOOLEAN,
term TEXT,
year INT,
PRIMARY KEY (week, course, book)
)
''')
def initScheduleDB(cursor):
cursor.execute('''
CREATE TABLE Lesson (
day TEXT,
time INT,
course TEXT,
type TEXT,
room TEXT,
term TEXT,
year INT,
PRIMARY KEY (course, day, time)
)
''')
def initBookDB(cursor):
cursor.execute('''
CREATE TABLE Book (
isbn TEXT PRIMARY KEY,
title TEXT,
author TEXT,
edition INTEGER
)
''')
def initCourseDB(cursor):
cursor.execute('''
CREATE TABLE Course (
code TEXT PRIMARY KEY,
title TEXT,
short TEXT,
red INT,
green INT,
blue INT
)
''')
def initCourseUsesBook(cursor):
cursor.execute('''
CREATE TABLE CourseUsesBook (
courseCode TEXT,
bookIsbn TEXT,
PRIMARY KEY (courseCode, bookIsbn)
)
''')
def addNewSemesterToDB(term, year):
cursor, conn = initDB()
cursor.execute('''
INSERT INTO Semester (term, year)
VALUES (?, ?)
''', (term, year))
exitDB(conn)
def addNewAssignmentToDB(semester, datetime, course, number, description, complete):
cursor, conn = initDB()
day = datetime.date().day()
month = datetime.date().month()
year = datetime.date().year()
hour = datetime.time().hour()
minute = datetime.time().minute()
timestring = "%02i-%02i-%02i %02i:%02i" % (year, month, day, hour, minute)
term = "%s" % semester.getTerm()
year = semester.getYear()
cursor.execute('''
INSERT INTO Assignment (date, course, number, description, complete, term, year)
VALUES (datetime(?), ?, ?, ?, ?, ?, ?)
''', (timestring, course.getCode(), number, description, complete, term, year))
exitDB(conn)
def addNewReadingToDB(semester, week, course, book, chapter, pages, done):
cursor, conn = initDB()
cursor.execute('''
INSERT INTO Reading (week, course, book, chapter, pages, done, term, year)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (week, course.getCode(), book.getIsbn(), chapter, pages, done, semester.getTerm(), semester.getYear()))
exitDB(conn)
def addNewLessonToDB(semester, day, time, course, type, room):
cursor, conn = initDB()
cursor.execute('''
INSERT INTO Lesson (day, time, course, type, room, term, year)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (day, time, course.getCode(), type, room, semester.getTerm(), semester.getYear()))
exitDB(conn)
def addNewCourseToDB(code, title, short, color, books):
cursor, conn = initDB()
red = color.red()
green = color.green()
blue = color.blue()
cursor.execute('''
INSERT INTO Course (code, title, short, red, green, blue)
VALUES (?, ?, ?, ?, ?, ?)
''', (code, title, short, red, green, blue))
for book in books:
cursor.execute('''
INSERT INTO CourseUsesBook (courseCode, bookIsbn)
VALUES (?, ?)
''', (code, book.getIsbn()))
exitDB(conn)
def addNewBookToDB(isbn, title, author, edition):
cursor, conn = initDB()
cursor.execute('''
INSERT INTO Book
VALUES (?, ?, ?, ?)
''', (isbn, title, author, edition))
exitDB(conn)
def getAssignmentsFromDB(semester):
cursor, conn = initDB()
term = "%s" % semester.getTerm()
year = (semester.getYear())
cursor.execute('''
SELECT *
FROM Assignment
WHERE term = ?
AND year = ?
''', (term, year))
assignments = []
for row in cursor.fetchall():
assignments.append(AssignmentModel(getQDateTime(row[0]), getCourseFromDB(row[1]), row[2], row[3], row[4]))
exitDB(conn)
return assignments
def getQDateTime(timestamp):
if not timestamp:
return None
datetimeList = timestamp.split()
dateString = datetimeList[0]
timeString = datetimeList[1]
dateList = dateString.split('-')
timeList = timeString.split(':')
year = string.atoi(dateList[0])
month = string.atoi(dateList[1])
day = string.atoi(dateList[2])
hour = string.atoi(timeList[0])
minute = string.atoi(timeList[1])
date = QDate(year, month, day)
time = QTime(hour, minute)
datetime = QDateTime(date, time)
return datetime
def getReadingsFromDB(semester):
cursor, conn = initDB()
term = "%s" % semester.getTerm()
year = semester.getYear()
cursor.execute('''
SELECT *
FROM Reading
WHERE term = ?
AND year = ?
''', (term, year))
readings = []
for row in cursor.fetchall():
readings.append(ReadingModel(row[0], getCourseFromDB(row[1]), getBookFromDB(row[2]), row[3], row[4], row[5]))
exitDB(conn)
return readings
def getLessonsFromDB(semester):
cursor, conn = initDB()
term = "%s" % semester.getTerm()
year = semester.getYear()
cursor.execute('''
SELECT *
FROM Lesson
WHERE term = ?
AND year = ?
''', (term, year))
lessons = []
for row in cursor.fetchall():
lessons.append(ScheduleModel(row[0], row[1], getCourseFromDB(row[2]), row[3], row[4]))
exitDB(conn)
return lessons
def getCoursesFromDB():
cursor, conn = initDB()
cursor.execute('''
SELECT *
FROM Course
''')
courses = []
for row in cursor.fetchall():
courses.append(CourseModel(row[0], row[1], row[2], QColor(row[3], row[4], row[5]), []))
for course in courses:
cursor.execute('''
SELECT bookIsbn
FROM CourseUsesBook
WHERE courseCode = ?
''', (course.getCode(),))
fetched = cursor.fetchall()
for fetchedRow in fetched:
cursor.execute('''
SELECT *
FROM Book
WHERE isbn = ?
''', (fetchedRow[0],))
for row in cursor:
course.addBook(BookModel(row[0], row[1], row[2], row[3]))
return courses
def getCourseFromDB(courseCode):
cursor, conn = initDB()
cursor.execute('''
SELECT *
FROM Course
WHERE code = ?
''', (courseCode,))
course = None
for row in cursor.fetchall():
course = CourseModel(row[0], row[1], row[2], QColor(row[3], row[4], row[5]), [])
cursor.execute('''
SELECT bookIsbn
FROM CourseUsesBook
WHERE courseCode = ?
''', (courseCode,))
fetched = cursor.fetchall()
for fetchedRow in fetched:
cursor.execute('''
SELECT *
FROM Book
WHERE isbn = ?
''', (fetchedRow[0],))
for row in cursor:
course.addBook(BookModel(row[0], row[1], row[2], row[3]))
exitDB(conn)
return course
def getBooksFromDB():
cursor, conn = initDB()
cursor.execute('''
SELECT *
FROM Book
''')
books = []
for row in cursor.fetchall():
books.append(BookModel(row[0], row[1], row[2], row[3]))
exitDB(conn)
return books
def getBookFromDB(isbn):
cursor, conn = initDB()
cursor.execute('''
SELECT *
FROM Book
WHERE isbn = ?
''', (isbn,))
for row in cursor.fetchall():
book = BookModel(row[0], row[1], row[2], row[3])
exitDB(conn)
return book
def getBookWithTitleFromDB(booktitle):
cursor, conn = initDB()
book = "%s" % booktitle
cursor.execute('''
SELECT *
FROM Book
WHERE title = ?
''', (book,))
for row in cursor.fetchall():
book = BookModel(row[0], row[1], row[2], row[3])
exitDB(conn)
return book
def getSemestersFromDB():
cursor, conn = initDB()
cursor.execute('''
SELECT *
FROM Semester
''')
semesters = []
for row in cursor.fetchall():
semesters.append(SemesterModel(row[0], row[1]))
exitDB(conn)
return semesters
def updateAssignmentCompletion(coursecode, num, completion):
cursor, conn = initDB()
complete = "%s" % completion
course = "%s" % coursecode
number = (num.toInt())[0]
cursor.execute('''
UPDATE Assignment
SET complete = ?
WHERE course = ?
AND number = ?
''', (complete, course, number))
exitDB(conn)
def updateReadingDone(week, coursecode, bookisbn, done):
cursor, conn = initDB()
course = "%s" % coursecode
book = "%s" % bookisbn
cursor.execute('''
UPDATE Reading
SET done = ?
WHERE week = ?
AND course = ?
AND book = ?
''', (done, week, course, book))
exitDB(conn)
def removeAssignmentFromDB(coursecode, num):
cursor, conn = initDB()
course = "%s" % coursecode
number = (num.toInt())[0]
cursor.execute('''
DELETE
FROM Assignment
WHERE course = ?
AND number = ?
''', (course, number))
exitDB(conn)
def removeReadingFromDB(week, coursecode, bookisbn):
cursor, conn = initDB()
course = "%s" % coursecode
book = "%s" % bookisbn
cursor.execute('''
DELETE
FROM Reading
WHERE week = ?
AND course = ?
AND book = ?
''', (week, course, book))
exitDB(conn)
def removeLessonFromDB(daystring, coursecode, fromTime):
cursor, conn = initDB()
day = "%s" % daystring
course = "%s" % coursecode
time = "%s" % fromTime
cursor.execute('''
DELETE
FROM Lesson
WHERE day = ?
AND course = ?
AND time = ?
''', (day, course, time))
exitDB(conn)
def exitDB(conn):
conn.commit()
conn.close()
def getCourseCode(courseFull):
course = courseFull.split(' ')
return course[0]
def addNewCourse(course):
courses.append(course)
addNewCourseToDB(course.getCode(), course.getTitle(), course.getShort(), course.getColor())
addNewCourseString(course)
def getCourses():
global courses
return courses
def addNewCourseString(course):
global coursesString
coursesString.append(course.getFull())
def makeCoursesString():
emptyCourses()
cs = getCoursesFromDB()
if cs:
for c in cs:
addNewCourseString(c)
s = getCoursesString()
return s
def getCoursesString():
global coursesString
return coursesString
def addNewBook(book):
books.append(book)
addNewBookToDB(book.getISBN(), book.getTitle(), book.getAuthor(), book.getEdition(), book.getCourse())
addNewBookString(book)
def getBooks():
global books
return books
def addNewBookString(book):
global booksString
booksString.append(book.getTitle())
def makeBooksString():
emptyBooks()
bs = getBooksFromDB()
if bs:
for b in bs:
addNewBookString(b)
s = getBooksString()
return s
def getBooksString():
global booksString
return booksString
def emptyCourses():
global courses
global coursesString
courses = []
coursesString = []
def emptyBooks():
global books
global booksString
books = []
booksString = []
def getRandomColor():
return QColor(getRandomColorPart(), getRandomColorPart(), getRandomColorPart())
def getRandomColorPart():
return random.random()*256
def getMain():
global main
return main
def main():
app = QApplication(sys.argv)
form = MainWindow()
app.setOrganizationName("PVV")
app.setOrganizationDomain("pvv.ntnu.no")
app.setApplicationName(form.title)
form.show()
app.exec_()
main()
#initNewDB()