#!/usr/bin/env python

import sys
import csv
from PyQt4 import QtGui, QtCore
from pyrpci import RemotePCI

VALUE_WIDTH = 90

COL_ADDRESS = 0
COL_NAME = 1
COL_WIDTH = 2
COL_VALUE = 3
COL_REMOVE = 4

FIELD_ADDRESS = "address"
FIELD_NAME = "name"
FIELD_WIDTH = "width"
PERSIST_FIELDS = [FIELD_ADDRESS, FIELD_NAME, FIELD_WIDTH]

DATA_WIDTHS = [8, 16, 32]

FONT_TYPEWRITER = QtGui.QFont("RPCI-GUI-FONT-TYPEWRITER")
FONT_TYPEWRITER.setStyleHint(QtGui.QFont.TypeWriter)

class StyledLabel(QtGui.QLabel):
    def __init__(self):
        super(StyledLabel, self).__init__()
        self.setFrameShape(QtGui.QFrame.StyledPanel)

class AddressWidget(QtGui.QLineEdit):
    """Widget for modifying the address.
    Supports 8-characters long HEX numbers.
    """
    def __init__(self, address):
        super(AddressWidget, self).__init__()
        
        self.setFont(FONT_TYPEWRITER)
        self.setMaxLength(8)
        self.setInputMask("\\0\\xHHHHHHHH")
        address_val = "0x00000000"
        if address is not None:
            address_val = address
        self.setText(address_val)
        self.setMaximumWidth(VALUE_WIDTH)
        self.setValidator(HexValidator())
        self.setAlignment(QtCore.Qt.AlignRight)

class TableSortItem(QtGui.QTableWidgetItem):
    """Used for storing the name of the address and sorting the table by address."""
    def __init__(self, name, w_address, cbox_width):
        super(TableSortItem, self).__init__(name, type=QtGui.QTableWidgetItem.UserType)
        self.w_address = w_address
        self.cbox_width = cbox_width
    
    def __lt__(self, other):
        """Sorts by address, width and name in this order."""
        if not isinstance(other, TableSortItem):
            return super(TableSortItem, self).__lt__(other)
        snum = int(str(self.w_address.text()), 0)
        onum = int(str(other.w_address.text()), 0)
        if snum != onum:
            return snum < onum
        if self.cbox_width.currentIndex() != other.cbox_width.currentIndex():
            return self.cbox_width.currentIndex() < other.cbox_width.currentIndex()
        return self.text() < other.text()
    
class ValWidget(QtGui.QWidget):
    """Widget for reading/writing and modifying the value of the register."""
    def __init__(self):
        super(ValWidget, self).__init__()
        
        self._text_write = QtGui.QLineEdit()
        self._text_write.setFont(FONT_TYPEWRITER)
        self._text_write.setValidator(HexValidator())
        text_write_sp = self._text_write.sizePolicy()
        text_write_sp.setVerticalPolicy(QtGui.QSizePolicy.Ignored)
        self._text_write.setSizePolicy(text_write_sp)
        self._text_write.setMaximumWidth(VALUE_WIDTH)
        self._text_write.setAlignment(QtCore.Qt.AlignRight)
        
        self.btn_write = QtGui.QPushButton("Write")
        btn_write_sp = self.btn_write.sizePolicy()
        btn_write_sp.setVerticalPolicy(QtGui.QSizePolicy.Ignored)
        self.btn_write.setSizePolicy(btn_write_sp)
        
        self._text_modify = QtGui.QLineEdit()
        self._text_modify.setFont(FONT_TYPEWRITER)
        self._text_modify.setValidator(HexValidator())
        text_modify_sp = self._text_modify.sizePolicy()
        text_modify_sp.setVerticalPolicy(QtGui.QSizePolicy.Ignored)
        self._text_modify.setSizePolicy(text_modify_sp)
        self._text_modify.setMaximumWidth(VALUE_WIDTH)
        self._text_modify.setAlignment(QtCore.Qt.AlignRight)
        
        self.btn_modify = QtGui.QPushButton("Modify")
        btn_modify_sp = self.btn_modify.sizePolicy()
        btn_modify_sp.setVerticalPolicy(QtGui.QSizePolicy.Ignored)
        self.btn_modify.setSizePolicy(btn_modify_sp)
        
        self._lbl_read = StyledLabel()
        self._lbl_read.setFont(FONT_TYPEWRITER)
        self._lbl_read.setMinimumWidth(VALUE_WIDTH)
        self._lbl_read.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        
        self.btn_read = QtGui.QPushButton("Read")
        btn_read_sp = self.btn_read.sizePolicy()
        btn_read_sp.setVerticalPolicy(QtGui.QSizePolicy.Ignored)
        self.btn_read.setSizePolicy(btn_read_sp)
        
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._text_write)
        layout.addWidget(self.btn_write)
        layout.addWidget(self._text_modify)
        layout.addWidget(self.btn_modify)
        layout.addWidget(self._lbl_read)
        layout.addWidget(self.btn_read)
        layout.setMargin(0)
        self.setLayout(layout)
        
        self.set_data_width(8)
    
    def set_read_data(self, data):
        data_str = ""
        if data != None:
            data_str = "0x" + format(data, "0" + str(self._data_width) + "X")
        self._lbl_read.setText(data_str)
    
    def get_write_data(self):
        """Returns data as a number."""
        return int(str(self._text_write.text()), 0)
    
    def get_modify_data(self):
        """Returns data as a number."""
        return int(str(self._text_modify.text()), 0)
    
    def set_data_width(self, width):
        """Data width is specified in bytes."""
        self._data_width = width
        input_mask = "\\0\\x" + width * "H"
        self._text_write.setInputMask(input_mask)
        self._text_write.setMaxLength(width)
        self._text_write.setText("0x" + width * "0")
        self._text_modify.setInputMask(input_mask)
        self._text_modify.setMaxLength(width)
        self._text_modify.setText("0x" + width * "F")

