示例#1
0
class PlayersWidget(QWidget):
    def __init__(self):
        factory = ApiRequestFactory.get_instance()
        QWidget.__init__(self)

        page_list = factory.get_players_from_page(1)

        self.layout = QVBoxLayout()

        label_widget = QWidget()
        label_widget.layout = QVBoxLayout()
        for page_obj in page_list[0]:
            for pl in page_obj[1]:
                lb_text = pl.first_name + ' ' + pl.last_name

                if pl.position is not None and (pl.position is not ''
                                                or pl.position is not ' '):
                    lb_text = lb_text + ': ' + pl.position

                player_lb = QLabel(text=lb_text)
                label_widget.layout.addWidget(player_lb)

        label_widget.setLayout(label_widget.layout)

        self.scroll_widget = QScrollArea()
        self.scroll_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scroll_widget.setBackgroundRole(QPalette.Light)
        self.scroll_widget.setWidgetResizable(True)

        self.scroll_widget.setWidget(label_widget)
        self.layout.addWidget(self.scroll_widget)

        self.setLayout(self.layout)
 def make_tab(self, title):
     area = QScrollArea()
     field = Field(area, title)
     area.setBackgroundRole(QPalette.Mid)
     area.setWidgetResizable(True)
     area.setWidget(self.add_fields(self, title, field))
     self.fields.append(field)
     return area
    def home(self):
        """
        Add the GUI elements to the window that represent the home state of the application.
        """
        toolbar = self.addToolBar("File")
        save = QAction(QIcon("res/icon_save.png"), "Save", self)
        save.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_S))
        toolbar.addAction(save)
        load = QAction(QIcon("res/icon_load.png"), "Load", self)
        load.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_O))
        toolbar.addAction(load)
        toolbar.addSeparator()
        undo = QAction(QIcon("res/icon_undo.png"), "Undo", self)
        undo.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Z))
        toolbar.addAction(undo)
        redo = QAction(QIcon("res/icon_redo.png"), "Redo", self)
        redo.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Y))
        toolbar.addAction(redo)
        toolbar.addSeparator()
        zoom_in = QAction(QIcon("res/icon_zoom_in.png"), "Zoom In", self)
        toolbar.addAction(zoom_in)
        zoom_out = QAction(QIcon("res/icon_zoom_out.png"), "Zoom Out", self)
        toolbar.addAction(zoom_out)
        toolbar.addSeparator()
        clear = QAction(QIcon("res/icon_clear.png"), "Clear", self)
        toolbar.addAction(clear)
        toolbar.addSeparator()
        grid = QAction(QIcon("res/icon_grid.png"), "Grid", self)
        toolbar.addAction(grid)
        toolbar.actionTriggered[QAction].connect(self.toolbar_pressed)

        splitter = QSplitter(self)
        splitter.setOrientation(Qt.Vertical)
        splitter.setHandleWidth(16)

        self.tile_ed = TileEd(self.size, self.tile_size, self.pixmap, self)
        scroll_area_tile_ed = QScrollArea()
        scroll_area_tile_ed.setBackgroundRole(QPalette.Dark)
        scroll_area_tile_ed.setWidgetResizable(True)
        scroll_area_tile_ed.setWidget(self.tile_ed)

        splitter.addWidget(scroll_area_tile_ed)

        self.tile_sel = TileSelector(self.tile_size, self.pixmap, self)
        scroll_area_tile_sel = QScrollArea()
        scroll_area_tile_sel.setBackgroundRole(QPalette.Dark)
        scroll_area_tile_sel.setWidgetResizable(True)
        scroll_area_tile_sel.setWidget(self.tile_sel)

        splitter.addWidget(scroll_area_tile_sel)
        self.setCentralWidget(splitter)
