def display (sc, title = "SVG scene") :
	"""Display a scene in a Qdialog
	
	:Parameters:
	 - `sc` (`SVGScene`)
	 - `title` (str) - window title
	"""
	qapp = QApplication.instance()
	if qapp is None :
		qapp = QApplication([])
	
	dial = QDialog()
	dial.setWindowTitle(title)
	dial.setPalette(QPalette(QColor(255,255,255) ) )
	lay = QVBoxLayout(dial)
	
	w = QSvgWidget(dial)
	data = QByteArray(str(to_xml(sc) ) )
	w.load(data)
	
	r = w.renderer()
	w.setMinimumSize(r.defaultSize() )
	lay.addWidget(w)
	
	dial.show()
	
	qapp.exec_()
def display(sc, title="SVG scene"):
    """Display a scene in a Qdialog
	
	:Parameters:
	 - `sc` (`SVGScene`)
	 - `title` (str) - window title
	"""
    qapp = QApplication.instance()
    if qapp is None:
        qapp = QApplication([])

    dial = QDialog()
    dial.setWindowTitle(title)
    dial.setPalette(QPalette(QColor(255, 255, 255)))
    lay = QVBoxLayout(dial)

    w = QSvgWidget(dial)
    data = QByteArray(str(to_xml(sc)))
    w.load(data)

    r = w.renderer()
    w.setMinimumSize(r.defaultSize())
    lay.addWidget(w)

    dial.show()

    qapp.exec_()
Beispiel #3
0
class PreviewBrowser(QWidget):
    """A Preview Browser for recent/premade scheme selection.
    """
    # Emitted when the current previewed item changes
    currentIndexChanged = Signal(int)

    # Emitted when an item is double clicked in the preview list.
    activated = Signal(int)

    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.__model = None
        self.__currentIndex = -1
        self.__template = DESCRIPTION_TEMPLATE
        self.__setupUi()

    def __setupUi(self):
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        top_layout = QHBoxLayout()
        top_layout.setContentsMargins(12, 12, 12, 12)

        # Top row with full text description and a large preview
        # image.
        self.__label = QLabel(self,
                              objectName="description-label",
                              wordWrap=True,
                              alignment=Qt.AlignTop | Qt.AlignLeft)

        self.__label.setWordWrap(True)
        self.__label.setFixedSize(220, PREVIEW_SIZE[1])

        self.__image = QSvgWidget(self, objectName="preview-image")
        self.__image.setFixedSize(*PREVIEW_SIZE)

        self.__imageFrame = DropShadowFrame(self)
        self.__imageFrame.setWidget(self.__image)

        # Path text below the description and image
        path_layout = QHBoxLayout()
        path_layout.setContentsMargins(12, 0, 12, 0)
        path_label = QLabel("<b>{0!s}</b>".format(self.tr("Path:")),
                            self,
                            objectName="path-label")

        self.__path = TextLabel(self, objectName="path-text")

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.__path)

        self.__selectAction = \
            QAction(self.tr("Select"), self,
                    objectName="select-action",
                    )

        top_layout.addWidget(self.__label,
                             1,
                             alignment=Qt.AlignTop | Qt.AlignLeft)
        top_layout.addWidget(self.__image,
                             1,
                             alignment=Qt.AlignTop | Qt.AlignRight)

        vlayout.addLayout(top_layout)
        vlayout.addLayout(path_layout)

        # An list view with small preview icons.
        self.__previewList = LinearIconView(objectName="preview-list-view")
        self.__previewList.doubleClicked.connect(self.__onDoubleClicked)

        vlayout.addWidget(self.__previewList)
        self.setLayout(vlayout)

    def setModel(self, model):
        """Set the item model for preview.
        """
        if self.__model != model:
            if self.__model:
                s_model = self.__previewList.selectionModel()
                s_model.selectionChanged.disconnect(self.__onSelectionChanged)
                self.__model.dataChanged.disconnect(self.__onDataChanged)

            self.__model = model
            self.__previewList.setModel(model)

            if model:
                s_model = self.__previewList.selectionModel()
                s_model.selectionChanged.connect(self.__onSelectionChanged)
                self.__model.dataChanged.connect(self.__onDataChanged)

            if model and model.rowCount():
                self.setCurrentIndex(0)

    def model(self):
        """Return the item model.
        """
        return self.__model

    def setPreviewDelegate(self, delegate):
        """Set the delegate to render the preview images.
        """
        raise NotImplementedError

    def setDescriptionTemplate(self, template):
        self.__template = template
        self.__update()

    def setCurrentIndex(self, index):
        """Set the selected preview item index.
        """
        if self.__model is not None and self.__model.rowCount():
            index = min(index, self.__model.rowCount() - 1)
            index = self.__model.index(index, 0)
            sel_model = self.__previewList.selectionModel()
            # This emits selectionChanged signal and triggers
            # __onSelectionChanged, currentIndex is updated there.
            sel_model.select(index, sel_model.ClearAndSelect)

        elif self.__currentIndex != -1:
            self.__currentIndex = -1
            self.__update()
            self.currentIndexChanged.emit(-1)

    def currentIndex(self):
        """Return the current selected index.
        """
        return self.__currentIndex

    def __onSelectionChanged(self, *args):
        """Selected item in the preview list has changed.
        Set the new description and large preview image.

        """
        rows = self.__previewList.selectedIndexes()
        if rows:
            index = rows[0]
            self.__currentIndex = index.row()
        else:
            index = QModelIndex()
            self.__currentIndex = -1

        self.__update()
        self.currentIndexChanged.emit(self.__currentIndex)

    def __onDataChanged(self, topleft, bottomRight):
        """Data changed, update the preview if current index in the changed
        range.

        """
        if self.__currentIndex <= topleft.row() and \
                self.__currentIndex >= bottomRight.row():
            self.__update()

    def __onDoubleClicked(self, index):
        """Double click on an item in the preview item list.
        """
        self.activated.emit(index.row())

    def __update(self):
        """Update the current description.
        """
        if self.__currentIndex != -1:
            index = self.model().index(self.__currentIndex, 0)
        else:
            index = QModelIndex()

        if not index.isValid():
            description = ""
            name = ""
            path = ""
            svg = NO_PREVIEW_SVG
        else:
            description = str(index.data(Qt.WhatsThisRole))
            if not description:
                description = "No description."

            description = escape(description)
            description = description.replace("\n", "<br/>")

            name = str(index.data(Qt.DisplayRole))
            if not name:
                name = "Untitled"

            name = escape(name)
            path = str(index.data(Qt.StatusTipRole))

            svg = str(index.data(previewmodel.ThumbnailSVGRole))

        desc_text = self.__template.format(description=description, name=name)

        self.__label.setText(desc_text)

        self.__path.setText(path)

        if not svg:
            svg = NO_PREVIEW_SVG

        if svg:
            self.__image.load(QByteArray(svg.encode("utf-8")))
