Exemplo n.º 1
0
class CodeCompletionWidget(QFrame):
    def __init__(self, editor):
        super(CodeCompletionWidget,
              self).__init__(None, Qt.FramelessWindowHint | Qt.ToolTip)
        self._editor = editor
        self._revision = 0
        self._block = 0
        self.stack_layout = QStackedLayout(self)
        self.stack_layout.setContentsMargins(0, 0, 0, 0)
        self.stack_layout.setSpacing(0)
        self.completion_list = QListWidget()
        self.completion_list.setMinimumHeight(200)
        self.completion_list.setAlternatingRowColors(True)
        self._list_index = self.stack_layout.addWidget(self.completion_list)

        self._icons = {
            'a': ":img/attribute",
            'f': ":img/function",
            'c': ":img/class",
            'm': ":img/module"
        }

        self.cc = code_completion.CodeCompletion()
        self._completion_results = {}
        self._prefix = ''
        self.setVisible(False)
        self.source = ''
        self._key_operations = {
            Qt.Key_Up: self._select_previous_row,
            Qt.Key_Down: self._select_next_row,
            Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
            Qt.Key_PageDown: (lambda: self._select_next_row(6)),
            Qt.Key_Right: lambda: None,
            Qt.Key_Left: lambda: None,
            Qt.Key_Enter: self.pre_key_insert_completion,
            Qt.Key_Return: self.pre_key_insert_completion,
            Qt.Key_Tab: self.pre_key_insert_completion,
            Qt.Key_Space: self.hide_completer,
            Qt.Key_Escape: self.hide_completer,
            Qt.Key_Backtab: self.hide_completer,
            Qt.NoModifier: self.hide_completer,
            Qt.ShiftModifier: self.hide_completer,
        }

        self.desktop = QApplication.instance().desktop()

        self.completion_list.itemClicked['QListWidgetItem*'].connect(
            self.pre_key_insert_completion)
        self._editor.document(
        ).cursorPositionChanged['const QTextCursor &'].connect(
            self.update_metadata)

    def _select_next_row(self, move=1):
        new_row = self.completion_list.currentRow() + move
        if new_row < self.completion_list.count():
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(0)
        return True

    def _select_previous_row(self, move=1):
        new_row = self.completion_list.currentRow() - move
        if new_row >= 0:
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(self.completion_list.count() -
                                               move)
        return True

    def update_metadata(self, cursor):
        if settings.CODE_COMPLETION:
            if self._editor.document().revision() != self._revision and \
               cursor.block().blockNumber() != self._block:
                source = self._editor.text()
                source = source.encode(self._editor.encoding)
                self.cc.analyze_file(self._editor.file_path, source,
                                     self._editor.indent, self._editor.useTabs)
                self._revision = self._editor.document().revision()
                self._block = cursor.block().blockNumber()

    def insert_completion(self, insert, type_=ord('a')):
        if insert != self._prefix:
            closing = ''
            if type_ in (ord('f'), ord('c')):
                closing = '()'
            extra = len(self._prefix) - len(insert)
            insertion = '%s%s' % (insert[extra:], closing)
            self._editor.textCursor().insertText(insertion)
        self.hide_completer()

    def _get_geometry(self):
        cr = self._editor.cursorRect()
        desktop_geometry = self.desktop.availableGeometry(self._editor)
        point = self._editor.mapToGlobal(cr.topLeft())
        cr.moveTopLeft(point)
        #Check new position according desktop geometry
        width = (self.completion_list.sizeHintForColumn(0) +
                 self.completion_list.verticalScrollBar().sizeHint().width() +
                 10)
        height = 200
        orientation = (point.y() + height) < desktop_geometry.height()
        if orientation:
            cr.moveTop(cr.bottom())
        cr.setWidth(width)
        cr.setHeight(height)
        if not orientation:
            cr.moveBottom(cr.top())
        xpos = desktop_geometry.width() - (point.x() + width)
        if xpos < 0:
            cr.moveLeft(cr.left() + xpos)
        return cr

    def complete(self, results):
        self.add_list_items(results)
        self.completion_list.setCurrentRow(0)
        cr = self._get_geometry()
        self.setGeometry(cr)
        self.completion_list.updateGeometries()
        self.show()

    def add_list_items(self, proposals):
        self.completion_list.clear()
        for p in proposals:
            self.completion_list.addItem(
                QListWidgetItem(QIcon(self._icons.get(p[0], ":img/attribute")),
                                p[1],
                                type=ord(p[0])))

    def set_completion_prefix(self, prefix, valid=True):
        self._prefix = prefix
        proposals = []
        proposals += [('m', item)
                      for item in self._completion_results.get('modules', [])
                      if item.startswith(prefix)]
        proposals += [('c', item)
                      for item in self._completion_results.get('classes', [])
                      if item.startswith(prefix)]
        proposals += [
            ('a', item)
            for item in self._completion_results.get('attributes', [])
            if item.startswith(prefix)
        ]
        proposals += [
            ('f', item)
            for item in self._completion_results.get('functions', [])
            if item.startswith(prefix)
        ]
        if proposals and valid:
            self.complete(proposals)
        else:
            self.hide_completer()

    def _invalid_completion_position(self):
        result = False
        cursor = self._editor.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor)
        selection = cursor.selectedText()[:-1].split(' ')
        if len(selection) == 0 or selection[-1] == '' or \
           selection[-1].isdigit():
            result = True
        return result

    def fill_completer(self, force_completion=False):
        if not force_completion and (self._editor.cursor_inside_string()
                                     or self._editor.cursor_inside_comment()
                                     or self._invalid_completion_position()):
            return
        source = self._editor.text()
        source = source.encode(self._editor.encoding)
        offset = self._editor.textCursor().position()
        results = self.cc.get_completion(source, offset)
        self._completion_results = results
        if force_completion:
            cursor = self._editor.textCursor()
            cursor.movePosition(QTextCursor.StartOfWord,
                                QTextCursor.KeepAnchor)
            prefix = cursor.selectedText()
        else:
            prefix = self._editor._text_under_cursor()
        self.set_completion_prefix(prefix)

    def hide_completer(self):
        self._prefix = ''
        self.hide()

    def pre_key_insert_completion(self):
        type_ = ord('a')
        current = self.completion_list.currentItem()
        insert = current.text()
        if not insert.endswith(')'):
            type_ = current.type()
        self.insert_completion(insert, type_)
        self.hide_completer()
        return True

    def process_pre_key_event(self, event):
        if not self.isVisible() or self._editor.lang != "python":
            return False
        skip = self._key_operations.get(event.key(), lambda: False)()
        self._key_operations.get(event.modifiers(), lambda: False)()
        if skip is None:
            skip = False
        return skip

    def process_post_key_event(self, event):
        if not settings.CODE_COMPLETION or self._editor.lang != "python":
            return
        if self.isVisible():
            source = self._editor.text()
            source = source.encode(self._editor.encoding)
            offset = self._editor.textCursor().position()
            prefix, valid = self.cc.get_prefix(source, offset)
            self.set_completion_prefix(prefix, valid)
            self.completion_list.setCurrentRow(0)
        force_completion = (event.key() == Qt.Key_Space
                            and event.modifiers() == Qt.ControlModifier)
        if event.key() == Qt.Key_Period or force_completion:
            self.fill_completer(force_completion)
