Example #1
0
                lines = f.read().split("\n")

            res = []
            while lines[-1] == '':
                lines.pop()
            for i in lines:
                u, v = map(float, i.split())
                res.append([u, v])
            self.data = res


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(53, 53, 53))
    palette.setColor(QPalette.WindowText, Qt.white)
    palette.setColor(QPalette.Base, QColor(25, 25, 25))
    palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    palette.setColor(QPalette.ToolTipBase, Qt.white)
    palette.setColor(QPalette.ToolTipText, Qt.white)
    palette.setColor(QPalette.Text, Qt.white)
    palette.setColor(QPalette.Button, QColor(53, 53, 53))
    palette.setColor(QPalette.ButtonText, Qt.white)
    palette.setColor(QPalette.BrightText, Qt.red)
    palette.setColor(QPalette.Link, QColor(42, 130, 218))
    palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    palette.setColor(QPalette.HighlightedText, Qt.black)
    app.setPalette(palette)
    view = Window()
    view.show()
Example #2
0
    def initUI(self):
        self.setGeometry(self.xPos, self.yPos, self.width, self.height)
        self.setFixedSize(self.width, self.height)
        self.setWindowTitle("Hachiko's Journal")

        windowBG = "rgb(0, 0, 77)"
        selectedColor = "rgb(0, 0, 179)"
        self.setStyleSheet(f"background-color: {windowBG}; font-size: 15px;")
        colorBG = "rgb(152, 208, 245)"
        self.tabWidget = QTabWidget()
        self.tabWidget.setStyleSheet(f"QTabBar::tab:selected {{color: white; background-color: {colorBG};}};")
        self.journalTab = QWidget()
        self.journalTab.setStyleSheet(f"background-color: {colorBG};")
        self.memoriesTab = QWidget()
        self.memoriesTab.setStyleSheet(f"background-color: {colorBG};")

        self.journalLayout = QGridLayout()
        self.journalEdit = QTextEdit()
        journalFont = QFont("Century Gothic")
        self.journalEdit.setFont(journalFont)
        self.journalEdit.setStyleSheet("background-image: url(img/linedpaper.png); background-repeat: no-repeat; background-position: center; font-size: 24px;")
        self.journalEdit.setText("Dear Hachiko,\n\n")
        self.journalLayout.addWidget(self.journalEdit, 0, 0, 1, 4)

        self.speechLabel = QLabel()
        self.speechLabel.setText("\t    Hi! I'm Hachiko!")
        self.speechLabel.setStyleSheet("background-image: url(img/speechbubble.png); background-repeat: no-repeat; font-size: 20px;")
        self.journalLayout.addWidget(self.speechLabel, 1, 0, 1, 3)

        self.hachikoLabel = QLabel()
        self.hachikoMovie = QMovie("img/HachikoHappyGif")
        self.hachikoLabel.setMovie(self.hachikoMovie)
        self.hachikoMovie.start()
        self.journalLayout.addWidget(self.hachikoLabel, 1, 3)

        self.saveButton = SharpButton(primaryColor = windowBG, secondaryColor = colorBG)
        self.saveButton.setText("Save Journal")
        self.saveButton.clicked.connect(self.save)
        self.journalLayout.addWidget(self.saveButton, 2, 0)

        self.wagButton = SharpButton(primaryColor = windowBG, secondaryColor = colorBG)
        self.wagButton.setText("Wag tail!")
        self.wagButton.clicked.connect(self.wag)
        self.journalLayout.addWidget(self.wagButton, 2, 1)

        self.howlButton = SharpButton(primaryColor = windowBG, secondaryColor = colorBG)
        self.howlButton.setText("Howl!")
        self.howlButton.clicked.connect(self.howl)
        self.journalLayout.addWidget(self.howlButton, 2, 2)

        self.headTiltButton = SharpButton(primaryColor = windowBG, secondaryColor = colorBG)
        self.headTiltButton.setText("Do a head tilt!")
        self.headTiltButton.clicked.connect(self.tilt)
        self.journalLayout.addWidget(self.headTiltButton, 2, 3)

        self.journalTab.setLayout(self.journalLayout)

        self.tabWidget.addTab(self.journalTab, "Journal")
        self.tabWidget.addTab(self.memoriesTab, "Memories")
        self.setCentralWidget(self.tabWidget)

        self.memoriesLayout = QGridLayout()
        self.journalsListLabel = QLabel()
        self.journalsListLabel.setText("Past Journals")
        self.memoriesLayout.addWidget(self.journalsListLabel, 0, 0, 1, 1)

        self.openButton = SharpButton(primaryColor = windowBG, secondaryColor = colorBG)
        self.openButton.setText("Open Journal")
        self.openButton.clicked.connect(self.open)
        self.memoriesLayout.addWidget(self.openButton, 0, 3, 1, 1)

        self.journalsList = QListWidget()
        self.journalsList.setStyleSheet(f"color: rgb(193, 193, 240); background-color: rgb(0, 13, 51); selection-color: rgb(0, 13, 51); selection-background-color: rgb(193, 193, 240)")
        for journal in os.listdir("journals/"):
            item = QListWidgetItem(journal)
            if journal[-6] == "1":
                item.setBackground(QColor(57, 172, 57))
            self.journalsList.addItem(item)
        self.memoriesLayout.addWidget(self.journalsList, 1, 0, 1, 4)

        self.memoriesTab.setLayout(self.memoriesLayout)

        self.sentThread.start()

        self.show()
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)

        # Drawing Background
        qp.setOpacity(0.5)
        qp.setBrush(QColor(185, 151, 91))
        qp.drawRect(0, 0, 1000, 650)
        qp.setOpacity(1)

        # Drawing Leaderboard
        qp.setFont(QFont("Arial", 36))
        qp.setPen(QPen(Qt.black, 40))
        qp.drawText(650, 90, "Leaderboard")
        qp.setFont(QFont("Arial", 18))
        qp.drawText(628, 135, "Rank")
        qp.drawText(728, 135, "Name")
        qp.drawText(825, 135, "Moves")

        lead_dict = {}
        lead_keys = []
        lead_vals = []
        with open('leaderboard.txt', 'r') as leaderboard:
            for line in leaderboard:
                # print(line)
                line = line.split()
                lead_dict[line[0]] = line[1]
        # print(lead_dict)
        for key in lead_dict.keys():
            lead_keys.append(key)
        for val in lead_dict.values():
            lead_vals.append(val)
        # print(lead_keys)
        # print(lead_vals)

        for r in range(LEAD_ROW):
            for c in range(LEAD_COL):
                if r%2 == 0:
                    qp.setBrush(QColor(17, 87, 64)) # Green
                else:
                    qp.setBrush(QColor(185, 151, 91)) # Gold

                qp.setFont(QFont("Arial", 16))
                qp.setPen(QPen(Qt.black, 2))
                qp.drawRect(LEAD_ORIGINX+c*LEAD_WIDTH, LEAD_ORIGINY+r*LEAD_HEIGHT, LEAD_WIDTH, LEAD_HEIGHT)

                if r%2 == 0:
                    qp.setPen(QColor(185, 151, 91)) # Gold
                    qp.setBrush(QColor(17, 87, 64)) # Green
                else:
                    qp.setPen(QColor(17, 87, 64))
                    qp.setBrush(QColor(185, 151, 91))

                if c == 0:
                    qp.drawText(LEAD_ORIGINX+c*LEAD_WIDTH+(LEAD_WIDTH//2.2), LEAD_ORIGINY+r*LEAD_HEIGHT+(LEAD_HEIGHT//2), \
                    str(rank[r]))
                elif c == 1:
                    qp.drawText(LEAD_ORIGINX+c*LEAD_WIDTH+(LEAD_WIDTH//3), LEAD_ORIGINY+r*LEAD_HEIGHT+(LEAD_HEIGHT//2), \
                    lead_keys[r])
                else:
                    qp.drawText(LEAD_ORIGINX+c*LEAD_WIDTH+(LEAD_WIDTH//2.5), LEAD_ORIGINY+r*LEAD_HEIGHT+(LEAD_HEIGHT//2), \
                    lead_vals[r])

        # Drawing Board
        for row in range(CELL_COUNT):
            for col in range(CELL_COUNT):
                if self.__board[row][col] != '':
                    qp.setBrush(QColor(17, 87, 64))
                    qp.setPen(QPen(Qt.black, 2))
                    qp.drawRect(GRID_ORIGINX+col*CELL_SIZE, GRID_ORIGINY+row*CELL_SIZE, CELL_SIZE, CELL_SIZE)
                    if len(str(self.__board[row][col])) < 2:
                        qp.setFont(QFont("Arial", 20))
                        qp.setPen(QColor(185, 151, 91))
                        qp.drawText(GRID_ORIGINX+col*CELL_SIZE+(CELL_SIZE/2.2), GRID_ORIGINY+row*CELL_SIZE+(CELL_SIZE/1.8), \
                        str(self.__board[row][col]))
                    else:
                        qp.setFont(QFont("Arial", 20))
                        qp.setPen(QColor(185, 151, 91))
                        qp.drawText(GRID_ORIGINX+col*CELL_SIZE+(CELL_SIZE/2.4), GRID_ORIGINY+row*CELL_SIZE+(CELL_SIZE/1.8), \
                        str(self.__board[row][col]))
                else:
                    qp.setBrush(QColor(185, 151, 91))
                    qp.setPen(QPen(Qt.black, 2))
                    qp.drawRect(GRID_ORIGINX+col*CELL_SIZE, GRID_ORIGINY+row*CELL_SIZE, CELL_SIZE, CELL_SIZE)

        # Winner Mode
        if self.is_winner() == True:
            qp.setPen(QPen(Qt.red))
            qp.setFont(QFont("Arial", 20))
            qp.drawText(GRID_ORIGINX*2.4, GRID_ORIGINY-20, "Game Over! You Win!")

        # Recording Moves
        qp.setPen(QPen(Qt.blue))
        qp.setFont(QFont("Arial", 14))
        qp.drawText(75, 550, ("Moves: " + str(self.__moves)))

        # Mii Music Button
        qp.setPen(QPen(Qt.black, 1))
        qp.setBrush(QColor(17, 87, 64)) # Green
        qp.drawRect(185, 535, 75, 20)
        qp.setPen(QColor(185, 151, 91)) # Gold
        qp.setFont(QFont("Arial", 14))
        qp.drawText(198, 550, "Play Mii")

        # BTS Music Button
        qp.setPen(QPen(Qt.black, 1))
        qp.drawRect(295, 535, 75, 20)
        qp.setPen(QColor(185, 151, 91)) # Gold
        qp.setFont(QFont("Arial", 14))
        qp.drawText(305, 550, "Play BTS")

        # No Music
        qp.setPen(QPen(Qt.black, 1))
        qp.drawRect(405, 535, 72, 20)
        qp.setPen(QColor(185, 151, 91)) # Gold
        qp.setFont(QFont("Arial", 14))
        qp.drawText(412, 550, "No Music")

        qp.end()
 def draw_flag(self, qp):
     # Задаем кисть
     qp.setBrush(QColor(255, 255, 0))
     R = random.randint(1, 500)
     qp.drawEllipse(20, 20, R, R)
Example #5
0
	def UpdatePacketTable(self,packet):
		'''Called each time sniffer captures a packet

		Thus glitches do appear when too many packets captured in a short time

		The function collects necessary info about packets and display in the table
		'''
		row_number=self.packet_table.rowCount()
		if row_number:
			time=packet.time-self.sniffer.initial_time
		else:
			self.sniffer.initial_time=packet.time
			self.sniffer.sniffed_time=0
			time=0

		layer_number=2
		layer=packet.getlayer(layer_number)
		while layer and layer.name not in ('Raw','Padding'):
			layer_number+=1
			layer=packet.getlayer(layer_number)
		protocol=packet.getlayer(layer_number-1).name

		if protocol=='ARP':
			source=packet.getlayer(1).hwsrc
			destination=packet.getlayer(1).hwdst
		else:
			source=packet.getlayer(1).src
			destination=packet.getlayer(1).dst
		
		'''Further analyse protocol through ports'''
		if packet.haslayer(TCP) or packet.haslayer(UDP):
			sport,dport=packet.sport,packet.dport
			if protocol=='TCP':
				sport_string=packet[TCP].fields_desc[0].i2repr(packet,sport)
				dport_string=packet[TCP].fields_desc[1].i2repr(packet,dport)
				if sport_string!=str(sport):
					protocol=sport_string.upper()
				if dport_string!=str(dport):
					protocol=dport_string.upper()
			elif protocol=='UDP':
				sport_string=packet[UDP].fields_desc[0].i2repr(packet,sport)
				dport_string=packet[UDP].fields_desc[1].i2repr(packet,dport)
				if sport_string!=str(sport):
					protocol=sport_string.upper()
				if dport_string!=str(dport):
					protocol=dport_string.upper()
		else:
			sport,dport=None,None

		info_list=packet.summary().split(' / ')[1:]
		info_list.sort(key=lambda x:len(x))

		'''The coloring rules are the default ones in Wireshark'''
		if protocol=='ARP':
			background,foreground=QColor(250,240,215),QColor(18,39,46) #ARP
		elif 'ICMP' in protocol:
			if protocol=='ICMP' and packet[ICMP].type in (3,4,5,11):
				background,foreground=QColor(18,39,46),QColor(183,247,116) #ICMP errors
			else:
				background,foreground=QColor(252,224,255),QColor(18,39,46) #ICMP or ICMPv6
		elif packet.haslayer(TCP):
			flag=int(packet[TCP].flags)
			if flag>>2&1:
				background,foreground=QColor(164,0,0),QColor(255,252,156) #TCP reset
			elif sport==80 or dport==80:
				background,foreground=QColor(228,255,199),QColor(18,39,46) #HTTP
			elif flag&3:
				background,foreground=QColor(160,160,160),QColor(18,39,46) #TCP SYN/FIN
			else:
				background,foreground=QColor(231,230,255),QColor(18,39,46) #TCP
		elif packet.haslayer(UDP):
			background,foreground=QColor(218,238,255),QColor(18,39,46) #UDP
		else:
			background,foreground=QColor(255,255,255),QColor(18,39,46)

		'''('No.','Time','Source','Destination','Protocol','Length','Info',background,foreground,sport,dport,packet)'''
		packet_tuple=(str(row_number),'{:.6f}'.format(time),source,destination,\
					protocol,str(len(packet)),info_list[-1],background,foreground,\
					sport,dport,packet)
		self.sniffer.packet_filter.packet_list.append(packet_tuple)

		self.packet_table.insertRow(row_number)
		for column in range(7):
			self.packet_table.setItem(row_number,column,QTableWidgetItem(packet_tuple[column]))
			self.packet_table.item(row_number,column).setBackground(background)
			self.packet_table.item(row_number,column).setForeground(foreground)

		'''Avoid scrolling too fast'''
		if time>0.05+self.sniffer.sniffed_time:
			self.packet_table.scrollToBottom()
			self.sniffer.sniffed_time=time
 def drawText(self, event, qp):
     qp.setPen(QColor(0, 0, 0))
     qp.setFont(QFont('SansSerif', 12))
     qp.drawText(event.rect(), Qt.AlignCenter, self.text)
Example #7
0
 def readSubstyles(self, editor):
     """
     Public method to load the sub-styles and configure the editor.
     
     @param editor reference to the editor object
     @type QsciScintilla
     """
     subStyleBasesLength = editor.SendScintilla(
         editor.SCI_GETSUBSTYLEBASES, 0, None)
     if not subStyleBasesLength:
         # lexer does not support sub-styling
         return
     
     self.loadSubstyles()
     
     # free existing sub-styles first
     editor.SendScintilla(editor.SCI_FREESUBSTYLES)
     subStyleBases = b"\00" * (subStyleBasesLength + 1)
     editor.SendScintilla(editor.SCI_GETSUBSTYLEBASES, 0, subStyleBases)
     distanceToSecondary = editor.SendScintilla(
         editor.SCI_DISTANCETOSECONDARYSTYLES)
     
     subStyleBases = [b for b in bytearray(subStyleBases[:-1])]
     if distanceToSecondary:
         subStyleBases.extend(b + distanceToSecondary
                              for b in subStyleBases[:])
     for baseStyleNo in subStyleBases:
         if baseStyleNo in self.__subStyles:
             subStylesData = self.__subStyles[baseStyleNo]
             subStyleLength = len(subStylesData)
             subStyleStart = editor.SendScintilla(
                 editor.SCI_ALLOCATESUBSTYLES, baseStyleNo, subStyleLength)
             if subStyleStart < 0:
                 continue
             
             subStyleIndex = -1
             for subStyleKey in sorted(subStylesData.keys()):
                 subStyleIndex += 1
                 styleNo = subStyleStart + subStyleIndex
                 subStyle = subStylesData[subStyleKey]
                 # set the words
                 editor.SendScintilla(
                     editor.SCI_SETIDENTIFIERS,
                     styleNo,
                     subStyle["Words"].encode())
                 
                 # set the style
                 style = subStyle["Style"]
                 if "fore" in style:
                     color = QColor(
                         style["fore"] >> 16 & 0xff,
                         style["fore"] >> 8 & 0xff,
                         style["fore"] & 0xff,
                     )
                 else:
                     color = self.color(baseStyleNo)
                 self.setColor(color, styleNo)
                 
                 if "paper" in style:
                     color = QColor(
                         style["paper"] >> 16 & 0xff,
                         style["paper"] >> 8 & 0xff,
                         style["paper"] & 0xff,
                     )
                 else:
                     color = self.paper(baseStyleNo)
                 self.setPaper(color, styleNo)
                 
                 if "eolfill" in style:
                     eolFill = style["eolfill"]
                 else:
                     eolFill = self.eolFill(baseStyleNo)
                 self.setEolFill(eolFill, styleNo)
                 
                 font = self.font(baseStyleNo)
                 if "font_family" in style:
                     font.setFamily(style["font_family"])
                 if "font_size" in style:
                     font.setPointSize(style["font_size"])
                 if "font_bold" in style:
                     font.setBold(style["font_bold"])
                 if "font_italic" in style:
                     font.setItalic(style["font_italic"])
                 if "font_underline" in style:
                     font.setUnderline(style["font_underline"])
                 self.setFont(font, styleNo)
 def color_row(self, row):
     for i in range(self.table_widget.columnCount()):
         self.table_widget.item(row, i).setBackground(QColor(0, 150, 100))
Example #9
0
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        # VENTANA
        self.setWindowTitle("EXADATA")
        self.setFixedSize(800, 600)
        self.setWindowIcon(QIcon("icono.jpg"))

        # FRAME
        paleta = QPalette()
        paleta.setColor(QPalette.Background, QColor(51, 0, 102))

        frame = QFrame(self)
        frame.setFrameShape(QFrame.NoFrame)
        frame.setFrameShadow(QFrame.Sunken)
        frame.setAutoFillBackground(True)
        frame.setPalette(paleta)
        frame.setFixedWidth(900)
        frame.setFixedHeight(100)
        frame.move(0, 0)

        labelIcono = QLabel(frame)
        labelIcono.setFixedWidth(65)
        labelIcono.setFixedHeight(65)
        labelIcono.setPixmap(
            QPixmap("icono.jpg").scaled(65, 65, Qt.KeepAspectRatio,
                                        Qt.SmoothTransformation))
        labelIcono.move(10, 28)

        fuenteTitulo = QFont()
        fuenteTitulo.setPointSize(25)
        fuenteTitulo.setBold(True)

        labelTitulo = QLabel("<font color='white'>EXADATA</font>", frame)
        labelTitulo.setFont(fuenteTitulo)
        labelTitulo.move(85, 30)

        fuenteSubtitulo = QFont()
        fuenteSubtitulo.setPointSize(13)

        labelSubtitulo = QLabel("<font color='white'>Análisis de Tweets ",
                                frame)
        labelSubtitulo.setFont(fuenteSubtitulo)
        labelSubtitulo.move(85, 68)

        labelVersion = QLabel(frame)
        labelVersion.setText(" EXADATA VERSIÓN BETA: 1.0  ")
        self.statusBar = self.statusBar()
        self.statusBar.addPermanentWidget(labelVersion, 0)

        oImage = QImage("back.jpg")
        sImage = oImage.scaled(QSize(800, 600))
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))  # 10 = Windowrole
        self.setPalette(palette)

        #LOGO

        # BARRA MENU
        self.menubar = QtWidgets.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 900, 21))
        self.menubar.setObjectName("menubar")

        # BOTON PROGRAMAS
        self.Programas = QtWidgets.QMenu(self.menubar)
        self.Apariencia = QtWidgets.QMenu(self.Programas)
        self.BaseDeDatos = QtWidgets.QAction(self)
        self.Muestra_Programa = QtWidgets.QAction(self)
        self.Cortar_Fecha = QtWidgets.QAction(self)
        self.Popularidad = QtWidgets.QAction(self)
        self.Nube_Palabras = QtWidgets.QAction(self)
        self.Bigramma = QtWidgets.QAction(self)
        self.Oscuro = QtWidgets.QAction(self)
        self.Claro = QtWidgets.QAction(self)

        # BOTON CONFIGURACIONES
        self.Configuracion = QtWidgets.QMenu(self.menubar)

        self.Programas.addAction(self.BaseDeDatos)
        self.Programas.addAction(self.Muestra_Programa)
        self.Programas.addAction(self.Cortar_Fecha)
        self.Programas.addAction(self.Popularidad)
        self.Programas.addAction(self.Nube_Palabras)
        self.Programas.addAction(self.Bigramma)
        self.Apariencia.addAction(self.Oscuro)
        self.Apariencia.addAction(self.Claro)
        self.Configuracion.addAction(self.Apariencia.menuAction())
        self.menubar.addAction(self.Configuracion.menuAction())

        # BOTON AYUDA
        self.Ayuda = QtWidgets.QMenu(self.menubar)
        self.Sobre_que = QtWidgets.QAction(self)
        self.Ayuda.addAction(self.Sobre_que)

        self.menubar.addAction(self.Programas.menuAction())
        self.menubar.addAction(self.Ayuda.menuAction())
        self.menubar.addAction(self.Configuracion.menuAction())

        # FUNCIONES
        self.BARRAMENU(self)