class PreviewBrowser(QWidget):
    """A Preview Browser for recent/premade scheme selection.
    """
    # Emitted when the current previewed item changes
    currentIndexChanged = Signal(int)

    # Emitted when an item is double clicked in the preview list.
    activated = Signal(int)

    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.__model = None
        self.__currentIndex = -1
        self.__template = DESCRIPTION_TEMPLATE
        self.__setupUi()

    def __setupUi(self):
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        top_layout = QHBoxLayout()
        top_layout.setContentsMargins(12, 12, 12, 12)

        # Top row with full text description and a large preview
        # image.
        self.__label = QLabel(self, objectName="description-label",
                              wordWrap=True,
                              alignment=Qt.AlignTop | Qt.AlignLeft)

        self.__label.setWordWrap(True)
        self.__label.setFixedSize(220, PREVIEW_SIZE[1])

        self.__image = QSvgWidget(self, objectName="preview-image")
        self.__image.setFixedSize(*PREVIEW_SIZE)

        self.__imageFrame = DropShadowFrame(self)
        self.__imageFrame.setWidget(self.__image)

        # Path text below the description and image
        path_layout = QHBoxLayout()
        path_layout.setContentsMargins(12, 0, 12, 0)
        path_label = QLabel("<b>{0!s}</b>".format(self.tr("Path:")), self,
                            objectName="path-label")

        self.__path = TextLabel(self, objectName="path-text")

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.__path)

        self.__selectAction = \
            QAction(self.tr("Select"), self,
                    objectName="select-action",
                    )

        top_layout.addWidget(self.__label, 1,
                             alignment=Qt.AlignTop | Qt.AlignLeft)
        top_layout.addWidget(self.__image, 1,
                             alignment=Qt.AlignTop | Qt.AlignRight)

        vlayout.addLayout(top_layout)
        vlayout.addLayout(path_layout)

        # An list view with small preview icons.
        self.__previewList = LinearIconView(objectName="preview-list-view")
        self.__previewList.doubleClicked.connect(self.__onDoubleClicked)

        vlayout.addWidget(self.__previewList)
        self.setLayout(vlayout)

    def setModel(self, model):
        """Set the item model for preview.
        """
        if self.__model != model:
            if self.__model:
                s_model = self.__previewList.selectionModel()
                s_model.selectionChanged.disconnect(self.__onSelectionChanged)
                self.__model.dataChanged.disconnect(self.__onDataChanged)

            self.__model = model
            self.__previewList.setModel(model)

            if model:
                s_model = self.__previewList.selectionModel()
                s_model.selectionChanged.connect(self.__onSelectionChanged)
                self.__model.dataChanged.connect(self.__onDataChanged)

            if model and model.rowCount():
                self.setCurrentIndex(0)

    def model(self):
        """Return the item model.
        """
        return self.__model

    def setPreviewDelegate(self, delegate):
        """Set the delegate to render the preview images.
        """
        raise NotImplementedError

    def setDescriptionTemplate(self, template):
        self.__template = template
        self.__update()

    def setCurrentIndex(self, index):
        """Set the selected preview item index.
        """
        if self.__model is not None and self.__model.rowCount():
            index = min(index, self.__model.rowCount() - 1)
            index = self.__model.index(index, 0)
            sel_model = self.__previewList.selectionModel()
            # This emits selectionChanged signal and triggers
            # __onSelectionChanged, currentIndex is updated there.
            sel_model.select(index, sel_model.ClearAndSelect)

        elif self.__currentIndex != -1:
            self.__currentIndex = -1
            self.__update()
            self.currentIndexChanged.emit(-1)

    def currentIndex(self):
        """Return the current selected index.
        """
        return self.__currentIndex

    def __onSelectionChanged(self, *args):
        """Selected item in the preview list has changed.
        Set the new description and large preview image.

        """
        rows = self.__previewList.selectedIndexes()
        if rows:
            index = rows[0]
            self.__currentIndex = index.row()
        else:
            index = QModelIndex()
            self.__currentIndex = -1

        self.__update()
        self.currentIndexChanged.emit(self.__currentIndex)

    def __onDataChanged(self, topleft, bottomRight):
        """Data changed, update the preview if current index in the changed
        range.

        """
        if self.__currentIndex <= topleft.row() and \
                self.__currentIndex >= bottomRight.row():
            self.__update()

    def __onDoubleClicked(self, index):
        """Double click on an item in the preview item list.
        """
        self.activated.emit(index.row())

    def __update(self):
        """Update the current description.
        """
        if self.__currentIndex != -1:
            index = self.model().index(self.__currentIndex, 0)
        else:
            index = QModelIndex()

        if not index.isValid():
            description = ""
            name = ""
            path = ""
            svg = NO_PREVIEW_SVG
        else:
            description = unicode(index.data(Qt.WhatsThisRole).toString())
            if not description:
                description = "No description."

            description = escape(description)
            description = description.replace("\n", "<br/>")

            name = unicode(index.data(Qt.DisplayRole).toString())
            if not name:
                name = "Untitled"

            name = escape(name)
            path = unicode(index.data(Qt.StatusTipRole).toString())

            svg = unicode(index.data(previewmodel.ThumbnailSVGRole).toString())

        desc_text = self.__template.format(description=description, name=name)

        self.__label.setText(desc_text)

        self.__path.setText(path)

        if not svg:
            svg = NO_PREVIEW_SVG

        if svg:
            self.__image.load(QByteArray(svg.encode("utf-8")))