Exemplo n.º 2
0
class CodeCompletionWidget(QFrame):

    def __init__(self, editor):
        super(CodeCompletionWidget, self).__init__(
            None, Qt.FramelessWindowHint | Qt.ToolTip)
        self._editor = editor
        self._revision = 0
        self._block = 0
        self.stack_layout = QStackedLayout(self)
        self.stack_layout.setContentsMargins(0, 0, 0, 0)
        self.stack_layout.setSpacing(0)
        self.completion_list = QListWidget()
        self.completion_list.setMinimumHeight(200)
        self.completion_list.setAlternatingRowColors(True)
        self._list_index = self.stack_layout.addWidget(self.completion_list)

        self._icons = {'a': resources.IMAGES['attribute'],
                       'f': resources.IMAGES['function'],
                       'c': resources.IMAGES['class'],
                       'm': resources.IMAGES['module']}

        self.cc = code_completion.CodeCompletion()
        self._completion_results = {}
        self._prefix = ''
        self.setVisible(False)
        self.source = ''
        self._key_operations = {
            Qt.Key_Up: self._select_previous_row,
            Qt.Key_Down: self._select_next_row,
            Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
            Qt.Key_PageDown: (lambda: self._select_next_row(6)),
            Qt.Key_Right: lambda: None,
            Qt.Key_Left: lambda: None,
            Qt.Key_Enter: self.pre_key_insert_completion,
            Qt.Key_Return: self.pre_key_insert_completion,
            Qt.Key_Tab: self.pre_key_insert_completion,
            Qt.Key_Space: self.hide_completer,
            Qt.Key_Escape: self.hide_completer,
            Qt.Key_Backtab: self.hide_completer,
            Qt.NoModifier: self.hide_completer,
            Qt.ShiftModifier: self.hide_completer,
        }

        self.desktop = QApplication.instance().desktop()

        self.completion_list.itemClicked['QListWidgetItem*'].connect(self.pre_key_insert_completion)
        self._editor.document().cursorPositionChanged['const QTextCursor &'].connect(self.update_metadata)

    def _select_next_row(self, move=1):
        new_row = self.completion_list.currentRow() + move
        if new_row < self.completion_list.count():
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(0)
        return True

    def _select_previous_row(self, move=1):
        new_row = self.completion_list.currentRow() - move
        if new_row >= 0:
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(
                self.completion_list.count() - move)
        return True

    def update_metadata(self, cursor):
        if settings.CODE_COMPLETION:
            if self._editor.document().revision() != self._revision and \
               cursor.block().blockNumber() != self._block:
                source = self._editor.get_text()
                source = source.encode(self._editor.encoding)
                self.cc.analyze_file(self._editor.ID, source,
                                     self._editor.indent, self._editor.useTabs)
                self._revision = self._editor.document().revision()
                self._block = cursor.block().blockNumber()

    def insert_completion(self, insert, type_=ord('a')):
        if insert != self._prefix:
            closing = ''
            if type_ in (ord('f'), ord('c')):
                closing = '()'
            extra = len(self._prefix) - len(insert)
            insertion = '%s%s' % (insert[extra:], closing)
            self._editor.textCursor().insertText(insertion)
        self.hide_completer()

    def _get_geometry(self):
        cr = self._editor.cursorRect()
        desktop_geometry = self.desktop.availableGeometry(self._editor)
        point = self._editor.mapToGlobal(cr.topLeft())
        cr.moveTopLeft(point)
        #Check new position according desktop geometry
        width = (self.completion_list.sizeHintForColumn(0) +
                 self.completion_list.verticalScrollBar().sizeHint().width() +
                 10)
        height = 200
        orientation = (point.y() + height) < desktop_geometry.height()
        if orientation:
            cr.moveTop(cr.bottom())
        cr.setWidth(width)
        cr.setHeight(height)
        if not orientation:
            cr.moveBottom(cr.top())
        xpos = desktop_geometry.width() - (point.x() + width)
        if xpos < 0:
            cr.moveLeft(cr.left() + xpos)
        return cr

    def complete(self, results):
        self.add_list_items(results)
        self.completion_list.setCurrentRow(0)
        cr = self._get_geometry()
        self.setGeometry(cr)
        self.completion_list.updateGeometries()
        self.show()

    def add_list_items(self, proposals):
        self.completion_list.clear()
        for p in proposals:
            self.completion_list.addItem(
                QListWidgetItem(
                    QIcon(
                        self._icons.get(p[0], resources.IMAGES['attribute'])),
                    p[1], type=ord(p[0])))

    def set_completion_prefix(self, prefix, valid=True):
        self._prefix = prefix
        proposals = []
        proposals += [('m', item)
                      for item in self._completion_results.get('modules', [])
                      if item.startswith(prefix)]
        proposals += [('c', item)
                      for item in self._completion_results.get('classes', [])
                      if item.startswith(prefix)]
        proposals += [('a', item)
                      for item in self._completion_results.get(
                          'attributes', [])
                      if item.startswith(prefix)]
        proposals += [('f', item)
                      for item in self._completion_results.get('functions', [])
                      if item.startswith(prefix)]
        if proposals and valid:
            self.complete(proposals)
        else:
            self.hide_completer()

    def _invalid_completion_position(self):
        result = False
        cursor = self._editor.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine,
                            QTextCursor.KeepAnchor)
        selection = cursor.selectedText()[:-1].split(' ')
        if len(selection) == 0 or selection[-1] == '' or \
           selection[-1].isdigit():
            result = True
        return result

    def fill_completer(self, force_completion=False):
        if not force_completion and (self._editor.cursor_inside_string() or
           self._editor.cursor_inside_comment() or
           self._invalid_completion_position()):
            return
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        offset = self._editor.textCursor().position()
        results = self.cc.get_completion(source, offset)
        self._completion_results = results
        if force_completion:
            cursor = self._editor.textCursor()
            cursor.movePosition(QTextCursor.StartOfWord,
                                QTextCursor.KeepAnchor)
            prefix = cursor.selectedText()
        else:
            prefix = self._editor._text_under_cursor()
        self.set_completion_prefix(prefix)

    def hide_completer(self):
        self._prefix = ''
        self.hide()

    def pre_key_insert_completion(self):
        type_ = ord('a')
        current = self.completion_list.currentItem()
        insert = current.text()
        if not insert.endswith(')'):
            type_ = current.type()
        self.insert_completion(insert, type_)
        self.hide_completer()
        return True

    def process_pre_key_event(self, event):
        if not self.isVisible() or self._editor.lang != "python":
            return False
        skip = self._key_operations.get(event.key(), lambda: False)()
        self._key_operations.get(event.modifiers(), lambda: False)()
        if skip is None:
            skip = False
        return skip

    def process_post_key_event(self, event):
        if not settings.CODE_COMPLETION or self._editor.lang != "python":
            return
        if self.isVisible():
            source = self._editor.get_text()
            source = source.encode(self._editor.encoding)
            offset = self._editor.textCursor().position()
            prefix, valid = self.cc.get_prefix(source, offset)
            self.set_completion_prefix(prefix, valid)
            self.completion_list.setCurrentRow(0)
        force_completion = (event.key() == Qt.Key_Space and
                            event.modifiers() == Qt.ControlModifier)
        if event.key() == Qt.Key_Period or force_completion:
            self.fill_completer(force_completion)