def setStyle(app):
    from PyQt5.QtCore import Qt
    app.setStyle("Fusion")
    darkPalette = QPalette()
    darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
    darkPalette.setColor(QPalette.WindowText, Qt.white)
    darkPalette.setColor(QPalette.Disabled, QPalette.WindowText,
                         QColor(127, 127, 127))
    darkPalette.setColor(QPalette.Base, QColor(42, 42, 42))
    darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
    darkPalette.setColor(QPalette.ToolTipBase, Qt.white)
    darkPalette.setColor(QPalette.ToolTipText, Qt.white)
    darkPalette.setColor(QPalette.Text, Qt.white)
    darkPalette.setColor(QPalette.Disabled, QPalette.Text,
                         QColor(127, 127, 127))
    darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35))
    darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20))
    darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
    darkPalette.setColor(QPalette.ButtonText, Qt.white)
    darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText,
                         QColor(127, 127, 127))
    darkPalette.setColor(QPalette.BrightText, Qt.red)
    darkPalette.setColor(QPalette.Link, QColor(42, 130, 218))
    darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    darkPalette.setColor(QPalette.Disabled, QPalette.Highlight,
                         QColor(80, 80, 80))
    darkPalette.setColor(QPalette.HighlightedText, Qt.white)
    darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText,
                         QColor(127, 127, 127))
    app.setPalette(darkPalette)