Beispiel #5
0
class BedbotWidget(QtGui.QWidget):

    loadedModules = None

    currentWidget = None
    currentWidgetIndex = 2

    listenToButtons = True

    hasIOLibraries = False

    autoCloseTimer = None

    currentAudioModule = None
    pinConfig = {}

    pinCallbacks = []
    disabledPins = []
    currentButtonIndicators = []

    pinStatusTimer = None

    def __init__(self, parent, modules):
        super(BedbotWidget, self).__init__(parent)

        self.resize(320, 240)

        self.loadPinConfig()

        self.loadedModules = modules

        self.connect(self, QtCore.SIGNAL('processPigpioEvent'),
                     self.pinEventCallback)

        self.initializeMenu()

        menuWidgets = []
        for m in self.loadedModules:
            self.connect(m, QtCore.SIGNAL('logEvent'), self.logEvent)
            """For a module to be used in the app, it must be located in the Modules folder and have 
            an 'Enabled' attribute set to True.  If it's not there, or it's false, the module is ignored
            """
            if (hasattr(m, "Enabled") == True and m.Enabled == True):
                """Scans all active modules to see if they should be added to the menu.  Module must have 'addMenuWidget' function """
                if (self.moduleHasFunction(m, "addMenuWidget")):
                    if (hasattr(m, "menuOrder") == True):
                        menuWidgets.insert(m.menuOrder, m)
                    else:
                        menuWidgets.insert(len(menuWidgets), m)
                """Scans all active modules to see if they require the pin configuration."""
                if (self.moduleHasFunction(m, "setPin")):
                    m.setPin(self.pinConfig)
                """Allows a module to tell other modules to send output on a specific pin (for the audio relay)"""
                self.connect(m, QtCore.SIGNAL('pinRequested'),
                             self.pinRequestedCallback)
                """Tells BedbotWidget to show a popup according to specifications provided"""
                self.connect(m, QtCore.SIGNAL('showPopup'),
                             self.showPopupCallback)
                """Tells BedbotWidget which colored circle indicators to display"""
                self.connect(m, QtCore.SIGNAL('requestButtonPrompt'),
                             self.buttonPromptRequestCallback)
                """Event that modules can call to invoke methods on other modules without knowing about them beforehand """
                self.connect(m, QtCore.SIGNAL('broadcastModuleRequest'),
                             self.broadcastModuleRequestCallback)
                """Allows active modules to send signals to all other modules to stop audio playback"""
                self.connect(m, QtCore.SIGNAL('stopAllAudio'),
                             self.stopAllAudioCallback)
                """If a modules uses the audio output, it must have the attribute 'UsesAudio' and have it set to True
                If it does, than it can use the audio status display in BedbotWidget to display it's current status
                """
                if (hasattr(m, "UsesAudio") == True and m.UsesAudio == True):
                    self.connect(m, QtCore.SIGNAL('audioStarted'),
                                 self.audioStartedCallback)
                    self.connect(m, QtCore.SIGNAL('audioStopped'),
                                 self.audioStoppedCallback)
        """ After all modules are loaded, use the attribute 'menuOrder' on active modules to organize the menu icons"""
        for i in range(0, len(menuWidgets)):
            menuWidgets[i].menuOrder = i
            self.addMainWidget(menuWidgets[i])

        self.menu_widget.configureMenu()
        self.toggleMainMenu(True)
        QtCore.QMetaObject.connectSlotsByName(self)

    def broadcastModuleRequestCallback(self,
                                       caller,
                                       methodToCall,
                                       methodArgs=None,
                                       callbackMethod=None,
                                       targetModuleName=None):
        """Callback for the 'broadcastModuleRequest' event that modules can call to invoke methods on other modules
        without knowing about them beforehand
        """
        results = []
        for m in self.loadedModules:
            if (targetModuleName != None
                    and type(m).__name__ != targetModuleName):
                continue
            if (hasattr(m, "Enabled") == True and m.Enabled == True):
                if (self.moduleHasFunction(m, methodToCall)):
                    if (callbackMethod != None):
                        if (methodArgs != None):
                            results.append(
                                getattr(m, methodToCall)(methodArgs))
                        else:
                            results.append(getattr(m, methodToCall)())
                    else:
                        getattr(m, methodToCall)(methodArgs)

        if (callbackMethod != None and hasattr(caller, "Enabled") == True
                and caller.Enabled == True):
            if (self.moduleHasFunction(caller, callbackMethod)):
                getattr(caller, callbackMethod)(results)

    def stopAllAudioCallback(self):
        self.stopAllAudio()

    def buttonPromptRequestCallback(self, buttonsToPrompt):
        self.clearButtonPrompts()
        for x in buttonsToPrompt:
            if (x == "ON"):
                self.onButtonIndicator.setVisible(True)
            elif (x == "CONTEXT"):
                self.contextButtonIndicator.setVisible(True)
            elif (x == "OFF"):
                self.offButtonIndicator.setVisible(True)

    def clearButtonPrompts(self):
        self.onButtonIndicator.setVisible(False)
        self.contextButtonIndicator.setVisible(False)
        self.offButtonIndicator.setVisible(False)

    def showPopupCallback(self,
                          caller,
                          msg=None,
                          popupType=None,
                          popupArgs=None):

        self.customPopup = Popup(self)
        self.connect(self.customPopup, QtCore.SIGNAL('popupResult'),
                     self.popupCallback)
        if (popupType == None):
            self.customPopup.doWait(msg)
        else:
            if (popupType == "optionSelect" and popupArgs != None):
                self.customPopup.optionSelect(msg, popupArgs)
            elif (popupType == "numberSelect"):
                self.customPopup.numberSelect(msg, popupArgs)
            elif (popupType == "alarm"):
                self.customPopup.alarm(popupArgs)
            elif (popupType == "snooze"):
                self.customPopup.snooze(popupArgs)

    def popupCallback(self, result):
        for m in self.loadedModules:
            if (self.moduleHasFunction(m, "popupResult")):
                m.popupResult(result)

    def pinRequestedCallback(self, pin):
        self.pinEventCallback(pin)

    def audioStoppedCallback(self, sourceModule):
        self.currentAudioModule = None
        self.stopAllAudio(self.currentAudioModule)
        self.statusDisplay.setText("")

    def audioStartedCallback(self, sourceModule):
        self.currentAudioModule = sourceModule
        self.stopAllAudio(self.currentAudioModule)
        self.statusDisplay.setText("")
        if (self.moduleHasFunction(self.currentAudioModule,
                                   "getAudioStatusDisplay")):
            self.statusDisplay.setText(
                self.currentAudioModule.getAudioStatusDisplay())

    def stopAllAudio(self, ignoredModule=None):
        for m in self.loadedModules:
            if (hasattr(m, "UsesAudio") == True and m.UsesAudio == True
                    and (ignoredModule == None or
                         (ignoredModule != None and m != ignoredModule))):
                if (self.moduleHasFunction(m, "stop")):
                    m.stop()

    def logEvent(self, evtStr):
        print(evtStr)
        logging.info(str(evtStr))

    def initializeMenu(self):
        self.menu_widget = DynamicMenu(self)
        self.menu_widget.setGeometry(QtCore.QRect(10, 10, 320, 190))
        self.menu_widget.setVisible(True)
        self.connect(self.menu_widget, QtCore.SIGNAL('showWidget'),
                     self.showWidgetCallback)

        self.menuButton = QSvgWidget("icons/three-bars.svg", self)
        self.menuButton.setGeometry(QtCore.QRect(10, 200, 30, 35))
        pressableSender(self.menuButton).connect(self.menuButtonPressed)
        self.menuButton.setVisible(False)

        self.onButtonIndicator = ButtonIndicator(self, 30, "green")
        self.onButtonIndicator.setGeometry(QtCore.QRect(50, 202, 30, 30))
        self.onButtonIndicator.setVisible(False)

        self.contextButtonIndicator = ButtonIndicator(self, 30, "blue")
        self.contextButtonIndicator.setGeometry(QtCore.QRect(80, 202, 30, 30))
        self.contextButtonIndicator.setVisible(False)

        self.offButtonIndicator = ButtonIndicator(self, 30, "red")
        self.offButtonIndicator.setGeometry(QtCore.QRect(110, 202, 30, 30))
        self.offButtonIndicator.setVisible(False)

        font = QtGui.QFont()
        font.setPointSize(15)

        self.statusDisplay = QtGui.QLabel(self)
        self.statusDisplay.setGeometry(QtCore.QRect(150, 200, 140, 35))
        self.statusDisplay.setAlignment(QtCore.Qt.AlignRight
                                        | QtCore.Qt.AlignVCenter)
        self.statusDisplay.setStyleSheet('color: #eaf736')
        self.statusDisplay.setFont(font)
        pressableSender(self.statusDisplay).connect(self.audioStatusPressed)

    def audioStatusPressed(self, obj):
        if (self.currentAudioModule != None):
            self.menu_widget.setMenuItemSelected(self.currentAudioModule)
            self.showWidgetCallback(self.currentAudioModule)

    def toggleMainMenu(self, showMenu):
        if (showMenu):
            self.hideMainWidgets()
            self.autoCloseTimer = QTimer()
            self.autoCloseTimer.timeout.connect(self.autoCloseMainMenu)
            self.autoCloseTimer.start(5000)
        self.menuButton.setVisible(not showMenu)
        self.menu_widget.setVisible(showMenu)

    def autoCloseMainMenu(self):
        self.autoCloseTimer.stop()
        self.autoCloseTimer = None
        if (self.currentWidget != None):
            self.showWidgetCallback(self.currentWidget)

    def triggerMenuButton(self):
        self.menuButtonTimer.stop()
        self.menuButton.load("icons/three-bars.svg")
        self.toggleMainMenu(True)

    def menuButtonPressed(self, obj):
        self.menuButton.load("icons/three-barsSelected.svg")
        self.menuButtonTimer = QTimer()
        self.menuButtonTimer.timeout.connect(self.triggerMenuButton)
        self.menuButtonTimer.start(500)

    def showWidgetCallback(self, w):
        if (self.autoCloseTimer != None):
            self.autoCloseTimer.stop()
            self.autoCloseTimer = None
        self.hideMainWidgets()
        w.showWidget()
        self.currentWidget = w
        self.toggleMainMenu(False)

    def hideMainWidgets(self):
        self.clearButtonPrompts()
        for m in self.loadedModules:
            if (hasattr(m, "Enabled") == True and m.Enabled == True):
                if (self.moduleHasFunction(m, "hideWidget")):
                    m.hideWidget()
        self.menu_widget.setVisible(False)

    def moduleHasFunction(self, m, functionName):
        """Helper to determine if a module has a specific function available"""
        funct = getattr(m, functionName, None)
        if (callable(funct)):
            return True
        return False

    def addMainWidget(self, w):
        """Adds a widget that has Enabled set to true, has a method called 'addMenuWidget' and has an optional menuOrder parameter"""
        w.addMenuWidget(self)
        self.menu_widget.addMenuItem(w)

    def simulateButton(self, buttonDesc):
        """Simulates a button call, usually for debug purposes"""
        self.pinEventCallback(self.pinConfig[buttonDesc])

    def pinEventCallback(self, channel):
        self.logEvent("pin callback for channel: " + str(channel))
        if (hasattr(self, "customPopup") == True):
            self.customPopup.processPin(self.pinConfig, channel)
        #else:
        for m in self.loadedModules:
            if (hasattr(m, "ListenForPinEvent") == True
                    and m.ListenForPinEvent == True
                    and self.moduleHasFunction(m, "processPinEvent")):
                m.processPinEvent(channel)

    def pigpioCallback(self, gpio, level, tick):
        currentlyDisabled = gpio in self.disabledPins
        if (currentlyDisabled == False):
            self.disabledPins.append(gpio)
            self.emit(QtCore.SIGNAL('processPigpioEvent'), gpio)
            t = Thread(target=self.reenablePin, args=(
                self,
                gpio,
            ))
            t.start()

    def reenablePin(self, parent, pin):
        """Renables a pin after it fires to prevent extra event from firing"""
        time.sleep(1)
        print("reenable pin: " + str(pin))
        parent.disabledPins.remove(pin)

    def loadPinConfig(self):
        """Loads the pinConfig.json file that specifies the pins used and a name"""
        with open("pinConfig.json") as data_file:
            data = json.load(data_file)
        self.pinConfig = {}

        if (hasIOLibraries):
            self.pi = pigpio.pi()

        for x in range(0, len(data["pins"])):
            p = data["pins"][x]
            self.pinConfig[p["type"]] = p["pin"]
            if (hasIOLibraries and self.listenToButtons == True
                    and p["listenForPress"] == True):
                self.logEvent("adding event to pin: " + str(p["pin"]))
                self.pi.set_pull_up_down(p["pin"], pigpio.PUD_DOWN)
                cb1 = self.pi.callback(p["pin"], pigpio.RISING_EDGE,
                                       self.pigpioCallback)

    def doClose(self):

        try:
            self.customPopup.closePopup()
        except Exception:
            print("problem disposing of popup")

        for m in self.loadedModules:
            try:
                m.dispose()
            except BaseException:
                print("problem disposing")
                print(m)
        try:
            self.pi.stop()
        except BaseException:
            print("problem cleaning up IO")
