Esempio n. 1
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(
         ['ID', 'Vault', '# of Items', '# of Peers'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader()
     vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     button = QPushButton('Create Vault', self)
     button.clicked.connect(self.createVault)
     hbox.addWidget(button)
     button = QPushButton('Connect to Vault', self)
     backend = QApplication.instance().backend()
     available = backend.locator_is_available()
     if available:
         button.clicked.connect(self.connectVault)
     else:
         button.setEnabled(False)
     hbox.addWidget(button)
     removebtn = QPushButton('Remove Vault', self)
     removebtn.setEnabled(False)
     removebtn.clicked.connect(self.removeVault)
     self.removebtn = removebtn
     hbox.addWidget(removebtn)
Esempio n. 2
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(['ID', 'Vault', '# of Items', '# of Peers'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader()
     vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     button = QPushButton('Create Vault', self)
     button.clicked.connect(self.createVault)
     hbox.addWidget(button)
     button = QPushButton('Connect to Vault', self)
     backend = QApplication.instance().backend()
     available = backend.locator_is_available()
     if available:
         button.clicked.connect(self.connectVault)
     else:
         button.setEnabled(False)
     hbox.addWidget(button)
     removebtn = QPushButton('Remove Vault', self)
     removebtn.setEnabled(False)
     removebtn.clicked.connect(self.removeVault)
     self.removebtn = removebtn
     hbox.addWidget(removebtn)
Esempio n. 3
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     preamble.setWordWrap(True)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(['ID', 'Vault', 'Source', 'On Node'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader()
     vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     cancelbtn = QPushButton('Cancel', self)
     cancelbtn.clicked.connect(self.vaultmgr.hide)
     hbox.addWidget(cancelbtn)
     self.cancelbtn = cancelbtn
     connectbtn = QPushButton('Connect', self)
     connectbtn.setEnabled(False)
     connectbtn.clicked.connect(self.connectVault)
     hbox.addWidget(connectbtn)
     self.connectbtn = connectbtn
     hbox.addStretch(100)
Esempio n. 4
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     preamble.setWordWrap(True)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(['ID', 'Vault', 'Source', 'On Node'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader(); vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     cancelbtn = QPushButton('Cancel', self)
     cancelbtn.clicked.connect(self.vaultmgr.hide)
     hbox.addWidget(cancelbtn)
     self.cancelbtn = cancelbtn
     connectbtn = QPushButton('Connect', self)
     connectbtn.setEnabled(False)
     connectbtn.clicked.connect(self.connectVault)
     hbox.addWidget(connectbtn)
     self.connectbtn = connectbtn
     hbox.addStretch(100)
Esempio n. 5
0
class ExpensesDialog(QDialog):

    holdc = {}

    def __init__(self, session, parent=None):
        super(ExpensesDialog, self).__init__(parent)
        self.session = session
        session = self.pullOnes('session', session)
        self.sessionname = str(session['name']) + ' Session'
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_account = {}
        self.hold_expenses = {}
        self.hold_expensesGroup = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        expensesGroup = self.pullGroupExpenses()
        account = self.pullAccount()

        self.expenseGroupText = QLabel('Category')
        self.expenseGroupData = QComboBox()
        self.expenseGroupData.currentIndexChanged.connect(self.reloadExpenses)
        self.expenseText = QLabel('Expenses')
        self.expenseData = QComboBox()
        self.amountText = QLabel('Amount')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Teller/Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.accountText = QLabel('Account')
        self.accountData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Brief Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        hboz = QHBoxLayout()
        self.gender = QLabel('State')
        self.r1 = QRadioButton('Expenses')
        self.r1.setChecked(True)
        self.r2 = QRadioButton('Refund')
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)

        i = 0
        for a in expensesGroup:
            self.hold_expensesGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseGroupData.addItem(tex)
            i += 1

        i = 0
        exp_key = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(exp_key)
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

        i = 0
        for a in account:
            self.hold_account[i] = a['id']
            tex = str(a['name']).upper()
            self.accountData.addItem(tex)
            i += 1

        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.expenseGroupText, self.expenseGroupData)
        self.FormLayout.addRow(self.expenseText, self.expenseData)
        self.FormLayout.addRow(self.accountText, self.accountData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.gender, hboz)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)

        groupBox1 = QGroupBox('Add Expenses')
        groupBox1.setLayout(self.FormLayout)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Expenses")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Expenses")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Expenses Data')
        groupBox2.setLayout(hbo)

        self.cols = ['SN', 'EXPENSES', 'ACCOUNT', 'AMOUNT', 'DATE']
        al = self.pullExpensesData()
        if len(al) > 0:
            al = al
        else:
            al = {}

        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()
        self.h1_pull_box = QVBoxLayout()
        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        self.connect(self.pull_btn,
                     SIGNAL("clicked()"),
                     lambda x=1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupExpenses(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 15, "active": 0})
        return arr

    def pullExpenses(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullAccount(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullExpensesData(self):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_expenses' + str(self.session)
        cn = Db()
        arr = cn.selectExpenseDate(db, st_date, en_date)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            self.editID = int(data['id'])
            if float(data['amount']) < 0:
                amt = float(data['amount']) * -1
                self.amountData.setText(str(amt))
                self.r1.setChecked(True)
            else:
                amt = float(data['amount'])
                self.amountData.setText(str(amt))
                self.r2.setChecked(True)

            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            acID = self.hold_account.keys()[self.hold_account.values().index(
                data['accountID'])]
            self.accountData.setCurrentIndex(acID)
            exID = self.hold_expenses.keys()[self.hold_expenses.values().index(
                data['expenseID'])]
            self.expenseData.setCurrentIndex(exID)

    def reloadExpenses(self):
        cat = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(cat)
        self.expenseData.clear()
        self.hold_expenses = {}
        i = 0
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

    def reloadTable(self, a):
        data = self.pullExpensesData()
        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        for j in item:
            g.delete(db, {'id': j})

        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            ups = {}
            ups['id'] = self.editID
            if int(self.editID) > 0:
                db = 'school_expenses' + str(_session)
                g = Db()
                g.update(db, arr, ups)
                if int(self.editID) > 0:
                    self.button_reset()

    def button_reset(self):
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            db = 'school_expenses' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
Esempio n. 6
0
class phonesDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width() / 2.5, screen.height() / 3)
        self.isPlaying = False
        #self.audioManager = audioManager(self)
        #self.playThread = threadedPlayer(self)

        self.sizer = QGridLayout()
        self.v1Sizer = QVBoxLayout()
        self.v2Sizer = QVBoxLayout()
        self.calibSizer = QGridLayout()

        self.phonesTableWidget = QTableWidget()
        self.phonesTableWidget.setColumnCount(4)
        self.phonesTableWidget.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.phonesTableWidget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

        self.phonesTableWidget.setHorizontalHeaderLabels([
            self.tr('Phones'),
            self.tr('Max Level'),
            self.tr('Default'), 'id'
        ])
        self.phonesTableWidget.hideColumn(3)
        self.phonesTableWidget.cellDoubleClicked[int, int].connect(
            self.onCellDoubleClicked)

        #RENAME Phones BUTTON
        self.renamePhonesButton = QPushButton(self.tr("Rename Phones"), self)
        self.renamePhonesButton.clicked.connect(self.onEditLabel)
        #Change Level Phones BUTTON
        self.changeLevelPhonesButton = QPushButton(self.tr("Change Max Level"),
                                                   self)
        self.changeLevelPhonesButton.clicked.connect(self.onEditMaxLevel)

        #ADD Phones BUTTON
        self.addPhonesButton = QPushButton(self.tr("Add Phones"), self)
        self.addPhonesButton.clicked.connect(self.onClickAddPhonesButton)
        #REMOVE Phones BUTTON
        self.removePhonesButton = QPushButton(self.tr("Remove Phones"), self)
        self.removePhonesButton.clicked.connect(self.onClickRemovePhonesButton)
        #Set Default Phones BUTTON
        self.setDefaultPhonesButton = QPushButton(self.tr("Set Default"), self)
        self.setDefaultPhonesButton.clicked.connect(self.onEditDefault)

        self.v1Sizer.addWidget(self.renamePhonesButton)
        self.v1Sizer.addWidget(self.changeLevelPhonesButton)
        self.v1Sizer.addWidget(self.addPhonesButton)
        self.v1Sizer.addWidget(self.removePhonesButton)
        self.v1Sizer.addWidget(self.setDefaultPhonesButton)
        self.v1Sizer.addStretch()
        self.phonesList = {}

        for i in range(len(self.prm['phones']['phonesChoices'])):
            currCount = i + 1
            thisID = self.prm['phones']['phonesID'][i]
            self.phonesList[thisID] = {}
            self.phonesList[thisID]['label'] = self.prm['phones'][
                'phonesChoices'][i]
            self.phonesList[thisID]['maxLevel'] = self.prm['phones'][
                'phonesMaxLevel'][i]
            self.phonesList[thisID]['default'] = self.prm['phones'][
                'defaultPhones'][i]
            self.phonesTableWidget.setRowCount(currCount)
            newItem = QTableWidgetItem(self.phonesList[thisID]['label'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount - 1, 0, newItem)
            newItem = QTableWidgetItem(
                self.currLocale.toString(self.phonesList[thisID]['maxLevel']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount - 1, 1, newItem)
            newItem = QTableWidgetItem(self.phonesList[thisID]['default'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount - 1, 2, newItem)
            self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.phonesTableWidget.setItem(currCount - 1, 3,
                                           self.phonesList[thisID]['qid'])

        ##CALIBRATION TONE
        n = 0
        self.calLabel = QLabel(self.tr('Calibration Tone:'), self)
        self.calibSizer.addWidget(self.calLabel, n, 0, 1, 2)
        n = n + 1
        self.toneFreqLabel = QLabel(self.tr('Frequency (Hz)'), self)
        self.toneFreqTF = QLineEdit("1000")
        self.toneFreqTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneFreqLabel, n, 0)
        self.calibSizer.addWidget(self.toneFreqTF, n, 1)
        n = n + 1
        self.toneLevLabel = QLabel(self.tr('Level (dB)'), self)
        self.toneLevTF = QLineEdit("60")
        self.toneLevTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneLevLabel, n, 0)
        self.calibSizer.addWidget(self.toneLevTF, n, 1)
        n = n + 1
        self.toneDurLabel = QLabel(self.tr('Duration (ms)'), self)
        self.toneDurTF = QLineEdit("980")
        self.toneDurTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneDurLabel, n, 0)
        self.calibSizer.addWidget(self.toneDurTF, n, 1)
        n = n + 1
        self.toneRampsLabel = QLabel(self.tr('Ramps (ms)'), self)
        self.toneRampsTF = QLineEdit("10")
        self.toneRampsTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneRampsLabel, n, 0)
        self.calibSizer.addWidget(self.toneRampsTF, n, 1)
        n = n + 1
        self.earLabel = QLabel(self.tr('Ear:'), self)
        self.earChooser = QComboBox()
        self.earChooser.addItems(
            [self.tr("Right"),
             self.tr("Left"),
             self.tr("Both")])
        self.calibSizer.addWidget(self.earLabel, n, 0)
        self.calibSizer.addWidget(self.earChooser, n, 1)
        n = n + 1
        self.playCalibButton = QPushButton(self.tr("Play"), self)
        self.playCalibButton.clicked.connect(self.onClickPlayCalibButton)
        self.playCalibButton.setIcon(
            QIcon.fromTheme("media-playback-start",
                            QIcon(":/media-playback-start")))
        self.calibSizer.addWidget(self.playCalibButton, n, 0, 1, 2)
        n = n + 1
        self.stopCalibButton = QPushButton(self.tr("Stop"), self)
        self.stopCalibButton.clicked.connect(self.onClickStopCalibButton)
        self.stopCalibButton.setIcon(
            QIcon.fromTheme("media-playback-stop",
                            QIcon(":/media-playback-stop")))
        self.calibSizer.addWidget(self.stopCalibButton, n, 0, 1, 2)
        if self.prm['pref']['sound']['playCommand'] in [
                "alsaaudio", "pyaudio"
        ]:
            self.stopCalibButton.show()
        else:
            self.stopCalibButton.hide()

        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply
                                     | QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        buttonBox.button(QDialogButtonBox.Apply).clicked.connect(
            self.permanentApply)

        self.sizer.addLayout(self.v1Sizer, 0, 0)
        self.v2Sizer.addLayout(self.calibSizer)
        self.v2Sizer.addStretch()
        self.sizer.addWidget(self.phonesTableWidget, 0, 1)
        self.sizer.addLayout(self.v2Sizer, 0, 2)
        self.sizer.addWidget(buttonBox, 1, 1, 1, 2)
        self.sizer.setColumnStretch(1, 2)
        self.setLayout(self.sizer)
        self.setWindowTitle(self.tr("Edit Phones"))
        self.show()

    def onCellDoubleClicked(self, row, col):
        if col == 0:
            self.onEditLabel()
        elif col == 1:
            self.onEditMaxLevel()
        elif col == 2:
            self.onEditDefault()

    def onEditLabel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one label can be renamed at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('New name:')
            text, ok = QInputDialog.getText(self, self.tr('Input Dialog'), msg)
            if ok:
                self.phonesTableWidget.item(
                    self.phonesList[selectedSound]['qid'].row(),
                    0).setText(text)
                self.phonesList[selectedSound]['label'] = text

    def onEditMaxLevel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('Level:')
            text, ok = QInputDialog.getDouble(
                self, self.tr('Input Dialog'), msg,
                self.phonesList[selectedSound]['maxLevel'])
            if ok:
                self.phonesTableWidget.item(
                    self.phonesList[selectedSound]['qid'].row(),
                    1).setText(self.currLocale.toString(text))
                self.phonesList[selectedSound]['maxLevel'] = text

    def onEditDefault(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            for i in range(self.phonesTableWidget.rowCount()):
                self.phonesTableWidget.item(i, 2).setText("\u2012")
                self.phonesList[str(self.phonesTableWidget.item(
                    i, 3).text())]['default'] = "\u2012"
            self.phonesTableWidget.item(
                self.phonesList[selectedSound]['qid'].row(),
                2).setText("\u2713")
            self.phonesList[selectedSound]['default'] = "\u2713"

    def findSelectedItemIds(self):
        selItems = self.phonesTableWidget.selectedItems()
        selItemsRows = []
        for i in range(len(selItems)):
            selItemsRows.append(selItems[i].row())
        selItemsRows = unique(selItemsRows)
        selItemsIds = []
        for i in range(len(selItemsRows)):
            selItemsIds.append(
                str(self.phonesTableWidget.item(selItemsRows[i], 3).text()))
        return selItemsIds

    def permanentApply(self):
        self.prm['phones']['phonesChoices'] = []
        self.prm['phones']['phonesMaxLevel'] = []
        self.prm['phones']['defaultPhones'] = []
        self.prm['phones']['phonesID'] = []

        keys = sorted(self.phonesList.keys())
        for key in keys:
            self.prm['phones']['phonesChoices'].append(
                str(self.phonesList[key]['label']))
            self.prm['phones']['phonesMaxLevel'].append(
                self.phonesList[key]['maxLevel'])
            self.prm['phones']['defaultPhones'].append(
                self.phonesList[key]['default'])
            self.prm['phones']['phonesID'].append(key)
        f = open(self.parent().prm['phonesPrefFile'], 'wb')
        pickle.dump(self.parent().prm['phones'], f)
        f.close()
        for i in range(self.parent().phonesChooser.count()):
            self.parent().phonesChooser.removeItem(0)
        self.parent().phonesChooser.addItems(
            self.prm['phones']['phonesChoices'])

    def onClickAddPhonesButton(self):
        keys = sorted(self.phonesList.keys())
        thisID = str(int(keys[-1]) + 1)
        currCount = self.phonesTableWidget.rowCount() + 1

        self.phonesList[thisID] = {}
        self.phonesList[thisID]['label'] = 'Phones' + ' ' + str(currCount)
        self.phonesList[thisID]['maxLevel'] = 100
        self.phonesList[thisID]['default'] = "\u2012"
        self.phonesTableWidget.setRowCount(currCount)
        newItem = QTableWidgetItem(self.phonesList[thisID]['label'])
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount - 1, 0, newItem)
        newItem = QTableWidgetItem(
            self.currLocale.toString(self.phonesList[thisID]['maxLevel']))
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount - 1, 1, newItem)
        newItem = QTableWidgetItem(self.phonesList[thisID]['default'])
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount - 1, 2, newItem)
        self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID)
        self.phonesTableWidget.setItem(currCount - 1, 3,
                                       self.phonesList[thisID]['qid'])

    def onClickRemovePhonesButton(self):
        if self.phonesTableWidget.rowCount() == 1:
            ret = QMessageBox.warning(
                self, self.tr("Warning"),
                self.tr("Only one phone left. Cannot remove!"), QMessageBox.Ok)
        else:
            ids = self.findSelectedItemIds()
            wasDefault = False
            for i in range(len(ids)):
                selectedPhones = ids[i]
                if self.phonesTableWidget.item(
                        self.phonesList[selectedPhones]['qid'].row(),
                        2).text() == "\u2713":
                    wasDefault = True
                self.phonesTableWidget.removeRow(
                    self.phonesList[selectedPhones]['qid'].row())
                del self.phonesList[selectedPhones]
            if wasDefault == True:
                self.phonesTableWidget.item(0, 2).setText("\u2713")
                self.phonesList[str(self.phonesTableWidget.item(
                    0, 3).text())]['default'] = "\u2713"

    def onClickPlayCalibButton(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one label can be renamed at a time'))
            return
        elif len(ids) < 1:
            QMessageBox.warning(self, self.tr('Warning'),
                                self.tr('Please, select a phone in the table'))
            return
        else:
            selectedSound = ids[0]
            calMaxLev = self.phonesList[selectedSound]['maxLevel']
            frequency = self.currLocale.toDouble(self.toneFreqTF.text())[0]
            level = self.currLocale.toDouble(self.toneLevTF.text())[0]
            duration = self.currLocale.toDouble(self.toneDurTF.text())[0]
            ramp = self.currLocale.toDouble(self.toneRampsTF.text())[0]
            channel = self.earChooser.currentText()
            fs = self.currLocale.toInt(self.parent().sampRateTF.text())[0]
            nBits = self.currLocale.toInt(
                self.parent().nBitsChooser.currentText())[0]
            calTone = pureTone(frequency, 0, level, duration, ramp, channel,
                               fs, calMaxLev)
            self.isPlaying = True
            if self.prm['pref']['sound']['playCommand'] in [
                    "alsaaudio", "pyaudio"
            ]:
                self.playThread = threadedAudioPlayer(self.parent())
            else:
                self.playThread = threadedExternalAudioPlayer(self.parent())
            self.playThread.playThreadedSound(
                calTone, fs, nBits, self.prm['pref']['sound']['playCommand'],
                True, 'calibrationTone.wav')
            if self.playThread.isFinished() == True:
                self.isPlaying = False

    def onClickStopCalibButton(self):
        if self.isPlaying == True:
            self.playThread.terminate()
            #self.playThread.__del__()

    def closeEvent(self, event):
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        event.accept()

    def accept(self):  #reimplement accept (i.e. ok button)
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        QDialog.accept(self)

    def reject(self):  #reimplement reject
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        QDialog.reject(self)
Esempio n. 7
0
class wavListDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().parent().prm
        self.audioManager = audioManager(self)
        self.currLocale = self.parent().parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        self.isPlaying = False

        self.sizer = QGridLayout()
        self.v1Sizer = QVBoxLayout()

        self.wavsTableWidget = QTableWidget()
        self.wavsTableWidget.setColumnCount(4)
        self.wavsTableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.wavsTableWidget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

        self.wavsTableWidget.setHorizontalHeaderLabels(
            [self.tr("File"),
             self.tr('Use'),
             self.tr("RMS Level"), 'id'])
        self.quidColumn = 3
        self.wavsTableWidget.hideColumn(self.quidColumn)
        self.wavsTableWidget.cellDoubleClicked[int, int].connect(
            self.onCellDoubleClicked)

        #ADD wav BUTTON
        self.addWavButton = QPushButton(self.tr("Add Wav"), self)
        self.addWavButton.clicked.connect(self.onClickAddWavButton)
        #REMOVE wav BUTTON
        self.removeWavButton = QPushButton(self.tr("Remove Wav"), self)
        self.removeWavButton.clicked.connect(self.onClickRemoveWavButton)

        #PLAY wav BUTTON
        self.playWavButton = QPushButton(self.tr("Play Wav"), self)
        self.playWavButton.clicked.connect(self.onClickPlayWavButton)
        #STOP wav BUTTON
        self.stopWavButton = QPushButton(self.tr("Stop Playing"), self)
        self.stopWavButton.clicked.connect(self.onClickStopWavButton)

        self.v1Sizer.addWidget(self.addWavButton)
        self.v1Sizer.addWidget(self.removeWavButton)
        self.v1Sizer.addWidget(self.playWavButton)
        self.v1Sizer.addWidget(self.stopWavButton)

        self.v1Sizer.addStretch()

        self.wavsList = {}

        for i in range(len(self.parent().wavsPref['endMessageFiles'])):
            currCount = i + 1
            thisID = self.parent().wavsPref['endMessageFilesID'][i]
            self.wavsList[thisID] = {}
            self.wavsList[thisID]['file'] = self.parent(
            ).wavsPref['endMessageFiles'][i]
            self.wavsList[thisID]['use'] = self.parent(
            ).wavsPref['endMessageFilesUse'][i]
            self.wavsList[thisID]['level'] = self.parent(
            ).wavsPref['endMessageLevels'][i]
            self.wavsTableWidget.setRowCount(currCount)
            n = 0
            newItem = QTableWidgetItem(self.wavsList[thisID]['file'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(self.wavsList[thisID]['use'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(
                self.currLocale.toString(self.wavsList[thisID]['level']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.wavsTableWidget.setItem(currCount - 1, n,
                                         self.wavsList[thisID]['qid'])

        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply
                                     | QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        self.sizer.addLayout(self.v1Sizer, 0, 0)
        self.sizer.addWidget(self.wavsTableWidget, 0, 1)
        self.sizer.addWidget(buttonBox, 1, 1)
        self.setLayout(self.sizer)
        self.setWindowTitle(self.tr("Edit Wavs"))
        self.show()

    def onCellDoubleClicked(self, row, col):
        if col == 0:
            pass
        elif col == 1:
            self.onEditUse()
        elif col == 2:
            self.onEditLevel()

    def onEditLevel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('RMS Level:')
            text, ok = QInputDialog.getDouble(
                self, self.tr('Input Dialog'), msg,
                self.wavsList[selectedSound]['level'])
            if ok:
                self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    2).setText(self.currLocale.toString(text))
                self.wavsList[selectedSound]['level'] = text

    def onEditUse(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            if self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    1).text() == "\u2012":
                self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    1).setText("\u2713")
                self.wavsList[selectedSound]['use'] = "\u2713"
            else:
                self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    1).setText("\u2012")
                self.wavsList[selectedSound]['use'] = "\u2012"

    def findSelectedItemIds(self):
        selItems = self.wavsTableWidget.selectedItems()
        selItemsRows = []
        for i in range(len(selItems)):
            selItemsRows.append(selItems[i].row())
        selItemsRows = unique(selItemsRows)
        selItemsIds = []
        for i in range(len(selItemsRows)):
            selItemsIds.append(
                str(
                    self.wavsTableWidget.item(selItemsRows[i],
                                              self.quidColumn).text()))
        return selItemsIds

    def permanentApply(self):
        self.wavListToPass = {}
        self.wavListToPass['endMessageFiles'] = []
        self.wavListToPass['endMessageFilesUse'] = []
        self.wavListToPass['endMessageFilesID'] = []
        self.wavListToPass['endMessageLevels'] = []

        keys = sorted(self.wavsList.keys())
        for key in keys:
            self.wavListToPass['endMessageFiles'].append(
                str(self.wavsList[key]['file']))
            self.wavListToPass['endMessageFilesUse'].append(
                self.wavsList[key]['use'])
            self.wavListToPass['endMessageLevels'].append(
                self.wavsList[key]['level'])
            self.wavListToPass['endMessageFilesID'].append(key)

    def onClickAddWavButton(self):
        fName = QFileDialog.getOpenFileName(
            self, self.tr("Choose wav file to load"), '',
            self.tr("wav files (*.wav);;All Files (*)"))[0]
        if len(fName) > 0:  #if the user didn't press cancel

            if len(self.wavsList.keys()) > 0:
                keys = sorted(self.wavsList.keys())
                thisID = str(int(keys[-1]) + 1)
            else:
                thisID = "1"
            currCount = self.wavsTableWidget.rowCount() + 1

            self.wavsList[thisID] = {}
            self.wavsList[thisID]['file'] = fName
            self.wavsList[thisID]['use'] = "\u2713"
            self.wavsList[thisID]['level'] = 60
            self.wavsTableWidget.setRowCount(currCount)
            n = 0
            newItem = QTableWidgetItem(self.wavsList[thisID]['file'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(self.wavsList[thisID]['use'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(
                self.currLocale.toString(self.wavsList[thisID]['level']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.wavsTableWidget.setItem(currCount - 1, n,
                                         self.wavsList[thisID]['qid'])

    def onClickRemoveWavButton(self):
        ids = self.findSelectedItemIds()
        for i in range(len(ids)):
            selectedWavs = ids[i]
            self.wavsTableWidget.removeRow(
                self.wavsList[selectedWavs]['qid'].row())
            del self.wavsList[selectedWavs]

    def onClickPlayWavButton(self):
        ids = self.findSelectedItemIds()
        if len(ids) < 1:
            QMessageBox.warning(self, self.tr('Warning'),
                                self.tr('No files selected for playing'))
        else:
            if len(ids) > 1:
                pass  #maybe say on the status bar that only the first one will be played
            selectedWav = ids[0]
            fName = self.wavsList[selectedWav]['file']
            level = self.wavsList[selectedWav]['level']
            nBits = self.currLocale.toInt(
                self.parent().parent().nBitsChooser.currentText())[0]
            maxLevel = float(self.prm['phones']['phonesMaxLevel'][
                self.parent().parent().phonesChooser.currentIndex()])
            msgSnd, fs = self.audioManager.loadWavFile(fName, level, maxLevel,
                                                       'Both')
            self.isPlaying = True
            if self.prm['pref']['sound']['playCommand'] in [
                    "alsaaudio", "pyaudio"
            ]:
                self.playThread = threadedAudioPlayer(self.parent().parent())
            else:
                self.playThread = threadedExternalAudioPlayer(
                    self.parent().parent())
            self.playThread.playThreadedSound(
                msgSnd, fs, nBits, self.prm['pref']['sound']['playCommand'],
                False, 'tmp.wav')
            if self.playThread.isFinished == True:
                self.isPlaying = False

    def onClickStopWavButton(self):
        if self.isPlaying == True:
            self.playThread.terminate()

    def closeEvent(self, event):
        if self.isPlaying == True:
            self.playThread.terminate()
        event.accept()

    def accept(self):  #reimplement accept (i.e. ok button)
        if self.isPlaying == True:
            self.playThread.terminate()
        QDialog.accept(self)

    def reject(self):  #reimplement reject
        if self.isPlaying == True:
            self.playThread.terminate()
        QDialog.reject(self)
Esempio n. 8
0
class UserDialog(QDialog):

    holdc = {}

    def __init__(self, parent=None):
        super(UserDialog, self).__init__(parent)
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        self.table = QTableWidget()
        self.cols = [
            'SN', 'ITEM', 'QUANTITY', 'UNIT AMOUNT', 'TOTAL AMOUNT', 'DATE'
        ]
        self.h1_pull_box = QVBoxLayout()

        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_unit = {}
        self.hold_store = {}
        self.hold_storeGroup = {}
        self.hold_borrowed = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        menu = QMenu()
        menu.addAction('All', lambda: self.reloadTable(0))
        menu.addAction('In-Stock', lambda: self.reloadTable(1))
        menu.addAction('Out-Stock', lambda: self.reloadTable(2))
        menu.addAction('Damaged', lambda: self.reloadTable(3))
        menu.addAction('Borrowed', lambda: self.reloadTable(4))
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        self.pull_btn.setMenu(menu)
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        storeGroup = self.pullGroupStore()
        unit = self.pullUnit()

        self.storeGroupText = QLabel('Category')
        self.storeGroupData = QComboBox()
        self.storeGroupData.currentIndexChanged.connect(self.reloadStore)
        self.storeText = QLabel('Items')
        self.storeData = QComboBox()

        self.amountText = QLabel('Total Cost')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.quantityText = QLabel('Quantity.')
        self.quantityData = QLineEdit()
        self.quantityData.setPlaceholderText('00.0')
        self.periodText = QLabel('Period (days)')
        self.periodData = QLineEdit()
        self.periodData.setPlaceholderText('00.0')
        self.personText = QLabel('Recieved By:')
        self.personData = QLineEdit()
        self.personData.setPlaceholderText('00.0')
        self.unitText = QLabel('Unit')
        self.unitData = QComboBox()
        self.borrowedText = QLabel('Borrowed')
        self.borrowedData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        self.borrowedText.hide()
        self.borrowedData.hide()

        mboz = QVBoxLayout()
        hboz = QHBoxLayout()
        self.state = QLabel('')
        self.r1 = QRadioButton('In-stock')
        self.r1.setChecked(True)
        self.r1.toggled.connect(lambda: self.changeStates())
        self.r2 = QRadioButton('Out-stock')
        self.r2.toggled.connect(lambda: self.changeStates())
        self.r3 = QRadioButton('Damaged')
        self.r3.toggled.connect(lambda: self.changeStates())
        self.r4 = QRadioButton('Borrowed')
        self.r4.toggled.connect(lambda: self.changeStates())
        self.r5 = QRadioButton('Returned')
        self.r5.toggled.connect(lambda: self.changeStates())
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)
        hboz.addWidget(self.r3)
        hboz.addWidget(self.r4)
        hboz.addWidget(self.r5)

        i = 0
        for a in storeGroup:
            self.hold_storeGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.storeGroupData.addItem(tex)
            i += 1

        i = 0
        str_key = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(str_key)
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

        i = 0
        for a in unit:
            self.hold_unit[i] = a['id']
            tex = str(a['name']).upper()
            self.unitData.addItem(tex)
            i += 1

        self.reloadBorrowed()
        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.storeGroupText, self.storeGroupData)
        self.FormLayout.addRow(self.storeText, self.storeData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.quantityText, self.quantityData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.periodText, self.periodData)
        self.FormLayout.addRow(self.borrowedText, self.borrowedData)
        self.FormLayout.addRow(self.personText, self.personData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)
        self.periodText.hide()
        self.periodData.hide()

        mboz.addLayout(hboz)
        mboz.addLayout(self.FormLayout)
        mboz.addWidget(self.state)

        groupBox1 = QGroupBox('Add Store Item')
        groupBox1.setLayout(mboz)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Store Item")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Store")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Store Data')
        groupBox2.setLayout(hbo)

        al = self.pullStoreData(0)
        if al and len(al) > 0:
            al = al
        else:
            al = {}

        self.storeData.currentIndexChanged.connect(
            lambda: self.reloadBorrowed())

        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Store")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()

        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        #self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x =1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def stateReciept(self):
        self.amountText.show()
        self.amountData.show()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Reciept No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Recieved By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(1)

    def stateIssue(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Issue No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Issued to:')
        self.personData.setPlaceholderText('Fullname or department issued to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(2)

    def stateDamage(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Reported By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(3)

    def stateBorrowed(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.show()
        self.periodData.show()
        self.personText.setText('Given to:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(4)

    def stateReturned(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Returned By:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.show()
        self.borrowedData.show()
        self.reloadBorrowed()
        self.reloadTable(5)

    def changeStates(self):
        self.getQuantity()
        if self.r1.isChecked():
            self.stateReciept()
        elif self.r2.isChecked():
            self.stateIssue()
        elif self.r3.isChecked():
            self.stateDamage()
        elif self.r4.isChecked():
            self.stateBorrowed()
        elif self.r5.isChecked():
            self.stateReturned()

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupStore(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 23, "active": 0})
        return arr

    def pullStore(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullUnit(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullStoreData(self, a=None):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_stores' + str(self.session)
        cn = Db()
        arr = cn.selectStoreDate(db, st_date, en_date, a)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            try:
                amt = float(data['amount'])
                qty = float(data['quantity'])
                if amt > 0 and qty > 0:
                    cost = amt * qty
                else:
                    cost = 0
            except:
                cost = 0
                amt = 0
                qty = 0

            if data['state'] == 1:
                self.r1.setChecked(True)
            elif data['state'] == 2:
                self.r2.setChecked(True)
            elif data['state'] == 3:
                self.r3.setChecked(True)
            elif data['state'] == 4:
                self.r4.setChecked(True)
            elif data['state'] == 5:
                self.r5.setChecked(True)

            self.amountData.setText(str(cost))
            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            self.periodData.setText(str(data['period']))
            self.personData.setText(str(data['person']))
            self.quantityData.setText(str(qty))
            stID = self.hold_store.keys()[self.hold_store.values().index(
                data['itemID'])]
            self.storeData.setCurrentIndex(stID)

    def reloadBorrowed(self):
        self.getQuantity()
        _store = self.hold_store[self.storeData.currentIndex()]
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', '', {'itemID': _store, 'state': 4})
        fig = 0
        self.borrowedData.clear()
        self.hold_borrowed = {}
        i = 0
        for a in data:
            ret = g.selectStoreReturned(db, a['id'])

            if ret:
                retu = ret['qty']
            else:
                retu = 0

            fig = float(a['quantity']) - float(retu)
            damz = float(a['datepaid'])
            if float(fig) > 0:
                self.hold_borrowed[i] = a['id']
                damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
                tex = str(damt) + " " + str(
                    a['person']).upper() + " (" + str(fig).upper() + ")"
                self.borrowedData.addItem(tex)
                i += 1

    def reloadStore(self):
        self.getQuantity()
        cat = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(cat)
        self.storeData.clear()
        self.hold_store = {}
        i = 0
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

    def getQuantity(self):
        if self.storeData.currentIndex() > -1:
            s = self.hold_store[self.storeData.currentIndex()]
            _session = self.session
            g = Db()
            db = 'school_stores' + str(_session)
            fi = g.selectStoreQuantity(db, s)
            remain = 0
            arr = {}
            for a in fi:
                arr[a['state']] = a['qty']

            if 1 in arr:
                re = arr[1]
            else:
                re = 0

            if 2 in arr:
                isu = arr[2]
            else:
                isu = 0

            if 3 in arr:
                dam = arr[3]
            else:
                dam = 0

            if 4 in arr:
                bor = arr[4]
            else:
                bor = 0

            if 5 in arr:
                ret = arr[5]
            else:
                ret = 0

            borrowed = float(bor) - float(ret)
            issued = float(isu) + float(borrowed) + float(dam)
            remain = float(re) - float(issued)
            self.quantityText.setText('QTY: ' + str(remain))
            if remain == 0 and (self.r2.isChecked() or self.r3.isChecked()
                                or self.r4.isChecked()):
                self.quantityData.setEnabled(False)
            else:
                self.quantityData.setEnabled(True)
            return remain

    def reloadTable(self, a):
        self.getQuantity()
        if not a == 0:
            data = self.pullStoreData(a)
        else:
            data = self.pullStoreData()

        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Stores")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id

            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        for j in item:
            g.delete(db, {'id': j})
        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]
        _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        ups = {}
        ups['id'] = self.editID
        if int(self.editID) > 0 and len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            g.update(db, arr, ups)
            if int(self.editID) > 0:
                self.button_reset()

    def button_reset(self):
        self.getQuantity()
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.personData.setText('')
        self.periodData.setText('')
        self.quantityData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()
        self.reloadBorrowed()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0 and self.borrowedData.currentIndex() > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        if len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
class wavListDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().parent().prm
        self.audioManager = audioManager(self)
        self.currLocale = self.parent().parent().prm['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        self.isPlaying = False
      
        self.sizer = QGridLayout() 
        self.v1Sizer = QVBoxLayout()
        
        self.wavsTableWidget = QTableWidget()
        self.wavsTableWidget.setColumnCount(4)
        self.wavsTableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.wavsTableWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        
        self.wavsTableWidget.setHorizontalHeaderLabels([self.tr("File"), self.tr('Use'), self.tr("RMS Level"), 'id'])
        self.quidColumn = 3
        self.wavsTableWidget.hideColumn(self.quidColumn)
        self.wavsTableWidget.cellDoubleClicked[int,int].connect(self.onCellDoubleClicked)

        
        #ADD wav BUTTON
        self.addWavButton = QPushButton(self.tr("Add Wav"), self)
        self.addWavButton.clicked.connect(self.onClickAddWavButton)
        #REMOVE wav BUTTON
        self.removeWavButton = QPushButton(self.tr("Remove Wav"), self)
        self.removeWavButton.clicked.connect(self.onClickRemoveWavButton)

        #PLAY wav BUTTON
        self.playWavButton = QPushButton(self.tr("Play Wav"), self)
        self.playWavButton.clicked.connect(self.onClickPlayWavButton)
        #STOP wav BUTTON
        self.stopWavButton = QPushButton(self.tr("Stop Playing"), self)
        self.stopWavButton.clicked.connect(self.onClickStopWavButton)
       
        self.v1Sizer.addWidget(self.addWavButton)
        self.v1Sizer.addWidget(self.removeWavButton)
        self.v1Sizer.addWidget(self.playWavButton)
        self.v1Sizer.addWidget(self.stopWavButton)
     
        self.v1Sizer.addStretch()

        self.wavsList = {}
    
        for i in range(len(self.parent().wavsPref['endMessageFiles'])):
            currCount = i+1
            thisID = self.parent().wavsPref['endMessageFilesID'][i]
            self.wavsList[thisID] = {}
            self.wavsList[thisID]['file'] = self.parent().wavsPref['endMessageFiles'][i]
            self.wavsList[thisID]['use'] = self.parent().wavsPref['endMessageFilesUse'][i]
            self.wavsList[thisID]['level'] = self.parent().wavsPref['endMessageLevels'][i]
            self.wavsTableWidget.setRowCount(currCount)
            n = 0
            newItem = QTableWidgetItem(self.wavsList[thisID]['file'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount-1, n, newItem)
            n = n+1
            newItem = QTableWidgetItem(self.wavsList[thisID]['use'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount-1, n, newItem)
            n = n+1
            newItem = QTableWidgetItem(self.currLocale.toString(self.wavsList[thisID]['level']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount-1, n, newItem)
            n = n+1
            self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.wavsTableWidget.setItem(currCount-1, n, self.wavsList[thisID]['qid'])

     
        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        self.sizer.addLayout(self.v1Sizer, 0, 0)
        self.sizer.addWidget(self.wavsTableWidget,0,1)
        self.sizer.addWidget(buttonBox, 1,1)
        self.setLayout(self.sizer)
        self.setWindowTitle(self.tr("Edit Wavs"))
        self.show()


    def onCellDoubleClicked(self, row, col):
        if col == 0:
            pass
        elif col == 1:
            self.onEditUse()
        elif col == 2:
            self.onEditLevel()

    def onEditLevel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('RMS Level:')
            text, ok = QInputDialog.getDouble(self, self.tr('Input Dialog'), msg, self.wavsList[selectedSound]['level'])
            if ok:
                self.wavsTableWidget.item(self.wavsList[selectedSound]['qid'].row(), 2).setText(self.currLocale.toString(text))
                self.wavsList[selectedSound]['level'] = text

    def onEditUse(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            if self.wavsTableWidget.item(self.wavsList[selectedSound]['qid'].row(), 1).text() == "\u2012":
                self.wavsTableWidget.item(self.wavsList[selectedSound]['qid'].row(), 1).setText("\u2713")
                self.wavsList[selectedSound]['use'] = "\u2713"
            else:
                self.wavsTableWidget.item(self.wavsList[selectedSound]['qid'].row(), 1).setText("\u2012")
                self.wavsList[selectedSound]['use'] = "\u2012"
    def findSelectedItemIds(self):
        selItems = self.wavsTableWidget.selectedItems()
        selItemsRows = []
        for i in range(len(selItems)):
            selItemsRows.append(selItems[i].row())
        selItemsRows = unique(selItemsRows)
        selItemsIds = []
        for i in range(len(selItemsRows)):
            selItemsIds.append(str(self.wavsTableWidget.item(selItemsRows[i], self.quidColumn).text()))
        return selItemsIds

    def permanentApply(self):
        self.wavListToPass = {}
        self.wavListToPass['endMessageFiles'] = []
        self.wavListToPass['endMessageFilesUse'] = []
        self.wavListToPass['endMessageFilesID'] = []
        self.wavListToPass['endMessageLevels'] = []

        keys = sorted(self.wavsList.keys())
        for key in keys:
            self.wavListToPass['endMessageFiles'].append(str(self.wavsList[key]['file']))
            self.wavListToPass['endMessageFilesUse'].append(self.wavsList[key]['use'])
            self.wavListToPass['endMessageLevels'].append(self.wavsList[key]['level'])
            self.wavListToPass['endMessageFilesID'].append(key)
      

    def onClickAddWavButton(self):
        fName = QFileDialog.getOpenFileName(self, self.tr("Choose wav file to load"), '', self.tr("wav files (*.wav);;All Files (*)"))[0]
        if len(fName) > 0: #if the user didn't press cancel

            if len(self.wavsList.keys()) > 0:
                keys = sorted(self.wavsList.keys())
                thisID = str(int(keys[-1])+1)
            else:
                thisID = "1"
            currCount = self.wavsTableWidget.rowCount() + 1

            self.wavsList[thisID] = {}
            self.wavsList[thisID]['file'] = fName
            self.wavsList[thisID]['use'] = "\u2713"
            self.wavsList[thisID]['level'] = 60
            self.wavsTableWidget.setRowCount(currCount)
            n = 0
            newItem = QTableWidgetItem(self.wavsList[thisID]['file'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount-1, n, newItem)
            n = n+1
            newItem = QTableWidgetItem(self.wavsList[thisID]['use'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount-1, n, newItem)
            n = n+1
            newItem = QTableWidgetItem(self.currLocale.toString(self.wavsList[thisID]['level']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount-1, n, newItem)
            n = n+1
            self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.wavsTableWidget.setItem(currCount-1, n, self.wavsList[thisID]['qid'])
      

    def onClickRemoveWavButton(self):
        ids = self.findSelectedItemIds()
        for i in range(len(ids)):
            selectedWavs = ids[i]
            self.wavsTableWidget.removeRow(self.wavsList[selectedWavs]['qid'].row())
            del self.wavsList[selectedWavs]

    def onClickPlayWavButton(self):
        ids = self.findSelectedItemIds()
        if len(ids) < 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('No files selected for playing'))
        else:
            if len(ids) > 1:
                pass #maybe say on the status bar that only the first one will be played
            selectedWav = ids[0]
            fName = self.wavsList[selectedWav]['file']
            level = self.wavsList[selectedWav]['level']
            nBits = self.currLocale.toInt(self.parent().parent().nBitsChooser.currentText())[0]
            maxLevel = float(self.prm['phones']['phonesMaxLevel'][self.parent().parent().phonesChooser.currentIndex()])
            msgSnd, fs = self.audioManager.loadWavFile(fName, level, maxLevel, 'Both')
            self.isPlaying = True
            if self.prm['pref']['sound']['playCommand'] in ["alsaaudio","pyaudio"]:
                self.playThread = threadedAudioPlayer(self.parent().parent())
            else:
                self.playThread = threadedExternalAudioPlayer(self.parent().parent())
            self.playThread.playThreadedSound(msgSnd, fs, nBits, self.prm['pref']['sound']['playCommand'], False, 'tmp.wav')
            if self.playThread.isFinished == True:
                self.isPlaying = False
    def onClickStopWavButton(self):
        if self.isPlaying == True:
            self.playThread.terminate()
          
        
    def closeEvent(self, event):
        if self.isPlaying == True:
            self.playThread.terminate()
        event.accept()
        
    def accept(self): #reimplement accept (i.e. ok button)
        if self.isPlaying == True:
            self.playThread.terminate()
        QDialog.accept(self)
    def reject(self): #reimplement reject
        if self.isPlaying == True:
            self.playThread.terminate()
        QDialog.reject(self)
class phonesDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width()/2.5,screen.height()/3)
        self.isPlaying = False
        #self.audioManager = audioManager(self)
        #self.playThread = threadedPlayer(self)
   
        self.sizer = QGridLayout() 
        self.v1Sizer = QVBoxLayout()
        self.v2Sizer = QVBoxLayout()
        self.calibSizer = QGridLayout()
        
        self.phonesTableWidget = QTableWidget()
        self.phonesTableWidget.setColumnCount(4)
        self.phonesTableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.phonesTableWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        
        self.phonesTableWidget.setHorizontalHeaderLabels([self.tr('Phones'), self.tr('Max Level'), self.tr('Default'), 'id'])
        self.phonesTableWidget.hideColumn(3)
        self.phonesTableWidget.cellDoubleClicked[int,int].connect(self.onCellDoubleClicked)

        #RENAME Phones BUTTON
        self.renamePhonesButton = QPushButton(self.tr("Rename Phones"), self)
        self.renamePhonesButton.clicked.connect(self.onEditLabel)
        #Change Level Phones BUTTON
        self.changeLevelPhonesButton = QPushButton(self.tr("Change Max Level"), self)
        self.changeLevelPhonesButton.clicked.connect(self.onEditMaxLevel)
        
        #ADD Phones BUTTON
        self.addPhonesButton = QPushButton(self.tr("Add Phones"), self)
        self.addPhonesButton.clicked.connect(self.onClickAddPhonesButton)
        #REMOVE Phones BUTTON
        self.removePhonesButton = QPushButton(self.tr("Remove Phones"), self)
        self.removePhonesButton.clicked.connect(self.onClickRemovePhonesButton)
        #Set Default Phones BUTTON
        self.setDefaultPhonesButton = QPushButton(self.tr("Set Default"), self)
        self.setDefaultPhonesButton.clicked.connect(self.onEditDefault)

        self.v1Sizer.addWidget(self.renamePhonesButton)
        self.v1Sizer.addWidget(self.changeLevelPhonesButton)
        self.v1Sizer.addWidget(self.addPhonesButton)
        self.v1Sizer.addWidget(self.removePhonesButton)
        self.v1Sizer.addWidget(self.setDefaultPhonesButton)
        self.v1Sizer.addStretch()
        self.phonesList = {}
    
        for i in range(len(self.prm['phones']['phonesChoices'])):
            currCount = i+1
            thisID = self.prm['phones']['phonesID'][i]
            self.phonesList[thisID] = {}
            self.phonesList[thisID]['label'] = self.prm['phones']['phonesChoices'][i]
            self.phonesList[thisID]['maxLevel'] = self.prm['phones']['phonesMaxLevel'][i]
            self.phonesList[thisID]['default'] = self.prm['phones']['defaultPhones'][i]
            self.phonesTableWidget.setRowCount(currCount)
            newItem = QTableWidgetItem(self.phonesList[thisID]['label'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount-1, 0, newItem)
            newItem = QTableWidgetItem(self.currLocale.toString(self.phonesList[thisID]['maxLevel']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount-1, 1, newItem)
            newItem = QTableWidgetItem(self.phonesList[thisID]['default'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount-1, 2, newItem)
            self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.phonesTableWidget.setItem(currCount-1, 3, self.phonesList[thisID]['qid'])

        ##CALIBRATION TONE
        n = 0
        self.calLabel = QLabel(self.tr('Calibration Tone:'), self)
        self.calibSizer.addWidget(self.calLabel, n, 0, 1, 2)
        n = n+1
        self.toneFreqLabel = QLabel(self.tr('Frequency (Hz)'), self)
        self.toneFreqTF = QLineEdit("1000")
        self.toneFreqTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneFreqLabel, n, 0)
        self.calibSizer.addWidget(self.toneFreqTF, n, 1)
        n = n+1
        self.toneLevLabel = QLabel(self.tr('Level (dB)'), self)
        self.toneLevTF = QLineEdit("60")
        self.toneLevTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneLevLabel, n, 0)
        self.calibSizer.addWidget(self.toneLevTF, n, 1)
        n = n+1
        self.toneDurLabel = QLabel(self.tr('Duration (ms)'), self)
        self.toneDurTF = QLineEdit("4980")
        self.toneDurTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneDurLabel, n, 0)
        self.calibSizer.addWidget(self.toneDurTF, n, 1)
        n = n+1
        self.toneRampsLabel = QLabel(self.tr('Ramps (ms)'), self)
        self.toneRampsTF = QLineEdit("10")
        self.toneRampsTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneRampsLabel, n, 0)
        self.calibSizer.addWidget(self.toneRampsTF, n, 1)
        n = n+1
        self.earLabel = QLabel(self.tr('Ear:'), self)
        self.earChooser = QComboBox()
        self.earChooser.addItems([self.tr("Right"), self.tr("Left"), self.tr("Both")])
        self.calibSizer.addWidget(self.earLabel, n, 0)
        self.calibSizer.addWidget(self.earChooser, n, 1)
        n = n+1
        self.playCalibButton = QPushButton(self.tr("Play"), self)
        self.playCalibButton.clicked.connect(self.onClickPlayCalibButton)
        self.playCalibButton.setIcon(QIcon.fromTheme("media-playback-start", QIcon(":/media-playback-start")))
        self.calibSizer.addWidget(self.playCalibButton, n, 0, 1, 2)
        n = n+1
        self.stopCalibButton = QPushButton(self.tr("Stop"), self)
        self.stopCalibButton.clicked.connect(self.onClickStopCalibButton)
        self.stopCalibButton.setIcon(QIcon.fromTheme("media-playback-stop", QIcon(":/media-playback-stop")))
        self.calibSizer.addWidget(self.stopCalibButton, n, 0, 1, 2)
        if self.prm['pref']['sound']['playCommand'] in ["alsaaudio","pyaudio"]:
            self.stopCalibButton.show()
        else:
            self.stopCalibButton.hide()
        
        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply)

        self.sizer.addLayout(self.v1Sizer, 0, 0)
        self.v2Sizer.addLayout(self.calibSizer)
        self.v2Sizer.addStretch()
        self.sizer.addWidget(self.phonesTableWidget, 0, 1)
        self.sizer.addLayout(self.v2Sizer, 0, 2)
        self.sizer.addWidget(buttonBox, 1,1,1,2)
        self.sizer.setColumnStretch(1,2)
        self.setLayout(self.sizer)
        self.setWindowTitle(self.tr("Edit Phones"))
        self.show()

    def onCellDoubleClicked(self, row, col):
        if col == 0:
            self.onEditLabel()
        elif col == 1:
            self.onEditMaxLevel()
        elif col == 2:
            self.onEditDefault()

    def onEditLabel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('Only one label can be renamed at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('New name:')
            text, ok = QInputDialog.getText(self, self.tr('Input Dialog'), msg)
            if ok:
                self.phonesTableWidget.item(self.phonesList[selectedSound]['qid'].row(), 0).setText(text)
                self.phonesList[selectedSound]['label'] = text
    def onEditMaxLevel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('Level:')
            text, ok = QInputDialog.getDouble(self, self.tr('Input Dialog'), msg, self.phonesList[selectedSound]['maxLevel'])
            if ok:
                self.phonesTableWidget.item(self.phonesList[selectedSound]['qid'].row(), 1).setText(self.currLocale.toString(text))
                self.phonesList[selectedSound]['maxLevel'] = text

    def onEditDefault(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            for i in range(self.phonesTableWidget.rowCount()):
                 self.phonesTableWidget.item(i, 2).setText("\u2012")
                 self.phonesList[str(self.phonesTableWidget.item(i, 3).text())]['default'] = "\u2012"
            self.phonesTableWidget.item(self.phonesList[selectedSound]['qid'].row(), 2).setText("\u2713")
            self.phonesList[selectedSound]['default'] = "\u2713"

    def findSelectedItemIds(self):
        selItems = self.phonesTableWidget.selectedItems()
        selItemsRows = []
        for i in range(len(selItems)):
            selItemsRows.append(selItems[i].row())
        selItemsRows = unique(selItemsRows)
        selItemsIds = []
        for i in range(len(selItemsRows)):
            selItemsIds.append(str(self.phonesTableWidget.item(selItemsRows[i], 3).text()))
        return selItemsIds

    def permanentApply(self):
        self.prm['phones']['phonesChoices'] = []
        self.prm['phones']['phonesMaxLevel'] = []
        self.prm['phones']['defaultPhones'] = []
        self.prm['phones']['phonesID'] = []

        keys = sorted(self.phonesList.keys())
        for key in keys:
            self.prm['phones']['phonesChoices'].append(str(self.phonesList[key]['label']))
            self.prm['phones']['phonesMaxLevel'].append(self.phonesList[key]['maxLevel'])
            self.prm['phones']['defaultPhones'].append(self.phonesList[key]['default'])
            self.prm['phones']['phonesID'].append(key)
        f = open(self.parent().prm['phonesPrefFile'], 'wb')
        pickle.dump(self.parent().prm['phones'], f)
        f.close()
        for i in range(self.parent().phonesChooser.count()):
            self.parent().phonesChooser.removeItem(0)
        self.parent().phonesChooser.addItems(self.prm['phones']['phonesChoices'])

    def onClickAddPhonesButton(self):
        keys = sorted(self.phonesList.keys())
        thisID = str(int(keys[-1])+1)
        currCount = self.phonesTableWidget.rowCount() + 1

        self.phonesList[thisID] = {}
        self.phonesList[thisID]['label'] = 'Phones' + ' ' + str(currCount)
        self.phonesList[thisID]['maxLevel'] = 100
        self.phonesList[thisID]['default'] = "\u2012"
        self.phonesTableWidget.setRowCount(currCount)
        newItem = QTableWidgetItem(self.phonesList[thisID]['label'])
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount-1, 0, newItem)
        newItem = QTableWidgetItem(self.currLocale.toString(self.phonesList[thisID]['maxLevel']))
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount-1, 1, newItem)
        newItem = QTableWidgetItem(self.phonesList[thisID]['default'])
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount-1, 2, newItem)
        self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID)
        self.phonesTableWidget.setItem(currCount-1, 3, self.phonesList[thisID]['qid'])
      

    def onClickRemovePhonesButton(self):
        if self.phonesTableWidget.rowCount() == 1:
            ret = QMessageBox.warning(self, self.tr("Warning"),
                                            self.tr("Only one phone left. Cannot remove!"),
                                            QMessageBox.Ok)
        else:
            ids = self.findSelectedItemIds()
            wasDefault = False
            for i in range(len(ids)):
                selectedPhones = ids[i]
                if self.phonesTableWidget.item(self.phonesList[selectedPhones]['qid'].row(), 2).text() == "\u2713":
                    wasDefault = True 
                self.phonesTableWidget.removeRow(self.phonesList[selectedPhones]['qid'].row())
                del self.phonesList[selectedPhones]
            if wasDefault == True:
                self.phonesTableWidget.item(0, 2).setText("\u2713")
                self.phonesList[str(self.phonesTableWidget.item(0, 3).text())]['default'] = "\u2713"


    def onClickPlayCalibButton(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('Only one label can be renamed at a time'))
            return
        elif len(ids) < 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('Please, select a phone in the table'))
            return
        else:
            selectedSound = ids[0]
            calMaxLev = self.phonesList[selectedSound]['maxLevel']
            frequency = self.currLocale.toDouble(self.toneFreqTF.text())[0]
            level = self.currLocale.toDouble(self.toneLevTF.text())[0]
            duration = self.currLocale.toDouble(self.toneDurTF.text())[0]
            ramp = self.currLocale.toDouble(self. toneRampsTF.text())[0]
            channel =  self.earChooser.currentText()
            fs = self.currLocale.toInt(self.parent().sampRateTF.text())[0]
            nBits = self.currLocale.toInt(self.parent().nBitsChooser.currentText())[0]
            calTone = pureTone(frequency, 0, level, duration, ramp, channel, fs, calMaxLev)
            self.isPlaying = True
            if self.prm['pref']['sound']['playCommand'] in ["alsaaudio","pyaudio"]:
                self.playThread = threadedAudioPlayer(self.parent())
            else:
                self.playThread = threadedExternalAudioPlayer(self.parent())
            self.playThread.playThreadedSound(calTone, fs, nBits, self.prm['pref']['sound']['playCommand'], True, 'calibrationTone.wav')
            if self.playThread.isFinished() == True:
                self.isPlaying = False

    def onClickStopCalibButton(self):
        if self.isPlaying == True:
            self.playThread.terminate()
            #self.playThread.__del__()

    def closeEvent(self, event):
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        event.accept()
        
    def accept(self): #reimplement accept (i.e. ok button)
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        QDialog.accept(self)
    def reject(self): #reimplement reject
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        QDialog.reject(self)