Example #11
0
 def resetOverlayColor(self):
     self._overlayColor = QColor(0, 0, .75, 150)
Example #12
0
class HealthStatusDisplay(QObject):
    indicator_side = 10
    indicator_border = 6
    health_colors = {
        HEALTH_GOOD: QColor(Qt.green),
        HEALTH_DEAD: QColor(Qt.red),
        HEALTH_MOOT: QColor(Qt.yellow),
        HEALTH_UNCHECKED: QColor("#B5B5B5"),
        HEALTH_CHECKING: QColor(Qt.yellow),
        HEALTH_ERROR: QColor(Qt.red)

    }

    def draw_text(self, painter, rect, text, color=QColor("#B5B5B5"), font=None, alignment=Qt.AlignVCenter):
        painter.save()
        text_flags = Qt.AlignLeft | alignment | Qt.TextSingleLine
        text_box = painter.boundingRect(rect, text_flags, text)
        painter.setPen(QPen(color, 1, Qt.SolidLine, Qt.RoundCap))
        if font:
            painter.setFont(font)

        painter.drawText(text_box, text_flags, text)
        painter.restore()

    def paint(self, painter, rect, index):
        data_item = index.model().data_items[index.row()]

        if u'health' not in data_item or data_item[u'health'] == "updated":
            data_item[u'health'] = get_health(data_item['num_seeders'],
                                              data_item['num_leechers'],
                                              data_item['last_tracker_check'])
        health = data_item[u'health']

        # ----------------
        # |b---b|        |
        # |b|i|b| 0S 0L  |
        # |b---b|        |
        # ----------------

        r = rect

        # Indicator ellipse rectangle
        y = r.top() + (r.height() - self.indicator_side) / 2
        x = r.left() + self.indicator_border
        w = self.indicator_side
        h = self.indicator_side
        indicator_rect = QRect(x, y, w, h)

        # Paint indicator
        painter.save()
        painter.setBrush(QBrush(self.health_colors[health]))
        painter.setPen(QPen(self.health_colors[health], 0, Qt.SolidLine, Qt.RoundCap))
        painter.drawEllipse(indicator_rect)
        painter.restore()

        x = indicator_rect.left() + indicator_rect.width() + 2 * self.indicator_border
        y = r.top()
        w = r.width() - indicator_rect.width() - 2 * self.indicator_border
        h = r.height()
        text_box = QRect(x, y, w, h)

        # Paint status text, if necessary
        if health in [HEALTH_CHECKING, HEALTH_UNCHECKED, HEALTH_ERROR]:
            self.draw_text(painter, text_box, health)
        else:
            seeders = int(data_item[u'num_seeders'])
            leechers = int(data_item[u'num_leechers'])

            txt = u'S' + str(seeders) + u' L' + str(leechers)

            self.draw_text(painter, text_box, txt)