Beispiel #6
0
class MainWindow(QWidget):
    """
    Create a surface for the chessboard.
    """
    def __init__(self, board_configuration=None):
        """
        Initialize the chessboard.
        """
        super().__init__()

        self.setWindowTitle("Chess GUI")
        self.setGeometry(300, 300, 800, 800)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 600, 600)

        self.boardSize = min(self.widgetSvg.width(),
                             self.widgetSvg.height())
        self.coordinates = True
        self.margin = 0.05 * self.boardSize if self.coordinates else 0
        self.squareSize = (self.boardSize - 2 * self.margin) / 8.0
        self.pieceToMove = [None, None]
        self.pieceToInsert = [None, None]
        self.board = chess.Board()
        if(board_configuration):
            self.board.set_piece_map(board_configuration)
        self.drawBoard()


    @pyqtSlot(QWidget)
    def mousePressEvent(self, event):
        """
        Handle left mouse clicks and enable moving chess pieces by
        clicking on a chess piece and then the target square.

        Moves must be made according to the rules of chess because
        illegal moves are suppressed.
        """
        if event.x() <= self.boardSize and event.y() <= self.boardSize:
            # if event.buttons() == Qt.RightButton:
            if self.margin < event.x() < self.boardSize - self.margin and self.margin < event.y() < self.boardSize - self.margin:
                file = int((event.x() - self.margin) / self.squareSize)
                rank = 7 - int((event.y() - self.margin) / self.squareSize)
                square = chess.square(file, rank)
                piece = self.board.piece_at(square)
                coordinates = "{}{}".format(chr(file + 97), str(rank + 1))
                if self.pieceToInsert[0] is not None and self.pieceToInsert[1] is not None:
                    print("INSERTING.....")
                    self.board.set_piece_at(square, chess.Piece(self.pieceToInsert[0], self.pieceToInsert[1]))
                    self.pieceToInsert = [None, None]
                elif self.pieceToMove[0] is not None:
                    #move = chess.Move.from_uci("{}{}".format(self.pieceToMove[1], coordinates))
                    # if move in self.board.legal_moves:
                    self.board.set_piece_at(square, self.pieceToMove[0])
                    self.board.set_piece_at(self.pieceToMove[1], None)
                    # self.board.push(move)
                    piece = None
                    coordinates = None
                
                self.pieceToMove = [piece, square]
                self.drawBoard()

    @pyqtSlot(QWidget)
    def keyPressEvent(self, event):
        """
        Handle left mouse clicks and enable moving chess pieces by
        clicking on a chess piece and then the target square.

        Moves must be made according to the rules of chess because
        illegal moves are suppressed.
        """
        pressed = event.key()
        print(pressed)
        if(pressed == 81):
            print("You want to insert a queen -- press q")
            self.pieceToInsert[0] = piece_name_index['queen']
        elif(pressed == 75):
            print("You want to insert a king -- press k")
            self.pieceToInsert[0] = piece_name_index['king']
        elif(pressed == 78):
            print("You want to insert a knight -- press n")
            self.pieceToInsert[0] = piece_name_index['knight']
        elif(pressed == 80):
            print("You want to insert a pawn -- press p")
            self.pieceToInsert[0] = piece_name_index['pawn']
        elif(pressed == 66):
            print("You want to insert a bishop -- press b")
            self.pieceToInsert[0] = piece_name_index['bishop']
        elif(pressed == 82):
            print("You want to insert a rook -- press r")
            self.pieceToInsert[0] = piece_name_index['rook']
        elif(pressed == 49):
            print("You want white")
            if(self.pieceToInsert[0]):
                self.pieceToInsert[1] = True
        elif(pressed == 48):
            print("You want black")
            if(self.pieceToInsert[0]):
                self.pieceToInsert[1] = False
        elif(pressed == 16777220):
            print("You are finished with the GUI")
            self.close()

    def drawBoard(self):
        global analyzed_board
        """
        Draw a chessboard with the starting position and then redraw
        it for every new move.
        """
        self.boardSvg = self.board._repr_svg_().encode("UTF-8")
        self.drawBoardSvg = self.widgetSvg.load(self.boardSvg)
        analyzed_board = self.board.copy()
        return self.drawBoardSvg

    def show(self):
        super().show()
        return self.board