class PCIDataTableWidget(QtGui.QTableWidget):
    """Table that contains the data for all the registers.
    The user can edit it in-place. It also contains the buttons for read/write/modify/remove.
    """
    def __init__(self):
        super(PCIDataTableWidget, self).__init__(0, 5)
        
        self.setSelectionMode(QtGui.QAbstractItemView.NoSelection)
        self.verticalHeader().hide()
        self.horizontalHeader().setResizeMode(QtGui.QHeaderView.Fixed)
        
        self.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("Address"))
        self.setHorizontalHeaderItem(1, QtGui.QTableWidgetItem("Name"))
        self.setHorizontalHeaderItem(2, QtGui.QTableWidgetItem("Width [bits]"))
        self.setHorizontalHeaderItem(3, QtGui.QTableWidgetItem("Value"))
        self.setHorizontalHeaderItem(4, QtGui.QTableWidgetItem(""))
        
        size_name = QtCore.QSize()
        size_name.setWidth(150)
        self.horizontalHeaderItem(1).setSizeHint(size_name)
        self.itemChanged.connect(self.sortCustom)
    
    def sortCustom(self):
        """Always sorts by name column, since it contains the item that specifies sorting."""
        self.sortItems(COL_NAME, QtCore.Qt.AscendingOrder)
        