Example #13
0
 def tab_indicator_color(self, idx):
     """Get the tab indicator color for the given index."""
     try:
         return self.tab_data(idx, 'indicator-color')
     except KeyError:
         return QColor()
    def paint(self, image):
        qp = QPainter(image)

        qp.setPen(QPen(QColor('blue'), 1))
        qp.drawRect(QPolygon(self.selected.getPoints()).boundingRect())
Example #15
0
    def paintEvent(self, event):

        painter = QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QPainter.Antialiasing)

        angle_step = 360 / self.n_states

        painter.save()  #Save_1. Save the state of the system (push matrix)
        painter.translate(
            self.dist_center.x(),
            self.dist_center.y())  # go to the center of the render area
        painter.rotate(
            -180
        )  #to start painting from the left side of the circle (clockwise)

        #center of the circumference where through we are going to paint our states
        x = self.dist_radius * math.cos(0)
        y = self.dist_radius * math.sin(0)

        for h in range(self.n_states):

            rot = angle_step * h  # each state is equidistant from the others. We paint them in circles

            painter.save()  #Save_2
            painter.rotate(
                rot)  #now our system is pointing to the next state to be drawn
            painter.translate(
                x, y
            )  #now our origin is in the center of the next state to be drawn

            #if the state is active, fill it green
            if self.machine.getState(h).isActive():
                painter.setBrush(self.greenGradientBrush)
            painter.drawEllipse(QPoint(0, 0), self.state_radius,
                                self.state_radius)  #draw the new state

            #global position of transformed coordinates (before any transformation, origin at top-left corner)
            gx = painter.worldTransform().map(QPoint(0, 0)).x()
            gy = painter.worldTransform().map(QPoint(0, 0)).y()
            self.machine.getState(h).setPos(
                gx, gy
            )  #store the center of the state without any transformation applied

            # text transformation. Our origin is still in the center of the current state
            painter.save()  #Save_3
            painter.rotate(180)  #making the text go vertical
            painter.rotate(
                -rot
            )  #undoing the rotation made for painting the state. No the text is horizontal
            font = painter.font()
            font.setPixelSize(self.state_radius * .4)
            painter.setFont(font)
            rect = QRect(-self.state_radius, -self.state_radius,
                         self.state_radius * 2, self.state_radius * 2)
            painter.drawText(rect, Qt.AlignCenter,
                             self.machine.getState(h).getName())
            painter.restore()  #Restore_3
            #end text transformation

            painter.restore()  #Restore_2

        painter.restore(
        )  #Restore_1. Restore the state of the system (pop matrix)

        #drawing transitions. Line between states
        painter.save()  # Save_4
        pptv = QTransform(
        )  #Define a new transformation. Needed to rotate the system along other axis than Z
        pptv.translate(
            0,
            self.height())  #We are now at the bottom-left corner of the screen
        pptv.rotate(
            -180, Qt.XAxis
        )  #Rotate along the X-axis so now we are in a typical cartesian system.
        painter.setTransform(pptv)  #Apply the transformation
        states = self.machine.getStates()
        for state in states:
            transitions = state.getTransitions()
            for transition in transitions:
                #get the center of the origin and destination states in our current system state
                orig = QPoint(state.getPos()[0], state.getPos()[1])
                end = QPoint(
                    self.machine.getState(
                        transition.getStateEnd()).getPos()[0],
                    self.machine.getState(
                        transition.getStateEnd()).getPos()[1])
                # get those coordinates without transformation
                orig2 = QPoint(painter.worldTransform().map(orig))
                end2 = QPoint(painter.worldTransform().map(end))

                #get the angle between states centers and the horizon
                angle = math.atan2(end2.y() - orig2.y(), end2.x() - orig2.x())

                #get the coordinates of the starting point of the transition (it starts in the bound of the state, not in the center)
                newX = self.state_radius * math.cos(angle) + orig2.x()
                newY = self.state_radius * math.sin(angle) + orig2.y()
                #now the transition starts at the border, not in the center
                orig2.setX(newX)
                orig2.setY(newY)

                #same for the destination state
                angle2 = math.atan2(orig2.y() - end2.y(), orig2.x() - end2.x())
                newX2 = self.state_radius * math.cos(angle2) + end2.x()
                newY2 = self.state_radius * math.sin(angle2) + end2.y()
                end2.setX(newX2)
                end2.setY(newY2)

                #draw the line between the origin and destination states
                painter.drawLine(orig2, end2)
                #get the start and the end of the transition untransformed
                init = QPoint(painter.worldTransform().map(orig2))
                end = QPoint(painter.worldTransform().map(end2))
                #store that info
                transition.setOrig(init.x(), init.y())
                transition.setDest(end.x(), end.y())
                transition.setAngle(angle)
        painter.restore()  #Restore_4

        #Appliying style to the transitions
        painter.setPen(QPen(QColor(Qt.gray), 3))
        for state in self.machine.getStates():
            for transition in state.getTransitions():
                #get the start and end coordinates of the transition
                i = QPoint(transition.getOrig()[0], transition.getOrig()[1])
                o = QPoint(transition.getDest()[0], transition.getDest()[1])
                painter.drawPolyline(i, o)

                #Drawing the arrow at the end of the transition
                painter.save()  #Save_5
                painter.setPen(QPen(QColor(Qt.gray), 2))
                painter.translate(
                    transition.getDest()[0],
                    transition.getDest()[1])  #Go to the end of the transition
                painter.rotate(
                    90 - transition.getAngle() * 180 / math.pi
                )  #Rotate to point in the direction of the transition

                #coordinates of the arrow (triangle)
                a = QPoint(0, 0)
                b = QPoint(-5, 10)
                c = QPoint(5, 10)

                #coordinates of the arrow untransformed
                a1 = painter.worldTransform().map(a)
                b1 = painter.worldTransform().map(b)
                c1 = painter.worldTransform().map(c)

                #Drawin the actual arrow
                pointer = QPolygon([a, b, c])
                painter.drawPolygon(pointer)
                painter.restore()  #Restore_5

                #For the animation of the transition
                painter.save()  #Save_6
                if transition.isActive(
                ):  #if the current transition is the active one the wave function will be running, so it's updating the canvas

                    painter.setPen(QPen(QColor(Qt.green), 3))
                    painter.drawPolyline(i, o)

                    painter.setPen(QPen(QColor(Qt.gray), 3))
                    painter.drawPolyline(self.poly(self.pts))

                    #Draw the arrow in the active state (red arrow)
                    painter.setBrush(QBrush(QColor(255, 0, 0)))
                    painter.setPen(QPen(QColor(Qt.red), 2))
                    pointer = QPolygon([a1, b1, c1])
                    painter.drawPolygon(pointer)

                    #Ball that follows the line animation
                    for x, y in self.pts:
                        painter.drawEllipse(
                            QRectF(self.pts[0][0] - 4, self.pts[0][1] - 4, 8,
                                   8))
                painter.restore()  #Restore_6

                #Painting the text of the transition
                painter.save()  #Save_7
                pptv = QTransform()
                painter.setPen(QPen(QColor(Qt.black), 3))
                #get the middle point of the transition
                middleX = (transition.getOrig()[0] +
                           transition.getDest()[0]) / 2
                middleY = (transition.getOrig()[1] +
                           transition.getDest()[1]) / 2
                pptv.translate(middleX, middleY)  #translate to that point
                painter.setTransform(pptv)  #apply the transformation
                font = painter.font()
                font.setPixelSize(self.state_radius * .2)
                painter.setFont(font)
                rect = QRect(-self.state_radius, -self.state_radius,
                             self.state_radius * 2, self.state_radius * 2)
                name = str(transition.getId()) + '. ' + transition.getName()
                painter.drawText(rect, Qt.AlignCenter, name)
                painter.restore()  #Restore_7

        #paint the actual canvas
        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