Exemplo n.º 3
0
    def initUI(self):
        ## Information Labels:
        infoLabel1 = QLabel()  ## NAME
        infoLabel1.setText(con[self.conNum - 1][0][0]["name"].upper())
        infoLabel1.setFont(QFont(fonts[1], rPix(25), weight=75))

        infoLabel2 = QLabel()
        infoLabel2.setText(con[self.conNum - 1][1][0]["name"].upper())
        infoLabel2.setFont(QFont(fonts[1], rPix(25), weight=75))

        infoLabel3 = QLabel()  ## SECTION
        if con[self.conNum - 1][0][1]["section"] == con[self.conNum -
                                                        1][1][1]["section"]:
            infoLabel3.setText(
                str(con[self.conNum - 1][2]["grade"]) + " - " +
                con[self.conNum - 1][0][1]["section"])
        else:
            infoLabel3.setText(
                str(con[self.conNum - 1][2]["grade"]) + " - " +
                con[self.conNum - 1][0][1]["section"] + " & " +
                con[self.conNum - 1][1][1]["section"])
        infoLabel3.setFont(QFont(fonts[0], rPix(15), weight=75))

        infoLabelLayout = [QHBoxLayout(),
                           QHBoxLayout(),
                           QHBoxLayout()
                           ]  ## Centralize Using Horizontal Box Layout
        for i in infoLabelLayout:
            i.setContentsMargins(0, 0, 0, 0)
            i.setSpacing(0)
        infoLabelLayout[0].addStretch()
        infoLabelLayout[0].addWidget(infoLabel1)
        infoLabelLayout[0].addStretch()
        infoLabelLayout[1].addStretch()

        infoLabelLayout[1].addWidget(infoLabel2)
        infoLabelLayout[1].addStretch()

        infoLabelLayout[2].addStretch()
        infoLabelLayout[2].addWidget(infoLabel3)
        infoLabelLayout[2].addStretch()

        ## Information Layout:
        infoLayout = QVBoxLayout()
        infoLayout.setSpacing(10)
        for i in infoLabelLayout:
            infoLayout.addLayout(i)
        ## Information Frame:
        infoFrame = QFrame()
        infoFrame.setFixedSize(rPix(780), rPix(205))
        infoFrame.setObjectName("infoFrame")
        infoFrame.setStyleSheet(
            ".QFrame#infoFrame{border-bottom:2px #A9A9A9;background:" +
            self.ui[(self.conNum - 1) % 4] + ";border-radius : 5px}")
        infoFrame.setLayout(infoLayout)

        ## Score Sheet Webview:
        if "-nosheet" in sys.argv:
            self.sheet = QFrame()
            self.sheet.setFixedSize(rPix(760), rPix(630))
        else:
            self.sheet = QWebView()
            self.sheet.loadFinished.connect(self.pageLoaded)
            _path = QUrl.fromLocalFile(currentDir() + "/resources/sheet.html")
            self.sheet.load(_path)

        ## Navigation Buttons
        resetButton = ImageButton("resources/img/buttons/reset",
                                  rPix(30),
                                  rPix(30),
                                  toggle=False,
                                  tooltip="<b>Reset Scores</b>")

        saveButton = ImageButton("resources/img/buttons/save",
                                 rPix(30),
                                 rPix(30),
                                 toggle=False,
                                 tooltip="<b>Save Scores</b>")

        if "-nosheet" not in sys.argv:
            resetButton.clicked.connect(self.resetScores)
            saveButton.clicked.connect(self.saveScores)

        ## Sheet Navigation Layout:
        sheetNavigationLayout = QHBoxLayout()
        sheetNavigationLayout.addStretch()
        sheetNavigationLayout.addWidget(resetButton)
        sheetNavigationLayout.addWidget(saveButton)

        ## Layout of Sheet Frame:
        sheetLayout = QVBoxLayout()
        sheetLayout.setContentsMargins(rPix(15), rPix(10), rPix(10), rPix(10))
        sheetLayout.setSpacing(rPix(5))
        sheetLayout.addWidget(self.sheet)
        sheetLayout.addLayout(sheetNavigationLayout)

        ## Sheet Frame:
        sheetFrame = QFrame()
        sheetFrame.setFixedSize(rPix(780), rPix(650))
        sheetFrame.setObjectName("sheetFrame")
        sheetFrame.setStyleSheet(
            ".QFrame#sheetFrame{border-bottom:2px #A9A9A9;background:" +
            self.ui[(self.conNum - 1) % 4] + ";border-radius : 5px}")
        sheetFrame.setLayout(sheetLayout)

        ## Left Placeholder Layout:
        leftLayout = QVBoxLayout()
        leftLayout.setContentsMargins(0, 0, 0, 0)
        leftLayout.setSpacing(10)
        leftLayout.addWidget(infoFrame)
        leftLayout.addWidget(sheetFrame)

        ## Previous Image Button:
        prevImage = ImageButton("resources/img/buttons/prevImg",
                                rPix(100),
                                rPix(845),
                                toggle=False,
                                tooltip="<b>Previous Image</b>")
        prevImage.clicked.connect(self.prevImageEvt)

        ## Next Image Button:
        nextImage = ImageButton("resources/img/buttons/nextImg",
                                rPix(100),
                                rPix(845),
                                toggle=False,
                                tooltip="<b>Next Image</b>")
        nextImage.clicked.connect(self.nextImageEvt)
        ##Con Num Label:
        conNumLabel = QLabel(str(self.conNum))
        conNumLabel.setFont(QFont(fonts[0], rPix(30)))

        ##Con Num Layout:
        conNumLabelLayout = QHBoxLayout()
        conNumLabelLayout.setContentsMargins(0, 0, 0, 0)
        conNumLabelLayout.setSpacing(0)
        conNumLabelLayout.addStretch()
        conNumLabelLayout.addWidget(conNumLabel)
        conNumLabelLayout.addStretch()

        ## Label for info
        self.infoconLabel = QLabel("NO IMAGE LOADED")
        self.infoconLabel.setFont(QFont(fonts[1], rPix(10)))

        ##Con Num Layout:
        infoconLabelLayout = QHBoxLayout()
        infoconLabelLayout.setContentsMargins(0, 0, 0, 0)
        infoconLabelLayout.setSpacing(0)
        infoconLabelLayout.addStretch()
        infoconLabelLayout.addWidget(self.infoconLabel)
        infoconLabelLayout.addStretch()

        ##Vertical Layout for conNum and Info
        vertConInfoLayout = QVBoxLayout()
        vertConInfoLayout.setContentsMargins(0, 0, 0, 0)
        vertConInfoLayout.setSpacing(rPix(20))
        vertConInfoLayout.addStretch()
        vertConInfoLayout.addLayout(conNumLabelLayout)
        vertConInfoLayout.addLayout(infoconLabelLayout)
        vertConInfoLayout.addStretch()

        ## Image Info Frame:
        infoFrame = ImageFrame()
        _infoPixmap = QPixmap("resources/img/infoFrame.png")
        infoFrame.setPixmap(
            _infoPixmap.scaled(rPix(560), rPix(120), Qt.KeepAspectRatio))
        infoFrame.setLayout(vertConInfoLayout)

        ## Image Info Filler:
        infoFiller = QLabel()
        infoFiller.setFixedSize(rPix(560), rPix(727))

        ## Image Info Layout:
        infoLayout = QVBoxLayout()
        infoLayout.addWidget(infoFiller)
        infoLayout.addWidget(infoFrame)
        infoLayout.setContentsMargins(0, 0, 0, 0)
        infoLayout.setSpacing(0)

        ## Image Navigation/Info Layout:
        navigLayout = QHBoxLayout()
        navigLayout.addWidget(prevImage)
        navigLayout.addLayout(infoLayout)
        navigLayout.addWidget(nextImage)
        navigLayout.setContentsMargins(0, 0, 0, 0)
        navigLayout.setSpacing(0)

        ## Image Navigation/Info Frame:
        navigFrame = QFrame()
        navigFrame.setObjectName("noframe")
        navigFrame.setStyleSheet(styles["noframe"])
        navigFrame.setLayout(navigLayout)

        ## Image Frame:
        self.imageFrame = ImageFrame(fade=True)
        try:  ##Checks if Pixmap is available, then sets it
            self.imageFrame.setPixmap(self.pixmaps[str(
                self.conNum)][self.imgNum])
            self.infoconLabel.setText(order[self.imgNum])
        except:
            pass
        self.imageFrame.setFixedSize(rPix(760), rPix(845))

        #self.imageFrame.setLayout(navigLayout)
        ## Image Stacked Layout:
        imageStacked = QStackedLayout()
        imageStacked.setStackingMode(QStackedLayout.StackAll)
        imageStacked.setContentsMargins(0, 0, 0, 0)
        imageStacked.setSpacing(0)
        imageStacked.insertWidget(0, self.imageFrame)
        imageStacked.insertWidget(1, navigFrame)

        ## Image Placeholder Layout:
        imagePlaceholderLayout = QHBoxLayout()
        imagePlaceholderLayout.setContentsMargins(rPix(15), rPix(10), rPix(10),
                                                  rPix(10))
        imagePlaceholderLayout.setSpacing(0)
        imagePlaceholderLayout.addLayout(imageStacked)

        ## Image Placeholder Frame
        imagePlaceholderFrame = QFrame()
        imagePlaceholderFrame.setObjectName("imageplaceholder")
        imagePlaceholderFrame.setStyleSheet(
            ".QFrame#imageplaceholder{border-bottom:2px #A9A9A9;background:" +
            self.ui[(self.conNum - 1) % 4] + ";border-radius : 5px}")
        imagePlaceholderFrame.setFixedSize(rPix(780), rPix(865))
        imagePlaceholderFrame.setLayout(imagePlaceholderLayout)

        ## Main Layout:
        mainLayout = QHBoxLayout()
        mainLayout.setContentsMargins(rPix(10), rPix(10), rPix(10), rPix(10))
        mainLayout.setSpacing(10)

        ## Dynamic Layouting (based on Contestant Number)
        if self.conNum <= (tconNum / 2):
            mainLayout.addLayout(leftLayout)
            mainLayout.addWidget(imagePlaceholderFrame)
        else:
            mainLayout.addWidget(imagePlaceholderFrame)
            mainLayout.addLayout(leftLayout)

        ## Background Frame:
        mainFrame = ImageFrame()
        mainFrame.setPixmap(self.bg)
        mainFrame.setLayout(mainLayout)

        ## Placeholder Layout:
        placeholderLayout = QHBoxLayout()
        placeholderLayout.setContentsMargins(0, 0, 0, 0)
        placeholderLayout.setSpacing(0)
        placeholderLayout.addWidget(mainFrame)

        self.setLayout(placeholderLayout)