class AdjustChunkBrightContrastDlg(QtWidgets.QDialog):
    # path = ''
    # image = Image

    def __init__(self, parent):

        QtWidgets.QDialog.__init__(self, parent)
        self.setWindowTitle(
            "ADJUST PHOTOS BRIGHTNESS - CONTRAST, CMG (MAROC)")

        # self.adjustSize()
        self.setMaximumHeight(880)
        self.createParamsGridLayout()
        self.createButtonsGridLayout()
        self.createProgressBar()
        self.createImageViewerLayout()

        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.groupBoxParams)
        vbox.addWidget(self.groupBoxViewer)
        vbox.addWidget(self.groupBoxProgressBar)
        vbox.addWidget(self.groupBoxButtons)

        self.setLayout(vbox)

        self.exec()

    def createImageViewerLayout(self):

        self.groupBoxViewer = QtWidgets.QGroupBox()

        gridViewerLayout = QtWidgets.QGridLayout()
        self.scaleFactor = 0.0
        self.imageLabel = QtWidgets.QLabel(self)
        self.imageLabel.setBackgroundRole(QtGui.QPalette.Base)
        self.imageLabel.setSizePolicy(
            QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)

        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.imageLabel)
        self.scrollArea.setMinimumHeight(605)
        # self.scrollArea.setMaximumHeight(605)

        self.scrollArea.setMinimumWidth(830)
        self.scrollArea.setMaximumWidth(830)

        self.getChunk()

        self.getPaths()

        self.getImage(0)

        self.scrollArea.setWidgetResizable(False)
        self.normalSize()
        self.scaleImage(0.16)

        gridViewerLayout.addWidget(self.scrollArea, 1, 0)
        self.createViewerButtons()
        gridViewerLayout.addWidget(self.groupBoxViewerBtn, 0, 0)
        self.groupBoxViewer.setLayout(gridViewerLayout)

    def createViewerButtons(self):
        self.groupBoxViewerBtn = QtWidgets.QGroupBox()

        gridViewerBtnLayout = QtWidgets.QGridLayout()

        self.btnNextPhoto = QtWidgets.QPushButton("->")
        self.btnNextPhoto.setFixedSize(23, 23)

        self.btnPreviousPhoto = QtWidgets.QPushButton("<-")
        self.btnPreviousPhoto.setFixedSize(23, 23)

        self.btnZoomIn = QtWidgets.QPushButton("+")
        self.btnZoomIn.setFixedSize(23, 23)

        self.btnZoomOut = QtWidgets.QPushButton("-")
        self.btnZoomOut.setFixedSize(23, 23)

        # self.btnZoomOut = QtWidgets.QPushButton("-")
        # self.btnZoomOut.setFixedSize(23, 23)

        gridViewerBtnLayout.addWidget(self.btnZoomIn, 0, 0)
        gridViewerBtnLayout.addWidget(self.btnZoomOut, 0, 1)

        gridViewerBtnLayout.addWidget(self.btnPreviousPhoto, 0, 3)
        gridViewerBtnLayout.addWidget(self.btnNextPhoto, 0, 4)

        QtCore.QObject.connect(
            self.btnZoomIn, QtCore.SIGNAL("clicked()"),  self.zoomIn)

        QtCore.QObject.connect(
            self.btnZoomOut, QtCore.SIGNAL("clicked()"),  self.zoomOut)
        QtCore.QObject.connect(
            self.btnNextPhoto, QtCore.SIGNAL("clicked()"),  self.nextPhoto)
        QtCore.QObject.connect(
            self.btnPreviousPhoto, QtCore.SIGNAL("clicked()"),  self.previousPhoto)

        self.groupBoxViewerBtn.setLayout(gridViewerBtnLayout)

    def createButtonsGridLayout(self):

        self.groupBoxButtons = QtWidgets.QGroupBox()

        gridBtnLayout = QtWidgets.QGridLayout()

        self.btnQuit = QtWidgets.QPushButton("Cancel")
        self.btnQuit.setFixedSize(150, 23)

        self.btnSubmit = QtWidgets.QPushButton("OK")
        self.btnSubmit.setFixedSize(150, 23)

        gridBtnLayout.addWidget(self.btnSubmit, 0, 0)
        gridBtnLayout.addWidget(self.btnQuit, 0, 1)
        self.btnSubmit.setEnabled(False)
        QtCore.QObject.connect(self.btnQuit, QtCore.SIGNAL(
            "clicked()"), self, QtCore.SLOT("reject()"))

        QtCore.QObject.connect(
            self.btnSubmit, QtCore.SIGNAL("clicked()"), self.adjustChunkPhotos)

        self.groupBoxButtons.setLayout(gridBtnLayout)

    def createParamsGridLayout(self):
        self.groupBoxParams = QtWidgets.QGroupBox('Adjustment parameters')

        gridParamsLayout = QtWidgets.QGridLayout()
        gridParamsLayout.setHorizontalSpacing(50)
        self.label_chunk = QtWidgets.QLabel('Chunk : ')

        self.chunksBox = QtWidgets.QComboBox()
        self.chunksBox.resize(200, 23)

        self.getChunks()
        for chunk in self.chunks:
            self.chunksBox.addItem(chunk.label, chunk.key)

        self.label_brightness = QtWidgets.QLabel('Image brightness (%): ')
        self.brightness = QtWidgets.QSpinBox()
        self.brightness.setMaximum(500)
        self.brightness.setSingleStep(20)
        self.brightness.setMinimum(0)
        self.brightness.setValue(100)

        self.label_contrast = QtWidgets.QLabel('Image contrast (%): ')
        self.contrast = QtWidgets.QSpinBox()
        self.contrast.setMaximum(500)
        self.contrast.setSingleStep(20)
        self.contrast.setMinimum(0)
        self.contrast.setValue(100)

        self.label_folder = QtWidgets.QLabel('Select folder  : ')
        self.btn_select_folder = QtWidgets.QPushButton("Select...")
        self.btn_select_folder.setFixedSize(150, 23)
        self.path_label = QtWidgets.QLabel('Selected Path : ...')

        self.space = QtWidgets.QLabel('         ')

        self.chunk_create_label = QtWidgets.QLabel("Create new Chunk")

        self.chkCreateChunk = QtWidgets.QCheckBox()
        self.chkCreateChunk.setChecked(True)
        # adding widget
        gridParamsLayout.addWidget(self.label_chunk, 0, 0)
        gridParamsLayout.addWidget(self.chunksBox, 0, 1)
        gridParamsLayout.addWidget(self.label_folder, 0, 2)
        gridParamsLayout.addWidget(self.btn_select_folder, 0, 3)

        gridParamsLayout.addWidget(self.label_brightness, 1, 0)
        gridParamsLayout.addWidget(self.brightness, 1, 1)
        gridParamsLayout.addWidget(self.path_label, 1, 2)

        gridParamsLayout.addWidget(self.label_contrast, 2, 0)
        gridParamsLayout.addWidget(self.contrast, 2, 1)

        gridParamsLayout.addWidget(self.chunk_create_label, 2, 2)
        gridParamsLayout.addWidget(self.chkCreateChunk, 2, 3)
        QtCore.QObject.connect(
            self.btn_select_folder, QtCore.SIGNAL("clicked()"), self.selectFolder)

        self.chunksBox.currentIndexChanged.connect(self.getChunk)
        self.brightness.valueChanged.connect(self.getPixmapFromEnhance)
        self.contrast.valueChanged.connect(self.getPixmapFromEnhance)
        self.groupBoxParams.setLayout(gridParamsLayout)

    def createProgressBar(self):
        self.groupBoxProgressBar = QtWidgets.QGroupBox()
        gridProgressBar = QtWidgets.QGridLayout()

        self.progressBar = QtWidgets.QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)

        gridProgressBar.addWidget(self.progressBar, 0, 0)
        self.groupBoxProgressBar.setLayout(gridProgressBar)

    def zoomIn(self):

        self.scaleImage(1.25)

    def zoomOut(self):

        self.scaleImage(0.8)

    def normalSize(self):
        self.imageLabel.adjustSize()
        self.scaleFactor = 1.0

    def scaleImage(self, factor):
        self.scaleFactor *= factor
        self.imageLabel.resize(
            self.scaleFactor * self.imageLabel.pixmap().size())

        self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
        self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)

    def adjustScrollBar(self, scrollBar, factor):
        scrollBar.setValue(int(factor * scrollBar.value()
                               + ((factor - 1) * scrollBar.pageStep()/2)))

    def fitToWindow(self, fitToWindow):

        self.scrollArea.setWidgetResizable(fitToWindow)
        if not fitToWindow:
            self.normalSize()

    def getChunks(self):
        self.chunks = Metashape.app.document.chunks

        if len(self.chunks) == 0:
            Metashape.app.messageBox('No chunk in project')

    def getChunk(self):
        chunk_key = self.chunksBox.currentData()
        self.chunk = doc.findChunk(chunk_key)
        self.brightness.setValue(100)
        self.contrast.setValue(100)
        self.getPaths()
        self.getImage(0)

    def selectFolder(self):

        directoryPath = QtWidgets.QFileDialog.getExistingDirectory(
            self, "Select Directory")
        dossier = directoryPath.split('/')[-1]
        path = 'Selected Path : {}'.format(directoryPath)
        self.path_label.setText(path)
        self.btnSubmit.setEnabled(True)
        self.path_folder = directoryPath

    def getPaths(self):
        self.paths = []
        for c in self.chunk.cameras:
            path = c.photo.path
            self.paths.append(path)

        if len(self.paths) == 0:
            Metashape.app.messageBox('No photos in this chunk')

    def getImage(self, index):
        self.path_photo = self.paths[index]

        self.image = QtGui.QPixmap(self.path_photo)

        self.imageLabel.setPixmap(self.image)

    def nextPhoto(self):

        index = self.paths.index(self.path_photo)
        if index == len(self.paths) - 1:
            index = 0
        else:
            index = index + 1
        self.path_photo = self.paths[index]
        self.getPixmapFromEnhance()

    def previousPhoto(self):
        index = self.paths.index(self.path_photo)
        if index == 0:
            index = len(self.paths) - 1
        else:
            index = index - 1
        self.path_photo = self.paths[index]
        self.getPixmapFromEnhance()

    def adjustImage(self, image):
        brghitness = self.brightness.value() / 100
        contrast = self.contrast.value() / 100

        imageEnhancer = ImageEnhance.Brightness(image)
        imgBright = imageEnhancer.enhance(brghitness)

        imageEnhancer = ImageEnhance.Contrast(imgBright)
        imgContrast = imageEnhancer.enhance(contrast)

        return imgContrast

    def getPixmapFromEnhance(self):

        image = Image.open(self.path_photo)

        img = self.adjustImage(image)

        self.image = img.toqimage()
        self.image = QtGui.QPixmap(self.image)
        self.imageLabel.setPixmap(self.image)
        image.close()

    def get_exif(self, image):

        exif = image._getexif()

        return exif

    def add_new_chunk(self, images):
        doc = Metashape.app.document
        new_chunk = doc.addChunk()
        new_chunk.label = 'Adjusted ' + self.chunk.label
        new_chunk.addPhotos(images)

    def copyPhots(self, c):
        self.i = self.i + 1
        self.progressBar.setValue(self.i)
        source = c.photo.path
        destination = self.path_folder

        path_without_drive = os.path.splitdrive(source)[1]
        subfolder = os.path.splitext(path_without_drive)[0]
        path_to_photo = os.path.split(path_without_drive)[0]

        folders = path_to_photo.split('/')
        path_dist = destination + path_to_photo

        path_dist = path_dist.replace(self.commun_without_drive, '')

        try:
            if not os.path.exists(path_dist):
                os.makedirs(path_dist)

            image = Image.open(source)
            exif = self.get_exif(image)

            enhancer = self.adjustImage(image)

            path = path_dist + '/' + c.label + '.jpg'
            enhancer.save(
                path, exif=image.info["exif"])

            self.imageList.append(path)
            image.close()

        except RuntimeError:
            Metashape.app.messageBox('error')

    def adjustChunkPhotos(self):
        print("Import Adjust Photos Script started...")

        self.imageList = []
        commun = os.path.commonpath(self.paths)
        commun_without_drive = os.path.splitdrive(commun)[1]
        self.commun_without_drive = commun_without_drive.replace('\\', '/')
        total = len(self.chunk.cameras)
        self.progressBar.setMaximum(total)
        self.i = 0

        # with concurrent.futures.ThreadPoolExecutor() as executor:
        #     executor.map(self.copyPhots, self.chunk.cameras)

        for c in self.chunk.cameras:

            self.copyPhots(c)
            QtWidgets.QApplication.processEvents()

        if self.chkCreateChunk.isChecked():

            self.add_new_chunk(self.imageList)
        self.close()
        print("Script finished!")
        # Metashape.app.messageBox('Adjusting and Copy  successful !')
        return True