def updateMask(control_image_path, rendered_image_path, mask_image_path):
    control_image = imageFromPath(control_image_path)
    if not control_image:
        error('Could not read control image {}'.format(control_image_path))

    rendered_image = imageFromPath(rendered_image_path)
    if not rendered_image:
        error('Could not read rendered image {}'.format(rendered_image_path))
    if not rendered_image.width() == control_image.width(
    ) or not rendered_image.height() == control_image.height():
        print(
            ('Size mismatch - control image is {}x{}, rendered image is {}x{}'.
             format(control_image.width(), control_image.height(),
                    rendered_image.width(), rendered_image.height())))

    max_width = min(rendered_image.width(), control_image.width())
    max_height = min(rendered_image.height(), control_image.height())

    # read current mask, if it exist
    mask_image = imageFromPath(mask_image_path)
    if mask_image.isNull():
        print('Mask image does not exist, creating {}'.format(mask_image_path))
        mask_image = QImage(control_image.width(), control_image.height(),
                            QImage.Format_ARGB32)
        mask_image.fill(QColor(0, 0, 0))

    # loop through pixels in rendered image and compare
    mismatch_count = 0
    linebytes = max_width * 4
    for y in range(max_height):
        control_scanline = control_image.constScanLine(y).asstring(linebytes)
        rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes)
        mask_scanline = mask_image.scanLine(y).asstring(linebytes)

        for x in range(max_width):
            currentTolerance = qRed(
                struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0])

            if currentTolerance == 255:
                # ignore pixel
                continue

            expected_rgb = struct.unpack('I',
                                         control_scanline[x * 4:x * 4 + 4])[0]
            rendered_rgb = struct.unpack('I',
                                         rendered_scanline[x * 4:x * 4 + 4])[0]
            difference = colorDiff(expected_rgb, rendered_rgb)

            if difference > currentTolerance:
                # update mask image
                mask_image.setPixel(x, y,
                                    qRgb(difference, difference, difference))
                mismatch_count += 1

    if mismatch_count:
        # update mask
        mask_image.save(mask_image_path, "png")
        print('Updated {} pixels in {}'.format(mismatch_count,
                                               mask_image_path))
    else:
        print('No mismatches in {}'.format(mask_image_path))
Example #17
0
class InsertSinePlugin(SignalEditorPlugin):
    insert_sine_wave_clicked = pyqtSignal()

    INSERT_INDICATOR_COLOR = QColor(0, 255, 0, 80)

    def __init__(self):

        self.__dialog_ui = None  # type: QDialog
        self.complex_wave = None

        self.__amplitude = 0.5
        self.__frequency = 10
        self.__phase = 0
        self.__sample_rate = 1e6
        self.__num_samples = int(1e6)

        self.original_data = None
        self.draw_data = None
        self.position = 0

        super().__init__(name="InsertSine")

    @property
    def dialog_ui(self) -> QDialog:
        if self.__dialog_ui is None:
            dir_name = os.path.dirname(
                os.readlink(__file__)) if os.path.islink(
                    __file__) else os.path.dirname(__file__)

            logging.getLogger().setLevel(logging.WARNING)
            self.__dialog_ui = uic.loadUi(
                os.path.realpath(
                    os.path.join(dir_name, "insert_sine_dialog.ui")))
            logging.getLogger().setLevel(logger.level)

            self.__dialog_ui.setAttribute(Qt.WA_DeleteOnClose)
            self.__dialog_ui.setModal(True)
            self.__dialog_ui.doubleSpinBoxAmplitude.setValue(self.__amplitude)
            self.__dialog_ui.doubleSpinBoxFrequency.setValue(self.__frequency)
            self.__dialog_ui.doubleSpinBoxPhase.setValue(self.__phase)
            self.__dialog_ui.doubleSpinBoxSampleRate.setValue(
                self.__sample_rate)
            self.__dialog_ui.doubleSpinBoxNSamples.setValue(self.__num_samples)
            self.__dialog_ui.lineEditTime.setValidator(
                QRegExpValidator(
                    QRegExp("[0-9]+([nmµ]*|([\.,][0-9]{1,3}[nmµ]*))?$")))

            scene_manager = SceneManager(self.dialog_ui.graphicsViewSineWave)
            self.__dialog_ui.graphicsViewSineWave.scene_manager = scene_manager
            self.insert_indicator = scene_manager.scene.addRect(
                0, -2, 0, 4, QPen(QColor(Qt.transparent), 0),
                QBrush(self.INSERT_INDICATOR_COLOR))
            self.insert_indicator.stackBefore(
                scene_manager.scene.selection_area)

            self.set_time()

        return self.__dialog_ui

    @property
    def amplitude(self) -> float:
        return self.__amplitude

    @amplitude.setter
    def amplitude(self, value: float):
        if value != self.amplitude:
            self.__amplitude = value
            self.draw_sine_wave()

    @property
    def frequency(self) -> float:
        return self.__frequency

    @frequency.setter
    def frequency(self, value: float):
        if value != self.frequency:
            self.__frequency = value
            self.draw_sine_wave()

    @property
    def phase(self) -> float:
        return self.__phase

    @phase.setter
    def phase(self, value: float):
        if value != self.phase:
            self.__phase = value
            self.draw_sine_wave()

    @property
    def sample_rate(self) -> float:
        return self.__sample_rate

    @sample_rate.setter
    def sample_rate(self, value: float):
        if value != self.sample_rate:
            self.__sample_rate = value
            self.set_time()
            self.draw_sine_wave()

    @property
    def num_samples(self) -> int:
        return self.__num_samples

    @num_samples.setter
    def num_samples(self, value: int):
        value = int(value)
        if value != self.num_samples:
            self.__num_samples = value
            self.set_time()
            self.draw_sine_wave()

    def create_connects(self):
        pass

    def create_dialog_connects(self):
        self.dialog_ui.doubleSpinBoxAmplitude.editingFinished.connect(
            self.on_double_spin_box_amplitude_editing_finished)
        self.dialog_ui.doubleSpinBoxFrequency.editingFinished.connect(
            self.on_double_spin_box_frequency_editing_finished)
        self.dialog_ui.doubleSpinBoxPhase.editingFinished.connect(
            self.on_double_spin_box_phase_editing_finished)
        self.dialog_ui.doubleSpinBoxSampleRate.editingFinished.connect(
            self.on_double_spin_box_sample_rate_editing_finished)
        self.dialog_ui.doubleSpinBoxNSamples.editingFinished.connect(
            self.on_spin_box_n_samples_editing_finished)
        self.dialog_ui.lineEditTime.editingFinished.connect(
            self.on_line_edit_time_editing_finished)
        self.dialog_ui.buttonBox.accepted.connect(self.on_button_box_accept)
        self.dialog_ui.buttonBox.rejected.connect(self.on_button_box_reject)
        self.__dialog_ui.finished.connect(self.on_dialog_finished)

    def get_insert_sine_dialog(self,
                               original_data,
                               position,
                               sample_rate=None,
                               num_samples=None) -> QDialog:
        if sample_rate is not None:
            self.sample_rate = sample_rate
            self.dialog_ui.doubleSpinBoxSampleRate.setValue(sample_rate)

        if num_samples is not None:
            self.__num_samples = int(num_samples)
            self.dialog_ui.doubleSpinBoxNSamples.setValue(num_samples)

        self.original_data = original_data
        self.position = position

        self.set_time()
        self.draw_sine_wave()
        self.create_dialog_connects()

        return self.dialog_ui

    def draw_sine_wave(self):
        if self.dialog_ui.graphicsViewSineWave.scene_manager:
            self.dialog_ui.graphicsViewSineWave.scene_manager.clear_path()

        QApplication.instance().setOverrideCursor(Qt.WaitCursor)
        self.__set_status_of_editable_elements(enabled=False)

        t = np.arange(0, self.num_samples) / self.sample_rate
        arg = 2 * np.pi * self.frequency * t + self.phase

        self.complex_wave = np.empty(len(arg), dtype=np.complex64)
        self.complex_wave.real = np.cos(arg)
        self.complex_wave.imag = np.sin(arg)
        self.complex_wave = IQArray(self.amplitude *
                                    self.complex_wave).convert_to(
                                        self.original_data.dtype)

        self.draw_data = np.insert(self.original_data[:, 0], self.position,
                                   self.complex_wave[:, 0])
        y, h = self.dialog_ui.graphicsViewSineWave.view_rect().y(
        ), self.dialog_ui.graphicsViewSineWave.view_rect().height()
        self.insert_indicator.setRect(self.position, y - h, self.num_samples,
                                      2 * h + abs(y))

        self.__set_status_of_editable_elements(enabled=True)
        QApplication.instance().restoreOverrideCursor()
        self.dialog_ui.graphicsViewSineWave.plot_data(self.draw_data)
        self.dialog_ui.graphicsViewSineWave.show_full_scene()

    def __set_status_of_editable_elements(self, enabled: bool):
        for obj in ("doubleSpinBoxAmplitude", "doubleSpinBoxFrequency",
                    "doubleSpinBoxPhase", "doubleSpinBoxSampleRate",
                    "doubleSpinBoxNSamples", "lineEditTime", "buttonBox"):
            getattr(self.dialog_ui, obj).setEnabled(enabled)

    def set_time(self):
        self.dialog_ui.lineEditTime.setText(
            Formatter.science_time(self.num_samples / self.sample_rate,
                                   decimals=3,
                                   append_seconds=False,
                                   remove_spaces=True))

    @pyqtSlot()
    def on_double_spin_box_amplitude_editing_finished(self):
        self.amplitude = self.dialog_ui.doubleSpinBoxAmplitude.value()

    @pyqtSlot()
    def on_double_spin_box_frequency_editing_finished(self):
        self.frequency = self.dialog_ui.doubleSpinBoxFrequency.value()

    @pyqtSlot()
    def on_double_spin_box_phase_editing_finished(self):
        self.phase = self.dialog_ui.doubleSpinBoxPhase.value()

    @pyqtSlot()
    def on_double_spin_box_sample_rate_editing_finished(self):
        self.sample_rate = self.dialog_ui.doubleSpinBoxSampleRate.value()

    @pyqtSlot()
    def on_spin_box_n_samples_editing_finished(self):
        self.num_samples = self.dialog_ui.doubleSpinBoxNSamples.value()

    @pyqtSlot()
    def on_line_edit_time_editing_finished(self):
        time_str = self.dialog_ui.lineEditTime.text().replace(",", ".")
        suffix = ""
        try:
            t = float(time_str)
        except ValueError:
            suffix = time_str[-1]
            try:
                t = float(time_str[:-1])
            except ValueError:
                return

        factor = 10**-9 if suffix == "n" else 10**-6 if suffix == "µ" else 10**-3 if suffix == "m" else 1
        time_val = t * factor

        if self.sample_rate * time_val >= 1:
            self.dialog_ui.doubleSpinBoxNSamples.setValue(self.sample_rate *
                                                          time_val)
            self.dialog_ui.doubleSpinBoxNSamples.editingFinished.emit()
        else:
            self.set_time()

    @pyqtSlot()
    def on_button_box_reject(self):
        self.dialog_ui.reject()

    @pyqtSlot()
    def on_button_box_accept(self):
        self.insert_sine_wave_clicked.emit()
        self.dialog_ui.accept()

    @pyqtSlot()
    def on_dialog_finished(self):
        self.sender().graphicsViewSineWave.eliminate()
        self.__dialog_ui = None