class HexValidator(QtGui.QValidator):
    """Validator for text fields that makes sure that there are
    no empty spaces and all hexadecimal letters are capitalized.
    """
    def __init__(self):
        super(HexValidator, self).__init__()
    
    def validate(self, s, pos):
        text = str(s)
        if text.count(" ") > 0:
            return QtGui.QValidator.Intermediate, pos
        for c in text:
            if c != 'x' and c.islower():
                return QtGui.QValidator.Intermediate, pos
        return QtGui.QValidator.Acceptable, pos
    
    def fixup(self, s):
        s.replace(0, s.size(), s.toUpper())
        s.replace("X", "x")
        s.replace(" ", "0")

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self._rpci = None
        self._exec_thread = None
        self._exec_obj = None
        self._exec_mutex = QtCore.QMutex()
        
        self._init_menus()
        
        self._txt_host = QtGui.QLineEdit()
        self._btn_connect = QtGui.QPushButton("Connect")
        self._btn_connect.clicked.connect(self._connect)
        
        w_connect = QtGui.QWidget()
        wc_layout = QtGui.QFormLayout()
        wc_layout.setLabelAlignment(QtCore.Qt.AlignRight)
        wc_layout.addRow("Hostname/IP:", self._txt_host)
        wc_layout.addRow(self._btn_connect)
        w_connect.setLayout(wc_layout)
        size_policy = w_connect.sizePolicy()
        size_policy.setVerticalPolicy(QtGui.QSizePolicy.Fixed)
        w_connect.setSizePolicy(size_policy)
        
        self._table_view = PCIDataTableWidget()
        self._add_address()
        self._table_view.resizeColumnsToContents()
        
        self._btn_add_address = QtGui.QPushButton("Add Address")
        self._btn_add_address.clicked.connect(lambda: self._add_address())
        self._btn_read_all = QtGui.QPushButton("Read All")
        self._btn_read_all.clicked.connect(self._read_all)
        self._btn_read_all.setEnabled(False)
        
        main_widget = QtGui.QWidget()
        layout = QtGui.QVBoxLayout()
        layout.addWidget(w_connect)
        layout.addWidget(self._table_view)
        layout.addWidget(self._btn_add_address)
        layout.addWidget(self._btn_read_all)
        main_widget.setLayout(layout)
        
        self.setCentralWidget(main_widget)
        self.setFixedSize(1000, 600)
        self.setWindowTitle("Remote PCI register access GUI")
        self.center()
        self.show()
    
    def center(self):
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    
    def _init_menus(self):
        self._act_new = QtGui.QAction("New", self)
        self._act_new.setShortcut('Ctrl+N')
        self._act_new.triggered.connect(self._remove_all)
        
        self._act_open = QtGui.QAction("Open", self)
        self._act_open.setShortcut('Ctrl+O')
        self._act_open.triggered.connect(self._load_registers)
        
        self._act_save = QtGui.QAction("Save", self)
        self._act_save.setShortcut('Ctrl+S')
        self._act_save.triggered.connect(self._save_registers)
        
        menubar = self.menuBar()
        reg_menu = menubar.addMenu("Register Map")
        reg_menu.addAction(self._act_new)
        reg_menu.addAction(self._act_open)
        reg_menu.addAction(self._act_save)
    
    def _enable_menus(self, enable):
        self._act_new.setEnabled(enable)
        self._act_open.setEnabled(enable)
        self._act_save.setEnabled(enable)
        
    def _save_registers(self):
        """Shows dialog and saves the data from the table to the CSV file."""
        file_name = QtGui.QFileDialog.getSaveFileName(self, "Save register map", ".")
        if not file_name:
            return
        
        with open(file_name, 'wb') as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=PERSIST_FIELDS)
            for row in range(self._table_view.rowCount()):
                text_addr = self._table_view.cellWidget(row, COL_ADDRESS)
                address = text_addr.text()
                cbox_width = self._table_view.cellWidget(row, COL_WIDTH)
                width = pow(2, cbox_width.currentIndex() + 3)
                item = self._table_view.item(row, COL_NAME)
                name = ""
                if item:
                    name = item.text()
                writer.writerow({FIELD_ADDRESS: address, FIELD_NAME: name, FIELD_WIDTH: width})
    
    def _load_registers(self):
        """Shows dialog and loads the data from the CSV file to the table.
        Table is populated only if the file contains valid/parsable data.
        In the opposite case, error dialog with the details is shown.
        """
        file_name = QtGui.QFileDialog.getOpenFileName(self, "Open register map", ".")
        if not file_name:
            return
        
        load_success = True
        items = []
        with open(file_name, 'rb') as csv_file:
            reader = csv.DictReader(csv_file, fieldnames=PERSIST_FIELDS)
            for i, row in enumerate(reader):
                try:
                    int(row[FIELD_ADDRESS], 0)
                    address = row[FIELD_ADDRESS]
                    name = row[FIELD_NAME]
                    if name is None:
                        raise Exception("Missing name attribute!")
                    width = int(row[FIELD_WIDTH])
                    if width not in DATA_WIDTHS:
                        raise Exception("Not supported width " + str(width))
                    
                    items.append((address, name, width))
                except Exception as e:
                    msg_box = QtGui.QMessageBox()
                    msg_box.setText("Cannot parse selected file!")
                    msg_box.setInformativeText("Error in line " + str(i) + ": " + str(e))
                    msg_box.setIcon(QtGui.QMessageBox.Warning)
                    msg_box.exec_()
                    load_success = False
                    break
        
        if load_success:
            self._table_view.setRowCount(0)
            for address, name, width in items:
                self._add_address(address, name, width)
    
    def _on_address_edited(self, w_val):
        w_val.set_read_data(None)
        self._table_view.sortCustom()
    
    def _on_width_changed(self, w_val, index):
        w_val.set_read_data(None)
        width = pow(2, index + 1)
        w_val.set_data_width(width)
        self._table_view.sortCustom()
        
    def _add_address(self, address=None, name=None, width=None):
        """Adds new row to the table with appropriate widgets initialized."""
        row_num = self._table_view.rowCount()
        self._table_view.insertRow(row_num)
        
        w_val = ValWidget()
        if not self._rpci:
            w_val.setEnabled(False)
        self._table_view.setCellWidget(row_num, COL_VALUE, w_val)
        
        w_address = AddressWidget(address)
        w_address.editingFinished.connect(lambda: self._on_address_edited(w_val))
        self._table_view.setCellWidget(row_num, COL_ADDRESS, w_address)
        
        cbox_width = QtGui.QComboBox()
        for i, dw in enumerate(DATA_WIDTHS):
            cbox_width.addItem(str(dw))
            if width is not None:
                if dw == width:
                    cbox_width.setCurrentIndex(i)
                    calc_width = pow(2, i + 1)
                    w_val.set_data_width(calc_width)
            else:
                if i == len(DATA_WIDTHS) - 1:
                    cbox_width.setCurrentIndex(i)
        cbox_width.currentIndexChanged.connect(lambda: self._on_width_changed(w_val, cbox_width.currentIndex()))
        self._table_view.setCellWidget(row_num, COL_WIDTH, cbox_width)
        
        btn_remove = QtGui.QPushButton("Remove")
        btn_remove.clicked.connect(self._remove)
        self._table_view.setCellWidget(row_num, COL_REMOVE, btn_remove)
        
        # connect value buttons
        w_val.btn_write.clicked.connect(lambda: self._write(w_val, w_address, cbox_width, btn_remove))
        w_val.btn_modify.clicked.connect(lambda: self._modify(w_val, w_address, cbox_width, btn_remove))
        w_val.btn_read.clicked.connect(lambda: self._read(w_val, w_address, cbox_width, btn_remove))
        
        name_str = ""
        if name is not None:
            name_str = name
        
        tw_item = TableSortItem(name_str, w_address, cbox_width)
        # will automatically sort when the item is changed
        self._table_view.setItem(row_num, COL_NAME, tw_item)
    
    def _remove(self):
        btn = self.sender()
        index = self._table_view.indexAt(btn.pos())
        if not index.isValid():
            return
        
        self._table_view.removeRow(index.row())
        if self._table_view.rowCount() == 0:
            self._add_address()
    
    def _remove_all(self):
        """Enforces at least one element in the table."""
        self._table_view.setRowCount(0)
        self._add_address()
    
    def _connect(self):
        if not self._rpci:
            try:
                self._btn_connect.setEnabled(False)
                self._rpci = RemotePCI(self._txt_host.text())
                # just simple tests to check if the connection works
                self._rpci.read_text(0, 1)
                self._txt_host.setEnabled(False)
                self._btn_connect.setText("Disconnect")
                self._enable_val_widgets(True)
            except Exception as e:
                self._rpci = None
                msg_box = QtGui.QMessageBox()
                msg_box.setText("Cannot connect! Check if the PCI register server is running and it is accessible on the network.")
                msg_box.setInformativeText(str(e))
                msg_box.setIcon(QtGui.QMessageBox.Warning)
                msg_box.exec_()
                self._txt_host.setFocus()
                #raise e, None, sys.exc_info()[2]
                return
            finally:
                self._btn_connect.setEnabled(True)
        else:
            self._rpci = None
            self._txt_host.setEnabled(True)
            self._btn_connect.setText("Connect")
            self._enable_val_widgets(False)
    
    def _enable_table_edit(self, enable):
        self._table_view.setEnabled(enable)
        self._btn_add_address.setEnabled(enable)
        self._btn_read_all.setEnabled(enable)
        self._enable_menus(enable)
    
    def _read_all(self):
        self._enable_table_edit(False)
        self._dev_communicate(self._dev_read_all, lambda: self._enable_table_edit(True))
    
    def _get_target_register(self, w_address, cbox_width):
        cid = cbox_width.currentIndex()
        width = pow(2, cid + 3)
        offset = int(str(w_address.text()), 0)
        return (offset, width)
    
    def _enable_row_edit(self, w_address, cbox_width, btn_remove, enable):
        w_address.setEnabled(enable)
        cbox_width.setEnabled(enable)
        btn_remove.setEnabled(enable)
        self._enable_val_widgets(enable)
        self._enable_menus(enable)
            
    def _read(self, w_val, w_address, cbox_width, btn_remove):
        self._enable_row_edit(w_address, cbox_width, btn_remove, False)
        offset, width = self._get_target_register(w_address, cbox_width)
        self._dev_communicate(lambda: self._dev_read(w_val, offset, width), lambda: self._enable_row_edit(w_address, cbox_width, btn_remove, True))
    
    def _write(self, w_val, w_address, cbox_width, btn_remove):
        self._enable_row_edit(w_address, cbox_width, btn_remove, False)
        offset, width = self._get_target_register(w_address, cbox_width)
        self._dev_communicate(lambda: self._dev_write(w_val, offset, width), lambda: self._enable_row_edit(w_address, cbox_width, btn_remove, True))
    
    def _modify(self, w_val, w_address, cbox_width, btn_remove):
        self._enable_row_edit(w_address, cbox_width, btn_remove, False)
        offset, width = self._get_target_register(w_address, cbox_width)
        self._dev_communicate(lambda: self._dev_modify(w_val, offset, width), lambda: self._enable_row_edit(w_address, cbox_width, btn_remove, True))
    
    def _enable_val_widgets(self, enable):
        """Enables/disables all the widgets for reading/writing the registers."""
        self._btn_read_all.setEnabled(enable)
        for row in range(self._table_view.rowCount()):
            w_val = self._table_view.cellWidget(row, COL_VALUE)
            w_val.setEnabled(enable)
    
    def _dev_read_all(self):
        for row in range(self._table_view.rowCount()):
            w_address = self._table_view.cellWidget(row, COL_ADDRESS)
            cbox_width = self._table_view.cellWidget(row, COL_WIDTH)
            w_val = self._table_view.cellWidget(row, COL_VALUE)
            offset, width = self._get_target_register(w_address, cbox_width)
            self._dev_read(w_val, offset, width)
            
    def _dev_read(self, widget_val, offset, width):
        data = self._rpci.read(offset, width)
        widget_val.set_read_data(data)

    def _dev_write(self, widget_val, offset, width):
        val_w = widget_val.get_write_data()
        self._rpci.write(offset, width, val_w)
        widget_val.set_read_data(None)
    
    def _dev_modify(self, widget_val, offset, width):
        val_w = widget_val.get_write_data()
        val_m = widget_val.get_modify_data()
        data = self._rpci.modify(offset, width, val_w, val_m)
        widget_val.set_read_data(data)
    
    def _dev_communicate(self, func_run, func_cleanup):
        """Executes passed functions in the background thread."""
        with QtCore.QMutexLocker(self._exec_mutex):
            if self._exec_obj:
                return
            self._exec_thread = QtCore.QThread()
            self._exec_obj = ExecThreadObj(func_run)
            self._exec_obj.moveToThread(self._exec_thread)
            self._exec_obj.finished.connect(self._exec_thread.quit)
            self._exec_thread.started.connect(self._exec_obj.do_run)
            self._exec_thread.finished.connect(lambda: self._stop_thread_callback(func_cleanup, self._exec_obj.exc))
            self._exec_thread.start()
    
    def _stop_thread_callback(self, func_cleanup, exc):
        if exc:
            msg_box = QtGui.QMessageBox()
            msg_box.setText("Device operation failed!")
            msg_box.setInformativeText(str(exc))
            msg_box.setIcon(QtGui.QMessageBox.Warning)
            msg_box.exec_()
        with QtCore.QMutexLocker(self._exec_mutex):
            self._exec_thread = None
            self._exec_obj = None
        func_cleanup()

class ExecThreadObj(QtCore.QObject):
    """Object that gets executed on the background thread."""
    finished = QtCore.pyqtSignal()
    
    def __init__(self, func_run):
        QtCore.QObject.__init__(self)
        self._func_run = func_run
        self.exc = None
    
    def do_run(self):
        try:
            self._func_run()
        except Exception as e:
            self.exc = e
        finally:
            self.finished.emit()
    
def main():
    app = QtGui.QApplication(sys.argv)
    _ = MainWindow()
    return app.exec_()
    
if __name__ == '__main__':
    sys.exit(main())