Exemplo n.º 4
0
class HistogramDisplayControl(QWidget):
    class Layout(Enum):
        STACKED = 0
        HORIZONTAL = 1
        VERTICAL = 2

    class DisplayType(Enum):
        GREY_SCALE = 0
        RBG = 1

    __LOG: Logger = LogHelper.logger("HistogramDisplayControl")

    limit_changed = pyqtSignal(LimitChangeEvent)
    limits_reset = pyqtSignal(LimitResetEvent)
    layout_changed = pyqtSignal(Layout)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.__menu = None
        self.__plots = dict()

        # Use stacked layout as default
        self.__create_stacked_layout()

    def __create_horizontal_layout(self):
        self.__plot_layout = QHBoxLayout()
        self.__plot_layout.setSpacing(1)
        self.__plot_layout.setContentsMargins(1, 1, 1, 1)
        self.setLayout(self.__plot_layout)
        self.__current_layout = HistogramDisplayControl.Layout.HORIZONTAL

    def __create_vertical_layout(self):
        self.__plot_layout = QVBoxLayout()
        self.__plot_layout.setSpacing(1)
        self.__plot_layout.setContentsMargins(1, 1, 1, 1)
        self.setLayout(self.__plot_layout)
        self.__current_layout = HistogramDisplayControl.Layout.VERTICAL

    def __create_stacked_layout(self):
        layout = QVBoxLayout()
        layout.setSpacing(1)
        layout.setContentsMargins(1, 1, 1, 1)

        self.__plot_layout = QStackedLayout()
        self.__plot_layout.setContentsMargins(1, 1, 1, 1)
        self.__plot_layout.setSpacing(1)

        self.__tab_widget = QWidget()
        self.__tab_widget.setFixedHeight(20)
        self.__tab_widget.hide()

        self.__tab_layout = QHBoxLayout()
        self.__tab_layout.setContentsMargins(1, 1, 1, 1)
        self.__tab_layout.setAlignment(Qt.AlignLeft)
        self.__tab_layout.addSpacing(10)

        self.__red_button = QRadioButton("Red")
        self.__red_button.setStyleSheet("QRadioButton {color: red}")
        self.__red_button.toggled.connect(self.__handle_red_toggled)
        self.__tab_layout.addWidget(self.__red_button)
        self.__red_plot_index = None

        self.__green_button = QRadioButton("Green")
        self.__green_button.setStyleSheet("QRadioButton {color: green}")
        self.__green_button.toggled.connect(self.__handle_green_toggled)
        self.__tab_layout.addWidget(self.__green_button)
        self.__green_plot_index = None

        self.__blue_button = QRadioButton("Blue")
        self.__blue_button.setStyleSheet("QRadioButton {color: blue}")
        self.__blue_button.toggled.connect(self.__handle_blue_toggled)
        self.__tab_layout.addWidget(self.__blue_button)
        self.__tab_widget.setLayout(self.__tab_layout)
        self.__blue_plot_index = None

        layout.addWidget(self.__tab_widget)
        layout.addLayout(self.__plot_layout)
        self.setLayout(layout)
        self.__current_layout = HistogramDisplayControl.Layout.STACKED

    def __init_menu(self):
        self.__menu: QMenu = QMenu(self)

        stacked_action = QAction("Stacked", self)
        stacked_action.triggered.connect(self.__handle_stacked_selected)
        self.__menu.addAction(stacked_action)

        horizontal_action = QAction("Horizontal", self)
        horizontal_action.triggered.connect(self.__handle_horizontal_selected)
        self.__menu.addAction(horizontal_action)

        vertical_action = QAction("Vertical", self)
        vertical_action.triggered.connect(self.__handle_vertical_selected)
        self.__menu.addAction(vertical_action)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(
            self.__handle_custom_context_menu)

    def __handle_custom_context_menu(self, position: QPoint):
        HistogramDisplayControl.__LOG.debug(
            "__handle_custom_context_menu called position: {0}", position)
        self.__menu.popup(self.mapToGlobal(position))

    def __handle_stacked_selected(self):
        self.__swap_layout(HistogramDisplayControl.Layout.STACKED)

    def __handle_horizontal_selected(self):
        self.__swap_layout(HistogramDisplayControl.Layout.HORIZONTAL)

    def __handle_vertical_selected(self):
        self.__swap_layout(HistogramDisplayControl.Layout.VERTICAL)

    def __swap_layout(self, new_layout: Layout):
        # The plot's will have had their parent set to the layout so first
        # we undo that so they won't get deleted when the layout does.
        for band, plot in self.__plots.items():
            plot.setParent(None)

        if self.__current_layout == HistogramDisplayControl.Layout.STACKED:
            self.__red_button.setParent(None)
            self.__green_button.setParent(None)
            self.__blue_button.setParent(None)
            self.__tab_widget.setParent(None)

        # Per Qt docs we need to delete the current layout before we can set a new one
        # And it turns out we can't delete the layout until we reassign it to another widget
        # who becomes it's parent, then we delete the parent.
        tmp = QWidget()
        tmp.setLayout(self.layout())
        del tmp

        if new_layout == HistogramDisplayControl.Layout.STACKED:
            self.__create_stacked_layout()

        if new_layout == HistogramDisplayControl.Layout.HORIZONTAL:
            self.__create_horizontal_layout()

        if new_layout == HistogramDisplayControl.Layout.VERTICAL:
            self.__create_vertical_layout()

        for band, plot in self.__plots.items():
            self.__plot_layout.addWidget(plot)
            self.__wire_band(band, plot)
            if new_layout != HistogramDisplayControl.Layout.STACKED:
                # stacked layout hides plots not displayed so set them back
                plot.show()

        self.layout_changed.emit(new_layout)

    def __wire_band(self, band: Band, plot: AdjustableHistogramControl):
        if self.__current_layout == HistogramDisplayControl.Layout.STACKED:
            set_checked: bool = False
            if self.__plot_layout.count() == 1:
                set_checked = True
                self.__tab_widget.show()

            if band == Band.RED:
                self.__red_plot_index = self.__plot_layout.indexOf(plot)
                self.__red_button.setChecked(set_checked)

            if band == Band.GREEN:
                self.__green_plot_index = self.__plot_layout.indexOf(plot)
                self.__green_button.setChecked(set_checked)

            if band == Band.BLUE:
                self.__blue_plot_index = self.__plot_layout.indexOf(plot)
                self.__blue_button.setChecked(set_checked)

    @pyqtSlot(bool)
    def __handle_red_toggled(self, checked: bool):
        if checked:
            HistogramDisplayControl.__LOG.debug("red toggle checked")
            self.__plot_layout.setCurrentIndex(self.__red_plot_index)

    @pyqtSlot(bool)
    def __handle_green_toggled(self, checked: bool):
        if checked:
            HistogramDisplayControl.__LOG.debug("green toggle checked")
            self.__plot_layout.setCurrentIndex(self.__green_plot_index)

    @pyqtSlot(bool)
    def __handle_blue_toggled(self, checked: bool):
        if checked:
            HistogramDisplayControl.__LOG.debug("blue toggle checked")
            self.__plot_layout.setCurrentIndex(self.__blue_plot_index)

    def add_plot(self, raw_data: HistogramPlotData,
                 adjusted_data: HistogramPlotData, band: Band):
        """Expects either one band with band of Band.GREY or three bands one each of
        Band.RED, Band.GREEN, Band.BLUE.  If these conditions are not met the code will attempt
        to be accommodating and won't throw and error but you might get strange results."""
        plots = AdjustableHistogramControl(band)
        plots.set_raw_data(raw_data)
        plots.set_adjusted_data(adjusted_data)
        plots.limit_changed.connect(self.limit_changed)
        plots.limits_reset.connect(self.limits_reset)

        self.__plots[band] = plots
        self.__plot_layout.addWidget(plots)

        if self.__plot_layout.count() == 2:
            self.__init_menu()

        if band == Band.RED or band == Band.GREEN or band == Band.BLUE:
            self.__wire_band(band, plots)

    def set_adjusted_data(self, data: HistogramPlotData, band: Band):
        """Update the adjusted data for a Band that has already been added using
        add_plot"""
        plots: AdjustableHistogramControl = self.__plots[band]
        if plots is not None:
            plots.set_adjusted_data(data)

    def update_limits(self, data: HistogramPlotData, band: Band):
        plots: AdjustableHistogramControl = self.__plots[band]
        if plots is not None:
            plots.update_limits(data)