Example #18
0
 def __init__(self, render_info):
     super().__init__()
     self.render_info = render_info
     self.color1 = QColor(0, 0, 0)
     self.color2 = QColor(0, 0, 0)
     self.wall_color = QColor(120, 120, 120)
Example #19
0
    def __init__(self, parent=None):
        super(AmzHistoryChart, self).__init__(parent=parent)

        self.dbsession = Session()
        self.context_menu_actions = []
        self._avg_pointspan = 0
        self._max_points = 100
        self.source = None
        self.history = None

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # Set up the chart
        self.chart_view = QChartView(self)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.chart_view.customContextMenuRequested.connect(self.context_menu)

        self.chart = QChart()
        self.chart.legend().hide()
        self.chart.setFlags(QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsSelectable)
        self.chart.installEventFilter(self)
        self.chart_view.setChart(self.chart)

        self.layout().addWidget(self.chart_view)

        # Create the axes
        rcolor = QColor(50, 130, 220)
        pcolor = QColor(0, 200, 0)
        ocolor = QColor(255, 175, 0)

        self.timeAxis = QDateTimeAxis()
        self.timeAxis.setFormat('M/dd hh:mm')
        self.timeAxis.setTitleText('Date/Time')
        self.chart.addAxis(self.timeAxis, Qt.AlignBottom)

        self.timeAxis.minChanged.connect(self.on_timeaxis_min_changed)

        self.rankAxis = QValueAxis()
        self.rankAxis.setLabelFormat('%\'i')
        self.rankAxis.setTitleText('Sales Rank')
        self.rankAxis.setLinePenColor(rcolor)
        self.rankAxis.setLabelsColor(rcolor)
        self.chart.addAxis(self.rankAxis, Qt.AlignLeft)

        self.priceAxis = QValueAxis()
        self.priceAxis.setLabelFormat('$%.2f')
        self.priceAxis.setTitleText('Price')
        self.priceAxis.setLinePenColor(pcolor)
        self.priceAxis.setLabelsColor(pcolor)
        self.chart.addAxis(self.priceAxis, Qt.AlignRight)

        # Create the series
        self.rankLine = QLineSeries()
        self.chart.addSeries(self.rankLine)
        self.rankLine.attachAxis(self.timeAxis)
        self.rankLine.attachAxis(self.rankAxis)
        self.rankLine.setColor(rcolor)

        self.priceLine = QLineSeries()
        self.chart.addSeries(self.priceLine)
        self.priceLine.attachAxis(self.timeAxis)
        self.priceLine.attachAxis(self.priceAxis)
        self.priceLine.setColor(pcolor)

        self.salesPoints = QScatterSeries()
        self.chart.addSeries(self.salesPoints)
        self.salesPoints.attachAxis(self.timeAxis)
        self.salesPoints.attachAxis(self.rankAxis)
        self.salesPoints.setColor(ocolor)
Example #20
0
from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout

app = QApplication([])
window = QWidget()

grid = QGridLayout()
window.setLayout(grid)

palette = QPalette()
palette.setColor(QPalette.Window, QColor(43,49,55))
palette.setColor(QPalette.ButtonText, QColor(97, 175, 239))
app.setPalette(palette)

grid.addWidget(QPushButton('1'), 1, 1)
grid.addWidget(QPushButton('2'), 1, 2)
grid.addWidget(QPushButton('3'), 2, 1)
grid.addWidget(QPushButton('4'), 2, 2)

window.show()
app.exec_()
Example #21
0
    def data(self, index, role=Qt.DisplayRole):
        data = None
        if not index.isValid():
            return QVariant(data)
        if role not in [
                Qt.DisplayRole, Qt.EditRole, Qt.ToolTipRole, Qt.FontRole,
                Qt.BackgroundRole
        ]:
            return None

        mn = self.masternodes[index.row()]
        i = index.column()

        if i == self.ALIAS:
            data = mn.alias
        elif i == self.STATUS:
            status = self.manager.masternode_statuses.get(
                mn.get_collateral_str())
            data = masternode_status(status)
            if role == Qt.BackgroundRole:
                data = QBrush(
                    QColor(ENABLED_MASTERNODE_BG)) if data[0] else None
            # Return the long description for data widget mappers.
            elif role == Qt.EditRole:
                data = data[2]
            else:
                data = data[1]
        elif i == self.VIN:
            txid = mn.vin.get('prevout_hash', '')
            out_n = str(mn.vin.get('prevout_n', ''))
            addr = mn.vin.get('address', '')
            value = str(mn.vin.get('value', ''))
            scriptsig = mn.vin.get('scriptSig', '')
            if role == Qt.EditRole:
                data = ':'.join([txid, out_n, addr, value, scriptsig])
            elif role == Qt.FontRole:
                data = util.MONOSPACE_FONT
            else:
                if all(attr for attr in [txid, out_n, addr]):
                    data = '%s:%s' % (txid, out_n)
                else:
                    data = ''
        elif i == self.COLLATERAL:
            data = mn.collateral_key
            if role in [Qt.EditRole, Qt.DisplayRole, Qt.ToolTipRole] and data:
                data = bitcoin.public_key_to_p2pkh(bfh(data))
            elif role == Qt.FontRole:
                data = util.MONOSPACE_FONT
        elif i == self.DELEGATE:
            data = mn.delegate_key
            if role in [Qt.EditRole, Qt.DisplayRole, Qt.ToolTipRole] and data:
                data = self.manager.get_delegate_privkey(data)
            elif role == Qt.FontRole:
                data = util.MONOSPACE_FONT
        elif i == self.ADDR:
            data = ''
            if mn.addr.ip:
                data = str(mn.addr)
        elif i == self.PROTOCOL_VERSION:
            data = mn.protocol_version

        return QVariant(data)
Example #22
0
 def as_color(self, background=False):
     color = self._get_color(background)
     return QColor(color)
Example #23
0
 def resetState(self):
     self._color = QColor(0, 0, 0, 150)
