def writeToFile(self, filename):
        """ Save all contacts in the model to a file. """
        try:
            f = open(filename, "wb")
            pickle.dump(self.tableModel.addresses, f)

        except IOError:
            QMessageBox.information(self, "Unable to open file: %s" % filename)
        finally:
            f.close()
Exemple #2
0
 def score(self):
     score = self.mineSweeper.score()
     if score is not None:
         self.mineSweeper.reveal()
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         for tile in self.mineSweeper:
             tile.delegate.marked = False
         self.mineSweeper.reset()
Exemple #3
0
    def saveFile(self, fileName):
        file = QFile(fileName)

        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(self, "MDI",
                    "Cannot write file %s:\n%s." % (fileName, file.errorString()))
            return False

        outstr = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outstr << self.toPlainText()
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        return True
    def readFromFile(self, filename):
        """ Read contacts in from a file. """
        try:
            f = open(filename, "rb")
            addresses = pickle.load(f)
        except IOError:
            QMessageBox.information(self, "Unable to open file: %s" % filename)
        finally:
            f.close()

        if len(addresses) == 0:
            QMessageBox.information(self, "No contacts in file: %s" % filename)
        else:
            for address in addresses:
                self.addEntry(address["name"], address["address"])
    def addEntry(self, name=None, address=None):
        """ Add an entry to the addressbook. """
        if name is None and address is None:
            addDialog = AddDialogWidget()

            if addDialog.exec_():
                name = addDialog.name
                address = addDialog.address

        address = {"name": name, "address": address}
        addresses = self.tableModel.addresses[:]

        # The QT docs for this example state that what we're doing here
        # is checking if the entered name already exists. What they
        # (and we here) are actually doing is checking if the whole
        # name/address pair exists already - ok for the purposes of this
        # example, but obviously not how a real addressbook application
        # should behave.
        try:
            addresses.remove(address)
            QMessageBox.information(self, "Duplicate Name",
                                    "The name \"%s\" already exists." % name)
        except ValueError:
            # The address didn't already exist, so let's add it to the model.

            # Step 1: create the  row
            self.tableModel.insertRows(0)

            # Step 2: get the index of the newly created row and use it.
            # to set the name
            ix = self.tableModel.index(0, 0, QModelIndex())
            self.tableModel.setData(ix, address["name"], Qt.EditRole)

            # Step 3: lather, rinse, repeat for the address.
            ix = self.tableModel.index(0, 1, QModelIndex())
            self.tableModel.setData(ix, address["address"], Qt.EditRole)

            # Remove the newAddressTab, as we now have at least one
            # address in the model.
            self.removeTab(self.indexOf(self.newAddressTab))

            # The screenshot for the QT example shows nicely formatted
            # multiline cells, but the actual application doesn't behave
            # quite so nicely, at least on Ubuntu. Here we resize the newly
            # created row so that multiline addresses look reasonable.
            tableView = self.currentWidget()
            tableView.resizeRowToContents(ix.row())
Exemple #6
0
    def transmitHex(self, hexarray):
        if len(hexarray) > 0:
            byteArray = bytearray(hexarray)
            if self.serialport.isOpen():
                try:
                    self.serialport.write(byteArray)
                except serial.SerialException as e:
                    print("Exception in transmitHex(%s)" % repr(hexarray))
                    QMessageBox.critical(self, "Exception in transmitHex", str(e),
                        QMessageBox.Close)
                else:
                    # self.txCount += len( b )
                    # self.frame.statusbar.SetStatusText('Tx:%d' % self.txCount, 2)

                    text = ''.join(['%02X ' % i for i in hexarray])
                    self.appendOutputText("\n%s T->:%s" % (self.timestamp(), text),
                        Qt.blue)
Exemple #7
0
    def loadFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(self, "MDI",
                    "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return False

        instr = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.setPlainText(instr.readAll())
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)

        self.document().contentsChanged.connect(self.documentWasModified)

        return True
Exemple #8
0
 def fileDropped(self, path):
     path = str(path)
     name, ext = os.path.splitext(path)
     ext = ext[1:]
     if not ext in self.supportedFormats:
         QMessageBox.warning(self, "Warning", "The dropped file is not supported")
         return
     pixmap = QPixmap(path)
     if pixmap.isNull():
         QMessageBox.warning(self, "Warning", "Can't load the image")
         return
     if self.path:
         self.fileWatcher.removePath(self.path)
     self.path = path
     self.fileWatcher.addPath(self.path)
     self.pixmapWidget.setPixmap(pixmap)
     self.generateAndExportButton.setEnabled(True)
     self.setTitle()
     self.activateWindow()
Exemple #9
0
    def sendTableRow(self, row):
        cols = self.quickSendTable.columnCount()
        try:
            data = ['0' + self.quickSendTable.item(row, col).text()
                for col in range(1, cols)
                if self.quickSendTable.item(row, col) is not None
                    and self.quickSendTable.item(row, col).text() is not '']
        except:
            print("Exception in get table data(row = %d)" % (row + 1))
        else:
            tmp = [d[-2] + d[-1] for d in data if len(d) >= 2]
            for t in tmp:
                if not is_hex(t):
                    QMessageBox.critical(self, "Error",
                        "'%s' is not hexadecimal." % (t), QMessageBox.Close)
                    return

            h = [int(t, 16) for t in tmp]
            self.transmitHex(h)