Exemplo n.º 5
0
class MainWindow(QWidget):
    """Class containing main window

    :param QWidget: Widget type
    :type QWidget: QWidget
    """
    def __init__(self, api):
        super().__init__()
        self.resiz = True
        self.setMinimumSize(BOARD_SIZE + 40, BOARD_SIZE + 105)
        size_pol = QSizePolicy(QSizePolicy.MinimumExpanding,
                               QSizePolicy.MinimumExpanding)
        self.setSizePolicy(size_pol)
        self.api = api
        self.start_color = self.api.board.white
        self.comm = Communicate()

        self.comm.backMenu.connect(self.return_to_menu)

        self.game = MainGame(api, self.comm, self.start_color)
        self.menu = MainMenu()

        self.tabs = QStackedLayout()
        self.tabs.addWidget(self.menu)
        self.tabs.addWidget(self.game)

        self.tab_names = {"start": 0, "game_board": 1}
        self.tabs.setCurrentIndex(self.tab_names["start"])

        self.tabs.setSpacing(self.tab_names["start"])
        self.tabs.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.tabs)

        for diff, difficulty in enumerate(self.menu.difficulties):
            difficulty.clicked.connect(
                self.start_game_with_difficulty(diff + 1))

        self.menu.resume.clicked.connect(self.resume_game)
        self.menu.white.clicked.connect(self.white_start)
        self.menu.black.clicked.connect(self.black_start)
        self.menu.human.clicked.connect(self.game_with_human)
        self.menu.computer.clicked.connect(self.choose_difficulty)

        self.setWindowTitle('Chess')
        self.show()

    def choose_difficulty(self):
        """Shows difficulty buttons
        """
        self.menu.computer.hide()
        self.menu.human.hide()
        self.menu.start_game.hide()
        self.menu.resume.hide()
        for difficulty in self.menu.difficulties:
            difficulty.show()
        self.menu.white.show()
        self.menu.black.show()
        if self.start_color == self.api.board.white:
            self.white_start()
        else:
            self.black_start()

    def game_with_human(self):
        """Starts game with human
        """
        self.api.start_new_game()
        self.game.board.game_human = True
        self.start_color = self.api.board.white
        self.start_new_game()

    def resume_game(self):
        """Resumes game
        """
        self.tabs.setCurrentIndex(self.tab_names["game_board"])

    def white_start(self):
        """Changes starting color for white
        """
        self.start_color = self.api.board.white
        self.menu.white.setProperty("pushed", "yes")
        self.menu.black.setProperty("pushed", "no")
        self.menu.black.setStyle(self.style())
        self.menu.white.setStyle(self.style())

    def black_start(self):
        """Changes starting color for white
        """
        self.start_color = self.api.board.black
        self.menu.black.setProperty("pushed", "yes")
        self.menu.white.setProperty("pushed", "no")
        self.menu.black.setStyle(self.style())
        self.menu.white.setStyle(self.style())

    def resizeEvent(self, event):
        """Process resize event

        :param event: new size of a vindow
        :type event: QEvent
        """
        if self.resiz:
            self.resiz = False
            new_size = min(event.size().height(), event.size().width())
            self.resize(new_size + 40, new_size + 105)

        self.resiz = True

    def return_to_menu(self):
        """Return user to main menu
        """
        for difficulty in self.menu.difficulties:
            difficulty.hide()
        self.menu.black.hide()
        self.menu.white.hide()
        self.menu.computer.hide()
        self.menu.human.hide()
        self.menu.start_game.show()
        if not self.game.board.game_over:
            self.menu.resume.show()
        self.tabs.setCurrentIndex(self.tab_names["start"])

    def start_game_with_difficulty(self, difficulty):
        """Makes functions that start a new game with a specific difficulty

        :param difficulty: difficulty of a game
        :type difficulty: int
        """
        def start_game():
            self.game.board.game_human = False
            self.api.start_new_game(difficulty + 1)
            if self.start_color == self.api.board.black:
                self.game.board.flip_board()
            self.start_new_game()

        return start_game

    def start_new_game(self):
        """Starts new game, reinitialize board
        """
        self.game.up_taken.set_color(self.start_color)
        self.game.down_taken.set_color(3 - self.start_color)
        self.game.up_taken.hide_all()
        self.game.down_taken.hide_all()

        self.game.board.color = self.api.board.white
        if self.start_color == self.api.board.black:
            self.game.board.pass_turn()
        else:
            self.game.board.clear_afterturn()

        self.game.board.history = 0
        self.game.board.reset_all()
        self.game.board.upd_whole_board()
        self.game.board.upd_possible_moves(self.start_color)
        self.tabs.setCurrentIndex(self.tab_names["game_board"])