Example #24
0
    def on_update(self):
        def item_path(
            item
        ):  # Recursively builds the path for an item eg 'parent_name/item_name'
            return item.text(0) if not item.parent() else item_path(
                item.parent()) + "/" + item.text(0)

        def remember_expanded_items(root):
            # Save the set of expanded items... so that address list updates don't annoyingly collapse
            # our tree list widget due to the update. This function recurses. Pass self.invisibleRootItem().
            expanded_item_names = set()
            for i in range(0, root.childCount()):
                it = root.child(i)
                if it and it.childCount():
                    if it.isExpanded():
                        expanded_item_names.add(item_path(it))
                    expanded_item_names |= remember_expanded_items(
                        it)  # recurse
            return expanded_item_names

        def restore_expanded_items(root, expanded_item_names):
            # Recursively restore the expanded state saved previously. Pass self.invisibleRootItem().
            for i in range(0, root.childCount()):
                it = root.child(i)
                if it and it.childCount():
                    restore_expanded_items(
                        it, expanded_item_names)  # recurse, do leaves first
                    old = bool(it.isExpanded())
                    new = bool(item_path(it) in expanded_item_names)
                    if old != new:
                        it.setExpanded(new)

        self.wallet = self.parent.wallet
        had_item_count = self.topLevelItemCount()
        sels = self.selectedItems()
        addresses_to_re_select = {item.data(0, Qt.UserRole) for item in sels}
        expanded_item_names = remember_expanded_items(self.invisibleRootItem())
        del sels  # avoid keeping reference to about-to-be delete C++ objects
        self.clear()
        receiving_addresses = self.wallet.get_receiving_addresses()
        change_addresses = self.wallet.get_change_addresses()

        if self.parent.fx and self.parent.fx.get_fiat_address_config():
            fx = self.parent.fx
        else:
            fx = None
        account_item = self
        sequences = [0, 1] if change_addresses else [0]
        items_to_re_select = []
        for is_change in sequences:
            if len(sequences) > 1:
                name = _("Receiving") if not is_change else _("Change")
                seq_item = QTreeWidgetItem([name, '', '', '', '', ''])
                account_item.addChild(seq_item)
                if not is_change and not had_item_count:  # first time we create this widget, auto-expand the default address list
                    seq_item.setExpanded(True)
                    expanded_item_names.add(item_path(seq_item))
            else:
                seq_item = account_item
            used_item = QTreeWidgetItem([_("Used"), '', '', '', '', ''])
            used_flag = False
            addr_list = change_addresses if is_change else receiving_addresses
            for n, address in enumerate(addr_list):
                num = len(self.wallet.get_address_history(address))
                is_used = self.wallet.is_used(address)
                balance = sum(self.wallet.get_addr_balance(address))
                address_text = address.to_ui_string()
                label = self.wallet.labels.get(address.to_storage_string(), '')
                balance_text = self.parent.format_amount(balance,
                                                         whitespaces=True)
                columns = [address_text, str(n), label, balance_text, str(num)]
                if fx:
                    rate = fx.exchange_rate()
                    fiat_balance = fx.value_str(balance, rate)
                    columns.insert(4, fiat_balance)
                address_item = SortableTreeWidgetItem(columns)
                address_item.setTextAlignment(3, Qt.AlignRight)
                address_item.setFont(3, QFont(MONOSPACE_FONT))
                if fx:
                    address_item.setTextAlignment(4, Qt.AlignRight)
                    address_item.setFont(4, QFont(MONOSPACE_FONT))

                address_item.setFont(0, QFont(MONOSPACE_FONT))
                address_item.setData(0, Qt.UserRole, address)
                address_item.setData(0, Qt.UserRole + 1,
                                     True)  # label can be edited
                if self.wallet.is_frozen(address):
                    address_item.setBackground(0, QColor('lightblue'))
                if self.wallet.is_beyond_limit(address, is_change):
                    address_item.setBackground(0, QColor('red'))
                if is_used:
                    if not used_flag:
                        seq_item.insertChild(0, used_item)
                        used_flag = True
                    used_item.addChild(address_item)
                else:
                    seq_item.addChild(address_item)
                if address in addresses_to_re_select:
                    items_to_re_select.append(address_item)

        for item in items_to_re_select:
            # NB: Need to select the item at the end becasue internally Qt does some index magic
            # to pick out the selected item and the above code mutates the TreeList, invalidating indices
            # and other craziness, which might produce UI glitches. See #1042
            item.setSelected(True)

        # Now, at the very end, enforce previous UI state with respect to what was expanded or not. See #1042
        restore_expanded_items(self.invisibleRootItem(), expanded_item_names)
    def __init__(self):
        QMainWindow.__init__(self)
        #self.setWindowFlags(Qt.CustomizeWindowHint)
        #self.setWindowFlags(Qt.WindowMinMaxButtonsHint)

        # creating map canvas, which draws the maplayers
        # setting up features like canvas color
        self.canvas = QgsMapCanvas()
        self.canvas.setMinimumSize(550, 700)
        self.canvas.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.setSelectionColor(QColor(255, 255, 26, 200))
        self.canvas.enableAntiAliasing(True)
        self.canvas.setParallelRenderingEnabled(True)

        # empty list for selected polygons
        self.selected_features = []

        # setting up label settings: object below houses all of them
        self.label_settings = QgsPalLayerSettings()

        # object for text settings
        text_format = QgsTextFormat()

        text_format.setFont(QFont("Helvetica", 12))
        text_format.setSize(7)

        # setting up a white buffer around the labels
        buffer_settings = QgsTextBufferSettings()
        buffer_settings.setEnabled(True)
        buffer_settings.setSize(0.65)
        buffer_settings.setColor(Qt.white)
        text_format.setBuffer(buffer_settings)

        # label settings:
        # fieldName = which field is shown as the label (currently Finnish name)
        # placement = labels can be placed differently in relation to one another
        #              - see documentation for details
        self.label_settings.setFormat(text_format)
        self.label_settings.fieldName = "namefin"
        self.label_settings.placement = 0
        self.label_settings.enabled = True

        # Qmainwindow requires a central widget. Canvas is placed
        self.setCentralWidget(self.canvas)

        # creating each desired action
        self.actionGet = QAction("Return selected and close", self)
        self.actionPan = QAction("Pan tool", self)
        self.actionSelect = QAction("Select tool", self)
        self.actionClear = QAction("Clear selection", self)
        self.actionCancel = QAction("Cancel and close", self)

        # these two function as on/off. the rest are clickable
        self.actionPan.setCheckable(True)
        self.actionSelect.setCheckable(True)

        # when actions are clicked, do corresponding function
        self.actionPan.triggered.connect(self.pan)
        self.actionSelect.triggered.connect(self.select)
        self.actionClear.triggered.connect(self.clearSelection)
        self.actionGet.triggered.connect(self.finishedSelection)
        self.actionCancel.triggered.connect(self.cancel)

        # toolbar at the top of the screen: houses actions as buttons
        # change order here to change their placement on window
        self.toolbar = self.addToolBar("Canvas actions")
        self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu)
        self.toolbar.setMovable(False)
        self.toolbar.addAction(self.actionGet)
        self.toolbar.addAction(self.actionPan)
        self.toolbar.addAction(self.actionSelect)
        self.toolbar.addAction(self.actionClear)
        self.toolbar.addAction(self.actionCancel)

        # link actions to premade map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(self.actionPan)
        self.toolSelect = QgsMapToolIdentifyFeature(self.canvas)
        self.toolSelect.setAction(self.actionSelect)
        self.toolSelect.featureIdentified.connect(self.selectFeature)

        self.blocks_flag = False

        self.selection_rectangle = False

        # set select tool as default
        self.select()
        self.notify_label.setText("Scan above QR to copy information")
        self.notify_label.setFont(self.notify_font)
        self.notify_label.setAlignment(Qt.AlignCenter)
        self.notify_label.setStyleSheet("color: #eee")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addStretch()
        layout.addWidget(self.qrcode_label, 0, Qt.AlignCenter)
        layout.addSpacing(20)
        layout.addWidget(self.file_name_label, 0, Qt.AlignCenter)
        layout.addSpacing(40)
        layout.addWidget(self.notify_label, 0, Qt.AlignCenter)
        layout.addStretch()

        self.qrcode_label.setPixmap(
            qrcode.make(url, image_factory=Image).pixmap())