示例#5
0
class PrettySL(QWidget):
    """
    This is the base widget to contain the graph view of the cutscene.

    :param MainFrame mainframe: application mainframe
    :param QWidget op: parent widget
    """
    def __init__(self, mainframe, op):
        QWidget.__init__(self)
        self.mainframe = mainframe
        self.op = op
        self.graph = self.op.link
        self.table = self.op.link.items
        self.lastButtonPressed = None
        self.needsRefresh = False
        self.tree = None
        self.subtree = []
        self.delete = None

        # View initializations...
        self.lab = None
        self.idLabel = None
        self.edit = None
        self.lkst = None
        self.rels = None

        self.initData()
        self.initUI()

    def initData(self):
        """
        Initialize the data to be used.
        """
        self.lab = None
        self.actionIDs = self.graph.getIDs()
        self.actionObjs = []
        for act in self.table:
            self.actionObjs.append(act[0])

    def initUI(self):
        """
        Initializes the GUI.
        Does lots of stuff.
        """
        self.grid = QGridLayout()
        self.setLayout(self.grid)

        self.tree = TreeWidget(self, self.actionObjs, self.actionIDs,
                               self.table)

        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.tree)
        if self.tree.rect().width() < 600:
            self.scrollArea.setFixedWidth(self.tree.rect().width() + 25)
        else:
            self.scrollArea.setFixedWidth(600)
        if self.tree.rect().height() < 600:
            self.scrollArea.setFixedHeight(self.tree.rect().height())
        else:
            self.scrollArea.setFixedHeight(600)
        self.scrollArea.ensureWidgetVisible(self.tree, 500, 500)

        self.grid.addWidget(self.scrollArea, 0, 0, 10, 3)

        self.legend = Legend(self)
        self.grid.addWidget(self.legend, 0, 3, 1, 2)

        self.setWindowModality(Qt.ApplicationModal)
        self.show()

    def trackIndex(self, index):
        """
        Update the Tree and info views with a new index.

        :param int index: the new index
        """
        self.needsRefresh = True
        self.lastButtonPressed = index
        self.subtree = self.graph.subTree(index)
        # Request all the lines and boxes be redrawn.
        self.tree.update()
        self.initInfoUI(index)

    def deleteSubtree(self):
        """
        Delete the subtree of the current selected index.
        """
        if not popup(
                "Are you certain you want to delete this item and it's subtree?\n(Everything in red and"
                " yellow will be deleted)", "Warning"):
            return
        self.graph.delItem(self.lastButtonPressed)
        self.lab.close()
        self.initData()
        self.lastButtonPressed = None
        self.delete.close()
        self.delete = None
        self.subtree = []
        self.needsRefresh = True
        self.idLabel.close()
        self.edit.clicked.disconnect()
        self.edit.close()
        self.op.linkstored.save()
        self.tree.close()
        self.tree = TreeWidget(self, self.actionObjs, self.actionIDs,
                               self.table)
        self.grid.addWidget(self.tree, 0, 0, 10, 3)

    def initInfoUI(self, index):
        """
        Initialize the node info GUI.
        Does a lot of stuff.

        :param int index: index of node to display info for
        """
        if not self.lab:
            self.lab = QLabel(self, text="Selected element summary:")
            self.grid.addWidget(self.lab, 2, 3, 1, 2)
            idt = ""
            if isinstance(self.table[index][0], Speak):
                idt += self.table[index][0].speaker + " says:\n\n"
            idt += self.actionIDs[index]
            self.idLabel = QLabel(self, text=idt)
            self.idLabel.setFixedSize(300, 40)
            self.idLabel.setWordWrap(True)
            self.grid.addWidget(self.idLabel, 3, 3, 1, 2)
            self.edit = QPushButton(self, text="Edit")
            self.edit.clicked.connect(lambda: self.enter(index))
            self.grid.addWidget(self.edit, 4, 3, 1, 2)
            self.lkst = QLabel(self, text="Selected element links to:")
            self.grid.addWidget(self.lkst, 5, 3, 1, 2)
            self.rels = QLabel(self)
            self.rels.setMaximumWidth(300)
            text = ""
            for relation in self.table[index][1:len(self.table[index])]:
                text += "(" + str(relation) + ") " + self.graph.getOneID(
                    self.table[relation][0]) + "\n\n"
            self.rels.setText(text)
            self.grid.addWidget(self.rels, 6, 3, 1, 2)
        else:
            text = ""
            idt = ""
            if isinstance(self.table[index][0], Speak):
                idt += self.table[index][0].speaker + " says:\n\n"
            idt += self.actionIDs[index]
            self.idLabel.setText(idt)
            for relation in self.table[index][1:len(self.table[index])]:
                text += "(" + str(relation) + ") " + self.graph.getOneID(
                    self.table[relation][0]) + "\n\n"
            self.rels.setText(text)
            self.edit.clicked.disconnect()
            self.edit.clicked.connect(lambda: self.enter(index))
        if not self.delete:
            self.delete = QPushButton(self, text="Delete element and subtree")
            self.delete.clicked.connect(self.deleteSubtree)
            self.grid.addWidget(self.delete, 1, 3, 1, 2)

    def enter(self, index):
        """
        Leave the graph view and edit a node.

        :param int index: index of node to edit
        """
        load = self.graph.getItem(index)
        self.close()
        self.op.view.setText("Graphic View")
        self.op.view.clicked.disconnect()
        self.op.view.clicked.connect(lambda: self.op.viewF(True))
        self.op.listview.changeFrame(load, index)
示例#6
0
class DatasheetView(QMainWindow):
    def __init__(self, pdfPath=None, openPages=[1]):

        super().__init__()

        if pdfPath:
            self.myPdfContext = PDFContext(pdfPath, openPages)

        # store diretory for debugging purposes
        self.svgDirectory = self.myPdfContext.directory

        # window dimensions
        self.top = 300
        self.left = 800
        self.width = 860
        self.height = 980

        self.setGeometry(self.left, self.top, self.width, self.height)

        # window title
        self.setWindowTitle("BetterSheets")

        # sets up main layout -- splitters
        self.initUILayout()
        self.initUIToolbar()
        self.initToC()

        # self.initPdfViewer()  # must be called after initUI to ensure PDFContext object exists
        self.show()

        print(self.mainDisplay.getVisibleChild())

    def initUILayout(self):

        # set left-side, Dynamic View
        self.dynamicViewDisplay = QLabel()

        self.vBoxA = QVBoxLayout()
        self.vBoxA.addWidget(self.dynamicViewDisplay)

        self.groupA = QGroupBox()
        self.groupA.setTitle("Dynamic Veiw")
        self.groupA.setLayout(self.vBoxA)

        # set left-side, Static View
        self.staticViewDisplay = QLabel()

        self.vBoxB = QVBoxLayout()
        self.vBoxB.addWidget(self.staticViewDisplay)

        self.groupB = QGroupBox()
        self.groupB.setTitle("Static View")
        self.groupB.setLayout(self.vBoxB)

        # add Dynamic and Static Views to resizeable left-side Splitter
        self.altViewSplit = QSplitter(Qt.Vertical)
        self.altViewSplit.addWidget(self.groupA)
        self.altViewSplit.addWidget(self.groupB)

        # set up Tools View section
        self.toolsTabView = QTabWidget()
        self.toolsTabView.setTabsClosable(True)
        self.toolsTabView.setMovable(True)
        self.toolsTabView.setDocumentMode(True)
        # self.toolsTabView.setTabBarAutoHide(True)

        # add attribute for storing page notes
        self.notesDB = []
        self.notesDisplay = QListWidget(self)
        self.notesDisplay.setMaximumHeight(200)

        # add ToC to Tools View
        self.ToCListView = QListWidget()
        self.toolsTabView.addTab(self.ToCListView, "Table of Contents")

        # add notes list to tools view
        self.toolsTabView.addTab(self.notesDisplay, "Notes")

        # add tools view to the left-side splitter
        self.altViewSplit.addWidget(self.toolsTabView)

        # set up main viewport
        self.mainDisplay = QDatasheetPageDisplayWidget(self.myPdfContext)
        self.mainDisplay.renderPages(1, 4)

        self.mainScroller = QScrollArea(self)
        self.mainScroller.setWidget(self.mainDisplay)
        self.mainScroller.setWidgetResizable(True)
        self.mainScroller.setBackgroundRole(QtGui.QPalette.Dark)
        self.mainScroller.setFixedHeight(800)

        print(self.mainScroller.viewport().childrenRect())

        # set up document tools

        self.hBoxDocTools = QHBoxLayout()

        self.searchLabel = QLabel("Search: ")
        self.searchBox = QLineEdit()
        self.searchBox.setPlaceholderText("Search")

        # self.

        self.vBoxMain = QVBoxLayout()
        self.vBoxMain.addWidget(self.mainScroller)

        self.notesArea = QLineEdit()
        self.notesArea.setPlaceholderText("Add a note about this page...")
        self.notesArea.returnPressed.connect(self.onAddNote)

        self.vBoxMain.addWidget(self.notesArea)

        self.mainViewGroup = QGroupBox()
        self.mainViewGroup.setTitle("Main View")
        self.mainViewGroup.setLayout(self.vBoxMain)

        # join both sides together
        self.leftRightSplit = QSplitter(Qt.Horizontal)
        self.leftRightSplit.addWidget(self.altViewSplit)
        self.leftRightSplit.addWidget(self.mainViewGroup)

        self.setCentralWidget(self.leftRightSplit)

    def initUIToolbar(self):

        mainMenu = self.menuBar(
        )  # get the menu bar already in use by this QMainWindow subclass

        fileMenu = mainMenu.addMenu("File")
        editMenu = mainMenu.addMenu("Edit")
        LayoutMenu = mainMenu.addMenu("Layout")
        AboutMenu = mainMenu.addMenu("About")

        saveAction = fileMenu.addAction("Save")
        quitAction = fileMenu.addAction("Exit Bettersheets")
        quitAction.triggered.connect(self.quitApp)
        copyAction = editMenu.addAction("Copy")
        resetAction = LayoutMenu.addAction("Reset Default Layout")

        self.toolBar = self.addToolBar("Tools")
        self.toolBar.addAction(saveAction)
        self.toolBar.addAction(copyAction)

    def contextMenuEvent(self, event):
        # return super().contextMenuEvent(event)
        contextMenu = QMenu()

        selectAction = contextMenu.addAction("Select Area")
        extractAction = contextMenu.addAction("Extract Content")
        openAction = contextMenu.addAction("Open PDF")
        closeAction = contextMenu.addAction("Close PDF")
        quitAction = contextMenu.addAction("Quit")

        triggered_action = contextMenu.exec_(self.mapToGlobal(event.pos()))

        if triggered_action == quitAction:
            self.quitApp()

    def quitApp(self):
        self.close()

    def onAddNote(self):
        print("note added")

        text = self.notesArea.text()

        if text:
            self.notesDB.append(text)
            self.notesDisplay.clear()
            self.notesDisplay.addItems(self.notesDB)
            self.notesArea.clear()

    def initPdfViewer(self, openPages: int):
        pass

    def initToC(self):

        # get table of contents
        ToC = self.myPdfContext.getToC()
        ToC_headings_list = [x[1] for x in ToC]

        self.ToCListView.clear()
        self.ToCListView.addItems(ToC_headings_list)