Exemplo n.º 6
0
class SimulationPage(QWidget):
    def setupUi(self,
                Form,
                username=None,
                userid=1,
                host='192.168.2.171',
                simid=None,
                reset=False):
        self.host = host
        self.username = username
        self.userid = userid
        self.simid = simid
        self.readonly = (simid is not None)
        self.showsettings = False
        self.currentindex = 0
        self.usedefaultsettings = True

        self.db = connector.connect(host=self.host,
                                    user="******",
                                    passwd="Sequal1234",
                                    database="simulation",
                                    use_pure=True)
        self.db.autocommit = True
        self.simrunning = False
        # self.esrunning = False
        if not reset:
            self.thread = None
            self.thread = QThread()
        self.cppath = getcwd() + "\\cutplans\\"
        self.logpath = getcwd() + "\\logs\\"
        self.shifts = 2
        self.simShift = 1
        index = []
        for i in range(1, self.shifts + 1):
            index.append(str(i))
        index.append("Total")
        cols = [
            "RunTime", "LogsCut", "Production", "LogVolume", "Recovery",
            "LogRate", "Uptime", "MSLDT", "BSLDT", "TSLDT", "SawdustVol"
        ]
        self.results = DataFrame(index=index, columns=cols)

        # self.OpenExtendSim()

        Form.setObjectName("Form")
        Form.resize(900, 750)
        Form.setMinimumSize(QSize(900, 750))
        Form.setStyleSheet("background-color: rgb(255, 255, 255);\n"
                           "color: rgb(0, 115, 119);")
        if Form.layout() is not None:
            QWidget().setLayout(Form.layout())
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")

        ss = \
            """
            QToolButton {
                background-color: qlineargradient(spread:pad,
                    x1:0, y1:0, x2:1, y2:1, stop:0 rgba(0, 115,
                    119, 255), stop:1 rgb(4, 147, 131));
                color: white;
                border: None;
                border-radius: 2px;
                font: 11pt "Tahoma";
                padding: 5px;
                margin-right: 20px;
            }
            """
        self.detailsLayout = QHBoxLayout()
        self.closeButton = QToolButton(Form)
        self.closeButton.setObjectName("closeButton")
        self.closeButton.setStyleSheet(ss)
        self.closeButton.setCursor(QCursor(Qt.PointingHandCursor))
        icon1 = QIcon("images/close.png")
        self.closeButton.setIcon(icon1)
        self.closeButton.setVisible(self.readonly)
        self.detailsLayout.addWidget(self.closeButton)
        self.nameLabel = QLabel(Form)
        self.nameLabel.setText("Name: ")
        self.nameLabel.setStyleSheet(
            "QLabel {"
            "background: none; font: 15pt \"Tahoma\";font-weight: bold;"
            "}")
        self.detailsLayout.addWidget(self.nameLabel)
        self.nameTextbox = QLineEdit(Form)
        self.nameTextbox.setText("Simulation")
        self.nameTextbox.setStyleSheet(
            "QLineEdit {\n"
            "background: none; font: 15pt \"Tahoma\";"
            "border: 1px solid rgb(0,115,119);\n"
            "}\n"
            "QLineEdit:disabled {border: none;}")
        self.detailsLayout.addWidget(self.nameTextbox)
        h = self.nameTextbox.size().height()
        self.closeButton.setMinimumSize(QSize(h, h))
        self.closeButton.setIconSize(QSize(h - 10, h - 10))
        self.PlayButton = QToolButton(Form)
        self.PlayButton.setObjectName("PlayButton")
        self.PlayButton.setStyleSheet(ss)
        self.PlayButton.setMinimumSize(QSize(h, h))
        self.PlayButton.setCursor(QCursor(Qt.PointingHandCursor))
        icon1 = QIcon("images/play.png")
        self.PlayButton.setIcon(icon1)
        self.PlayButton.setIconSize(QSize(h - 10, h - 10))
        self.PlayButton.setVisible(False)
        self.detailsLayout.addWidget(self.PlayButton)
        hSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                              QSizePolicy.Minimum)
        self.detailsLayout.addItem(hSpacer)
        self.CreateNewButton = QToolButton(Form)
        self.CreateNewButton.setObjectName("CreateNewButton")
        self.CreateNewButton.setStyleSheet(ss)
        self.CreateNewButton.setMinimumSize(QSize(h, h))
        self.CreateNewButton.setText("Create New")
        self.CreateNewButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        icon1 = QIcon("images/new.png")
        self.CreateNewButton.setIcon(icon1)
        self.CreateNewButton.setIconSize(QSize(h - 10, h - 10))
        self.CreateNewButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.CreateNewButton.setVisible(False)
        self.detailsLayout.addWidget(self.CreateNewButton)
        self.SettingsButton = QToolButton(Form)
        self.SettingsButton.setObjectName("SettingsButton")
        self.SettingsButton.setStyleSheet(ss)
        self.SettingsButton.setMinimumSize(QSize(h, h))
        self.SettingsButton.setCursor(QCursor(Qt.PointingHandCursor))
        icon1 = QIcon("images/settings.png")
        self.SettingsButton.setIcon(icon1)
        self.SettingsButton.setIconSize(QSize(h - 10, h - 10))
        self.detailsLayout.addWidget(self.SettingsButton)
        self.detailsLayout.setSpacing(5)
        self.verticalLayout.addLayout(self.detailsLayout)

        self.mainhorilayout = QHBoxLayout()
        self.ResultsArea = QScrollArea(Form)
        self.ResultsWidget = ResultsWidget()
        self.ResultsWidget.setupUi(self.ResultsArea)
        self.ResultsWidget.setObjectName("ResultsWidget")
        self.ResultsArea.setWidget(self.ResultsWidget)
        self.ResultsArea.setWidgetResizable(True)
        self.ResultsArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.ResultsArea.setFrameShape(QFrame.NoFrame)
        self.mainhorilayout.addWidget(self.ResultsArea)

        self.StackedWidget = QWidget(Form)
        self.StackedLayout = QStackedLayout(self.StackedWidget)
        self.CutplanArea = QScrollArea(self.StackedWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.CutplanArea.sizePolicy().hasHeightForWidth())
        self.CutplanArea.setSizePolicy(sizePolicy)
        self.CutplanArea.setMinimumSize(QSize(0, 250))
        self.CutplanArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # self.CutplanArea.setSizeAdjustPolicy(
        #    QAbstractScrollArea.AdjustToContents)
        self.CutplanArea.setWidgetResizable(True)
        self.CutplanArea.setFrameShape(QFrame.NoFrame)
        self.CutplanArea.setObjectName("CutplanArea")
        self.CPWidget = QWidget()
        self.Cutplans = CutplanWidget()
        self.Cutplans.setupUi(self.CPWidget)
        self.Cutplans.setObjectName("Cutplans")
        self.CutplanArea.setWidget(self.CPWidget)
        self.StackedLayout.addWidget(self.CutplanArea)
        self.StackedLayout.setSpacing(0)
        self.StackedLayout.setContentsMargins(0, 0, 0, 0)
        self.StackedWidget.setStyleSheet('background-color:rhba(0,0,0,0);')
        self.StackedWidget.setMaximumWidth(250)
        self.AddWindow = AddCutplanDialog(self.StackedWidget)
        self.AddWindow.setupUi(None, "support/cpquery.sql", self.Cutplans.host)
        self.StackedLayout.addWidget(self.AddWindow)
        self.SettingsWidget = QWidget(self.StackedWidget)
        self.SettingsUI = SettingsWindow(self.SettingsWidget)
        self.SettingsUI.setupUi(self.SettingsWidget)
        self.GetDefaultSettings()
        self.StackedLayout.addWidget(self.SettingsWidget)
        self.StackedLayout.setCurrentIndex(0)
        self.mainhorilayout.addWidget(self.StackedWidget)

        self.verticalLayout.addLayout(self.mainhorilayout)
        self.verticalLayout.setContentsMargins(50, 30, 50, 30)
        self.verticalLayout.setSpacing(50)
        self.timer = QTimer(self)
        self.timer.setInterval(100)

        self.timer.timeout.connect(self.UpdateGUI)
        self.PlayButton.clicked.connect(self.OnPlay)
        self.SettingsButton.clicked.connect(self.OnSettings)
        self.Cutplans.newcutplans.connect(self.ThreadSetup)
        self.Cutplans.AddButton.clicked.connect(self.AddClick)
        self.Cutplans.cploadfinish.connect(self.showPlayButton)
        self.AddWindow.buttonBox.rejected.connect(self.AddReject)
        self.AddWindow.buttonBox.accepted.connect(self.AddAccept)
        self.SettingsUI.buttonbox.accepted.connect(self.GetSettings)
        self.SettingsUI.buttonbox.rejected.connect(self.SendSettings)

        self.retranslateUi(Form)
        QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))

    def ThreadSetup(self, show):
        self.PlayButton.setVisible(False)
        self.cpid = 0
        self.cpfinish = False
        for i in range(self.results.shape[0]):
            for j in range(self.results.shape[1]):
                self.results.iloc[i, j] = 0

    def showPlayButton(self):
        if not self.readonly:
            self.PlayButton.setVisible(True)

    def AddClick(self):
        self.Cutplans.onClick2()
        if self.Cutplans.addData is not None:
            self.AddWindow.addData = self.Cutplans.addData
        else:
            self.AddWindow.addData = DataFrame(
                columns=['ID', 'Log Count', 'Description'])
        self.AddWindow.onDateChange()
        self.AddWindow.RTVSetUp()
        self.StackedLayout.setCurrentIndex(1)
        self.currentindex = 1

    def AddReject(self):
        self.StackedLayout.setCurrentIndex(0)
        self.currentindex = 0

    def AddAccept(self):
        self.Cutplans.addData = self.AddWindow.addData
        self.StackedLayout.setCurrentIndex(0)
        self.currentindex = 0
        self.Cutplans.AddCP()

    def OnPlay(self):
        self.PlayButton.setVisible(False)
        self.Cutplans.AddButton.setVisible(False)
        self.nameTextbox.setDisabled(True)
        self.simrunning = True
        self.cpfinish = False
        self.SendData()
        self.timer.start()
        # if self.esrunning:
        #     # self.esa.RunSim()
        #     self.timer.start()

    def SendData(self):
        try:
            cursor = self.db.cursor()
        except connector.Error:
            self.db = connector.connect(host=self.host,
                                        user="******",
                                        passwd="Sequal1234",
                                        database="simulation",
                                        use_pure=True)
            self.db.autocommit = True
            cursor = self.db.cursor()

        f = open('support\\initResults.sql', 'r')
        query = f.read()
        cursor.execute(query)

        # Simulations query
        query = "INSERT INTO simulations (Name, UserID) VALUES " \
            "(\'" + self.nameTextbox.text() + "\', " + str(self.userid) + ");"

        cursor.execute(query)
        cursor.execute("SELECT LAST_INSERT_ID();")
        (sid, ) = cursor.fetchone()
        self.simid = sid

        # check for downtime setting
        if sum(self.downtime_setting) == 0:
            # all downtime off
            dt = 0
        elif sum(self.downtime_setting) == len(self.downtime_setting):
            # all downtime on
            dt = 1
        else:
            # custom downtime so insert downtime into downtimesettings
            dt = 2
            temp = self.SettingsUI.downtimeCBtexts.copy()
            temp.insert(0, 'SimID')
            tstr = str(temp).replace('\'', '').replace('[',
                                                       '(').replace(']', ')')
            query = "INSERT INTO DowntimeSettings " + tstr
            temp = self.downtime_setting.copy()
            temp.insert(0, self.simid)
            tstr = str(temp).replace('[', '(').replace(']', ')')
            query = query + " VALUES " + tstr + ";"
            cursor.execute(query)

        # check for cutback default setting
        defcb = self.SettingsUI.defaultcutbacks
        cbtext = self.SettingsUI.cutbackCBtexts
        cb = True
        for tstr in defcb:
            if not self.cutback_setting[cbtext.index(tstr)]:
                cb = False
        if cb and sum(self.cutback_setting) == len(defcb):
            cb = 1
        else:
            cb = 0
            temp = cbtext.copy()
            temp.insert(0, 'SimID')
            tstr = str(temp).replace('\'', '`').replace('[',
                                                        '(').replace(']', ')')
            query = "INSERT INTO CutbackSettings " + tstr
            temp = self.cutback_setting.copy()
            temp.insert(0, self.simid)
            tstr = str(temp).replace('[', '(').replace(']', ')')
            query = query + " VALUES " + tstr + ";"
            cursor.execute(query)

        # SimHistory Query
        f = open('support\\simHistQuery.sql', 'r')
        sqltext = f.read()
        query = sqltext.replace('@SimID', str(self.simid))
        query = query.replace('@Name', str(self.nameTextbox.text()))
        query = query.replace('@UserID', str(self.userid))
        query = query.replace('@LogGap', str(self.loggap_setting))
        query = query.replace('@Downtime', str(dt))
        query = query.replace('@NumBins', str(self.numbins_setting))
        query = query.replace('@LineSpeed', str(self.linespeed_setting))
        query = query.replace('@Cutbacks', str(cb))
        cursor.execute(query)

        # Cutplans Query
        f = open('support\\simQuery.sql', 'r')
        sqltext = f.read()
        for i in range(self.Cutplans.addData.shape[0]):
            sqltext_full = sqltext.replace("@SimID", str(sid))
            sqltext_full = sqltext_full.replace(
                "@CutplanID", str(self.Cutplans.addData.ID[i]))
            sqltext_full = sqltext_full.replace(
                "@Description", str(self.Cutplans.addData.Description[i]))
            sqltext_full = sqltext_full.replace(
                "@NumLogs", str(self.Cutplans.addData['Log Count'][i]))

            cursor.execute(sqltext_full)

    def GetDefaultSettings(self):
        self.loggap_setting = self.SettingsUI.default[0]
        self.downtime_setting = []
        for cb in self.SettingsUI.downtimeCBs:
            self.downtime_setting.append(cb.isChecked())
        self.numbins_setting = self.SettingsUI.default[2]
        self.linespeed_setting = self.SettingsUI.default[3]
        self.cutback_setting = []
        for cb in self.SettingsUI.cutbackCBs:
            self.cutback_setting.append(cb.isChecked())

    def GetSettings(self):
        s = self.SettingsUI
        if s.loggapAuto.isChecked():
            self.loggap_setting = -1
        else:
            self.loggap_setting = s.loggapTB.value()
        self.downtime_setting = []
        for cb in s.downtimeCBs:
            self.downtime_setting.append(cb.isChecked())
        self.numbins_setting = s.numbinsTB.value()
        if s.highspeedRB.isChecked():
            self.linespeed_setting = 55.0
        elif s.lowspeedRB.isChecked():
            self.linespeed_setting = 35.0
        elif s.autospeedRB.isChecked():
            self.linespeed_setting = -1.0
        else:
            self.linespeed_setting = s.customspeedTB.value()
        self.cutback_setting = []
        for cb in s.cutbackCBs:
            self.cutback_setting.append(cb.isChecked())

        self.usedefaultsettings = not s.resetbutton.isVisible()

        self.showsettings = False
        speed = int(self.linespeed_setting)
        if speed == -1:
            speed = 55
        self.Cutplans.speedsetting = speed
        self.Cutplans.onClick2()
        self.Cutplans.AddCP()
        self.StackedLayout.setCurrentIndex(self.currentindex)

    def SendSettings(self):
        s = self.SettingsUI
        if self.loggap_setting == -1:
            s.loggapAuto.setChecked(True)
        else:
            s.loggapAuto.setChecked(False)
            s.loggapTB.setValue(self.loggap_setting)
        for i in range(len(s.downtimeCBs)):
            s.downtimeCBs[i].setChecked(self.downtime_setting[i])
        s.numbinsTB.setValue(self.numbins_setting)
        if self.linespeed_setting == 55.0:
            s.highspeedRB.setChecked(True)
        elif self.linespeed_setting == 35.0:
            s.lowspeedRB.setChecked(True)
        elif self.linespeed_setting == -1.0:
            s.autospeedRB.setChecked(True)
        else:
            s.customspeedRB.setChecked(True)
            s.customspeedTB.setValue(self.linespeed_setting)
        for i in range(len(s.cutbackCBs)):
            s.cutbackCBs[i].setChecked(self.cutback_setting[i])

        if self.usedefaultsettings:
            s.resetbutton.setVisible(False)

        self.showsettings = False
        self.StackedLayout.setCurrentIndex(self.currentindex)

    def OnSettings(self):
        if not self.showsettings:
            self.SettingsUI.resetbutton.setVisible(not self.usedefaultsettings)
            self.StackedLayout.setCurrentIndex(2)
            self.showsettings = True

    def UpdateGUI(self):
        if not self.cpfinish:
            f = open('support\\cpProgress.sql', 'r')
            sqltext = f.read().replace('@SimID', str(self.simid))
            try:
                cursor = self.db.cursor()
            except connector.Error:
                self.db = connector.connect(host=self.host,
                                            user="******",
                                            passwd="Sequal1234",
                                            database="simulation",
                                            use_pure=True)
                self.db.autocommit = True
                cursor = self.db.cursor()
            complete = 0
            for i in range(self.Cutplans.addData.shape[0]):
                query = sqltext.replace('@CPID',
                                        str(self.Cutplans.addData.ID[i]))
                cursor.execute(query)
                (v, ) = cursor.fetchone()
                self.Cutplans.CPProgress[i].setValue(v)
                if v >= 100:
                    complete += 1
            if complete == self.Cutplans.addData.shape[0]:
                self.cpfinish = True
        else:
            f = open('support\\getResults.sql', 'r')
            sqltext = f.read()
            self.results = read_sql(sqltext, self.db)
            self.ResultsWidget.updateResults(self.results)
            if self.results['RunTime'][2] >= 17.66:
                self.timer.stop()
                self.simrunning = False
                self.setupPostSimulation()

    def setupPostSimulation(self):
        self.Cutplans.AddButton.setVisible(False)
        self.nameTextbox.setDisabled(True)
        self.CreateNewButton.setVisible(True)

        ss = "    background-color: ;\n" \
             "    background-color: qlineargradient(spread:pad, x1:0, y1:0, " \
             "x2:1, y2:1, stop:0 rgba(0, 115, 119, 255), stop:1 rgb(4, 147, " \
             "131));\n" \
             "    color: white;\n" \
             "    height: 25px;\n" \
             "    border: None;\n" \
             "    border-radius: 2px;\n" \
             "    \n" \
             "    font: 11pt \"Tahoma\";\n" \
             "    width: 70px;"

        # SETTINGS READ ONLY
        self.SettingsUI.buttonbox.setStandardButtons(QDialogButtonBox.Cancel)
        for w in self.SettingsUI.buttonbox.children():
            if w.metaObject().className() == "QPushButton":
                w.setCursor(QCursor(Qt.PointingHandCursor))
                w.setStyleSheet(ss)
        self.SettingsUI.setupReadOnly()
        self.CheckCPErrors()

    def setupReadOnly(self, loadcp=True):
        self.closeButton.setVisible(True)
        self.Cutplans.AddButton.setVisible(False)
        qry = "SELECT * FROM simulation.fullresults Where SimID = " + str(
            self.simid)
        data = read_sql(qry, self.db)
        self.nameTextbox.setText(data["SimName"][0])
        self.nameTextbox.setDisabled(True)
        qry = "SELECT CutplanID as ID, NumLogs as \"Log Count\" From " + \
              "cutplans WHERE SimID = " + str(self.simid)

        self.results = data.iloc[:, 3:15].copy()
        self.results.columns = [
            'RunTime', 'LogsCut', 'Production', 'LogVolume', 'Recovery',
            'LogRate', 'Uptime', 'MSLDT', 'BSLDT', 'TSLDT', 'Sawdust', 'Shift'
        ]
        self.results.loc[self.results.index[0],
                         'Shift'] = self.results.shape[0]
        self.results = self.results.sort_values(by=['Shift'])
        self.results['Sawdust'] = self.results['Sawdust'] / \
            self.results['LogVolume']
        self.ResultsWidget.updateResults(self.results)

        if loadcp:
            cpdata = read_sql(qry, self.db)
            self.Cutplans.AddCP(addData=cpdata, errors=self.CheckCPErrors())

        qry = "SELECT * From SimHistory Where SimID = " + str(self.simid) + ";"
        settings = read_sql(qry, self.db)
        self.loggap_setting = settings.LogGap[0]
        dt = settings.Downtime[0]
        if dt == 0:
            self.downtime_setting = []
            for i in range(len(self.SettingsUI.downtimeCBs)):
                self.downtime_setting.append(False)
        elif dt == 1:
            self.downtime_setting = []
            for i in range(len(self.SettingsUI.downtimeCBs)):
                self.downtime_setting.append(True)
        else:
            qry = "SELECT * FROM DowntimeSettings Where SimID = " + str(
                self.simid) + ";"
            dt = read_sql(qry, self.db)
            for i in range(len(self.SettingsUI.downtimeCBs)):
                x = (dt.iloc[0, i + 1] == 1)
                self.SettingsUI.downtimeCBs[i].setChecked(x)
        self.SettingsUI.numbinsTB.setValue(settings.NumBins[0])
        if settings.LineSpeed[0] == 55.0:
            self.SettingsUI.highspeedRB.setChecked(True)
        elif settings.LineSpeed[0] == 35.0:
            self.SettingsUI.lowspeedRB.setChecked(True)
        elif settings.LineSpeed[0] == -1.0:
            self.SettingsUI.autospeedRB.setChecked(True)
        else:
            self.SettingsUI.customspeedRB.setChecked(True)
            self.SettingsUI.customspeedTB.setValue(settings.LineSpeed[0])
        if settings.Downtime[0] == 0:
            qry = "SELECT * FROM CutbackSettings Where SimID = " + str(
                self.simid) + ";"
            cb = read_sql(qry, self.db)
            for i in range(len(self.SettingsUI.downtimeCBs)):
                x = (cb.iloc[0, i + 1] == 1)
                self.SettingsUI.downtimeCBs[i].setChecked(x)

        self.SettingsUI.buttonbox.setStandardButtons(QDialogButtonBox.Cancel)
        for w in self.SettingsUI.buttonbox.children():
            if w.metaObject().className() == "QPushButton":
                w.setCursor(QCursor(Qt.PointingHandCursor))
        self.SettingsUI.setupReadOnly()

    def CheckCPErrors(self):
        with open('support\\cpErrors.sql', 'r') as f:
            query = f.read().replace('@SimID', str(self.simid))
        cperrors = read_sql(query, self.db)

        return cperrors