Exemple #10
0
    def mousePressEvent(self, mouseEvent: QMouseEvent):
        closestNode = self.playerNode.closest(mouseEvent.pos() - self.paintOffset)
        direction = closestNode.row - self.playerNode.row, closestNode.column - self.playerNode.column
        crawlNode = self.playerNode.crawl(direction)

        self.animation = QPropertyAnimation(self, b"player", self)
        if len(crawlNode.links) > 2:
            self.animation.setEasingCurve(QEasingCurve.OutBack);
        else:
            self.animation.setEasingCurve(QEasingCurve.OutBounce);
        self.animation.setStartValue(self.player)
        self.animation.setEndValue(crawlNode.point)
        self.animation.setDuration(400)
        self.animation.start()

        self.playerNode = crawlNode
        if self.playerNode == self.finishNode:
            QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
            self.initMaze()
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(self, "Threaded Fortune Server",
                    "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
Exemple #12
0
    def loadCSV(self, path, notifyExcept = False):
        data = []
        set_rows = 0
        set_cols = 0
        try:
            with open(path) as csvfile:
                csvData = csv.reader(csvfile)
                for row in csvData:
                    data.append(row)
                    set_rows = set_rows + 1
                    if len(row) > set_cols:
                        set_cols = len(row)
        except IOError as e:
            print("({})".format(e))
            if notifyExcept:
                QMessageBox.critical(self, "Open failed", str(e), QMessageBox.Close)
            return

        rows = self.quickSendTable.rowCount()
        cols = self.quickSendTable.columnCount()
        # clear table
        for col in range(cols):
            for row in range(rows):
                self.quickSendTable.setItem(row, col, QTableWidgetItem(""))

        self._csvFilePath = path
        if (cols - 1) < set_cols:   # first colume is used by the "send" buttons.
            cols = set_cols + 10
            self.quickSendTable.setColumnCount(cols)
        if rows < set_rows:
            rows = set_rows + 20
            self.quickSendTable.setRowCount(rows)

        for row, rowdat in enumerate(data):
            if len(rowdat) > 0:
                for col, cell in enumerate(rowdat, 1):
                    self.quickSendTable.setItem(row, col, QTableWidgetItem(str(cell)))

        self.quickSendTable.resizeColumnsToContents()
Exemple #13
0
    def maybeSave(self):
        if self.document().isModified():
            ret = QMessageBox.warning(self, "MDI",
                    "'%s' has been modified.\nDo you want to save your "
                    "changes?" % self.userFriendlyCurrentFile(),
                    QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

            if ret == QMessageBox.Save:
                return self.save()

            if ret == QMessageBox.Cancel:
                return False

        return True
Exemple #14
0
 def round(self, tile: TicTacToe.Tile):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.player.tile = tile
     score = self.ticTacToe.round(True)
     QApplication.restoreOverrideCursor()
     if score is not None:
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == 0:
             QMessageBox.warning(self, self.tr("Tie!"), self.tr("You tied :|"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         self.ticTacToe.reset(True)
Exemple #15
0
 def round(self, disc: FourPlay.Disc):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.player.disc = disc
     score = self.fourPlay.round(True)
     QApplication.restoreOverrideCursor()
     if score is not None:
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == 0:
             QMessageBox.warning(self, self.tr("Tie!"), self.tr("You tied :|"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         self.fourPlay.reset(True)
    def displayError(self, socketError, message):
        if socketError == QAbstractSocket.HostNotFoundError:
            QMessageBox.information(self, "Blocking Fortune Client",
                    "The host was not found. Please check the host and port "
                    "settings.")
        elif socketError == QAbstractSocket.ConnectionRefusedError:
            QMessageBox.information(self, "Blocking Fortune Client",
                    "The connection was refused by the peer. Make sure the "
                    "fortune server is running, and check that the host name "
                    "and port settings are correct.")
        else:
            QMessageBox.information(self, "Blocking Fortune Client",
                    "The following error occurred: %s." % message)

        self.getFortuneButton.setEnabled(True)
Exemple #17
0
    def openPort(self):
        if self.serialport.isOpen():
            return

        _port = self.GetPort()
        if '' == _port:
            QMessageBox.information(self, "Invalid parameters", "Port is empty.")
            return

        _baudrate = self.cmbBaudRate.currentText()
        if '' == _baudrate:
            QMessageBox.information(self, "Invalid parameters", "Baudrate is empty.")
            return

        self.serialport.port     = _port
        self.serialport.baudrate = _baudrate
        self.serialport.bytesize = self.GetDataBits()
        self.serialport.stopbits = self.GetStopBits()
        self.serialport.parity   = self.GetParity()
        self.serialport.rtscts   = self.chkRTSCTS.isChecked()
        self.serialport.xonxoff  = self.chkXonXoff.isChecked()
        # self.serialport.timeout  = THREAD_TIMEOUT
        # self.serialport.writeTimeout = SERIAL_WRITE_TIMEOUT
        try:
            self.serialport.open()
        except serial.SerialException as e:
            QMessageBox.critical(self, "Could not open serial port", str(e),
                QMessageBox.Close)
        else:
            self._start_reader()
            self.setWindowTitle("%s on %s [%s, %s%s%s%s%s]" % (
                appInfo.title,
                self.serialport.portstr,
                self.serialport.baudrate,
                self.serialport.bytesize,
                self.serialport.parity,
                self.serialport.stopbits,
                self.serialport.rtscts and ' RTS/CTS' or '',
                self.serialport.xonxoff and ' Xon/Xoff' or '',
                )
            )
            pal = self.btnOpen.palette()
            pal.setColor(QtGui.QPalette.Button, QtGui.QColor(0,0xff,0x7f))
            self.btnOpen.setAutoFillBackground(True)
            self.btnOpen.setPalette(pal)
            self.btnOpen.setText('Close')
            self.btnOpen.update()
Exemple #18
0
    def openWorkspaceAction(self, workspacePath=None, updateWorkspace=False):
        if not self.editorTabs.closeAllTabs():
            return
        if not workspacePath:
            workspacePath = QFileDialog.getExistingDirectory(
                self, "Open workspace", "select new workspace directory")
            if not workspacePath:
                return
        regex = re.compile('[@!#$%^&*()<>?/\|}{~:]')
        if ' ' in workspacePath or regex.search(
                os.path.basename(workspacePath)):
            msg = QMessageBox()
            msg.setStyleSheet("background-color: #2D2D30; color: white;")
            msg.setModal(True)
            msg.setIcon(QMessageBox.Critical)
            msg.setText(
                "Workspace path/name cannot contain whitespace or special characters."
            )
            msg.setWindowTitle("Workspace creation error")
            msg.exec_()
            return False
        path = os.path.join(workspacePath, ".metadata")
        backup_path = os.path.join(workspacePath, ".backup")
        if os.path.isdir(path) or os.path.isdir(backup_path):
            self.msgInvalidFolderError(workspacePath)
            return
        workspace = WorkspaceProxy()
        self.workspace = WorkspaceNode()
        if os.path.exists(path):
            try:  # in try block in case there is a corrupted .metadata file on the path
                with open(path, 'rb') as file:
                    workspace = pickle.load(file)
            except:
                workspace.closedNormally = False  # set it to false to trigger backup msg in case .metadata is corrupted
        elif not os.path.exists(
                backup_path
        ):  # creates a .metadata file for a clean new workspace
            self.workspace.proxy = workspace
            self.applyWsCompatibilityFix(workspacePath)
            self.saveWorkspaceAction(workspacePath)
        self.workspace.proxy = workspace
        self.applyWsCompatibilityFix(workspacePath)
        attempted_backup = False
        if not self.workspace.proxy.closedNormally:
            if self.restoreBackupMessage(workspacePath,
                                         updateWorkspace=updateWorkspace):
                attempted_backup = True
                if self.loadWorkspaceAction(
                        workspacePath, backup=True):  # attempt to load backup
                    self.updateProjectList()
                    return True
                else:
                    self.messageBackupError("closedAbruptly")

        if self.loadWorkspaceAction(
                workspacePath,
                backup=False):  # attempt to load regular ws file
            self.updateProjectList()
            return True
        # If the regular file won't load for some reason and there was no backup attempt, ask to load the backup file
        elif not attempted_backup and self.restoreBackupMessage(
                workspacePath, failedToLoad=True):
            if self.loadWorkspaceAction(
                    workspacePath,
                    backup=True):  # attempt to load the backup file
                self.updateProjectList()
                return True
            else:
                self.messageBackupError()
        return False
Exemple #19
0
 def readerExcept(self, e):
     self.closePort()
     QMessageBox.critical(self, "Read failed", str(e), QMessageBox.Close)
Exemple #20
0
 def debugAction(self, projectProxy=None):
     currentProject: ProjectNode = self.configurationManager.currentProject
     if not currentProject:
         self.showNoCurrentProjectMessage("Debug")
         return
     if not os.path.exists(currentProject.proxy.getProjectPath()):
         currentProject.eventManager.invalidProject.emit(currentProject)
         return
     proxy = None
     if projectProxy:
         proxy = projectProxy
     else:
         if currentProject:
             proxy = currentProject.proxy
     if proxy:
         commandString = proxy.getProjectDebugCommand()
         self.terminal.console.setFocus()
         if self.terminal.executeCommand(proxy.getProjectCompileCommand()):
             copmileString = proxy.getProjectCompileCommand()
             if ' -g ' not in copmileString:
                 msg = QMessageBox()
                 msg.setStyleSheet(
                     "background-color: #2D2D30; color: white;")
                 msg.setModal(True)
                 msg.setIcon(QMessageBox.Warning)
                 msg.setText(
                     "Please set '-g' option in compiler configuration to be able to debug your project."
                 )
                 msg.setWindowTitle("Debug warning")
                 msg.exec_()
                 return False
             self.terminal.executeCommand(commandString)
         self.toolBar.projectComboBox.setCurrentText(proxy.path)
Exemple #21
0
 def onAbout(self):
     q = QWidget()
     icon = QtGui.QIcon(":/icon.ico")
     q.setWindowIcon(icon)
     QMessageBox.about(q, "About MyTerm", appInfo.aboutme)
Exemple #22
0
 def terminated(self):
     QMessageBox.critical(self, self.tr("Game Over!"), self.tr("You toppped out."), QMessageBox.Ok)
     self.tetris.restart()
Exemple #23
0
    def import_from_excel(self):
        msg_box = QMessageBox()
        msg_box.setText(
            "Use one of the available templates to import your collection from an Excel spreadsheet."
        )
        msg_box.setInformativeText(
            "Note: do not change the filename of the template.")
        msg_box.setStandardButtons(QMessageBox.Open | QMessageBox.Cancel)
        expanded = msg_box.addButton('Create Expanded...',
                                     QMessageBox.ApplyRole)
        condensed = msg_box.addButton('Create Condensed...',
                                      QMessageBox.ApplyRole)
        msg_box.setDefaultButton(QMessageBox.Cancel)
        ret = msg_box.exec_()

        if msg_box.clickedButton() == expanded:
            path = QFileDialog.getExistingDirectory(
                self, "Select Directory for Template...") + '/'
            import_export.generate_sheet(path, expanded=True)
        elif msg_box.clickedButton() == condensed:
            path = QFileDialog.getExistingDirectory(
                self, "Select Directory for Template...") + '/'
            import_export.generate_sheet(path, expanded=False)
        elif ret == QMessageBox.Open:
            path = QFileDialog.getOpenFileName(
                self, "Select Filled-Out Template...")
            import_export.import_db(path[0])
Exemple #24
0
    def delete_wine(self):
        # Deletes wine from the database entirely. This is permenant and
        # dangerous, so it uses a message box to confirm.
        if 'wine_id' in self.bottle.wine_info and self.bottle.wine_info[
                'wine_id'] != None:
            msg_box = QMessageBox()
            msg_box.setText(
                "WARNING: You are about to delete this wine from the database, along with all bottles of it. You cannot undo this. Continue?"
            )
            msg_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
            msg_box.setDefaultButton(QMessageBox.Cancel)
            msg_box.setIcon(QMessageBox.Warning)
            ret = msg_box.exec_()

            if ret == QMessageBox.Ok:
                self.bottle.delete_wine()
            else:
                return

            self.inv_table_pop()
Exemple #25
0
    def delete_bottle(self):
        # Deletes bottle from the database entirely. This is different
        # from checking out a bottle because the entire thing is removed.
        # This is permenant and dangerous, so it uses a message box to
        # confirm.
        if 'wine_id' in self.bottle.bottle_info and self.bottle.bottle_info[
                'wine_id'] != None:
            msg_box = QMessageBox()
            msg_box.setText(
                "WARNING: You are about to delete this bottle from the database. You cannot undo this. Continue?"
            )
            msg_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
            msg_box.setDefaultButton(QMessageBox.Cancel)
            msg_box.setIcon(QMessageBox.Warning)
            ret = msg_box.exec_()

            if ret == QMessageBox.Ok:
                self.bottle.delete_bottle()
            else:
                return

            self.inv_table_pop()
 def setServo(self, i):
     logger.info("User requested to set hop servo to position " + str(i))
     try:
         devicehandler.goToHopPosition(i)
     except ComponentControlError as e:
             QMessageBox.information(self, "Component Control Error", str(e))
 def decreaseServo(self):
     logger.info("User requested to decrease servo angle by 5 degrees")
     try:
         devicehandler.setHopServoPosition(self.deviceState.hopservoangle-1)
     except ComponentControlError as e:
             QMessageBox.information(self, "Component Control Error", str(e))
Exemple #28
0
def show_failed_generation_exception(exception: GenerationFailure):
    QMessageBox.critical(
        None, "An error occurred while generating a seed",
        "{}\n\nSome errors are expected to occur, please try again.".format(
            exception))
Exemple #29
0
 def newWorkspaceAction(self):
     remaining = self.timer.remainingTime()
     self.timer.stop(
     )  # timer for creating backups needs to be paused when switching ws
     if not self.editorTabs.closeAllTabs():
         self.timer.start(remaining)  # timer for saving backups is resumed
         return False
     self.workspace.proxy.closedNormally = True
     self.saveWorkspaceAction()
     workspace = WorkspaceNode()
     name = QFileDialog.getExistingDirectory(
         self, "New workspace", "select new workspace directory")
     if name:
         path = os.path.join(name, ".metadata")
         backup_path = os.path.join(name, ".backup")
         if os.path.isdir(path) or os.path.isdir(backup_path):
             self.msgInvalidFolderError(name)
             self.timer.start(
                 remaining)  # timer for saving backups is resumed
             return
         wsname = name[name.rindex(os.path.sep) + 1:]
         regex = re.compile('[@!#$%^&*()<>?/\|}{~:]')
         if ' ' in name or regex.search(wsname):
             msg = QMessageBox()
             msg.setStyleSheet("background-color: #2D2D30; color: white;")
             msg.setModal(True)
             msg.setIcon(QMessageBox.Critical)
             msg.setText(
                 "Workspace path/name cannot contain whitespace or special characters."
             )
             msg.setWindowTitle("Workspace creation error")
             msg.exec_()
             self.timer.start(
                 remaining)  # timer for saving backups is resumed
             return False
         workspace.path = name
         proxy = WorkspaceProxy()
         proxy.path = name
         workspace.proxy = proxy
         workspace.setIcon(0,
                           QIcon(resource_path("resources/workspace.png")))
         workspace.setText(0, wsname)
         self.workspace = workspace
         self.treeView.setRoot(self.workspace)
         self.saveWorkspaceAction()
         self.configurationManager.allProjects = []
         self.configurationManager.currentProject = None
         self.toolBar.updateComboBox()
         self.terminal.executeCommand("cd {}".format(self.workspace.path))
         self.workspaceConfiguration.addWorkspace(self.workspace.proxy.path)
         self.timer.start(remaining)  # timer for saving backups is resumed
         return True
     self.timer.start(remaining)  # timer for saving backups is resumed
     return False
Exemple #30
0
        data = self.ioDevice.readAll()
        availableSamples = data.size() // resolution
        start = 0
        if (availableSamples < sampleCount):
            start = sampleCount - availableSamples
            for s in range(start):
                self.buffer[s].setY(self.buffer[s + availableSamples].y())

        dataIndex = 0
        for s in range(start, sampleCount):
            value = (ord(data[dataIndex]) - 128) / 128
            self.buffer[s].setY(value)
            dataIndex = dataIndex + resolution
        self.series.replace(self.buffer)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    inputDevice = QAudioDeviceInfo.defaultInputDevice()
    if (inputDevice.isNull()):
        QMessageBox.warning(None, "audio", "There is no audio input device available.")
        sys.exit(-1)

    mainWin = MainWindow(inputDevice)
    mainWin.setWindowTitle("audio")
    availableGeometry = app.desktop().availableGeometry(mainWin)
    size = availableGeometry.height() * 3 / 4
    mainWin.resize(size, size)
    mainWin.show()
    sys.exit(app.exec_())
Exemple #31
0
    def generate_barcode(self):
        barcode_img = self.bottle.generate_label()
        msg_box = QMessageBox()
        msg_box.setText(
            "Lable has been created. Select one of the options below to continue:"
        )
        msg_box.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel)
        pr_button = msg_box.addButton('Print', QMessageBox.ApplyRole)
        msg_box.setDefaultButton(pr_button)
        ret = msg_box.exec_()

        if ret != QMessageBox.Cancel:
            if msg_box.clickedButton() == pr_button:
                self.bottle.print_label()
            elif ret == QMessageBox.Save:
                path = QFileDialog.getSaveFileName(self, "Save As...", '',
                                                   'Picture Files (*.png)')[0]
                shutil.copyfile(barcode_img + '.png', path)
 def show_help(self):
     QMessageBox.information(self, "Dynamic Layouts Help",
                         "This example shows how to change layouts "
                         "dynamically.")
Exemple #33
0
 def edit_preferences(self):
     msg_box = QMessageBox()
     msg_box.setText('Coming soon!')
     msg_box.setStandardButtons(QMessageBox.Ok)
     msg_box.exec_()
        def openMenu(position):
            # Создание PopupMenu
            menu = QMenu()
            if mode > 0:
                addAction = menu.addAction('Добавить событие')
                #menu.addSeparator()
                editAction = menu.addAction('Переименовать событие')
                #menu.addSeparator()
                delAction = menu.addAction('Удалить событие')
                delAllAction = menu.addAction('Удалить все события')
                menu.addSeparator()
            else:
                addAction, editAction, delAction, delAllAction = QAction(
                ), QAction(), QAction(), QAction()
            quitAction = menu.addAction('Выход')
            action = menu.exec_(self.mapToGlobal(position))

            # Привязка событий к Actions
            if action == addAction:
                text, ok = QInputDialog().getText(self, "Название события",
                                                  "Ввкдите название события:",
                                                  QLineEdit.Normal, '')
                if ok:
                    text = 'Новое событие' if text == '' else text
                    res = self.db.add_event({
                        'alid': self.alid,
                        'event_head': text
                    })
                    if len(res) == 1:
                        event = res[0]
                        text = event['event_head'] if type(event) == type(
                            {}
                        ) and 'event_head' in event.keys(
                        ) and event['event_head'] != '' else 'Новое событие'
                        item = QListWidgetItem(text)
                        item.setWhatsThis(str(event['eid']))
                        self.listWidget.addItem(item)
                        db.events.save()
                        #self.changed = True
                self.event_ids = db.get_all_event_ids(self.alid)

            if action == editAction:
                eid = self.listWidget.currentItem()
                if eid is not None:
                    eid = self.listWidget.currentItem().whatsThis()
                    last_name = self.db.get_event_data(self.alid,
                                                       eid)['event_head']
                    text, ok = QInputDialog().getText(
                        self, "Название события",
                        "Ввкдите новое название события:", QLineEdit.Normal,
                        str(last_name))
                    if ok:
                        event = self.db.edit_event({
                            'alid': self.alid,
                            'eid': eid,
                            'event_head': text
                        })
                        self.listWidget.currentItem().setText(text)
                        self.db.events.save()
                        if event:
                            event = self.db.get_event_data(alid, eid)
                            #b = layout.takeAt(1)
                            self.dictViewer.close()
                            #b.widget().deleteLater()
                            self.dictViewer = DictViewer(
                                event, 1, self.db.events.invizible_fields,
                                self.db.events.editable_fields)
                            self.layout.addWidget(self.dictViewer, 0, 2)
                    self.event_ids = db.get_all_event_ids(self.alid)

            if action == delAction:
                res = QMessageBox.question(
                    self, 'ВНИМАНИЕ!!!',
                    "Вы действительно хотите удалить событие?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if res == QMessageBox.Yes:
                    eid = self.listWidget.currentItem()
                    if eid is not None:
                        eid = self.listWidget.currentItem().whatsThis()
                        self.db.del_event({'alid': self.alid, 'eid': eid})
                        self.listWidget.takeItem(self.listWidget.currentRow())
                        self.db.events.save()
                        #self.changed = True
                    self.event_ids = db.get_all_event_ids(self.alid)

            if action == delAllAction:
                res = QMessageBox.question(
                    self, 'ВНИМАНИЕ!!!',
                    "Вы действительно хотите удалить все события?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if res == QMessageBox.Yes:
                    if self.db.del_all_events(int(self.alid)):
                        self.listWidget.clear()
                        self.db.events.save()
                        #self.changed = True
                    self.event_ids = db.get_all_event_ids(self.alid)

                    #db.photos.save()

            if action == quitAction:
                self.accept()
Exemple #35
0
 def handleActionHelpClicked(self):
     helpBox = QMessageBox()
     helpBox.setIcon(QMessageBox.Information)
     helpBox.setStandardButtons(QMessageBox.Ok)
     helpBox.setWindowTitle("Need Help?")
     helpBox.setText(
         "For Help, please reach out to your Instructor or TA or read the lab manual"
     )
     helpBox.setTextFormat(Qt.RichText)
     helpBox.setInformativeText(
         f"You can access the project <a href=\"{utils.docs_link}\">Manual</a> and source in the <a href=\"{utils.repo_link}\">Github Repo!</a>"
     )
     helpBox.setWindowIcon(self.appIcon)
     helpBox.exec_()
Exemple #36
0
 def onAboutQt(self):
     QMessageBox.aboutQt(None)
Exemple #37
0
 def handleActionAboutClicked(self):
     aboutBox = QMessageBox()
     aboutBox.setIcon(QMessageBox.Information)
     aboutBox.setStandardButtons(QMessageBox.Ok)
     aboutBox.setWindowTitle("About the Software")
     aboutBox.setText(utils.license_text)
     aboutBox.setWindowIcon(self.appIcon)
     aboutBox.exec_()
Exemple #38
0
 def restoreBackupMessage(self,
                          wsName,
                          failedToLoad=False,
                          updateWorkspace=False):
     try:
         msg = QMessageBox()
         msg.setStyleSheet("background-color: #2D2D30; color: white;")
         msg.setParent(None)
         msg.setModal(True)
         msg.setWindowTitle("Workspace recovery")
         time = strftime(
             '%m/%d/%Y %H:%M:%S',
             localtime(os.path.getmtime(os.path.join(wsName, ".backup"))))
         if failedToLoad:
             msg.setText("The workplace {} could not be loaded.\n"
                         "\nTime the backup was created: {}".format(
                             wsName, time))
         elif updateWorkspace:
             msg.setText(
                 "Choose if you want to reload workspace or to recover from backup.\n"
                 "\nTime the backup was created: {}".format(wsName, time))
         else:
             msg.setText("The workplace {} was closed unexpectedly.\n"
                         "\nTime the backup was created: {}".format(
                             wsName, time))
         if not updateWorkspace:
             msg.setInformativeText(
                 "Would you like to recover from backup?")
         else:
             msg.setInformativeText(
                 "Would you like to recover from backup? Select No if you just want to update the workspace."
             )
         msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
         msg.setDefaultButton(QMessageBox.Yes)
         retValue = msg.exec_()
         if retValue == QMessageBox.Yes:
             return True
         else:
             return
     except:
         return False
Exemple #39
0
 def handleActionGetRPiIPClicked(self):
     self.logger.log("Attempting to Get Raspberry Pi IP Address",
                     type="INFO")
     if not self.b_serialConnected:
         replyMessage = "Serial is not connected, Please connect serial first"
     else:
         self.executer = Executer(serialObj=self.port,
                                  loggerObj=self.logger)
         ipaddr = self.executer.executeOther("GET_IP")
         replyMessage = (
             "Raspberry Pi IP is " + ipaddr
         ) if ipaddr != ExecutionResult.FAILED else "Failed to obtain the IP Address"
     self.logger.log(replyMessage)
     ipAddrMessage = QMessageBox()
     ipAddrMessage.setIcon(QMessageBox.Information)
     ipAddrMessage.setStandardButtons(QMessageBox.Ok)
     ipAddrMessage.setWindowTitle("Raspberry Pi IP Address")
     ipAddrMessage.setText(replyMessage)
     ipAddrMessage.setTextFormat(Qt.RichText)
     ipAddrMessage.setWindowIcon(self.appIcon)
     ipAddrMessage.exec_()
Exemple #40
0
 def messageBackupError(self, msgType=None):
     msg = QMessageBox()
     msg.setStyleSheet("background-color: #2D2D30; color: white;")
     msg.setModal(True)
     msg.setIcon(QMessageBox.Critical)
     if msgType == "closedAbruptly":
         msg.setText("Failed to load {}."
                     "\nRegular workspace save will be restored.".format(
                         ".backup workspace file"))
     else:
         msg.setText("Failed to load {}.".format(".backup workspace file"))
     msg.setWindowTitle("Failed to load backup workspace.")
     msg.exec_()
Exemple #41
0
 def saveAllFiles(self, projectProxy=None):
     couldNotBeSaved = []
     for i in range(len(self.editorTabs.tabs)):
         fileProxy = self.editorTabs.tabs[i]
         try:
             if fileProxy and fileProxy.hasUnsavedChanges:
                 if projectProxy and fileProxy.parent.path != projectProxy.path:
                     continue
                 with open(fileProxy.getFilePath(), 'w') as file:
                     file.write(fileProxy.text)
                     fileProxy.hasUnsavedChanges = False
                 self.updateEditorTrie(fileProxy)
         except:
             couldNotBeSaved.append(fileProxy.path)
     self.saveWorkspaceAction()
     if couldNotBeSaved:
         msg = QMessageBox()
         msg.setStyleSheet("background-color: #2D2D30; color: white;")
         msg.setModal(True)
         msg.setIcon(QMessageBox.Critical)
         msg.setText("The following file(s) could not be saved: {}".format(
             ','.join(couldNotBeSaved)))
         msg.setWindowTitle("File save error")
         msg.exec_()
Exemple #42
0
 def msgInvalidFolderError(self, path):
     msg = QMessageBox()
     msg.setStyleSheet("background-color: #2D2D30; color: white;")
     msg.setModal(True)
     msg.setIcon(QMessageBox.Critical)
     msg.setText(
         "Invalid folder for a workspace."
         "\nEnsure there are no .metadata and .backup folders in \n{}".
         format(path))
     msg.setWindowTitle("Failed to load workspace.")
     msg.exec_()
Exemple #43
0
 def showNoCurrentProjectMessage(self, action: str):
     msg = QMessageBox()
     msg.setStyleSheet("background-color: #2D2D30; color: white;")
     msg.setModal(True)
     msg.setIcon(QMessageBox.Critical)
     msg.setText("You have to select a project first.")
     msg.setWindowTitle("{} error".format(action.capitalize()))
     msg.exec_()
Exemple #44
0
 def about(self):
     QMessageBox.about(self, "About MDI",
             "The <b>MDI</b> example demonstrates how to write multiple "
             "document interface applications using Qt.")
Exemple #45
0
 def about_qt(self):
     QMessageBox.aboutQt(self)
Exemple #46
0
 def findAction(self):
     currentTab: EditorTabWidget = self.editorTabs.getCurrentTab()
     if not currentTab:
         msg = QMessageBox()
         msg.setStyleSheet("background-color: #2D2D30; color: white;")
         msg.setModal(True)
         msg.setIcon(QMessageBox.Critical)
         msg.setText(
             "Cannot open file and replace window because there is no open file at the moment."
         )
         msg.setWindowTitle("Find & Replace error")
         msg.exec_()
         return
     currentTab.widget.find.setVisible(True)
     if currentTab.widget.editor.lastFind:
         currentTab.widget.find.findLabel.setText(
             currentTab.widget.editor.lastFind)
     currentTab.widget.find.findLabel.setFocus()
    def funcListIssues(self):
        try:
            if self.allIssuesRadioBtn.isChecked():
                self.funcDisplayIssues()
            elif self.ongoingIssuesRadioBtn.isChecked():
                query = "SELECT " \
                        "issue_id, " \
                        "issue_date, " \
                        "issue_priority, " \
                        "issue_observer," \
                        "issue_inspection, " \
                        "issue_theme, " \
                        "issue_facility, " \
                        "issue_insp_dept," \
                        "issue_deadline, " \
                        "status, " \
                        "created_on " \
                        "FROM issues WHERE status='Open' " \
                        "AND issue_deadline > DATETIME('now')"
                issues = db.cur.execute(query).fetchall()

                for i in reversed(range(self.issuesTable.rowCount())):
                    self.issuesTable.removeRow(i)

                for row_data in issues:
                    row_number = self.issuesTable.rowCount()
                    self.issuesTable.insertRow(row_number)
                    # Add checkboxes to the table
                    qwidget = QWidget()
                    checkbox = QCheckBox()
                    checkbox.setCheckState(Qt.Unchecked)
                    qhboxlayout = QHBoxLayout(qwidget)
                    qhboxlayout.addWidget(checkbox)
                    qhboxlayout.setAlignment(Qt.AlignCenter)
                    self.issuesTable.setCellWidget(row_number, 0, qwidget)
                    self.issuesTable.setItem(row_number, 0, QTableWidgetItem(row_number))
                    for column_number, data in enumerate(row_data, start=1):
                        if column_number == 1:
                            self.issuesTable.setItem(row_number, column_number,
                                                     QTableWidgetItem("ISS#" + str(data)))
                        else:
                            self.issuesTable.setItem(row_number, column_number, QTableWidgetItem(str(data)))
            elif self.lateIssuesRadioBtn.isChecked():
                query = "SELECT issue_id, " \
                        "issue_date, " \
                        "issue_priority, " \
                        "issue_observer," \
                        "issue_inspection, " \
                        "issue_theme, " \
                        "issue_facility, " \
                        "issue_insp_dept," \
                        "issue_deadline, " \
                        "status, " \
                        "created_on " \
                        "FROM issues " \
                        "WHERE status='Open' AND issue_deadline < DATETIME('now')"
                issues = db.cur.execute(query).fetchall()

                for i in reversed(range(self.issuesTable.rowCount())):
                    self.issuesTable.removeRow(i)

                for row_data in issues:
                    row_number = self.issuesTable.rowCount()
                    self.issuesTable.insertRow(row_number)
                    # Add checkboxes to the table
                    qwidget = QWidget()
                    checkbox = QCheckBox()
                    checkbox.setCheckState(Qt.Unchecked)
                    qhboxlayout = QHBoxLayout(qwidget)
                    qhboxlayout.addWidget(checkbox)
                    qhboxlayout.setAlignment(Qt.AlignCenter)
                    self.issuesTable.setCellWidget(row_number, 0, qwidget)
                    self.issuesTable.setItem(row_number, 0, QTableWidgetItem(row_number))
                    for column_number, data in enumerate(row_data, start=1):
                        if column_number == 1:
                            self.issuesTable.setItem(row_number, column_number,
                                                     QTableWidgetItem("ISS#" + str(data)))
                        else:
                            self.issuesTable.setItem(row_number, column_number, QTableWidgetItem(str(data)))
            elif self.closedIssuesRadioBtn.isChecked():
                query = "SELECT " \
                        "issue_id, " \
                        "issue_date, " \
                        "issue_priority, " \
                        "issue_observer," \
                        "issue_inspection, " \
                        "issue_theme, " \
                        "issue_facility, " \
                        "issue_insp_dept," \
                        "issue_deadline, " \
                        "status, " \
                        "created_on " \
                        "FROM issues WHERE status='Closed'"
                issues = db.cur.execute(query).fetchall()

                for i in reversed(range(self.issuesTable.rowCount())):
                    self.issuesTable.removeRow(i)

                for row_data in issues:
                    row_number = self.issuesTable.rowCount()
                    self.issuesTable.insertRow(row_number)
                    # Add checkboxes to the table
                    qwidget = QWidget()
                    checkbox = QCheckBox()
                    checkbox.setCheckState(Qt.Unchecked)
                    qhboxlayout = QHBoxLayout(qwidget)
                    qhboxlayout.addWidget(checkbox)
                    qhboxlayout.setAlignment(Qt.AlignCenter)
                    self.issuesTable.setCellWidget(row_number, 0, qwidget)
                    self.issuesTable.setItem(row_number, 0, QTableWidgetItem(row_number))
                    for column_number, data in enumerate(row_data, start=1):
                        if column_number == 1:
                            self.issuesTable.setItem(row_number, column_number,
                                                     QTableWidgetItem("ISS#" + str(data)))
                        else:
                            self.issuesTable.setItem(row_number, column_number, QTableWidgetItem(str(data)))
        except:
            QMessageBox.information(self, "Info", "Cannot access database")
Exemple #48
0
 def load(self):
     axSelect = QAxSelect(self)
     if axSelect.exec_() == QDialog.Accepted:
         clsid = axSelect.clsid()
         if not self.axWidget.setControl(clsid):
             QMessageBox.warning(self, "AxViewer", "Unable to load " + clsid + ".")
    def funcCloseIssue(self):
        indices = self.funcIssuesCheckBox()
        # Close issues with selected checkboxes
        if indices:
            try:
                for index in range(len(indices)):
                    statusQuery = "SELECT status FROM issues WHERE issue_id=?"
                    currentStatus = db.cur.execute(statusQuery, (indices[index],)).fetchone()

                    if currentStatus[0] == "Open":
                        query = "UPDATE issues SET status='Closed' WHERE issue_id=?"

                        db.cur.execute(query, (indices[index],))
                        db.conn.commit()
                    else:
                        QMessageBox.information(self, "Info", "Issue(s) is already closed")

                QMessageBox.information(self, "Info", "Operation completed successfully")
                self.funcDisplayIssues()

            except:
                QMessageBox.information(self, "Info", "Something went wrong")
        else:
            row = self.issuesTable.currentRow()
            issueId = self.issuesTable.item(row, 2).text()
            issueId = issueId.lstrip("ISS#")

            try:
                statusQuery = "SELECT status FROM issues WHERE issue_id=?"
                currentStatus = db.cur.execute(statusQuery, (issueId,)).fetchone()

                if currentStatus[0] == "Open":
                    query = "UPDATE issues SET status='Closed' WHERE issue_id=?"

                    db.cur.execute(query, (issueId,))
                    db.conn.commit()

                    QMessageBox.information(self, "Info", "Issue closed successfully")
                    self.funcDisplayIssues()
                else:
                    QMessageBox.information(self, "Info", "Issue is already closed")

            except:
                QMessageBox.information(self, "Info", "Something went wrong")
    def funcIssuesToPdf(self):
        indices = self.funcIssuesCheckBox()

        if indices:
            try:
                date = datetime.datetime.now()

                # Get file location and add timestamp it was created on to the filename
                fileName, _ = QFileDialog.getSaveFileName(
                    self, "Save as...", "~/IssuesPDF" + "{:%d%b%Y_%Hh%Mm}".format(date) + ".pdf",
                    "PDF files (*.pdf)")

                if fileName:
                    pdf = PDF()
                    pdf.add_page()
                    pdf.set_font('Arial', 'B', 13)

                    for index in range(len(indices)):
                        query = "SELECT * FROM issues WHERE issue_id=?"
                        issue_record = db.cur.execute(query, (indices[index],)).fetchone()

                        # This string allows for text formatting in the pdf, easy to implement and test
                        stringIssue = "\nIssue id: " + str(issue_record[0]) + \
                                      "\nIssue date: " + str(issue_record[1]) + \
                                      "\nPriority: " + str(issue_record[2]) + \
                                      "\nObserver: " + str(issue_record[3]) + \
                                      "\nRevision team: " + str(issue_record[4]) + \
                                      "\nInspection name: " + str(issue_record[5]) + \
                                      "\nHSE theme: " + str(issue_record[6]) + \
                                      "\nFacility: " + str(issue_record[7]) + \
                                      "\nFacility supervisor: " + str(issue_record[8]) + \
                                      "\nSpecific location: " + str(issue_record[9]) + \
                                      "\nInspected department: " + str(issue_record[10]) + \
                                      "\nInspected contractor: " + str(issue_record[11]) + \
                                      "\nInspected subcontractor: " + str(issue_record[12]) + \
                                      "\nDeadline: " + str(issue_record[13]) + \
                                      "\nStatus: " + str(issue_record[14]) + \
                                      "\nCreated on: " + str(issue_record[15]) + \
                                      "\nClosed on: " + str(issue_record[16])

                        effectivePageWidth = pdf.w - 2 * pdf.l_margin

                        ybefore = pdf.get_y()
                        pdf.multi_cell(effectivePageWidth / 2, 10, stringIssue)

                        if issue_record[18]:
                            pdf.set_xy(effectivePageWidth / 2 + pdf.l_margin, ybefore)
                            pdf.image(issue_record[18], effectivePageWidth / 2 + 20, 40, w=70)
                        pdf.ln(0.5)

                        # Page break is achieved by adding a new page
                        # after all items except for the last one
                        if index != (len(indices) - 1):
                            pdf.add_page()

                    pdf.output(fileName, 'F')

                    QMessageBox.information(self, "Info", "Data exported successfully into {}".format(fileName))

            except:
                QMessageBox.information(self, "Info", "Export failed")
        else:
            QMessageBox.information(
                self, "Info", "Nothing selected for export\nUse checkboxes to select issues to export")
Exemple #51
0
from foundry.gui.MainWindow import MainWindow


def main(path_to_rom):
    load_settings()

    app = QApplication()
    MainWindow(path_to_rom)
    app.exec_()

    save_settings()


if __name__ == "__main__":
    if len(sys.argv) > 1:
        path = sys.argv[1]
    else:
        path = ""

    try:
        main(path)
    except Exception as e:
        box = QMessageBox()
        box.setWindowTitle("Crash report")
        box.setText(
            f"An unexpected error occurred! Please contact the developers at {github_issue_link} "
            f"with the error below:\n\n{str(e)}\n\n{traceback.format_exc()}")
        box.exec_()
        raise
Exemple #52
0
import math
import numpy
import ctypes
from PySide2.QtCore import QCoreApplication, Signal, SIGNAL, SLOT, Qt, QSize, QPoint
from PySide2.QtGui import (QVector3D, QOpenGLFunctions, QOpenGLVertexArrayObject, QOpenGLBuffer,
    QOpenGLShaderProgram, QMatrix4x4, QOpenGLShader, QOpenGLContext, QSurfaceFormat)
from PySide2.QtWidgets import (QApplication, QWidget, QMessageBox, QHBoxLayout, QSlider,
    QOpenGLWidget)
from PySide2.shiboken2 import VoidPtr

try:
    from OpenGL import GL
except ImportError:
    app = QApplication(sys.argv)
    messageBox = QMessageBox(QMessageBox.Critical, "OpenGL hellogl",
                                         "PyOpenGL must be installed to run this example.",
                                         QMessageBox.Close)
    messageBox.setDetailedText("Run:\npip install PyOpenGL PyOpenGL_accelerate")
    messageBox.exec_()
    sys.exit(1)


class Window(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.glWidget = GLWidget()

        self.xSlider = self.createSlider(SIGNAL("xRotationChanged(int)"),
                                         self.glWidget.setXRotation)
        self.ySlider = self.createSlider(SIGNAL("yRotationChanged(int)"),
Exemple #53
0
    def closeEvent(self, event):
        """It requests the user's confirmation to close the system."""
        box = QMessageBox(self)
        box.setIcon(QMessageBox.Question)
        box.setWindowTitle(App._text['close_window'])
        box.setText(App._text['msg_close_window'])
        box.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
        btn_y = box.button(QMessageBox.Yes)
        btn_y.setText(App._text['yes'])
        btn_n = box.button(QMessageBox.No)
        btn_n.setText(App._text['no'])
        box.exec_()

        if box.clickedButton() == btn_y:
            event.accept()
        else:
            event.ignore()
Exemple #54
0
    def handleActionUpdateRPiScript(self):
        self.logger.log(
            'Attempting to "git pull" for the Raspberry Pi Python Script',
            type="INFO")
        if not self.b_serialConnected:
            replyMessage = "Serial is not connected, Please connect serial first"
        else:
            self.executer = Executer(serialObj=self.port,
                                     loggerObj=self.logger)
            result = self.executer.executeOther("UPDATE_SCRIPT")
            if result != ExecutionResult.FAILED and "FAIL" not in result:
                replyMessage = "Raspberry Pi Script has been updated. You still need to reboot or power cycle the Raspberry Pi for the updated script to run" \
                                    "\nReceived: " + result
            else:
                replyMessage = "Failed to update the RPi Script"
                if "FAIL" in str(result):
                    replyMessage = replyMessage + "\nReceived: " + str(result)

        self.logger.log(replyMessage)
        ipAddrMessage = QMessageBox()
        ipAddrMessage.setIcon(QMessageBox.Information)
        ipAddrMessage.setStandardButtons(QMessageBox.Ok)
        ipAddrMessage.setWindowTitle("Raspberry Pi Script Updating Status")
        ipAddrMessage.setText(replyMessage)
        ipAddrMessage.setTextFormat(Qt.RichText)
        ipAddrMessage.setWindowIcon(self.appIcon)
        ipAddrMessage.exec_()
Exemple #55
0
 def saveFileAction(self):
     if len(self.editorTabs.tabs):
         proxy = self.editorTabs.getCurrentFileProxy()
         if proxy and proxy.hasUnsavedChanges:
             try:
                 with open(proxy.getFilePath(), 'w') as file:
                     file.write(proxy.text)
                     proxy.hasUnsavedChanges = False
                 self.updateEditorTrie(proxy)
             except:
                 msg = QMessageBox()
                 msg.setStyleSheet(
                     "background-color: #2D2D30; color: white;")
                 msg.setModal(True)
                 msg.setIcon(QMessageBox.Critical)
                 msg.setText(
                     "The following file could not be saved: {}".format(
                         proxy.path))
                 msg.setWindowTitle("File save error")
                 msg.exec_()
         self.saveWorkspaceAction()
         return True
    def loadFile(self, path):
        """
         Attempts to load the file at path
        """
        error = False
        if path[-5:] == '.proj':
            try:
                # Load dictionary from file
                with open(path, 'rb') as f:
                    p = pickle.Unpickler(f)
                    d = p.load()

                if not p:
                    # file is empty
                    error = True  # Checks if file is empty

                else:
                    self.techID = d['techID']
                    self.ui.techID.setText(str(self.techID))
                    self.ui.techIDbutton.setChecked(True)

                    for tab in range(0, 1):  # TODO: Change
                        machine = self.machines[tab]

                        # Load all values
                        startTime = d[tab]['startTime']
                        endTime = d[tab]['endTime']
                        loadTime = d[tab]['loadTime']
                        unloadTime = d[tab]['unloadTime']
                        cdn = d[tab]['cdn']
                        testRun = d[tab]['testRun']
                        coatingRun = d[tab]['coatingRun']
                        loadingRun = d[tab]['loadingRun']
                        setupRun = d[tab]['setupRun']

                        # Check if they exist
                        if startTime:
                            machine.startTime = startTime

                            time = QTime().fromString(startTime)
                            tmp = 'self.ui.startTime'
                            but = 'self.ui.stButton'
                            if tab in (1, 2):
                                tmp += '_' + str(tab + 1)
                                but += '_' + str(tab + 1)
                            exec(tmp + '.setTime(time)')
                            exec(but + '.setChecked(True)')

                        if endTime:
                            machine.endTime = endTime

                            time = QTime().fromString(endTime)
                            tmp = 'self.ui.endTime'
                            but = 'self.ui.etButton'
                            if tab in (1, 2):
                                tmp += '_' + str(tab + 1)
                                but += '_' + str(tab + 1)
                            exec(tmp + '.setTime(time)')
                            exec(but + '.setChecked(True)')

                        if loadTime:
                            machine.loadTime = loadTime

                            time = QTime().fromString(loadTime)
                            tmp = 'self.ui.loadTime'
                            but = 'self.ui.ltButton'
                            if tab in (1, 2):
                                tmp += '_' + str(tab + 1)
                                but += '_' + str(tab + 1)
                            exec(tmp + '.setTime(time)')
                            exec(but + '.setChecked(True)')

                        if unloadTime:
                            machine.unloadTime = unloadTime

                            time = QTime().fromString(unloadTime)
                            tmp = 'self.ui.unloadTime'
                            but = 'self.ui.utButton'
                            if tab in (1, 2):
                                tmp += '_' + str(tab + 1)
                                but += '_' + str(tab + 1)
                            exec(tmp + '.setTime(time)')
                            exec(but + '.setChecked(True)')

                        if cdn:  # If there's the cdn, the other 4 are there too
                            machine.cdn = cdn
                            machine.testRun = testRun
                            machine.coatingRun = coatingRun
                            machine.loadingRun = loadingRun
                            machine.setupRun = setupRun

                            cdnBox = 'self.ui.cdn'
                            testBox = 'self.ui.testRun'
                            coatBox = 'self.ui.coatRun'
                            loadBox = 'self.ui.loadingRun'
                            setupBox = 'self.ui.setupTestRun'
                            vButton = 'self.ui.validateButton'

                            if tab in (1, 2):
                                cdnBox += '_' + str(tab + 1)
                                testBox += '_' + str(tab + 1)
                                coatBox += '_' + str(tab + 1)
                                loadBox += '_' + str(tab + 1)
                                setupBox += '_' + str(tab + 1)
                                vButton += '_' + str(tab + 1)

                            codeList = [
                                cdnBox + '.setText(str(cdn))',
                                testBox + '.setText(str(testRun))',
                                coatBox + '.setText(str(coatingRun))',
                                loadBox + '.setText(str(loadingRun))',
                                setupBox + '.setText(str(setupRun))',
                                vButton + '.setChecked(True)'
                            ]

                            code = '\n'.join(codeList)
                            exec(code)

                        # Initialize planets
                        for planetNum in d[tab]['planets']:
                            sum = d[tab]['planets'][planetNum]
                            if sum:
                                pie = 'self.ui.pie' + str(planetNum) + 'series'
                                if tab in (1, 2):
                                    pie += '_' + str(tab + 1)
                                exec(pie + '.setEnabled(sum)')

                        sortedWOList = []
                        for woName in d[tab]['workOrders']:
                            params = d[tab]['workOrders'][woName]

                            wo = WorkOrder()
                            wo.name = woName
                            wo.machineNum = tab + 1
                            wo.pieces = params[0]
                            wo.side = params[1]
                            wo.planetNum = params[2]
                            if params[3]:
                                wo.setYield(params[3])

                            sortedWOList.append(wo)
                        sortedWOList.sort(
                            key=lambda workOrder: int(workOrder.name[4:]))

                        unsuccessful = []
                        for wo in sortedWOList:
                            success = self.addToPlanets(wo)
                            if success:
                                self.results.addRowFor(wo)
                                self.machines[wo.machineNum -
                                              1].workOrders.append(wo)
                            else:
                                unsuccessful.append(wo)
                        if unsuccessful:
                            for wo in unsuccessful:
                                print(wo.name)
            except Exception as e:
                raise e
        else:
            # not a proj file
            error = True

        if error:
            title = "Error Loading Project"
            message = "Could not load the selected file successfully."
            buttons = QMessageBox.Ok
            message = QMessageBox(QMessageBox.Warning,
                                  title,
                                  message,
                                  buttons=buttons,
                                  flags=Qt.Dialog)
            message.exec_()
Exemple #57
0
def main():
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    QMessageBox.information(None, "Info", "Just drag and drop the items.")
    sys.exit(app.exec_())