示例#7
0
class MainApp(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.initial_x = 100
        self.initial_y = 100
        self.video_size = QSize(640, 480)

        self.scale = 1.0
        self.pause = False

        self.setup_ui()
        self.setup_camera()

    def setup_ui(self):
        """Initialize widgets.
        """
        # self.setStyleSheet('background-color: rgb(50, 50, 50);')

        self.image_label = QLabel()
        self.image_label.setGeometry(self.initial_x, self.initial_y,
                                     self.initial_x + self.video_size.width(),
                                     self.initial_y + self.video_size.height())
        self.image_label.setMinimumSize(640, 480)

        self.scrolling_image_label = QScrollArea()
        self.scrolling_image_label.setBackgroundRole(QPalette.Dark)
        self.scrolling_image_label.setWidget(self.image_label)
        self.img = cv2.imread('test_imgs/4.jpg')

        _, self.save_video_button, _, self.quit_and_save_layout = ui.create_save_and_quit(
            self.capture_photo, self.capture_video, self.close)

        self.photo = PhotoViewer(self)
        self.photo.setMinimumSize(640, 480)

        self.contrast_slider, self.contrast_layout = ui.create_slider(
            'contrast', 33, 99, self.change_contrast)
        self.brightness_slider, self.brightness_layout = ui.create_slider(
            'brightness', 1, 100, self.change_brightness)
        self.trace_slider, self.trace_layout = ui.create_slider(
            'trace', 20, 300, self.change_trace_threshold)

        self.sharpen_button, self.enhance_button, self.trace_button, self.pause_button, self.toggle_layout = ui.create_toggle(
            self.change_sharpen, self.change_enhance, self.change_trace,
            self.pause_stream)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.photo)
        self.main_layout.addLayout(self.quit_and_save_layout)
        self.main_layout.addLayout(self.contrast_layout)
        self.main_layout.addLayout(self.brightness_layout)
        self.main_layout.addLayout(self.trace_layout)
        self.main_layout.addLayout(self.toggle_layout)

        self.setLayout(self.main_layout)

    def setup_camera(self):
        """Initialize camera.
        """
        self.capture = cv2.VideoCapture(0)
        self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.video_size.width())
        self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.video_size.height())

        self.contrast = 1.0
        self.brightness = 1.0
        self.trace_threshold = 20.0
        self.sharpen = False
        self.enhance = False
        self.trace = False

        self.timer = QTimer()
        self.timer.timeout.connect(self.display_video_stream)
        self.timer.start(30)
        # self.timer.timeout.connect(self.display_image_stream)
        # self.timer.start(1000)

    def display_image_stream(self):
        # self.beta = (self.beta + 10) % 100
        self.frame = p.process_contrast_frame(self.img,
                                              self.contrast,
                                              self.brightness,
                                              enhance=self.enhance,
                                              sharpen=self.sharpen,
                                              trace=self.trace)

        image = QImage(
            self.frame,
            self.frame.shape[1],
            self.frame.shape[0],
            # self.frame.strides[0], self.QImage.Format_RGB888)
            self.frame.strides[0],
            QImage.Format_Grayscale8)
        pixmap = QPixmap.fromImage(image).scaledToWidth(
            self.video_size.width())
        self.scrolling_image_label.setGeometry(
            self.initial_x, self.initial_y,
            self.initial_x + self.video_size.width(),
            self.initial_y + self.video_size.height())
        self.scrolling_image_label.setPixmap(pixmap)
        self.photo.setPhoto(pixmap)

    def display_video_stream(self):
        """Read frame from camera and repaint QLabel widget.
        """
        if not self.pause:
            _, self.raw_img = self.capture.read()

        self.frame = p.process_contrast_frame(self.raw_img,
                                              self.contrast,
                                              self.brightness,
                                              self.trace_threshold,
                                              enhance=self.enhance,
                                              sharpen=self.sharpen,
                                              trace=self.trace)
        if self.save_video_button.is_recording:
            self.save_video_button.write_img(self.frame)

        image = QImage(
            self.frame,
            self.frame.shape[1],
            self.frame.shape[0],
            # self.frame.strides[0], self.QImage.Format_RGB888)
            self.frame.strides[0],
            QImage.Format_Grayscale8)
        pixmap = QPixmap.fromImage(image).scaledToWidth(
            self.video_size.width())
        # self.image_label.setGeometry(self.initial_x, self.initial_y, self.initial_x + self.video_size.width(), self.initial_y + self.video_size.height())
        # self.image_label.setPixmap(pixmap)
        # self.photo._photo.setPixmap(pixmap)
        self.photo.setPhotoContinuous(pixmap)

    def resizeEvent(self, event):
        # Resize the video_size based on the current window size
        # Don't set the size here directly, though
        self.video_size = QSize(self.frameGeometry().width() - 40,
                                self.frameGeometry().height() - 96)

    def capture_photo(self):
        im = Image.fromarray(self.frame)
        fname = QFileDialog.getSaveFileName(self, 'Save File As',
                                            "Captures/untitled.png",
                                            "Images (*.png *.jpg)")
        im.save(fname[0])

    def capture_video(self):
        pass  # empty function

    def pause_stream(self):
        self.pause = not self.pause

    def change_contrast(self):
        self.contrast = self.contrast_slider.value()
        self.contrast = self.contrast / 33.0  # keep range in 1.0-3.0

    def change_brightness(self):
        self.brightness = self.brightness_slider.value()

    def change_trace_threshold(self):
        self.trace_threshold = self.trace_slider.value()

    def change_sharpen(self):
        self.sharpen = not self.sharpen

    def change_enhance(self):
        self.enhance = not self.enhance

    def change_trace(self):
        self.trace = not self.trace