if __name__ == "__main__":
    from PyQt5.QtWidgets import QApplication
    import sys
    import signal
    app = QApplication(sys.argv)

    test = AirShareWidget("/home/andy/rms/1.jpg", QColor(0, 0, 0, 255))
    test.show()

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    sys.exit(app.exec_())
Example #27
0
    def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant:
        # note: this method is performance-critical.
        # it is called a lot, and so must run extremely fast.
        assert index.isValid()
        col = index.column()
        tx_item = self.transactions.value_from_pos(index.row())
        is_lightning = tx_item.get('lightning', False)
        timestamp = tx_item['timestamp']
        if is_lightning:
            status = 0
            txpos = tx_item['txpos']
            if timestamp is None:
                status_str = 'unconfirmed'
            else:
                status_str = format_time(int(timestamp))
        else:
            tx_hash = tx_item['txid']
            conf = tx_item['confirmations']
            txpos = tx_item['txpos_in_block'] or 0
            height = tx_item['height']
            try:
                status, status_str = self.tx_status_cache[tx_hash]
            except KeyError:
                tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
                status, status_str = self.parent.wallet.get_tx_status(
                    tx_hash, tx_mined_info)

        # we sort by timestamp
        if timestamp is None:
            timestamp = float("inf")

        if role == Qt.UserRole:
            # for sorting
            d = {
                HistoryColumns.STATUS:
                    # height breaks ties for unverified txns
                    # txpos breaks ties for verified same block txns
                    (-timestamp, conf, -status, -height, -txpos) if not is_lightning else (-timestamp, 0,0,0,-txpos),
                HistoryColumns.DESCRIPTION:
                    tx_item['label'] if 'label' in tx_item else None,
                HistoryColumns.AMOUNT:
                    (tx_item['bc_value'].value if 'bc_value' in tx_item else 0)\
                    + (tx_item['ln_value'].value if 'ln_value' in tx_item else 0),
                HistoryColumns.BALANCE:
                    (tx_item['balance'].value if 'balance' in tx_item else 0)\
                    + (tx_item['balance_msat']//1000 if 'balance_msat'in tx_item else 0),
                HistoryColumns.FIAT_VALUE:
                    tx_item['fiat_value'].value if 'fiat_value' in tx_item else None,
                HistoryColumns.FIAT_ACQ_PRICE:
                    tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None,
                HistoryColumns.FIAT_CAP_GAINS:
                    tx_item['capital_gain'].value if 'capital_gain' in tx_item else None,
                HistoryColumns.TXID: tx_hash if not is_lightning else None,
            }
            return QVariant(d[col])
        if role not in (Qt.DisplayRole, Qt.EditRole):
            if col == HistoryColumns.STATUS and role == Qt.DecorationRole:
                icon = "lightning" if is_lightning else TX_ICONS[status]
                return QVariant(read_QIcon(icon))
            elif col == HistoryColumns.STATUS and role == Qt.ToolTipRole:
                msg = 'lightning transaction' if is_lightning else str(
                    conf) + _(" confirmation" + ("s" if conf != 1 else ""))
                return QVariant(msg)
            elif col > HistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole:
                return QVariant(Qt.AlignRight | Qt.AlignVCenter)
            elif col != HistoryColumns.STATUS and role == Qt.FontRole:
                monospace_font = QFont(MONOSPACE_FONT)
                return QVariant(monospace_font)
            #elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole and not is_lightning\
            #        and self.parent.wallet.invoices.paid.get(tx_hash):
            #    return QVariant(read_QIcon("seal"))
            elif col in (HistoryColumns.DESCRIPTION, HistoryColumns.AMOUNT) \
                    and role == Qt.ForegroundRole and tx_item['value'].value < 0:
                red_brush = QBrush(QColor("#BC1E1E"))
                return QVariant(red_brush)
            elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \
                    and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None:
                blue_brush = QBrush(QColor("#1E1EFF"))
                return QVariant(blue_brush)
            return QVariant()
        if col == HistoryColumns.STATUS:
            return QVariant(status_str)
        elif col == HistoryColumns.DESCRIPTION and 'label' in tx_item:
            return QVariant(tx_item['label'])
        elif col == HistoryColumns.AMOUNT:
            bc_value = tx_item['bc_value'].value if 'bc_value' in tx_item else 0
            ln_value = tx_item['ln_value'].value if 'ln_value' in tx_item else 0
            value = bc_value + ln_value
            v_str = self.parent.format_amount(value,
                                              is_diff=True,
                                              whitespaces=True)
            return QVariant(v_str)
        elif col == HistoryColumns.BALANCE:
            balance = tx_item['balance'].value
            balance_str = self.parent.format_amount(balance, whitespaces=True)
            return QVariant(balance_str)
        elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item:
            value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value)
            return QVariant(value_str)
        elif col == HistoryColumns.FIAT_ACQ_PRICE and \
                tx_item['value'].value < 0 and 'acquisition_price' in tx_item:
            # fixme: should use is_mine
            acq = tx_item['acquisition_price'].value
            return QVariant(self.parent.fx.format_fiat(acq))
        elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item:
            cg = tx_item['capital_gain'].value
            return QVariant(self.parent.fx.format_fiat(cg))
        elif col == HistoryColumns.TXID:
            return QVariant(tx_hash) if not is_lightning else QVariant('')
        return QVariant()
    def __init__(self, buffer_id, url):
        Buffer.__init__(self, buffer_id, url, False, QColor(0, 0, 0, 255))

        self.add_widget(AirShareWidget(url, QColor(0, 0, 0, 255)))
Example #29
0
 def __init__(self, parent=None):
     '''
         Initialize the flowsheet display
     '''
     super(fsScene, self).__init__(parent)
     # Location of mouse events and whether the mouse button is down
     self.mouseDown = False
     self.pressX = 0.0
     self.pressY = 0.0
     self.releaseX = 0.0
     self.releaseY = 0.0
     #
     self.minorGrid = 20  # Minor grid spacing
     self.majorGrid = 100  # Major grid spacing
     self.xMaxGrid = 800  # Extent of grid area up x
     self.xMinGrid = -800  # Extent of grid area lo x
     self.yMaxGrid = 600  # Extent of grid area up y
     self.yMinGrid = -600  # Extent of grid area lo y
     self.nodeSize = 20  # size of node
     self.edgeArrowSize = 16  # size of the edge arrows
     self.actNodeSize = 25  # size of an active node
     self.mode = self.MODE_SELECT  # Mouse mode
     self.p = parent  # Parent class
     self.node1 = None  # Node 1 for drawing edges
     self.node2 = None  # Node 2 for drawing edges
     self.selectedNodes = []  # Set of selected nodes
     self.selectedEdges = []  # Set of selected edges
     self.majorGridPen = None  # Pen for major grids
     self.minorGridPen = None  # Pen for minor grids
     self.edgePen = None  # Pen for edges
     self.tearEdgePen = None  # Pen for tear edges
     self.nodePen = None  # Pen for nodes
     self.activeNodePen = None  # Pen for active node
     self.selectionPen = None  # Pen for node selection markers
     self.eSelectionPen = None  # Pen for edge selection markers
     #
     # Line styles
     self.lcMajorGrid = QColor(255, 190, 240)  # minor grid color
     self.lcMinorGrid = QColor(190, 240, 255)  # major grid color
     self.ltGrid = QtCore.Qt.DashLine  # grid line type
     self.lwMinorGrid = 1  # grid line width
     self.lwMajorGrid = 1  #
     #
     self.lcEdge = QColor(0, 50, 200)
     self.ltEdge = QtCore.Qt.SolidLine
     self.lwEdge = 2
     self.lcTear = QColor(100, 200, 255)
     self.ltTear = QtCore.Qt.SolidLine
     #
     self.lcNode = QColor(0, 0, 0)
     self.ltNode = QtCore.Qt.SolidLine
     self.lwNode = 2
     self.lcActNode = QColor(0, 0, 0)
     #
     self.lcSelect = QColor(0, 255, 0)
     self.ltSelect = QtCore.Qt.SolidLine
     self.lwSelect = 4
     self.lwEdgeSelect = 10
     #
     # Set font
     self.font = None
     self.fontSize = 12
     #
     # Set Brushes
     self.nodeBrush = None
     self.actNodeBrush = None
     #
     self.fcNode = QColor(128, 128, 128)
     self.fcActNode = QColor(128, 250, 128)
     self.fpNode = QtCore.Qt.SolidPattern
     self.fpActNode = QtCore.Qt.SolidPattern
     #
     self.edgeArrowBrush = None
     self.fcEdgeArrow = QColor(0, 50, 200)
     self.fpEdgeArrow = QtCore.Qt.SolidPattern
     #
     self.whiteBrush = None
     self.fcWB = QColor(240, 240, 240)
     self.fpWB = QtCore.Qt.SolidPattern
     #
     self.loadPens()  #setup pens, brushes, and font
Example #30
0
 def color(self, color):
     pal = self.palette()
     pal.setColor(QPalette.Background, QColor(color))
     self.setPalette(pal)