示例#8
0
class PipedImagerPQ(QMainWindow):
    '''
    A PyQt graphics viewer that receives images and commands through
    a pipe.

    A command is a dictionary with string keys.  For example,
        { "action":"save",
          "filename":"ferret.png",
          "fileformat":"png" }

    The command { "action":"exit" } will shutdown the viewer.
    '''
    def __init__(self, cmndpipe, rspdpipe):
        '''
        Create a PyQt viewer which reads commands from the Pipe
        cmndpipe and writes responses back to rspdpipe.
        '''
        super(PipedImagerPQ, self).__init__()
        self.__cmndpipe = cmndpipe
        self.__rspdpipe = rspdpipe
        # ignore Ctrl-C
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        # unmodified image for creating the scene
        self.__sceneimage = None
        # bytearray of data for the above image
        self.__scenedata = None
        # flag set if in the process of reading image data from commands
        self.__loadingimage = False
        # width and height of the unmodified scene image
        # when the image is defined
        # initialize the width and height to values that will create
        # a viewer (mainWindow) of the right size
        self.__scenewidth = int(10.8 * self.physicalDpiX())
        self.__sceneheight = int(8.8 * self.physicalDpiY())
        # by default pay attention to any alpha channel values in colors
        self.__noalpha = False
        # initial default color for the background (opaque white)
        self.__lastclearcolor = QColor(0xFFFFFF)
        self.__lastclearcolor.setAlpha(0xFF)
        # scaling factor for creating the displayed scene
        self.__scalefactor = 1.0
        # automatically adjust the scaling factor to fit the window frame?
        self.__autoscale = True
        # minimum label width and height (for minimum scaling factor)
        # and minimum image width and height (for error checking)
        self.__minsize = 128
        # create the label, that will serve as the canvas, in a scrolled area
        self.__scrollarea = QScrollArea(self)
        self.__label = QLabel(self.__scrollarea)
        # set the initial label size and other values for the scrolled area
        self.__label.setMinimumSize(self.__scenewidth, self.__sceneheight)
        self.__label.resize(self.__scenewidth, self.__sceneheight)
        # setup the scrolled area
        self.__scrollarea.setWidget(self.__label)
        self.__scrollarea.setBackgroundRole(QPalette.Dark)
        self.setCentralWidget(self.__scrollarea)
        # default file name and format for saving the image
        self.__lastfilename = "ferret.png"
        self.__lastformat = "png"
        # command helper object
        self.__helper = CmndHelperPQ(self)
        # create the menubar
        self.__scaleact = QAction(
            self.tr("&Scale"),
            self,
            shortcut=self.tr("Ctrl+S"),
            statusTip=self.tr(
                "Scale the image (canvas and image change size)"),
            triggered=self.inquireSceneScale)
        self.__saveact = QAction(self.tr("Save &As..."),
                                 self,
                                 shortcut=self.tr("Ctrl+A"),
                                 statusTip=self.tr("Save the image to file"),
                                 triggered=self.inquireSaveFilename)
        self.__redrawact = QAction(
            self.tr("&Redraw"),
            self,
            shortcut=self.tr("Ctrl+R"),
            statusTip=self.tr("Clear and redraw the image"),
            triggered=self.redrawScene)
        self.__aboutact = QAction(
            self.tr("&About"),
            self,
            statusTip=self.tr("Show information about this viewer"),
            triggered=self.aboutMsg)
        self.__aboutqtact = QAction(
            self.tr("About &Qt"),
            self,
            statusTip=self.tr("Show information about the Qt library"),
            triggered=self.aboutQtMsg)
        self.createMenus()
        # set the initial size of the viewer
        self.__framedelta = 4
        mwwidth = self.__scenewidth + self.__framedelta
        mwheight = self.__sceneheight + self.__framedelta \
                 + self.menuBar().height() \
                 + self.statusBar().height()
        self.resize(mwwidth, mwheight)
        # check the command queue any time there are no window events to deal with
        self.__timer = QTimer(self)
        self.__timer.timeout.connect(self.checkCommandPipe)
        self.__timer.setInterval(0)
        self.__timer.start()

    def createMenus(self):
        '''
        Create the menu items for the viewer
        using the previously created actions.
        '''
        menuBar = self.menuBar()
        sceneMenu = menuBar.addMenu(menuBar.tr("&Image"))
        sceneMenu.addAction(self.__scaleact)
        sceneMenu.addAction(self.__saveact)
        sceneMenu.addAction(self.__redrawact)
        helpMenu = menuBar.addMenu(menuBar.tr("&Help"))
        helpMenu.addAction(self.__aboutact)
        helpMenu.addAction(self.__aboutqtact)

    def resizeEvent(self, event):
        '''
        Monitor resizing in case auto-scaling of the image is selected.
        '''
        if self.__autoscale:
            if self.autoScaleScene():
                # continue with the window resize
                event.accept()
            else:
                # another resize coming in, so ignore this one
                event.ignore()
        else:
            # continue with the window resize
            event.accept()

    def closeEvent(self, event):
        '''
        Clean up and send the WINDOW_CLOSED_MESSAGE on the response pipe
        before closing the window.
        '''
        self.__timer.stop()
        self.__cmndpipe.close()
        try:
            try:
                self.__rspdpipe.send(WINDOW_CLOSED_MESSAGE)
            finally:
                self.__rspdpipe.close()
        except Exception:
            pass
        event.accept()

    def exitViewer(self):
        '''
        Close and exit the viewer.
        '''
        self.close()

    def aboutMsg(self):
        QMessageBox.about(self, self.tr("About PipedImagerPQ"),
            self.tr("\n" \
            "PipedImagerPQ is a graphics viewer application that receives its " \
            "displayed image and commands primarily from another application " \
            "through a pipe.  A limited number of commands are provided by the " \
            "viewer itself to allow saving and some manipulation of the " \
            "displayed image.  The controlling application, however, may be " \
            "unaware of these modifications made to the image. " \
            "\n\n" \
            "PipedImagerPQ was developed by the Thermal Modeling and Analysis " \
            "Project (TMAP) of the National Oceanographic and Atmospheric " \
            "Administration's (NOAA) Pacific Marine Environmental Lab (PMEL). "))

    def aboutQtMsg(self):
        QMessageBox.aboutQt(self, self.tr("About Qt"))

    def ignoreAlpha(self):
        '''
        Return whether the alpha channel in colors should always be ignored.
        '''
        return self.__noalpha

    def updateScene(self):
        '''
        Clear the displayed scene using self.__lastclearcolor,
        then draw the scaled current image.
        '''
        # get the scaled scene size
        labelwidth = int(self.__scalefactor * self.__scenewidth + 0.5)
        labelheight = int(self.__scalefactor * self.__sceneheight + 0.5)
        # Create the new pixmap for the label to display
        newpixmap = QPixmap(labelwidth, labelheight)
        newpixmap.fill(self.__lastclearcolor)
        if self.__sceneimage != None:
            # Draw the scaled image to the pixmap
            mypainter = QPainter(newpixmap)
            trgrect = QRectF(0.0, 0.0, float(labelwidth), float(labelheight))
            srcrect = QRectF(0.0, 0.0, float(self.__scenewidth),
                             float(self.__sceneheight))
            mypainter.drawImage(trgrect, self.__sceneimage, srcrect,
                                Qt.AutoColor)
            mypainter.end()
        # Assign the new pixmap to the label
        self.__label.setPixmap(newpixmap)
        # set the label size and values
        # so the scrollarea knows of the new size
        self.__label.setMinimumSize(labelwidth, labelheight)
        self.__label.resize(labelwidth, labelheight)
        # update the label from the new pixmap
        self.__label.update()

    def clearScene(self, bkgcolor=None):
        '''
        Deletes the scene image and fills the label with bkgcolor.
        If bkgcolor is None or an invalid color, the color used is
        the one used from the last clearScene or redrawScene call
        with a valid color (or opaque white if a color has never
        been specified).
        '''
        # get the color to use for clearing (the background color)
        if bkgcolor:
            if bkgcolor.isValid():
                self.__lastclearcolor = bkgcolor
        # Remove the image and its bytearray
        self.__sceneimage = None
        self.__scenedata = None
        # Update the scene label using the current clearing color and image
        self.updateScene()

    def redrawScene(self, bkgcolor=None):
        '''
        Clear and redraw the displayed scene.
        '''
        # get the background color
        if bkgcolor:
            if bkgcolor.isValid():
                self.__lastclearcolor = bkgcolor
        # Update the scene label using the current clearing color and image
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.statusBar().showMessage(self.tr("Redrawing image"))
        try:
            self.updateScene()
        finally:
            self.statusBar().clearMessage()
            QApplication.restoreOverrideCursor()

    def resizeScene(self, width, height):
        '''
        Resize the scene to the given width and height in units of pixels.
        If the size changes, this deletes the current image and clear the
        displayed scene.
        '''
        newwidth = int(width + 0.5)
        if newwidth < self.__minsize:
            newwidth = self.__minsize
        newheight = int(height + 0.5)
        if newheight < self.__minsize:
            newheight = self.__minsize
        if (newwidth != self.__scenewidth) or (newheight !=
                                               self.__sceneheight):
            # set the new size for the empty scene
            self.__scenewidth = newwidth
            self.__sceneheight = newheight
            # If auto-scaling, set scaling factor to 1.0 and resize the window
            if self.__autoscale:
                self.__scalefactor = 1.0
                barheights = self.menuBar().height() + self.statusBar().height(
                )
                self.resize(newwidth + self.__framedelta,
                            newheight + self.__framedelta + barheights)
            # clear the scene with the last clearing color
            self.clearScene(None)

    def loadNewSceneImage(self, imageinfo):
        '''
        Create a new scene image from the information given in this
        and subsequent dictionaries imageinfo.  The image is created
        from multiple calls to this function since there is a limit
        on the size of a single object passed through a pipe.

        The first imageinfo dictionary given when creating an image
        must define the following key and value pairs:
            "width": width of the image in pixels
            "height": height of the image in pixels
            "stride": number of bytes in one line of the image
                      in the bytearray
        The scene image data is initialized to all zero (transparent)
        at this time.

        This initialization call must be followed by (multiple) calls
        to this method with imageinfo dictionaries defining the key
        and value pairs:
            "blocknum": data block number (1, 2, ... numblocks)
            "numblocks": total number of image data blocks
            "startindex": index in the bytearray of image data
                          where this block of image data starts
            "blockdata": this block of data as a bytearray

        On receipt of the last block of data (blocknum == numblocks)
        the scene image will be created and the scene will be updated.

        Raises:
            KeyError - if one of the above keys is not given
            ValueError - if a value for a key is not valid
        '''
        if not self.__loadingimage:
            # prepare for a new image data from subsequent calls
            # get dimensions of the new image
            myimgwidth = int(imageinfo["width"])
            myimgheight = int(imageinfo["height"])
            myimgstride = int(imageinfo["stride"])
            if (myimgwidth < self.__minsize) or (myimgheight < self.__minsize):
                raise ValueError(
                    "image width and height cannot be less than %s" %
                    str(self.__minsize))
            # Newer PyQt versions allow separate specification of the stride
            if myimgstride != 4 * myimgwidth:
                raise ValueError(
                    "image stride is not four times the image width")
            # create the bytearray to contain the new scene data
            # automatically initialized to zero
            self.__scenedata = bytearray(myimgstride * myimgheight)
            self.__scenewidth = myimgwidth
            self.__sceneheight = myimgheight
            # set the flag for subsequent calls to this method
            self.__loadingimage = True
            # change the cursor to warn the user this may take some time
            QApplication.setOverrideCursor(Qt.WaitCursor)
            # put up an appropriate status message
            self.statusBar().showMessage(self.tr("Loading new image"))
            return
        # loading an image; add the next block of data
        myblocknum = int(imageinfo["blocknum"])
        mynumblocks = int(imageinfo["numblocks"])
        mystartindex = int(imageinfo["startindex"])
        myblockdata = imageinfo["blockdata"]
        if (myblocknum < 1) or (myblocknum > mynumblocks):
            self.statusBar().clearMessage()
            QApplication.restoreOverrideCursor()
            raise ValueError(
                "invalid image data block number or number of blocks")
        if (mystartindex < 0) or (mystartindex >= len(self.__scenedata)):
            self.statusBar().clearMessage()
            QApplication.restoreOverrideCursor()
            raise ValueError("invalid start index for an image data block")
        myblocksize = len(myblockdata)
        myendindex = mystartindex + myblocksize
        if (myblocksize < 1) or (myendindex > len(self.__scenedata)):
            self.statusBar().clearMessage()
            QApplication.restoreOverrideCursor()
            raise ValueError("invalid length of an image data block")
        # update the status message to show progress
        self.statusBar().showMessage( self.tr("Loading new image (block %s of %s)" % \
                                              (str(myblocknum),str(mynumblocks))) )
        # assign the data
        self.__scenedata[mystartindex:myendindex] = myblockdata
        # if this is the last block of data, create and display the scene image
        if myblocknum == mynumblocks:
            self.__loadingimage = False
            self.statusBar().showMessage(self.tr("Creating new image"))
            try:
                self.__sceneimage = QImage(self.__scenedata, self.__scenewidth,
                                           self.__sceneheight,
                                           QImage.Format_ARGB32_Premultiplied)
                self.statusBar().showMessage(self.tr("Drawing new image"))
                # update the displayed scene in the label
                self.updateScene()
            finally:
                # clear the status message
                self.statusBar().clearMessage()
                # restore the cursor back to normal
                QApplication.restoreOverrideCursor()

    def inquireSceneScale(self):
        '''
        Prompt the user for the desired scaling factor for the scene.
        '''
        labelwidth = int(self.__scenewidth * self.__scalefactor + 0.5)
        labelheight = int(self.__sceneheight * self.__scalefactor + 0.5)
        scaledlg = ScaleDialogPQ(self.__scalefactor, labelwidth, labelheight,
                                 self.__minsize, self.__minsize,
                                 self.__autoscale, self)
        if scaledlg.exec_():
            (newscale, autoscale, okay) = scaledlg.getValues()
            if okay:
                if autoscale:
                    self.__autoscale = True
                    self.autoScaleScene()
                else:
                    self.__autoscale = False
                    self.scaleScene(newscale, False)

    def autoScaleScene(self):
        '''
        Selects a scaling factor that maximizes the scene within the window
        frame without requiring scroll bars.  Intended to be called when
        the window size is changed by the user and auto-scaling is turn on.

        Returns:
            True if scaling of this scene is done (no window resize)
            False if the a window resize command was issued
        '''
        barheights = self.menuBar().height() + self.statusBar().height()

        # get the size for the central widget
        cwheight = self.height() - barheights - self.__framedelta
        heightsf = float(cwheight) / float(self.__sceneheight)

        cwwidth = self.width() - self.__framedelta
        widthsf = float(cwwidth) / float(self.__scenewidth)

        if heightsf < widthsf:
            factor = heightsf
        else:
            factor = widthsf

        newcwheight = int(factor * self.__sceneheight + 0.5)
        newcwwidth = int(factor * self.__scenewidth + 0.5)

        # if the window does not have the correct aspect ratio, resize it so
        # it will; this will generate another call to this method.  Otherwise,
        # scale the scene and be done.
        if self.isMaximized() or \
           ( (abs(cwheight - newcwheight) <= self.__framedelta) and \
             (abs(cwwidth - newcwwidth) <= self.__framedelta) ):
            self.scaleScene(factor, False)
            return True
        else:
            self.resize(newcwwidth + self.__framedelta,
                        newcwheight + self.__framedelta + barheights)
            return False

    def scaleScene(self, factor, resizewin):
        '''
        Scales both the horizontal and vertical directions by factor.
        Scaling factors are not accumulative.  So if the scene was
        already scaled, that scaling is "removed" before this scaling
        factor is applied.  If resizewin is True, the main window is
        resized to accommodate this new scaled scene size.

        If factor is zero, just switch to auto-scaling at the current
        window size.  If factor is negative, rescale using the absolute
        value (possibly resizing the window) then switch to auto-scaling.
        '''
        fltfactor = float(factor)
        if fltfactor != 0.0:
            if resizewin:
                # from command - turn off autoscaling for the following
                # then turn back on if appropriate
                self.__autoscale = False
            newfactor = abs(fltfactor)
            newlabwidth = int(newfactor * self.__scenewidth + 0.5)
            newlabheight = int(newfactor * self.__sceneheight + 0.5)
            if (newlabwidth < self.__minsize) or (newlabheight <
                                                  self.__minsize):
                # Set to minimum size
                if self.__scenewidth <= self.__sceneheight:
                    newfactor = float(self.__minsize) / float(
                        self.__scenewidth)
                else:
                    newfactor = float(self.__minsize) / float(
                        self.__sceneheight)
                newlabwidth = int(newfactor * self.__scenewidth + 0.5)
                newlabheight = int(newfactor * self.__sceneheight + 0.5)
            oldlabwidth = int(self.__scalefactor * self.__scenewidth + 0.5)
            oldlabheight = int(self.__scalefactor * self.__sceneheight + 0.5)
            if (newlabwidth != oldlabwidth) or (newlabheight != oldlabheight):
                # Set the new scaling factor
                self.__scalefactor = newfactor
                # Update the scene label using the current clearing color and image
                QApplication.setOverrideCursor(Qt.WaitCursor)
                self.statusBar().showMessage(self.tr("Scaling image"))
                try:
                    self.updateScene()
                finally:
                    self.statusBar().clearMessage()
                    QApplication.restoreOverrideCursor()
            if resizewin:
                # resize the main window (if possible)
                barheights = self.menuBar().height() + self.statusBar().height(
                )
                mwheight = newlabheight + barheights + self.__framedelta
                mwwidth = newlabwidth + self.__framedelta
                # Do not exceed the available real estate on the screen.
                # If autoscaling is in effect, the resize will trigger
                # any required adjustments.
                scrnrect = QApplication.desktop().availableGeometry()
                if mwwidth > 0.95 * scrnrect.width():
                    mwwidth = int(0.9 * scrnrect.width() + 0.5)
                if mwheight > 0.95 * scrnrect.height():
                    mwheight = int(0.9 * scrnrect.height() + 0.5)
                self.resize(mwwidth, mwheight)
        if fltfactor <= 0.0:
            # From command - turn on autoscaling
            self.__autoscale = True
            self.autoScaleScene()

    def inquireSaveFilename(self):
        '''
        Prompt the user for the name of the file into which to save the scene.
        The file format will be determined from the filename extension.
        '''
        formattypes = [
            ("png", "PNG - Portable Networks Graphics (*.png)"),
            ("jpeg",
             "JPEG - Joint Photographic Experts Group (*.jpeg *.jpg *.jpe)"),
            ("tiff", "TIFF - Tagged Image File Format (*.tiff *.tif)"),
            ("bmp", "BMP - Windows Bitmap (*.bmp)"),
            ("ppm", "PPM - Portable Pixmap (*.ppm)"),
            ("xpm", "XPM - X11 Pixmap (*.xpm)"),
            ("xbm", "XBM - X11 Bitmap (*.xbm)"),
        ]
        filters = ";;".join([t[1] for t in formattypes])
        if PYTHONQT_VERSION == 'PyQt4':
            # getSaveFileNameAndFilter; tr returns QStrings in PyQt4 (Python2)
            (fileName, fileFilter) = QFileDialog.getSaveFileNameAndFilter(
                self, self.tr("Save the current image as "),
                self.tr(self.__lastfilename), self.tr(filters))
        else:
            # getSaveFileName; tr returns Python unicode strings in PySide2 and PyQt5 (Python3)
            (fileName, fileFilter) = QFileDialog.getSaveFileName(
                self, self.tr("Save the current image as "),
                self.tr(self.__lastfilename), self.tr(filters))
        if fileName:
            for (fmt, fmtQName) in formattypes:
                if self.tr(fmtQName) == fileFilter:
                    fileFormat = fmt
                    break
            else:
                raise RuntimeError("Unexpected file format name '%s'" %
                                   fileFilter)
            self.saveSceneToFile(fileName, fileFormat, None, None)
            self.__lastfilename = fileName
            self.__lastformat = fileFormat

    def saveSceneToFile(self, filename, imageformat, transparent, rastsize):
        '''
        Save the current scene to the named file.

        If imageformat is empty or None, the format is guessed from
        the filename extension.

        If transparent is False, the entire scene is initialized
        to the last clearing color.

        If given, rastsize is the pixels size of the saved image.
        If rastsize is not given, the saved image will be saved
        at the current scaled image size.
        '''
        # This could be called when there is no image present.
        # If this is the case, ignore the call.
        if (self.__sceneimage == None):
            return
        if not imageformat:
            # Guess the image format from the filename extension
            # This is only done to silently change gif to png
            fileext = (os.path.splitext(filename)[1]).lower()
            if fileext == '.gif':
                myformat = 'gif'
            else:
                # let QImage figure out the format
                myformat = None
        else:
            myformat = imageformat.lower()

        if myformat == 'gif':
            # Silently convert gif filename and format to png
            myformat = 'png'
            myfilename = os.path.splitext(filename)[0] + ".png"
        else:
            myfilename = filename
        # set the cursor and status message to indicate a save is happending
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.statusBar().showMessage(self.tr("Saving image"))
        try:
            if rastsize:
                imagewidth = int(rastsize.width() + 0.5)
                imageheight = int(rastsize.height() + 0.5)
            else:
                imagewidth = int(self.__scenewidth * self.__scalefactor + 0.5)
                imageheight = int(self.__sceneheight * self.__scalefactor +
                                  0.5)
            myimage = QImage(QSize(imagewidth, imageheight),
                             QImage.Format_ARGB32_Premultiplied)
            # Initialize the image
            if not transparent:
                # Clear the image with self.__lastclearcolor
                fillint = self.__helper.computeARGB32PreMultInt(
                    self.__lastclearcolor)
            else:
                fillint = 0
            myimage.fill(fillint)
            # draw the scaled scene to this QImage
            mypainter = QPainter(myimage)
            trgrect = QRectF(0.0, 0.0, float(imagewidth), float(imageheight))
            srcrect = QRectF(0.0, 0.0, float(self.__scenewidth),
                             float(self.__sceneheight))
            mypainter.drawImage(trgrect, self.__sceneimage, srcrect,
                                Qt.AutoColor)
            mypainter.end()
            # save the image to file
            if not myimage.save(myfilename, myformat):
                raise ValueError("Unable to save the plot as " + myfilename)
        finally:
            self.statusBar().clearMessage()
            QApplication.restoreOverrideCursor()

    def checkCommandPipe(self):
        '''
        Get and perform commands waiting in the pipe.
        Stop when no more commands or if more than 50
        milliseconds have passed.
        '''
        try:
            if (sys.version_info[0] >= 3) and (sys.version_info[1] >= 3):
                starttime = time.process_time()
            else:
                starttime = time.clock()
            # Wait up to 2 milliseconds waiting for a command.
            # This prevents unchecked spinning when there is
            # nothing to do (Qt immediately calling this method
            # again only for this method to immediately return).
            while self.__cmndpipe.poll(0.002):
                cmnd = self.__cmndpipe.recv()
                self.processCommand(cmnd)
                # Continue to try to process commands until
                # more than 50 milliseconds have passed.
                # This reduces Qt overhead when there are lots
                # of commands waiting in the queue.
                if (sys.version_info[0] >= 3) and (sys.version_info[1] >= 3):
                    elapsed = time.process_time() - starttime
                else:
                    elapsed = time.clock() - starttime
                if elapsed > 0.050:
                    break
        except EOFError:
            # Assume PyFerret has shut down
            self.exitViewer()
        except Exception:
            # Some problem, but presumably still functional
            (exctype, excval) = sys.exc_info()[:2]
            try:
                if excval:
                    self.__rspdpipe.send("**ERROR %s: %s" %
                                         (str(exctype), str(excval)))
                else:
                    self.__rspdpipe.send("**ERROR %s" % str(exctype))
            except Exception:
                pass

    def processCommand(self, cmnd):
        '''
        Examine the action of cmnd and call the appropriate
        method to deal with this command.  Raises a KeyError
        if the "action" key is missing.
        '''
        try:
            cmndact = cmnd["action"]
        except KeyError:
            raise ValueError("Unknown command '%s'" % str(cmnd))

        if cmndact == "clear":
            try:
                bkgcolor = self.__helper.getColorFromCmnd(cmnd)
            except KeyError:
                bkgcolor = None
            self.clearScene(bkgcolor)
        elif cmndact == "exit":
            self.exitViewer()
        elif cmndact == "hide":
            self.showMinimized()
        elif cmndact == "screenInfo":
            scrnrect = QApplication.desktop().availableGeometry()
            info = (self.physicalDpiX(), self.physicalDpiY(), scrnrect.width(),
                    scrnrect.height())
            self.__rspdpipe.send(info)
        elif cmndact == "redraw":
            try:
                bkgcolor = self.__helper.getColorFromCmnd(cmnd)
            except KeyError:
                bkgcolor = None
            self.redrawScene(bkgcolor)
        elif cmndact == "rescale":
            self.scaleScene(float(cmnd["factor"]), True)
        elif cmndact == "resize":
            mysize = self.__helper.getSizeFromCmnd(cmnd)
            self.resizeScene(mysize.width(), mysize.height())
        elif cmndact == "newImage":
            self.loadNewSceneImage(cmnd)
        elif cmndact == "save":
            filename = cmnd["filename"]
            fileformat = cmnd.get("fileformat", None)
            try:
                bkgcolor = self.__helper.getColorFromCmnd(cmnd)
            except KeyError:
                bkgcolor = None
            rastsize = self.__helper.getSizeFromCmnd(cmnd["rastsize"])
            self.saveSceneToFile(filename, fileformat, bkgcolor, rastsize)
        elif cmndact == "setTitle":
            self.setWindowTitle(cmnd["title"])
        elif cmndact == "imgname":
            myvalue = cmnd.get("name", None)
            if myvalue:
                self.__lastfilename = myvalue
            myvalue = cmnd.get("format", None)
            if myvalue:
                self.__lastformat = myvalue.lower()
        elif cmndact == "show":
            if not self.isVisible():
                self.show()
        elif cmndact == "noalpha":
            # ignore any alpha channel values in colors
            self.__noalpha = True
        else:
            raise ValueError("Unknown command action %s" % str(cmndact))
示例#9
0
class MyWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.thread = SerialMonitorThread()
        self.thread.dataReady.connect(self.get_data, Qt.QueuedConnection)
        self.thread.setTerminationEnabled(True)

        #Menu
        self.setPalette(get_verifone_color())

        collapsible = CollapsibleWidget()
        self.init_logging(collapsible)

        self.init_download(collapsible)

        self.init_analyser(collapsible)

        collapsible.add_sections()
        # Scroll Area
        self.createLoggingDisplayLabel()
        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.text)
        self.scrollArea.setWidgetResizable(True)

        hLayout = QHBoxLayout()
        #hLayout.addLayout(vLayout)
        hLayout.addWidget(collapsible)
        hLayout.addWidget(self.scrollArea)

        self.setLayout(hLayout)

    def init_logging(self, collapsible):

        self.logger = QPushButton("Start Logging", self)
        self.logger.setFont(QFont("Times", 14, QFont.Bold))
        self.logger.clicked.connect(lambda: self.display_log_data())
        self.logger.setStyleSheet("background-color: white")

        #self.filterLayout = QtWidgets.QHBoxLayout()
        self.logFilterLabel = QLabel('Filter', self)
        self.logFilterLabel.setFont(QFont("Times", 14, QFont.Bold))
        self.logFilterLabel.setPalette(get_white_color_text())
        self.logFilterLabel.setFixedWidth(60)
        self.logFilter = QLineEdit(self)
        self.logFilter.setPalette(get_white_color())
        self.logFilter.setStyleSheet("background-color: white")
        self.logFilter.setFixedWidth(200)
        #self.filterLayout.addWidget(self.logFilterLabel, QtCore.Qt.AlignLeft)
        #self.filterLayout.addWidget(self.logFilter, QtCore.Qt.AlignLeft)

        self.serialList = QComboBox()
        ports = get_available_serial_ports()
        if (len(ports) == 1):
            self.serialList.addItem(ports[0])
            self.thread.set_comport(self.serialList.currentText())
        else:
            self.serialList.addItem("Select")
            for port in ports:
                self.serialList.addItem(port)

        self.serialList.currentIndexChanged.connect(
            lambda: self.set_serial_port())
        self.serialList.setStyleSheet("background-color: white")
        self.clear = QPushButton("Clear Log File", self)
        self.clear.setStyleSheet("background-color: white")
        self.clear.setFont(QFont("Times", 14, QFont.Bold))
        self.clear.clicked.connect(lambda: self.clear_data())

        widget = QFrame(collapsible.get_tree())
        widget.setPalette(get_verifone_color())
        title = "Logging"
        self.loggerGrid = QGridLayout(widget)
        self.loggerGrid.addWidget(self.logger, 0, 0, 1, 2)
        self.loggerGrid.addWidget(self.logFilterLabel, 1, 0, 1, 1)
        self.loggerGrid.addWidget(self.logFilter, 1, 1, 1, 1)
        self.loggerGrid.addWidget(self.serialList, 2, 0, 1, 2)
        self.loggerGrid.addWidget(self.clear, 3, 0, 1, 2)

        collapsible.include_section(title, widget)

    def init_download(self, collapsible):
        self.download = QPushButton("Download Package", self)
        self.download.setFont(QFont("Times", 14, QFont.Bold))
        self.download.clicked.connect(lambda: self.send_file())
        self.download.setStyleSheet("background-color: white")

        self.loadDownloadFile = QPushButton("Load File", self)
        self.loadDownloadFile.setFont(QFont("Times", 14, QFont.Bold))
        self.loadDownloadFile.clicked.connect(self.loadFromFile)
        self.loadDownloadFile.setStyleSheet("background-color: white")

        self.downloadFileName = QLineEdit("File name", self)
        self.downloadFileName.setStyleSheet("background-color: white")
        self.downloadFileName.setFixedWidth(300)

        self.downloadAddress = QLineEdit("IP Address", self)
        self.downloadAddress.setStyleSheet("background-color: white")
        self.downloadAddress.setFixedWidth(300)

        self.downloadStatus = QLabel("Download Status", self)
        self.downloadStatus.setStyleSheet(
            "background-color: rgba(3, 169, 229, 0); color : white")
        self.downloadStatus.setFixedWidth(300)
        widget = QFrame(collapsible.get_tree())
        title = "Download"

        self.downloadGrid = QGridLayout(widget)
        self.downloadGrid.addWidget(self.download, 0, 0, 1, 2)
        self.downloadGrid.addWidget(self.loadDownloadFile, 1, 0, 1, 2)
        self.downloadGrid.addWidget(self.downloadFileName, 2, 0, 1, 2)
        self.downloadGrid.addWidget(self.downloadAddress, 3, 0, 1, 2)
        self.downloadGrid.addWidget(self.downloadStatus, 4, 0, 1, 2)
        collapsible.include_section(title, widget)

    def init_analyser(self, collapsible):
        self.performanceData = QPushButton("View Performance Data", self)
        self.performanceData.setFont(QFont("Times", 14, QFont.Bold))
        self.performanceData.clicked.connect(
            lambda: self.display_performance_data())
        self.performanceData.setStyleSheet("background-color: white")

        self.performanceChart = QPushButton("View Performance Chart", self)
        self.performanceChart.setFont(QFont("Times", 14, QFont.Bold))
        self.performanceChart.clicked.connect(
            lambda: self.display_performance_chart())
        self.performanceChart.setStyleSheet("background-color: white")

        widget = QFrame(collapsible.get_tree())
        title = "Analyser"
        self.analyserGrid = QGridLayout(widget)
        self.analyserGrid.addWidget(self.performanceData, 0, 0, 1, 2)
        self.analyserGrid.addWidget(self.performanceChart, 1, 0, 1, 2)
        collapsible.include_section(title, widget)

    def loadFromFile(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Load Package", '', "Download Files (*.tgz);;All Files (*)")

        if not fileName:
            return

        try:
            in_file = open(str(fileName), 'rb')
        except IOError:
            QMessageBox.information(
                self, "Unable to open file",
                "There was an error opening \"%s\"" % fileName)
            return
        in_file.close()
        self.downloadFileName.setText(fileName)

    def createLoggingDisplayLabel(self):
        # Display Area
        self.text = QPlainTextEdit(self)
        self.text.setReadOnly(True)
        self.text.setFont(QFont("Times", 12, QFont.Bold))
        self.text.setTextInteractionFlags(Qt.TextSelectableByMouse
                                          | Qt.TextSelectableByKeyboard)

    def clear_data(self):
        self.text.clear()
        os.remove(logfile_path, dir_fd=None)

    def display_log_data(self):
        #send_file()

        if ('COM' in self.serialList.currentText()):
            self.createLoggingDisplayLabel()
            self.scrollArea.setWidget(self.text)
            self.thread.stop()
            self.thread.start()

            data = get_data_from_file(logfile_path)
            if (len(data) > 0 and data != None):
                self.text.appendPlainText(data)
            self.logger.setDisabled(True)

    def get_data(self, data):
        if (len(data) > 0):
            logFile = open(logfile_path, "a")
            logFile.write(data)
            logFile.close()
            filterText = self.logFilter.text()
            if filterText in data.rstrip():
                self.text.appendPlainText(data.rstrip())
                vbar = self.scrollArea.verticalScrollBar()
                vbar.setValue(vbar.maximum())

    def display_performance_data(self):
        self.thread.stop()
        data = get_data_from_file(logfile_path)
        jsonData = translate_data_to_json(data)
        self.performanceData = DisplayPerformanceData()
        self.performanceData.loadCsv(
            os.path.join(base_log_path, "performance_data.csv"))
        self.scrollArea.setWidget(self.performanceData)
        self.logger.setDisabled(False)

    def display_performance_chart(self):
        self.thread.stop()
        self.scrollArea.setWidget(get_performace_chart())
        self.logger.setDisabled(False)

    def set_serial_port(self):
        self.thread.set_comport(self.serialList.currentText())

    def send_file(self):
        base_path = os.path.join("c:/", "VFI", 'wks',
                                 'global-payment-application', 'GPA', 'output',
                                 'vos2', 'gpa', 'dl.gpa-1.0.0.0-000.tgz')
        fileName = self.downloadFileName.text()
        try:
            in_file = open(str(fileName), 'rb')
        except IOError:
            QMessageBox.information(
                self, "Unable to open file",
                "There was an error opening \"%s\"" % fileName)
            return
        in_file.close()

        load_vos_package_ip('192.168.0.104', fileName, self.downloadStatus)