Esempio n. 1
0
    def __init__(self, parentWindow, address=None, port=None):
        self.widget = parentWindow.findChild(QWidget, 'connectPage')
        self.errorLabel = parentWindow.findChild(QLabel, 'connect_errorLabel')
        self.confirmButton = parentWindow.findChild(QPushButton, 'connect_confirmButton')
        self.connectIndicator = parentWindow.findChild(QLabel, 'connect_indicator')
        self.hostLineEdit = parentWindow.findChild(QLineEdit, 'connect_hostnameLineEdit')
        self.portLineEdit = parentWindow.findChild(QLineEdit, 'connect_portLineEdit')
        self.logo = parentWindow.findChild(QLabel, 'connect_logoImage')
        self.hostLabel = parentWindow.findChild(QLabel, 'hostLabel')
        self.portLabel = parentWindow.findChild(QLabel, 'hostPortLabel')

        self.logo.setPixmap(QPixmap("resources/icon-256.png"))
        self.logo.setVisible(False)

        movie = QMovie("resources/loader-small.gif")
        movie.start()
        self.connectIndicator.setMovie(movie)
        self.connectIndicator.setVisible(False)

        self.errorLabel.setVisible(False)

        self.hostLineEdit.setText(constants.DEFAULT_ADDRESS)
        self.portLineEdit.setText(str(constants.DEFAULT_TCP_PORT))

        self.confirmButton.clicked.connect(self.onConfirm)
        self.hostLineEdit.returnPressed.connect(self.onConfirm)
        self.portLineEdit.returnPressed.connect(self.onConfirm)
class StatusWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.status_label = QLabel("0%")
        self.load_icon_movie = QMovie(SpinnerIconPath)
        self.load_icon_label = QLabel()
        self.load_icon_label.setMovie(self.load_icon_movie)
        self.layout = QHBoxLayout()
        self.layout.addStretch(2)
        self.layout.addWidget(self.load_icon_label)
        self.layout.addWidget(self.status_label)
        self.layout.addStretch(3)
        self.layout.setSpacing(0)
        self.layout.setMargin(0)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)

    def update_progress(self, new_progress):
        self.status_label.setText(str(new_progress) + "%")

    def start_loading(self):
        self.load_icon_movie.start()

    def stop_loading(self):
        self.load_icon_movie.stop()
    def __init__(self, *args, **kwargs):
        super(MenuWindow, self).__init__(*args, **kwargs)

        # Loading Fonts
        QFontDatabase.addApplicationFont("fonts/BebasNeue-Light.ttf")

        # Window Settings 
        self.setFixedSize(1280, 720)
        self.setWindowTitle("Systeme d'apprentissage base sur les reseaux de neurones")
        #background = QPixmap("images/menu")
        #palette = QPalette()
        #palette.setBrush(QPalette.Background, background)
        #self.setAttribute(Qt.WA_StyledBackground, True)
        #self.setPalette(palette)
        self.setAutoFillBackground(True)
        background = QLabel(self)
        movie = QMovie("images/menu")
        background.setMovie(movie)
        self.setCentralWidget(background)
        movie.start()

        # Stylesheet Settings
        styleFile = QFile( "stylesheets/menu.qss" )
        styleFile.open( QFile.ReadOnly )
        style = str( styleFile.readAll() )
        self.setStyleSheet( style )

        # Title Settings
        self.title = QLabel("Neural networks based learning system", self)
        self.title.setFont(QFont("BebasNeue", 45, QFont.Bold))
        self.title.setAlignment(Qt.AlignCenter)
        self.title.setGeometry(0, 60, 1280, 120)

        # Button Settings 
        self.buttons = []
        for x in range(5) :
           self.buttons.append(x)
           self.buttons[x] = QPushButton(self)
           self.buttons[x].setCursor(Qt.PointingHandCursor)
           self.buttons[x].setObjectName("select")
           self.buttons[x].setFont(QFont("BebasNeue", 15, QFont.Bold))
           self.buttons[x].setGeometry(400, 210 + x * 100, 550, 80)
           #self.buttons[x].clicked.connect(lambda : self.notifyMe(x))
        self.buttons[0].setText("Image preprocessing")        
        self.buttons[1].setText("Text preprocessing")        
        self.buttons[2].setText("Learning")
        self.buttons[3].setText("Testing")
        self.buttons[4].setText("Quit")

       

        



#app = QApplication(sys.argv)
#window = MenuWindow()
#window.show()
#app.exec_()
Esempio n. 4
0
 def __init__(self, parent=None):
     super().__init__(parent)
     lbl = QLabel(self)
     movie = QMovie('../example_data/sample.gif')
     lbl.setMovie(movie)
     lbl.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     movie.start()
     self.setCentralWidget(lbl)
Esempio n. 5
0
    def submit(self):
        _movie = QMovie(os.getcwd()+'/loading.gif')
        _movie.setScaledSize(QSize(50, 50))
        self.text.setMovie(_movie)
        _movie.start()

        t = threading.Thread(target=self.processEmployee)
        t.start()
Esempio n. 6
0
    def __init__(self) -> None:
        super().__init__()

        self.setupUi(self)

        movie = QMovie(icons.get_icon_path("loader.gif"))
        self.load_image_label.setMovie(movie)

        movie.start()
 def stackStart(self):
     self.setButton(self.ui.btn_left, show=False)
     self.setButton(self.ui.btn_right, show=False)
     self.ui.lbl_notification.hide()
     self.playSound('audio11')
     gif_start = QMovie("animations/slider1.gif")
     self.ui.lbl_slider_start.setMovie(gif_start)
     gif_start.start()
     self.delivery_state = 'default'
     self.ui.Stack.setCurrentWidget(self.ui.pageStart)
Esempio n. 8
0
 def setPicContent(self, path: str):
     if path.split(".")[-1] in suffix:
         pixmap = QPixmap(path)
         self.picLab.setPixmap(pixmap)
     elif path.split(".")[-1] in suffix2:
         movie = QMovie(path)
         self.picLab.setMovie(movie)
         movie.start()  # 播放,必须在show之前
     else:
         pass
class SplashScreen(QSplashScreen):
    def __init__(self):
        super(SplashScreen, self).__init__()
        self.movie = QMovie(r'20190320111722218.gif')
        self.movie.frameChanged.connect(
            lambda: self.setPixmap(self.movie.currentPixmap()))
        self.movie.start()

    def mousePressed(self, event):
        pass
 def stackWallet(self):
     self.setButton(self.ui.btn_left,
                    function=self.stackWalletServices,
                    text='بازگشت',
                    icon='images/icon/back.png',
                    show=True)
     self.setButton(self.ui.btn_right, show=False)
     self.ui.lbl_notification.hide()
     gif_wallet = QMovie("animations/wallet.gif")
     gif_wallet.setScaledSize(QSize().scaled(256, 256, Qt.KeepAspectRatio))
     self.ui.lbl_gif_wallet.setMovie(gif_wallet)
     gif_wallet.start()
     self.ui.lbl_wallet.setText(str(
         ("{:,.0f}").format(self.user['wallet'])))
     self.ui.Stack.setCurrentWidget(self.ui.pageWallet)
class xASL_ImagePlayer(QLabel):
    def __init__(self,
                 filepath,
                 parent=None,
                 alignment=Qt.AlignLeft,
                 h_offset=0,
                 v_offset=5,
                 initial_movie_size=None):
        """
        A modified QLabel which features a GIF movie that can be played

            Parameters:
                • filepath: The filepath to the .gif file which will be played
                • parent: The parent of this widget
                • alignment: The alignment of the movie w.r.t the label itself
                • h_offset: When resizing based on a buddy widget, the additional horizontal size that should be given
                • v_offset: When resizing based on a buddy widget, the additional vertical size that should be given
                • initial_movie_size: None, QSize or a 2-element tuple to indicate the initial pixel dimensions that
                the movie should be set to
        """
        super(xASL_ImagePlayer, self).__init__(parent=parent)
        self.h_offset, self.v_offset = h_offset, v_offset
        self.setContentsMargins(0, 0, 0, 0)
        self.setAlignment(alignment)

        # Load the file into a QMovie with the appropriate size
        self.movie = QMovie(str(filepath), QByteArray(), self)
        self.movie.setCacheMode(QMovie.CacheAll)
        self.movie.setSpeed(100)

        self.setMovie(self.movie)
        self.ping()

        if initial_movie_size is not None:
            if isinstance(initial_movie_size, tuple):
                initial_movie_size = QSize(*initial_movie_size)
            self.movie.setScaledSize(initial_movie_size)

    def ping(self):
        self.movie.start()
        self.movie.stop()
        self.movie.jumpToFrame(0)

    @Slot(int, int)
    def listen_resize(self, width, height):
        self.movie.setScaledSize(
            QSize(width + self.h_offset, height + self.v_offset))
        self.ping()
def main():
    # print('minha main')

    movie = QMovie('EYE_WALLEroxo.gif')
    ui.label_2.setMovie(movie)
    movie.setSpeed(160)
    rect = ui.label_2.geometry()
    size = QSize(min(rect.width(), rect.height()),
                 min(rect.width(), rect.height()))
    movie.setScaledSize(size)
    movie.start()
    movieLoading(False)
    inicializarWarningMSG(False)

    ui.pushButton_2.setEnabled(False)
    ui.pushButton.clicked.connect(procurar_diretorio)
    ui.pushButton_2.clicked.connect(converter_py_exe)
Esempio n. 13
0
 def setupProgressSection(self):
     self.progress_layout = QHBoxLayout()
     progress_vertical_layout = QVBoxLayout()
     progress_wrapper_layout = QHBoxLayout()
     self.progress_label = QLabel()
     movie = QMovie('icons/ajax-loader.gif')
     self.progress_label.setMovie(movie)
     movie.start()
     self.progress_label.setSizePolicy(QSizePolicy.Maximum,
                                       QSizePolicy.Maximum)
     self.progress_description_label = QLabel()
     self.progress_description_label.setText(
         "Transaction is being confirmed. Please wait!")
     self.progress_description_label.setSizePolicy(QSizePolicy.Maximum,
                                                   QSizePolicy.Maximum)
     progress_wrapper_layout.addWidget(self.progress_label)
     progress_wrapper_layout.addWidget(self.progress_description_label)
     progress_vertical_layout.addLayout(progress_wrapper_layout, 1)
     self.progress_layout.addLayout(progress_vertical_layout)
     self.sendTransactionFinished()
Esempio n. 14
0
class AnimatedSplash(QSplashScreen):
    def __init__(self, path):

        self.__movie = QMovie(path)
        self.__movie.jumpToFrame(0)

        pixmap = QPixmap(self.__movie.frameRect().size())
        QSplashScreen.__init__(self, pixmap)
        self.__movie.frameChanged.connect(self.repaint)

    def showEvent(self, event):
        self.__movie.start()

    def hideEvent(self, event):
        self.__movie.stop()

    def paintEvent(self, event):
        painter = QPainter(self)
        pixmap = self.__movie.currentPixmap()
        self.setMask(pixmap.mask())
        painter.drawPixmap(0, 0, pixmap)
Esempio n. 15
0
    def __init__(self, window_title, parent):
        """Initializes class.

        Args:
            window_title (str)
            parent (QMainWindow)
        """
        super().__init__(window_title, parent)
        self.setObjectName(window_title)
        self.label_msg = QLabel(self)
        self.label_msg.setFont(QFont("arial,helvetica", 12))
        self.label_msg.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.label_msg.setWordWrap(True)
        self.button_left = QPushButton(self)
        self.button_right = QPushButton(self)
        self.label_loader = QLabel(self)
        self.label_loader.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        movie = QMovie(":/animated_gifs/ajax-loader.gif")
        movie.start()
        self.label_loader.setMovie(movie)
        button_container = QWidget(self)
        button_layout = QHBoxLayout(button_container)
        button_layout.addStretch()
        button_layout.addWidget(self.button_left)
        button_layout.addWidget(self.button_right)
        button_layout.addStretch()
        widget = QWidget(self)
        layout = QVBoxLayout(widget)
        layout.addStretch()
        layout.addWidget(self.label_msg)
        layout.addStretch()
        layout.addWidget(self.label_loader)
        layout.addStretch()
        layout.addWidget(button_container)
        self.setWidget(widget)
        self.machine = None
        self.welcome = None
        self._welcome_text = "<html><p>Welcome!</p></html>"
        self._current_state = None
        self.setAttribute(Qt.WA_DeleteOnClose)
class Ui_ScrollArea(object):
    def setupUi(self, ScrollArea):
        if ScrollArea.objectName():
            ScrollArea.setObjectName(u"ScrollArea")

        flags = Qt.WindowFlags(Qt.FramelessWindowHint)
        ScrollArea.setWindowFlags(flags)
        ScrollArea.resize(899, 603)
        ScrollArea.setMaximumSize(QSize(899, 671))
        ScrollArea.setStyleSheet(u"background-color: #2c3e50;")
        ScrollArea.setWidgetResizable(False)
        #ScrollArea.setAlignment(Qt.AlignCenter)

        self.threadpool = QThreadPool()
        self.scrollAreaWidgetContents = QWidget()
        self.scrollAreaWidgetContents.setObjectName(
            u"scrollAreaWidgetContents")
        self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 897, 601))
        self.label = QLabel(self.scrollAreaWidgetContents)
        self.label.setObjectName(u"label")
        self.label.setGeometry(QRect(0, 0, 901, 81))
        self.label.setStyleSheet(u"background-color: #262b33;")
        self.tabWidget = QTabWidget(self.scrollAreaWidgetContents)
        self.tabWidget.setObjectName(u"tabWidget")
        self.tabWidget.setGeometry(QRect(0, 80, 901, 591))

        font = QFont()
        font.setBold(True)
        font.setWeight(75)

        self.tabWidget.setFont(font)
        self.tabWidget.setStyleSheet(
            "QTabWidget>QWidget>QWidget{background: #2f3640;}\n"
            "QTabBar::tab{background-color: #2f3640;color: white}\n"
            "QTabBar::tab:selected{background-color: rgb(29, 29, 29);}\n  QTabBar{qproperty-drawBase: 0;}"
        )
        self.tabWidget.setTabPosition(QTabWidget.West)
        self.tabWidget.setIconSize(QSize(70, 100))
        self.tabWidget.setTabBarAutoHide(True)
        self.tabWidget.setDocumentMode(True)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setMovable(False)

        iconSave = QIcon()
        iconSave.addFile(os.path.join('gpr', 'ButtonSaveIcon.png'), QSize(),
                         QIcon.Normal, QIcon.On)

        PlayButton = QIcon()
        PlayButton.addFile(os.path.join('gpr', 'PlayButton.png'), QSize(),
                           QIcon.Normal, QIcon.On)

        AddMore = QIcon()
        AddMore.addFile(os.path.join('gpr', 'Addmore.png'), QSize(),
                        QIcon.Normal, QIcon.On)

        iconMinus = QIcon()
        iconMinus.addFile(os.path.join('gpr', 'RemoveButton.png'), QSize(),
                          QIcon.Normal, QIcon.On)

        icon = QIcon()
        icon.addFile(os.path.join('gpr', 'FolderIcon.png'), QSize(),
                     QIcon.Normal, QIcon.On)

        icon2 = QIcon()
        icon2.addFile(os.path.join('gpr', 'ico2.png'), QSize(), QIcon.Normal,
                      QIcon.On)

        self.tab = QWidget()
        self.tab.setObjectName(u"tab")
        self.label_9 = QLabel(self.tab)
        self.label_9.setObjectName(u"label_9")
        self.label_9.setGeometry(QRect(10, 0, 251, 231))
        self.label_9.setStyleSheet(u"background-color: #8BC34A;")
        self.label_10 = QLabel(self.tab)
        self.label_10.setObjectName(u"label_10")
        self.label_10.setGeometry(QRect(270, 0, 541, 231))
        self.label_10.setStyleSheet(u"background-color: #CDDC39;")
        self.label_12 = QLabel(self.tab)
        self.label_12.setObjectName(u"label_12")
        self.label_12.setGeometry(QRect(10, 240, 801, 341))
        self.label_12.setStyleSheet(u"background-color: #222f3e;")

        self.OpenFileFolder = QPushButton(self.tab)
        self.OpenFileFolder.setObjectName(u"OpenFileFolder")
        self.OpenFileFolder.setGeometry(QRect(80, 40, 120, 120))
        self.OpenFileFolder.setStyleSheet(
            u"border:none;\n"
            "background-color: rgb(46, 52, 54)\n;"
            "color:white;")
        self.OpenFileFolder.setIcon(AddMore)
        self.OpenFileFolder.setIconSize(QSize(100, 100))

        self.WidthVideo = QLineEdit(self.tab)
        self.WidthVideo.setObjectName(u"WidthMany")
        self.WidthVideo.setGeometry(QRect(320, 100, 201, 27))
        self.WidthVideo.setStyleSheet(u"border:none;\n"
                                      "background-color: white;\n"
                                      "color: black;")

        self.SaveVideo = QPushButton(self.tab)
        self.SaveVideo.setObjectName(u"SaveMany")
        self.SaveVideo.setGeometry(QRect(550, 40, 141, 141))
        self.SaveVideo.setStyleSheet(u"border:none;\n"
                                     "background-color: rgb(46, 52, 54);\n"
                                     "color:white")
        self.SaveVideo.setIcon(iconSave)
        self.SaveVideo.setIconSize(QSize(100, 100))

        self.animatedContainer = QLabel(self.tab)
        self.animatedContainer.setObjectName(u"animated")
        self.animatedContainer.setGeometry(QRect(100, 435, 80, 80))
        self.animatedContainer.setScaledContents(False)
        self.animatedContainer.setStyleSheet(u"border:none;\n"
                                             "background-color: #222f3e")

        self.movieAnimation = QMovie(
            os.path.join('gpr', 'Loading', 'animation.gif'))
        self.animatedContainer.setMovie(self.movieAnimation)

        self.InfoText = QLineEdit(self.tab)
        self.InfoText.setObjectName(u"InfoText")
        self.InfoText.setGeometry(QRect(470, 480, 300, 27))
        self.InfoText.setStyleSheet(u"background-color: #222f3e;\n"
                                    "border:none;\n"
                                    "color:white;")
        self.InfoText.setReadOnly(True)

        self.CloseX = QPushButton(self.scrollAreaWidgetContents)
        self.CloseX.setObjectName(u"CloseButtonX")
        self.CloseX.setGeometry(QRect(850, 0, 31, 27))
        self.CloseX.setStyleSheet(u"background-color:2f3640;\n"
                                  "color:white;\n"
                                  "border:none;")
        self.MinimizedWindow = QPushButton(self.scrollAreaWidgetContents)
        self.MinimizedWindow.setObjectName(u"Minimized Window")
        self.MinimizedWindow.setGeometry(QRect(810, 0, 31, 27))
        self.MinimizedWindow.setStyleSheet(u"background-color:2f3640;\n"
                                           "color:white;\n"
                                           "border:none;")

        self.MinusButton = QPushButton(self.tab)
        self.MinusButton.setObjectName(u"SaveMany")
        self.MinusButton.setGeometry(QRect(190, 165, 60, 60))
        self.MinusButton.setStyleSheet(u"border:none;\n"
                                       "background-color: rgb(46, 52, 54);")
        self.MinusButton.setIcon(iconMinus)
        self.MinusButton.setIconSize(QSize(50, 50))

        self.HeightVideo = QLineEdit(self.tab)
        self.HeightVideo.setObjectName(u"HeightVideo")
        self.HeightVideo.setGeometry(QRect(320, 40, 201, 27))
        self.HeightVideo.setStyleSheet(u"border:none;\n"
                                       "background-color: white;\n"
                                       "color: black;")

        self.Fps = QLineEdit(self.tab)
        self.Fps.setObjectName(u"FPS")
        self.Fps.setGeometry(QRect(320, 160, 201, 27))
        self.Fps.setStyleSheet(u"border:none;\n"
                               "background-color: white;\n"
                               "color: black;")

        self.OpenFolder = QPushButton(self.tab)
        self.OpenFolder.setObjectName(u"OpenFolder")
        self.OpenFolder.setGeometry(QRect(670, 430, 90, 90))
        self.OpenFolder.setStyleSheet(u"border:none;\n"
                                      "background-color: rgb(46, 52, 54);")
        self.OpenFolder.setIcon(icon)
        self.OpenFolder.setIconSize(QSize(80, 80))
        self.OpenFolder.setEnabled(False)
        self.OpenFolder.setVisible(False)

        self.areaTabTable = QTableWidget(self.tab)
        self.areaTabTable.setGeometry(QRect(10, 240, 781, 192))
        self.areaTabTable.setShowGrid(True)
        self.areaTabTable.setColumnCount(2)
        self.areaTabTable.setStyleSheet(u"border:none;\n"
                                        "background-color: white;\n"
                                        "color: black;")
        self.areaTabTable.setHorizontalHeaderLabels(
            ['Videos', 'Extract Time Range (From-To)'])
        self.areaTabTable.horizontalHeader().resizeSection(0, 380)
        self.areaTabTable.horizontalHeader().resizeSection(1, 380)

        self.StartButton = QPushButton(self.tab)
        self.StartButton.setObjectName(u"StartButton")
        self.StartButton.setGeometry(QRect(360, 435, 91, 81))
        self.StartButton.setStyleSheet(u"border:none;\n"
                                       "background-color: rgb(46, 52, 54);")
        self.StartButton.setIcon(PlayButton)
        self.StartButton.setIconSize(QSize(40, 40))

        icon3 = QIcon()
        icon3.addFile(u"gpr\ico4.png", QSize(), QIcon.Normal, QIcon.On)
        self.tabWidget.addTab(self.tab, icon3, "1")
        self.tab_2 = QWidget()
        self.tab_2.setObjectName(u"tab_2")
        self.label_3 = QLabel(self.tab_2)
        self.label_3.setObjectName(u"label_3")
        self.label_3.setGeometry(QRect(350, 120, 31, 41))
        self.label_3.setStyleSheet(u"background-color: #2f3640;")
        self.label_3.setPixmap(QPixmap(os.path.join('gpr',
                                                    'LogoTopSmall.png')))
        self.label_3.setScaledContents(True)

        icon4 = QIcon()
        icon4.addFile(os.path.join('gpr', 'ico3.png'), QSize(), QIcon.Normal,
                      QIcon.On)

        self.label_11 = QLabel(self.scrollAreaWidgetContents)
        self.label_11.setObjectName(u"label_11")
        self.label_11.setGeometry(QRect(50, 20, 31, 41))
        self.label_11.setStyleSheet(u"background-color: #262b33;")
        self.label_11.setPixmap(
            QPixmap(os.path.join('gpr', 'LogoTopSmall.png')))
        self.label_11.setScaledContents(True)

        self.Tagline = QLineEdit(self.scrollAreaWidgetContents)
        self.Tagline.setObjectName(u"lineEdit")
        self.Tagline.setGeometry(QRect(660, 50, 200, 27))
        self.Tagline.setStyleSheet(u"background-color: #262b33;\n"
                                   "border:none;\n"
                                   "color:white;")
        self.Tagline.setReadOnly(True)

        ScrollArea.setWidget(self.scrollAreaWidgetContents)
        self.CloseX.pressed.connect(self.CloseProgram)
        self.MinimizedWindow.pressed.connect(self.Minimize)

        self.OpenFileFolder.pressed.connect(self.AppendMovieTimeSheet)
        self.MinusButton.pressed.connect(self.RemoveTable)
        self.StartButton.pressed.connect(self.SaveCSVFile)
        self.SaveVideo.pressed.connect(self.SaveConfigurationVideo)
        self.StartButton.setEnabled(False)
        self.OpenFolder.pressed.connect(self.FolderPath)

        self.retranslateUi(ScrollArea)

        self.tabWidget.setCurrentIndex(2)

        QMetaObject.connectSlotsByName(ScrollArea)

    def FolderPath(self):
        pathOS = os.getcwd()
        if platform.system() == "Windows":
            os.startfile(os.getcwd(pathOS))
        else:
            QMessageBox.information(None, "Successful!",
                                    "The file has been saved at " + pathOS)

    def CloseProgram(self):
        app.quit()

    def Minimize(self):
        ScrollArea.setWindowState(Qt.WindowMinimized)

    def Processing(self):
        time.sleep(0.1)
        self.movieAnimation.start()
        self.animatedContainer.setVisible(True)
        self.InfoText.setText("Processing, Grab a Cup of Coffee! ..")
        self.ThreadProcess()
        self.StartButton.setEnabled(False)
        self.OpenFolder.setEnabled(False)
        self.OpenFolder.setVisible(False)

    def ThreadProcess(self):
        threadClass = MainThread()
        time.sleep(0.1)
        self.threadpool.start(threadClass)
        threadClass.signals.finished.connect(self.OnComplete)
        return

    def OnComplete(self):
        self.InfoText.setText("Done!")
        self.movieAnimation.stop()
        self.StartButton.setEnabled(True)
        self.OpenFolder.setEnabled(True)
        self.OpenFolder.setVisible(True)
        self.animatedContainer.setVisible(False)
        return

    def AppendMovieTimeSheet(self):
        global videosFolders
        videosFolders = QFileDialog.getOpenFileName(None, "Select Videos", "",
                                                    "*.avi *.mp4 *.mov")

        getVideoPath = map(str, videosFolders)
        sanatizePath = 'removeme'.join(getVideoPath)
        splitPath = sanatizePath.split('removeme')
        extractString = map(str, splitPath[0])
        readytoAppendPath = ''.join(extractString)

        if readytoAppendPath != "":
            AppendTimes = "00:00:00-00:00:00"

            rowPosition = self.areaTabTable.rowCount()
            self.areaTabTable.insertRow(rowPosition)

            self.areaTabTable.setItem(rowPosition, 1,
                                      QTableWidgetItem(AppendTimes))
            self.areaTabTable.setItem(rowPosition, 0,
                                      QTableWidgetItem(readytoAppendPath))
            self.StartButton.setEnabled(True)
        else:
            print("Error Missing Data, No videos were Added")

    def RemoveTable(self):
        self.areaTabTable.removeRow(0)

    def SaveCSVFile(self):
        import csv
        path = "movies.csv"
        if path != '':
            with open(path, 'w') as csv_file:
                writer = csv.writer(csv_file, dialect='excel')
                for row in range(self.areaTabTable.rowCount()):
                    row_data = []
                    for column in range(self.areaTabTable.columnCount()):
                        item = self.areaTabTable.item(row, column)
                        if item is not None:
                            row_data.append(item.text())
                        else:
                            row_data.append('')
                    writer.writerow(row_data)
        self.Processing()

    def SaveConfigurationVideo(self):
        from configparser import ConfigParser
        SetFps = self.Fps.text()
        SetWidthVideo = self.WidthVideo.text()
        SetHeightVideo = self.HeightVideo.text()

        if SetFps and SetHeightVideo and SetWidthVideo != "":

            config = ConfigParser()

            config.add_section('Settings')
            config.set('Settings', 'Height', SetHeightVideo)
            config.set('Settings', 'Width', SetWidthVideo)
            config.set('Settings', 'FPS', SetFps)
            self.InfoText.setText("Saved Configuration!")

            with open('CSettings.cfg', 'w') as configfile:
                config.write(configfile)
                configfile.close()

        else:
            QMessageBox.critical(None, "Mising Fields",
                                 "Please Complete All Fields")

    def retranslateUi(self, ScrollArea):
        ScrollArea.setWindowTitle(
            QCoreApplication.translate("ScrollArea",
                                       u"ExtractAndMerge 0.1 Beta", None))
        self.WidthVideo.setPlaceholderText(
            QCoreApplication.translate("ScrollArea", u"Set Width", None))
        self.HeightVideo.setPlaceholderText(
            QCoreApplication.translate("ScrollArea", u"Set Height", None))
        self.OpenFileFolder.setToolTip(
            QCoreApplication.translate("ScrollArea", u"Add a Video", None))
        self.SaveVideo.setToolTip(
            QCoreApplication.translate("ScrollArea", u"Save Configuration",
                                       None))
        self.Fps.setPlaceholderText(
            QCoreApplication.translate("ScrollArea", u"FPS: 25", None))
        self.label_9.setText("")
        self.label_10.setText("")
        self.label_12.setText("")
        self.OpenFileFolder.setText("")

        #if QT_CONFIG(tooltip)
        self.WidthVideo.setToolTip(
            QCoreApplication.translate("ScrollArea", u"Set Width", None))
        #endif // QT_CONFIG(tooltip)
        self.WidthVideo.setText("")
        self.SaveVideo.setText("")
        #if QT_CONFIG(tooltip)
        self.HeightVideo.setToolTip(
            QCoreApplication.translate("ScrollArea", u"Set Height", None))
        #endif // QT_CONFIG(tooltip)
        self.HeightVideo.setText("")
        #if QT_CONFIG(tooltip)
        self.Fps.setToolTip(
            QCoreApplication.translate("ScrollArea", u"FPS del Video", None))

        #endif // QT_CONFIG(tooltip)
        self.Fps.setText("")
        #self.StartVideo.setText("")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), "")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), "")
        self.CloseX.setText(
            QCoreApplication.translate("ScrollArea", u"X", None))
        self.MinimizedWindow.setText(
            QCoreApplication.translate("ScrollArea", u"_", None))
        self.label_11.setText("")
        self.Tagline.setText(
            QCoreApplication.translate("ScrollArea",
                                       u"ExtractAndMerge 0.1 Beta", None))
Esempio n. 17
0
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.crashes = []
        self.thread_holder = []
        self.paused_fuzzer_threads = []
        self.start_time = None

        # Select config profile before starting
        self.cfg = ConfigWindow()
        if self.cfg.exec() == QtWidgets.QDialog.Rejected:
            sys.exit(1)

        # Set up basic window
        self.setWindowTitle("Sienna Locomotive 2")
        self.setMinimumSize(QSize(1800, 1300))

        _central_widget = QtWidgets.QWidget(self)
        self.setCentralWidget(_central_widget)
        self._layout = QtWidgets.QVBoxLayout(_central_widget)
        _central_widget.setLayout(self._layout)

        # Set up Checksec, Wizard and Server threads so we don't block the UI
        # when they're running
        self.checksec_thread = ChecksecThread(
            config.config["target_application_path"])
        self.wizard_thread = WizardThread(config.config)
        self.server_thread = ServerThread(close_on_exit=True)

        # CREATE WIDGETS #

        # Menu bar
        self.menu_bar = self.menuBar()
        self.file_menu = self.menu_bar.addMenu("&File")
        self.change_profile_action = self.file_menu.addAction("Change Profile")
        self.open_report_in_browser = QtWidgets.QAction(
            "Open exported report in browser", self, checkable=True)
        self.file_menu.addAction(self.open_report_in_browser)
        self.open_report_in_browser.setChecked(True)

        # Target info
        self.target_status = QtWidgets.QStatusBar()
        self.target_label = QtWidgets.QLabel()
        self.target_status.addWidget(self.target_label)
        self._layout.addWidget(self.target_status)
        self.checksec_thread.start()
        self.checksec_thread.result_ready.connect(self.checksec_finished)

        # Create wizard button
        self.wizard_button = QtWidgets.QPushButton("Run Wizard")
        self._layout.addWidget(self.wizard_button)

        # Set up function tree display
        self._func_tree = CheckboxTreeWidget()
        self._layout.addWidget(self._func_tree)

        # Set up underlying model for exposing function data
        self.target_data = get_target(config.config)
        self.model = CheckboxTreeModel()
        self.func_proxy_model = CheckboxTreeSortFilterProxyModel()
        self.func_proxy_model.setSourceModel(self.model)
        self.func_proxy_model.setFilterKeyColumn(0)
        self.file_proxy_model = CheckboxTreeSortFilterProxyModel()
        self.file_proxy_model.setSourceModel(self.func_proxy_model)
        self.file_proxy_model.setFilterKeyColumn(1)
        self.module_proxy_model = CheckboxTreeSortFilterProxyModel()
        self.module_proxy_model.setSourceModel(self.file_proxy_model)
        self.module_proxy_model.setFilterKeyColumn(4)
        self.build_func_tree()
        self._func_tree.setModel(self.module_proxy_model)
        self._func_tree.setItemDelegate(
            ComboboxTreeItemDelegate(self.target_data))

        # These need to happen after we set the model
        self._func_tree.expandAll()
        self._func_tree.resizeColumnToContents(0)
        self._func_tree.resizeColumnToContents(1)
        self._func_tree.resizeColumnToContents(2)
        self._func_tree.resizeColumnToContents(3)

        # Create menu items for the context menu
        self.expand_action = QtWidgets.QAction("Expand All")
        self.collapse_action = QtWidgets.QAction("Collapse All")
        self.check_action = QtWidgets.QAction("Check All")
        self.uncheck_action = QtWidgets.QAction("Uncheck All")

        # Build layout for function filter text boxes
        self.filter_layout = QtWidgets.QHBoxLayout()
        self.filter_layout.addWidget(QtWidgets.QLabel("Filter Function: "))
        self.func_filter_box = QtWidgets.QLineEdit()
        self.filter_layout.addWidget(self.func_filter_box)
        self.filter_layout.addWidget(QtWidgets.QLabel("Filter Files: "))
        self.file_filter_box = QtWidgets.QLineEdit()
        self.filter_layout.addWidget(self.file_filter_box)
        self.filter_layout.addWidget(QtWidgets.QLabel("Filter Modules: "))
        self.module_filter_box = QtWidgets.QLineEdit()
        self.filter_layout.addWidget(self.module_filter_box)

        # Set up fuzzer button
        self.fuzzer_button = QtWidgets.QPushButton("Fuzz selected targets")
        if not self.target_data.target_list:
            self.fuzzer_button.setEnabled(False)

        # Create checkboxes for continuous mode
        self.continuous_mode_cbox = QtWidgets.QCheckBox("Continuous")
        self.pause_mode_cbox = QtWidgets.QCheckBox("Pause on crash")
        if config.config["continuous"]:
            self.continuous_mode_cbox.setChecked(True)
        if config.config["exit_early"]:
            self.pause_mode_cbox.setChecked(True)

        # Set up spinboxes for setting timeout values
        self.fuzz_timeout_box = QtWidgets.QSpinBox()
        self.fuzz_timeout_box.setSuffix(" seconds")
        self.fuzz_timeout_box.setMaximum(1200)
        if "fuzz_timeout" in config.config:
            self.fuzz_timeout_box.setValue(config.config["fuzz_timeout"])
        self.fuzz_timeout_box.setSpecialValueText("None")
        self.tracer_timeout_box = QtWidgets.QSpinBox()
        self.tracer_timeout_box.setSuffix(" seconds")
        self.tracer_timeout_box.setMaximum(2400)
        if "tracer_timeout" in config.config:
            self.tracer_timeout_box.setValue(config.config["tracer_timeout"])
        self.tracer_timeout_box.setSpecialValueText("None")
        self.tracer_timeout_box.setSingleStep(10)
        self.verbose_cbox = QtWidgets.QCheckBox()
        self.verbose_cbox.clicked.connect(self.toggle_verbose_state)

        # Create spinbox for controlling simultaneous fuzzing instances
        self.thread_count = QtWidgets.QSpinBox()
        self.thread_count.setSuffix(" threads")
        self.thread_count.setRange(1, 2 * cpu_count())
        if "simultaneous" in config.config:
            self.thread_count.setValue(config.config["simultaneous"])

        # Create button for hiding and showing the extended controls
        self.expand_button = QtWidgets.QToolButton()
        self.expand_button.setArrowType(Qt.DownArrow)

        # Create nested widget to hold the expanded fuzzing controls
        self.extension_widget = QtWidgets.QWidget()
        self.extension_layout = QtWidgets.QGridLayout()
        self.extension_widget.setLayout(self.extension_layout)

        # Create layouts for fuzzing controls
        self.fuzz_controls_outer_layout = QtWidgets.QHBoxLayout()
        self.fuzz_controls_inner_left = QtWidgets.QVBoxLayout()
        self.fuzz_controls_inner_right = QtWidgets.QVBoxLayout()

        # Add widgets to left, right, and expanded layouts
        self.fuzz_controls_inner_left.addLayout(self.filter_layout)
        self.fuzz_controls_inner_left.addWidget(self.extension_widget)
        self.extension_widget.hide()
        self.fuzz_controls_inner_left.addWidget(self.fuzzer_button)
        self.extension_layout.addWidget(self.continuous_mode_cbox, 0, 0)
        self.extension_layout.addWidget(self.pause_mode_cbox, 1, 0)
        self.extension_layout.addWidget(QtWidgets.QLabel("Fuzz timeout:"), 0,
                                        1, 1, 1, Qt.AlignRight)
        self.extension_layout.addWidget(self.fuzz_timeout_box, 0, 2, 1, 1,
                                        Qt.AlignLeft)
        self.extension_layout.addWidget(QtWidgets.QLabel("Triage Timeout:"), 1,
                                        1, 1, 1, Qt.AlignRight)
        self.extension_layout.addWidget(self.tracer_timeout_box, 1, 2, 1, 1,
                                        Qt.AlignLeft)
        self.extension_layout.addWidget(
            QtWidgets.QLabel("Simultaneous fuzzing threads:"), 0, 3, 1, 1,
            Qt.AlignRight)
        self.extension_layout.addWidget(self.thread_count, 0, 4, 1, 1,
                                        Qt.AlignLeft)

        self.extension_layout.addWidget(QtWidgets.QLabel("Verbose:"), 1, 3, 1,
                                        1, Qt.AlignRight)
        self.extension_layout.addWidget(self.verbose_cbox, 1, 4, 1, 1,
                                        Qt.AlignLeft)

        self.fuzz_controls_inner_right.addWidget(self.expand_button)

        # Compose layouts
        self.fuzz_controls_outer_layout.addLayout(
            self.fuzz_controls_inner_left)
        self.fuzz_controls_outer_layout.addLayout(
            self.fuzz_controls_inner_right)
        self._layout.addLayout(self.fuzz_controls_outer_layout)

        # Crashes table
        session = db.getSession()
        self.crashes_model = sqlalchemy_model.SqlalchemyModel(
            session,
            db.Crash,
            [
                ("Time", db.Crash.timestamp, "timestamp", {}),
                ("RunID", db.Crash.runid, "runid", {}),
                ("Reason", db.Crash.crashReason, "crashReason", {}),
                ("Exploitability", db.Crash.exploitability, "exploitability",
                 {}),
                ("Ranks", db.Crash.ranksString, "ranksString", {}),
                ("Crashash", db.Crash.crashash, "crashash", {}),
                ("Crash Address", db.Crash.crashAddressString,
                 "crashAddressString", {}),
                ("RIP", db.Crash.instructionPointerString,
                 "instructionPointerString", {}),
                ("RSP", db.Crash.stackPointerString, "stackPointerString", {}),
                ("RDI", db.Crash.rdi, "rdi", {}),
                ("RSI", db.Crash.rsi, "rsi", {}),
                ("RBP", db.Crash.rdx, "rbp", {}),
                ("RAX", db.Crash.rax, "rax", {}),
                ("RBX", db.Crash.rbx, "rbx", {}),
                ("RCX", db.Crash.rcx, "rcx", {}),
                ("RDX", db.Crash.rdx, "rdx", {}),
            ],
            orderBy=desc(db.Crash.timestamp),
            filters={"target_config_slug": get_target_slug(config.config)},
        )
        self.crashes_table = QtWidgets.QTableView()
        self.crashes_table.setFont(
            QFontDatabase.systemFont(QFontDatabase.FixedFont))
        self.crashes_table.setModel(self.crashes_model)
        self._layout.addWidget(self.crashes_table)
        self.crashes_table.horizontalHeader().setStretchLastSection(True)
        self.crashes_table.resizeColumnsToContents()
        self.crashes_table.show()
        self.crashes_table.clicked.connect(self.crash_clicked)

        # Crash Browser, details about a crash
        self.crash_browser = QtWidgets.QTextBrowser()
        self.crash_browser.setText("<NO CRASH SELECTED>")
        self.crash_browser.setFont(
            QFontDatabase.systemFont(QFontDatabase.FixedFont))
        self._layout.addWidget(self.crash_browser)

        self.stats_widget = stats.StatsWidget(get_target_slug(config.config))
        self._layout.addWidget(self.stats_widget)

        # Set up stop button (and hide it)
        self.stop_button = QtWidgets.QPushButton("Stop Fuzzing")
        self.stop_button.hide()
        self._layout.addWidget(self.stop_button)

        self.export_triage_button = QtWidgets.QPushButton("Export Triage")
        self._layout.addWidget(self.export_triage_button)

        # Set up status bar
        self.status_bar = QtWidgets.QStatusBar()
        self._layout.addWidget(self.status_bar)

        # Create helper variables for storing counters with signals attached
        self.runs, self.crash_counter = QIntVariable(0), QIntVariable(0)
        self.throughput = QFloatVariable(0.0)
        self.run_adapter = QTextAdapter("Fuzzing Runs: {0.value} ", self.runs)
        self.throughput_adapter = QTextAdapter(" {0.value:.3f} Runs/s ",
                                               self.throughput)
        self.crash_adapter = QTextAdapter(" Crashes Found: {0.value} ",
                                          self.crash_counter)

        # Create the busy label
        self.busy_label = QtWidgets.QLabel()
        busy_gif = QMovie("gui/busy.gif")
        self.busy_label.setMovie(busy_gif)
        busy_gif.start()
        self.busy_label.hide()

        # Set up labels for the status bar
        self.fuzz_count = QtWidgets.QLabel()
        self.throughput_label = QtWidgets.QLabel()
        self.crash_count = QtWidgets.QLabel()

        # Add all the labels to the status bar
        self.status_bar.addPermanentWidget(self.busy_label)
        self.status_bar.addWidget(self.fuzz_count)
        self.status_bar.addWidget(self.throughput_label)
        self.status_bar.addWidget(self.crash_count)

        # CONNECT SIGNALS #
        self.change_profile_action.triggered.connect(self.change_profile)

        # Update the text of the status bar adapters whenever the underlying variables change
        self.runs.valueChanged.connect(self.run_adapter.update)
        self.throughput.valueChanged.connect(self.throughput_adapter.update)
        self.crash_counter.valueChanged.connect(self.crash_adapter.update)

        self.run_adapter.updated.connect(self.fuzz_count.setText)
        self.throughput_adapter.updated.connect(self.throughput_label.setText)
        self.crash_adapter.updated.connect(self.crash_count.setText)

        # Start the wizard when we click the button and update the tree when we're done
        self.wizard_button.clicked.connect(self.wizard_thread.start)
        self.wizard_thread.started.connect(
            partial(self.setCursor, Qt.WaitCursor))
        self.wizard_thread.finished.connect(self.unsetCursor)
        self.wizard_thread.result_ready.connect(self.wizard_finished)

        # Connect the context menu buttons
        self.expand_action.triggered.connect(self._func_tree.expandAll)
        self.collapse_action.triggered.connect(self._func_tree.collapseAll)
        self.check_action.triggered.connect(self.check_all)
        self.uncheck_action.triggered.connect(self.uncheck_all)

        # Filter the list of functions displayed when we type things into the boxes
        self.func_filter_box.textChanged.connect(
            self.func_proxy_model.setFilterFixedString)
        self.file_filter_box.textChanged.connect(
            self.file_proxy_model.setFilterFixedString)
        self.module_filter_box.textChanged.connect(
            self.module_proxy_model.setFilterFixedString)

        # Handle checks/unchecks in the target tree
        self._func_tree.itemCheckedStateChanged.connect(self.tree_changed)

        self.export_triage_button.clicked.connect(self.export_triage)

        # Fuzzer control buttons for showing the panel and starting a run
        self.expand_button.clicked.connect(self.toggle_expansion)
        self.fuzzer_button.clicked.connect(self.server_thread.start)
        self.server_thread.finished.connect(self.start_all_threads)

        # If the user changes the continuous or pause mode, then we make sure the
        # two are consistent.
        self.pause_mode_cbox.stateChanged.connect(self.unify_pause_state)
        self.continuous_mode_cbox.stateChanged.connect(
            self.unify_continuous_state)

        # Connect the stop button to the thread so we can pause it
        self.stop_button.clicked.connect(self.pause_all_threads)

        # Connect the thread counter to the thread pool
        self.thread_count.valueChanged.connect(self.change_thread_count)
        self.change_thread_count(self.thread_count.value())
class NotificationsDialog(object):
    def __init__(self, parent, parent_window, notifications, dp=None):
        self._dialog = QDialog(parent_window)
        self._dp = dp

        self._notifications = notifications
        self._parent = parent
        self._parent_window = parent_window

        self._dialog.setWindowIcon(QIcon(':/images/icon.png'))
        self._ui = Ui_Dialog()
        self._ui.setupUi(self._dialog)

        self._init_ui()

    def _init_ui(self):
        self._dialog.setWindowFlags(Qt.Dialog)
        self._dialog.setAttribute(Qt.WA_TranslucentBackground)
        self._dialog.setAttribute(Qt.WA_MacFrameworkScaled)

        self._notifications_list = NotificationsList(self._dp)
        self._ui.notifications_area.setWidget(self._notifications_list)
        self._ui.notifications_area.verticalScrollBar().valueChanged.connect(
            self._on_list_scroll_changed)

        self._old_main_resize_event = self._ui.centralwidget.resizeEvent
        self._ui.centralwidget.resizeEvent = self._main_resize_event

        self._loader_movie = QMovie(":/images/loader.gif")
        self._ui.loader_label.setMovie(self._loader_movie)

    def show(self, on_finished):
        def finished():
            self.show_cursor_normal()
            self._dialog.finished.disconnect(finished)
            on_finished()

        logger.debug("Opening notifications dialog")

        screen_width = QApplication.desktop().width()
        parent_x = self._dialog.parent().x()
        parent_width = self._dialog.parent().width()
        width = self._dialog.width()
        offset = 16
        if parent_x + parent_width / 2 > screen_width / 2:
            x = parent_x - width - offset
            if x < 0:
                x = 0
        else:
            x = parent_x + parent_width + offset
            diff = x + width - screen_width
            if diff > 0:
                x -= diff
        self._dialog.move(x, self._dialog.parent().y())

        # Execute dialog
        self._dialog.finished.connect(finished)
        if not self._parent.load_notifications(show_loading=True):
            self.show_notifications()
        self._dialog.raise_()
        self._dialog.show()

    def raise_dialog(self):
        self._dialog.raise_()

    def close(self):
        self._dialog.reject()

    def show_cursor_loading(self, show_movie=False):
        if show_movie:
            self._ui.notifications_pages.setCurrentIndex(2)
            self._loader_movie.start()
        else:
            self._dialog.setCursor(Qt.WaitCursor)
            self._parent_window.setCursor(Qt.WaitCursor)

    def show_cursor_normal(self):
        self._dialog.setCursor(Qt.ArrowCursor)
        self._parent_window.setCursor(Qt.ArrowCursor)
        if self._loader_movie.state() == QMovie.Running:
            self._loader_movie.stop()

    def show_notifications(self):
        if not self._notifications:
            self._ui.notifications_pages.setCurrentIndex(1)
        else:
            self._ui.notifications_pages.setCurrentIndex(0)
            self._notifications_list.show_notifications(self._notifications)

        self.show_cursor_normal()

    def _on_list_scroll_changed(self, *args, **kwargs):
        # value = self._ui.notifications_area.verticalScrollBar().value()
        # logger.debug("Scroll value %s", value)
        if self._parent.all_loaded or self._parent.is_querying:
            return

        if self._notifications_list.loading_needed(self._parent.limit):
            logger.debug("Loading notifications")
            self._parent.load_notifications()

    def _main_resize_event(self, e):
        self._old_main_resize_event(e)
        self._notifications_list.setFixedWidth(
            self._ui.notifications_pages.width() - 8)

        self._on_list_scroll_changed()
Esempio n. 19
0
class SmartSyncDialog(object):
    def __init__(self, parent):
        self._dialog = QDialog(parent)
        self._dialog.setWindowIcon(QIcon(':/images/icon.png'))
        self._ui = Ui_Dialog()
        self._ui.setupUi(self._dialog)

        self._ui.centralWidget.setFrameShape(QFrame.NoFrame)
        self._ui.centralWidget.setLineWidth(1)

        self._model = None
        self._proxy_model = QSortFilterProxyModel()

        self._view = self._ui.folder_list_view
        self._view.setModel(self._proxy_model)
        self._view.expanded.connect(self.on_item_expanded)

        self._offline_paths = None

        # for frameless window moving
        self._x_coord = 0
        self._y_coord = 0
        self._dialog.mousePressEvent = self.on_mouse_press_event
        self._dialog.mouseMoveEvent = self.on_mouse_move_event

        self._loader_movie = QMovie(":/images/loader.gif")
        self._ui.loader_label.setMovie(self._loader_movie)

    def on_mouse_press_event(self, ev):
        self._x_coord = ev.x()
        self._y_coord = ev.y()

    def on_mouse_move_event(self, ev):
        self._dialog.move(
            ev.globalX() - self._x_coord, ev.globalY() - self._y_coord)

    def on_item_expanded(self, index):
        if self._model:
            self._model.on_item_expanded(self._proxy_model.mapToSource(index))

    def show(self, root_path, hide_dotted=False):
        if LOGGING_ENABLED:
            logger.info(
                "Opening smart sync dialog for path '%s'...", root_path)

        self._model = TreeModel(
            root_path, hide_dotted=hide_dotted)

        self._proxy_model.setSourceModel(self._model)

        self.show_cursor_loading(show_movie=True)
        # Execute dialog
        result = self._dialog.exec_()
        if result == QDialog.Accepted:
            offline_dirs = self._model.get_added_to_offline_paths()
            new_online = list(self._model.get_removed_from_offline_paths())
            new_offline = list(offline_dirs - self._offline_paths)
            if LOGGING_ENABLED:
                logger.debug("new offline dirs %s, new online dirs %s",
                             new_offline, new_online)
            return new_offline, new_online
        else:
            return [], []

    def set_offline_paths(self, offline_paths):
        self._offline_paths = offline_paths
        logger.debug("offline paths %s", offline_paths)
        self._model.set_offline_dirs(offline_paths)
        self.show_cursor_normal()

        self._view.expand(self._proxy_model.mapFromSource(
            self._model.get_root_path_index()))
        self._proxy_model.sort(0, Qt.AscendingOrder)


    def show_cursor_loading(self, show_movie=False):
        if show_movie:
            self._ui.stackedWidget.setCurrentIndex(1)
            self._loader_movie.start()
        else:
            self._dialog.setCursor(Qt.WaitCursor)

    def show_cursor_normal(self):
        self._dialog.setCursor(Qt.ArrowCursor)
        if self._loader_movie.state() == QMovie.Running:
            self._loader_movie.stop()
        self._ui.stackedWidget.setCurrentIndex(0)
class InstallerProgressPage(QtW.QWidget):
    allow_close = Signal()
    close = Signal()

    def __init__(self):
        super(InstallerProgressPage, self).__init__()

        self._main_layout = QtW.QVBoxLayout()
        self._progress_bar_layout = QtW.QVBoxLayout()

        self._close_btn = QtW.QPushButton()
        self._close_btn.setText("CLOSE")
        self._close_btn.setEnabled(False)
        self._close_btn.clicked.connect(self._close_btn_handler)

        self._main_image_lb = QtW.QLabel()
        self._main_gif_mov = QMovie(resource_path("UI\\dog_haircut.gif"))
        self._main_image_lb.setAlignment(Qt.AlignCenter)

        self._main_image_lb.setMovie(self._main_gif_mov)
        self._main_gif_mov.start()

        self._progress_bar = QtW.QProgressBar()
        self._progress_bar.setRange(0, 0)
        self._progress_bar.setTextVisible(False)

        self._main_lb = QtW.QLabel()
        self._main_lb.setProperty('Title', True)
        self.set_install()
        self._task_lb = QtW.QLabel()
        self._task_lb.setText(str())

        self.setLayout(self._main_layout)

        self._main_layout.addLayout(self._progress_bar_layout)
        self._progress_bar_layout.insertStretch(-1, 0)
        self._progress_bar_layout.addWidget(self._main_image_lb)
        self._progress_bar_layout.addWidget(self._main_lb)
        self._progress_bar_layout.addWidget(self._progress_bar)
        self._progress_bar_layout.addWidget(self._task_lb)
        self._progress_bar_layout.insertStretch(-1, 0)
        self._main_layout.addWidget(self._close_btn)

    def _close_btn_handler(self):
        self.close.emit()

    def get_progress_bar(self):
        return self._progress_bar

    def set_complete(self):
        self._progress_bar.setValue(self._progress_bar.maximum())
        self._close_btn.setEnabled(True)
        self._main_lb.setText("Complete!")
        self._task_lb.setText(str())
        self.allow_close.emit()

    def set_install(self):
        self._main_lb.setText("Installing:")

    def set_uninstall(self):
        self._main_lb.setText("Uninstalling:")

    @Slot(int)
    def set_tasks(self, task_number):
        if task_number > 0:
            self._progress_bar.setTextVisible(True)
            self._progress_bar.setRange(0, task_number)
        else:
            self._progress_bar.setTextVisible(False)
            self._progress_bar.setRange(0, 0)

    @Slot(int)
    def add(self, num=1):
        self._progress_bar.setValue(self._progress_bar.value() + num)

    @Slot(str)
    def print_error(self, message):
        self._task_lb.setText(message)
        self._main_lb.setText("ERROR!")

        self._main_lb.setProperty('Title', False)
        self._main_lb.setProperty('Error', True)
        self._main_lb.setStyle(self._main_lb.style())

        self._close_btn.setEnabled(True)
        self._main_gif_mov.setPaused(True)
        self.allow_close.emit()

    def set_status(self, status):
        self._task_lb.setText(status)
Esempio n. 21
0
class CollaborationSettingsDialog(object):
    ADD_BUTTON_ACTIVE_COLOR = "#f78d1e"
    ADD_BUTTON_PASSIVE_COLOR = "#9a9a9a"
    ERROR_COLOR = '#FF9999'
    LINE_EDIT_NORMAL_COLOR = "#EFEFF1"

    def __init__(self, parent, parent_window, colleagues, folder, dp):
        self._dialog = QDialog(parent_window)
        self._dp = dp
        self._colleagues = colleagues
        self._parent = parent
        self._parent_window = parent_window
        self._folder = folder

        self._is_owner = False
        self._dialog.setWindowIcon(QIcon(':/images/icon.png'))
        self._ui = Ui_Dialog()
        self._ui.setupUi(self._dialog)

        self._init_ui()

    def _init_ui(self):
        self._dialog.setWindowFlags(Qt.Dialog)
        self._dialog.setAttribute(Qt.WA_TranslucentBackground)
        self._dialog.setAttribute(Qt.WA_MacFrameworkScaled)
        self._dialog.setWindowTitle(self._dialog.windowTitle() + self._folder)

        self._ui.colleagues_list.setAlternatingRowColors(True)
        self._colleagues_list = ColleaguesList(self._parent,
                                               self._ui.colleagues_list,
                                               self._dp, self._show_menu)

        self._loader_movie = QMovie(":/images/loader.gif")
        self._ui.loader_label.setMovie(self._loader_movie)
        self._set_fonts()

        self._ui.add_frame.setVisible(False)
        self._set_add_button_background(self.ADD_BUTTON_PASSIVE_COLOR)
        self._ui.add_button.clicked.connect(self._on_add_button_clicked)
        self._ui.add_button.setVisible(False)
        self._ui.close_button.clicked.connect(self._on_close_button_clicked)
        self._ui.refresh_button.clicked.connect(self._on_refresh)

        self._line_edit_style = "background-color: {};"
        self._ui.error_label.setStyleSheet("color: {};".format(
            self.ERROR_COLOR))

    def _set_fonts(self):
        ui = self._ui
        controls = [
            ui.colleagues_label, ui.mail_edit, ui.edit_radio, ui.view_radio,
            ui.add_button
        ]

        for control in controls:
            font = control.font()
            font_size = control.font().pointSize() * self._dp
            if font_size > 0:
                control_font = QFont(font.family(), font_size)
                control_font.setBold(font.bold())
                control.setFont(control_font)

    def show(self):
        logger.debug("Opening collaboration settings dialog")

        screen_width = QApplication.desktop().width()
        parent_x = self._dialog.parent().x()
        parent_width = self._dialog.parent().width()
        width = self._dialog.width()
        offset = 16
        if parent_x + parent_width / 2 > screen_width / 2:
            x = parent_x - width - offset
            if x < 0:
                x = 0
        else:
            x = parent_x + parent_width + offset
            diff = x + width - screen_width
            if diff > 0:
                x -= diff
        self._dialog.move(x, self._dialog.parent().y())

        # Execute dialog
        self._dialog.raise_()
        self.show_cursor_loading(True)
        self._dialog.exec_()

    def close(self):
        self._dialog.reject()

    def show_cursor_loading(self, show_movie=False):
        if show_movie:
            self._ui.stackedWidget.setCurrentIndex(1)
            self._loader_movie.start()
        else:
            self._dialog.setCursor(Qt.WaitCursor)
            self._parent_window.setCursor(Qt.WaitCursor)

    def show_cursor_normal(self):
        self._dialog.setCursor(Qt.ArrowCursor)
        self._parent_window.setCursor(Qt.ArrowCursor)
        if self._loader_movie.state() == QMovie.Running:
            self._loader_movie.stop()

    def show_colleagues(self):
        if not self._colleagues:
            self._ui.stackedWidget.setCurrentIndex(2)
        else:
            self._ui.stackedWidget.setCurrentIndex(0)
            self._colleagues_list.show_colleagues(self._colleagues)
        self.show_cursor_normal()

    def set_owner(self, is_owner):
        self._is_owner = is_owner
        self._ui.add_button.setVisible(self._is_owner)

    def _on_add_button_clicked(self):
        if self._ui.add_frame.isVisible():
            if not self._validate_email():
                return

            to_edit = self._ui.edit_radio.isChecked()
            self._ui.add_frame.setVisible(False)
            self._set_add_button_background(self.ADD_BUTTON_PASSIVE_COLOR)
            self._parent.add_colleague(self._ui.mail_edit.text(), to_edit)
        else:
            self._ui.add_frame.setVisible(True)
            self._set_add_button_background(self.ADD_BUTTON_ACTIVE_COLOR)
            self._ui.mail_edit.setText("")

    def _set_add_button_background(self, color):
        self._ui.add_button.setStyleSheet(
            'background-color: {}; color: #fff; '
            'border-radius: 4px; font: bold "Gargi"'.format(color))

    def _on_close_button_clicked(self):
        self._ui.add_frame.setVisible(False)
        self._set_add_button_background(self.ADD_BUTTON_PASSIVE_COLOR)
        self._clear_error()
        self._ui.mail_edit.setText("")

    def _validate_email(self):
        email_control = self._ui.mail_edit
        email_control.setStyleSheet(
            self._line_edit_style.format(self.LINE_EDIT_NORMAL_COLOR))
        regex = '^.+@.{2,}$'

        email_control.setText(email_control.text().strip())
        if not re.match(regex, email_control.text()):
            self._ui.error_label.setText(tr("Please enter a valid e-mail"))
            email_control.setStyleSheet(
                self._line_edit_style.format(self.ERROR_COLOR))
            email_control.setFocus()
            return False

        self._clear_error()
        return True

    def _clear_error(self):
        self._ui.error_label.setText("")
        self._ui.mail_edit.setStyleSheet(
            self._line_edit_style.format(self.LINE_EDIT_NORMAL_COLOR))

    def _on_refresh(self):
        self.show_cursor_loading()
        self._parent.query_collaboration_info()

    def _show_menu(self, colleague, pos):
        if not self._is_owner and not colleague.is_you or colleague.is_deleting:
            return

        menu = QMenu(self._ui.colleagues_list)
        menu.setStyleSheet("background-color: #EFEFF4; ")
        if colleague.is_you:
            if colleague.is_owner:
                action = menu.addAction(tr("Quit collaboration"))
                action.triggered.connect(self._on_quit_collaboration)
            else:
                action = menu.addAction(tr("Leave collaboration"))
                action.triggered.connect(self._on_leave_collaboration)
        else:
            rights_group = QActionGroup(menu)
            rights_group.setExclusive(True)

            menu.addSection(tr("Access rights"))
            action = menu.addAction(tr("Can view"))
            action.setCheckable(True)
            rights_action = rights_group.addAction(action)
            rights_action.setData(False)
            rights_action.setChecked(not colleague.can_edit)
            action = menu.addAction(tr("Can edit"))
            action.setCheckable(True)
            rights_action = rights_group.addAction(action)
            rights_action.setChecked(colleague.can_edit)
            rights_action.setData(True)
            rights_group.triggered.connect(
                lambda a: self._on_grant_edit(colleague, a))
            menu.addSeparator()

            action = menu.addAction(tr("Remove user"))
            action.triggered.connect(lambda: self._on_remove_user(colleague))

        pos_to_show = QPoint(pos.x(), pos.y() + 10)
        menu.exec_(pos_to_show)

    def _on_quit_collaboration(self):
        alert_str = "Collaboration will be cancelled, " \
                    "collaboration folder will be deleted " \
                    "from all colleagues' Pvtbox secured sync folders " \
                    "on all nodes."
        if self._user_confirmed_action(alert_str):
            self._parent.cancel_collaboration()

    def _on_leave_collaboration(self):
        alert_str = "Collaboration folder will be deleted " \
                    "from Pvtbox secured sync folders " \
                    "on all your nodes."
        if self._user_confirmed_action(alert_str):
            self._parent.leave_collaboration()

    def _on_remove_user(self, colleague):
        alert_str = "Colleague {} will be removed from collaboration. " \
                    "Collaboration folder will be deleted from colleague's " \
                    "Pvtbox secured sync folders on all nodes." \
            .format(colleague.email)
        if self._user_confirmed_action(alert_str):
            self._parent.remove(colleague.id)

    def _on_grant_edit(self, colleague, action):
        to_edit = action.data()
        self._parent.grant_edit(colleague.id, to_edit)

    def _user_confirmed_action(self, alert_str):
        msg = tr("<b>Are</b> you <b>sure</b>?<br><br>{}".format(alert_str))
        user_answer = msgbox(msg,
                             title=' ',
                             buttons=[
                                 (tr('Cancel'), 'Cancel'),
                                 (tr('Yes'), 'Yes'),
                             ],
                             parent=self._dialog,
                             default_index=0,
                             enable_close_button=True)

        return user_answer == 'Yes'
Esempio n. 22
0
class UpdatePrompt(QDialog):
    def __init__(self):
        super().__init__()
        self.makeView()
        return

    def makeView(self):
        layout = QVBoxLayout()
        btnLayout = QHBoxLayout()
        self.centStack = QStackedWidget()
        self.updateButton = QPushButton('Update')
        self.cancelButton = QPushButton('Cancel')
        notifyLabel = QLabel('There are upgrades scheduled')
        self.inputBox = QLineEdit()
        self.outputBox = QTextBrowser()
        #refreshIcon = QIcon.fromTheme('process-working')
        self.refreshIcon = QMovie('assets/spin3.gif')
        refreshAnimation = QLabel()

        layout.addWidget(notifyLabel)
        layout.addWidget(self.centStack)
        layout.addWidget(self.inputBox)
        layout.addLayout(btnLayout)
        btnLayout.addWidget(self.cancelButton)
        btnLayout.addWidget(self.updateButton)

        self.centStack.addWidget(refreshAnimation)
        self.centStack.addWidget(self.outputBox)
        refreshAnimation.setMovie(self.refreshIcon)
        refreshAnimation.setAlignment(Qt.AlignCenter)
        self.refreshIcon.start()

        self.inputBox.setEchoMode(QLineEdit.Password)
        self.inputBox.setFocus()
        self.inputBox.returnPressed.connect(self.pkgUpdates)
        self.updateButton.clicked.connect(self.pkgUpdates)
        self.cancelButton.clicked.connect(self.cancelUpdates)
        self.updateButton.setDefault(True)

        self.centStack.setCurrentIndex(1)
        notifyLabel.setAlignment(Qt.AlignTop)
        self.outputBox.setReadOnly(True)
        #self.outputBox.setAlignment(Qt.AlignTop)
        self.setWindowTitle('Package Upgrades')
        self.setLayout(layout)
        self.resize(450, 250)
        return

    async def asetup(self, password):
        async with trio.open_nursery() as nursery:
            finishedState = trio.Event()
            nursery.start_soon(self.upProc, password, 'update', finishedState)
            #nursery.start_soon(self.KEAlive, finishedState)
        return

    async def upProc(self, password, cmd, finishedState):
        proc = await trio.open_process(['sudo', '-S', 'apt-get', cmd, '-y'],
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT)
        await proc.stdin.send_all((password + '\n').encode())

        while (proc.poll() == None):
            QCoreApplication.processEvents()
            await trio.sleep(0.1)

        result = ''
        result = await self.pullOutput(proc)
        self.appendToOutput(result)
        proc.terminate()

        if (cmd == 'update'):
            await self.upProc(password, 'upgrade', finishedState)
            finishedState.set()
        return

    async def pullOutput(self, proc):
        x = await proc.stdout.receive_some()
        x = x.decode()
        result = ''
        while (x != ''):
            QCoreApplication.processEvents()
            result = result + x
            x = await proc.stdout.receive_some()
            x = x.decode()
        return result

    async def KEAlive(self, finishedState):
        while finishedState.is_set():
            QCoreApplication.processEvents()
            trio.sleep(0.1)
        return

        return

    def appendToOutput(self, add):
        currentText = self.outputBox.toPlainText()
        self.outputBox.setText(currentText + 'Running updates\n' + add + '\n')
        print(add)
        return

    def pkgUpdates(self):
        self.centStack.setCurrentIndex(0)
        self.refreshIcon.start()
        QCoreApplication.processEvents()

        password = self.inputBox.text()

        if (password == ''):
            self.passError('The password field cannot be empty')
            return

        self.inputBox.clear()
        self.inputBox.setDisabled(True)
        self.updateButton.setDisabled(True)
        trio.run(self.asetup, password)
        self.centStack.setCurrentIndex(1)
        self.refreshIcon.stop()
        self.updateButton.setDisabled(False)
        self.inputBox.setDisabled(False)
        return

    def passError(self, s):
        passError = QDialog(self)
        msg = QLabel(s)
        layout = QVBoxLayout()
        layout.addWidget(msg)
        passError.setLayout(layout)

        okBtn = QPushButton('OK')
        okBtn.clicked.connect(passError.reject)
        layout.addWidget(okBtn)

        passError.exec_()
        return

    def cancelUpdates(self):
        #Needs way of closing subprocess during async run
        self.reject()
        return
    def initUi(self):
        self.layout = QGridLayout()

        header = QLabel(self)
        header.setGeometry(0, 0, 655, 106)
        pixmap = QPixmap("./resources/ui/conflict.png")
        header.setPixmap(pixmap)
        self.layout.addWidget(header, 0, 0)

        self.gridLayout = QGridLayout()
        TEXT = "" + \
                "<b>You are clear for takeoff</b>" + \
                "" + \
                "<h2>For Singleplayer :</h2>\n" + \
                "In DCS, open the Mission Editor, and load the file : \n" + \
                "<i>liberation_nextturn</i>\n" + \
                "<p>Then once the mission is loaded in ME, in menu \"Flight\",\n" + \
                "click on FLY Mission to launch.</p>\n" + \
                "" + \
                "<h2>For Multiplayer :</h2>" + \
                "In DCS, open the Mission Editor, and load the file : " + \
                "<i>liberation_nextturn</i>" + \
                "<p>Click on File/Save. Then exit the mission editor, and go to Multiplayer.</p>" + \
                "<p>Then host a server with the mission, and tell your friends to join !</p>" + \
                "<i>(The step in the mission editor is important, and fix a game breaking bug.)</i>" + \
                "<h2>Finishing</h2>" + \
                "<p>Once you have played the mission, click on the \"Accept Results\" button.</p>" + \
                "<p>If DCS Liberation does not detect mission end, use the manually submit button, and choose the state.json file.</p>"

        self.instructions_text = QTextEdit(TEXT)
        self.instructions_text.setReadOnly(True)
        self.gridLayout.addWidget(self.instructions_text, 1, 0)

        progress = QLabel("")
        progress.setAlignment(QtCore.Qt.AlignCenter)
        progress_bar = QMovie("./resources/ui/loader.gif")
        progress.setMovie(progress_bar)

        self.actions = QGroupBox("Actions :")
        self.actions_layout = QHBoxLayout()
        self.actions.setLayout(self.actions_layout)

        self.manually_submit = QPushButton("Manually Submit [Advanced users]")
        self.manually_submit.clicked.connect(self.submit_manually)
        self.actions_layout.addWidget(self.manually_submit)
        self.cancel = QPushButton("Abort mission")
        self.cancel.clicked.connect(self.close)
        self.actions_layout.addWidget(self.cancel)
        self.gridLayout.addWidget(self.actions, 2, 0)

        self.actions2 = QGroupBox("Actions :")
        self.actions2_layout = QHBoxLayout()
        self.actions2.setLayout(self.actions2_layout)
        self.manually_submit2 = QPushButton("Manually Submit [Advanced users]")
        self.manually_submit2.clicked.connect(self.submit_manually)
        self.actions2_layout.addWidget(self.manually_submit2)
        self.cancel2 = QPushButton("Abort mission")
        self.cancel2.clicked.connect(self.close)
        self.actions2_layout.addWidget(self.cancel2)
        self.proceed = QPushButton("Accept results")
        self.proceed.setProperty("style", "btn-success")
        self.proceed.clicked.connect(self.process_debriefing)
        self.actions2_layout.addWidget(self.proceed)

        progress_bar.start()
        self.layout.addLayout(self.gridLayout, 1, 0)
        self.setLayout(self.layout)
Esempio n. 24
0
    def initUi(self):
        self.layout = QGridLayout()

        header = QLabel(self)
        header.setGeometry(0, 0, 655, 106)
        pixmap = QPixmap("./resources/ui/conflict.png")
        header.setPixmap(pixmap)
        self.layout.addWidget(header, 0, 0)

        self.gridLayout = QGridLayout()

        jinja = Environment(
            loader=FileSystemLoader("resources/ui/templates"),
            autoescape=select_autoescape(
                disabled_extensions=("", ),
                default_for_string=True,
                default=True,
            ),
            trim_blocks=True,
            lstrip_blocks=True,
        )
        self.instructions_text = QTextBrowser()
        self.instructions_text.setHtml(
            jinja.get_template("mission_start_EN.j2").render())
        self.instructions_text.setOpenExternalLinks(True)
        self.gridLayout.addWidget(self.instructions_text, 1, 0)

        progress = QLabel("")
        progress.setAlignment(QtCore.Qt.AlignCenter)
        progress_bar = QMovie("./resources/ui/loader.gif")
        progress.setMovie(progress_bar)

        self.actions = QGroupBox("Actions :")
        self.actions_layout = QHBoxLayout()
        self.actions.setLayout(self.actions_layout)

        self.manually_submit = QPushButton("Manually Submit [Advanced users]")
        self.manually_submit.clicked.connect(self.submit_manually)
        self.actions_layout.addWidget(self.manually_submit)
        self.cancel = QPushButton("Abort mission")
        self.cancel.clicked.connect(self.close)
        self.actions_layout.addWidget(self.cancel)
        self.gridLayout.addWidget(self.actions, 2, 0)

        self.actions2 = QGroupBox("Actions :")
        self.actions2_layout = QHBoxLayout()
        self.actions2.setLayout(self.actions2_layout)
        self.manually_submit2 = QPushButton("Manually Submit [Advanced users]")
        self.manually_submit2.clicked.connect(self.submit_manually)
        self.actions2_layout.addWidget(self.manually_submit2)
        self.cancel2 = QPushButton("Abort mission")
        self.cancel2.clicked.connect(self.close)
        self.actions2_layout.addWidget(self.cancel2)
        self.proceed = QPushButton("Accept results")
        self.proceed.setProperty("style", "btn-success")
        self.proceed.clicked.connect(self.process_debriefing)
        self.actions2_layout.addWidget(self.proceed)

        progress_bar.start()
        self.layout.addLayout(self.gridLayout, 1, 0)
        self.setLayout(self.layout)
Esempio n. 25
0
class LoadingVideosInfoDialog(QDialog):
    def __init__(self, videos_list):
        super().__init__()
        self.setWindowTitle("Loading Media Info")
        self.videos_list = videos_list
        self.videos_count = len(self.videos_list)
        self.current_video_done_index = 0
        self.status_label = QLabel("Scanning Video " +
                                   str(self.current_video_done_index) + "/" +
                                   str(self.videos_count))
        self.load_icon_movie = QMovie(SpinnerIconPath)
        self.load_icon_label = QLabel()
        self.load_icon_label.setMovie(self.load_icon_movie)
        self.layout = QHBoxLayout()
        self.layout.addStretch(2)
        self.layout.addWidget(self.load_icon_label)
        self.layout.addWidget(self.status_label)
        self.layout.addStretch(3)
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(8, 12, 8, 12)
        self.setLayout(self.layout)
        self.disable_question_mark_window()
        self.generate_media_info_files()

    # noinspection PyAttributeOutsideInit
    def generate_media_info_files(self):
        self.generate_media_info_files_thread = QThread()
        self.generate_media_info_files_worker = GenerateMediaInfoFilesWorker(
            self.videos_list)
        self.generate_media_info_files_worker.moveToThread(
            self.generate_media_info_files_thread)
        self.generate_media_info_files_thread.started.connect(
            self.generate_media_info_files_worker.run)
        self.generate_media_info_files_worker.job_succeeded_signal.connect(
            self.update_progress)
        self.generate_media_info_files_worker.finished_all_jobs_signal.connect(
            self.generate_media_info_files_thread.quit)
        self.generate_media_info_files_worker.finished_all_jobs_signal.connect(
            self.generate_media_info_files_worker.deleteLater)
        self.generate_media_info_files_thread.finished.connect(
            self.generate_media_info_files_thread.deleteLater)
        self.generate_media_info_files_thread.finished.connect(
            self.stop_loading)
        self.start_loading()
        self.generate_media_info_files_thread.start()

    def disable_question_mark_window(self):
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, on=False)

    def update_progress(self):
        self.current_video_done_index += 1
        self.status_label.setText(" Scanning Video " +
                                  str(self.current_video_done_index) + "/" +
                                  str(self.videos_count))

    def start_loading(self):
        self.load_icon_movie.start()

    def stop_loading(self):
        time.sleep(0.1)
        self.load_icon_movie.stop()
        self.close()

    def execute(self):
        self.exec()
from PySide2.QtGui import QIcon, QMovie
from PySide2.QtWidgets import QApplication, QPushButton, QLabel
from PySide2.QtCore import Slot, QSize


@Slot()
def say_hello():
    print("You have clicked PICARD")


# Create the Qt Application
app = QApplication(sys.argv)

# A BUTTON WITH IMAGE ON
button = QPushButton("")
button.setWindowTitle("Image button test")
button.setIcon(QIcon('assets/picard.jpg'))
button.setIconSize(QSize(800, 450))
button.clicked.connect(say_hello)
button.show()

# A GIF
label = QLabel()
label.setWindowTitle("Spiral GIF test")
movie = QMovie("assets/spiral.gif")
label.setMovie(movie)
movie.start()
label.show()

# Run the main Qt loop
app.exec_()
Esempio n. 27
0
    def img_viewer(self, undo_op=False):
        if self.idx_curr_file >= len(self.file_paths) or len(
                self.file_paths) == 0:
            self.infos_dict['fd_info'] = "No img"
            self.ui.status_bar.showMessage(self.infos_dict['fd_info'])
            self.ui.img_show_label.setText(" ")
        else:
            while self.idx_curr_file < len(self.file_paths):
                QApplication.processEvents()
                img_path = self.file_paths[self.idx_curr_file]
                if img_path.endswith(".gif"):
                    movie = QMovie(img_path)
                    self.ui.img_show_label.setMovie(movie)
                    movie.start()
                    self.infos_dict['fd_info'] = "%d/%d: %s" % (
                        self.idx_curr_file, len(self.file_paths),
                        self.file_paths[self.idx_curr_file])
                    self.ui.status_bar.showMessage(self.infos_dict['fd_info'])
                    break
                pixmap = QPixmap(img_path)
                if not pixmap.isNull():
                    try:
                        image = Image.open(img_path)
                        rotated_flag = False
                        angle = 0
                        for orientation in ExifTags.TAGS.keys():
                            if ExifTags.TAGS[orientation] == 'Orientation':
                                break
                        exif = dict(image._getexif().items())
                        print(img_path, " exif: ", exif[orientation])
                        if exif[orientation] == 3:
                            angle = 180
                            rotated_flag = True
                        elif exif[orientation] == 6:
                            angle = 270
                            rotated_flag = True
                        elif exif[orientation] == 8:
                            angle = 90
                            rotated_flag = True
                        if rotated_flag:
                            pixmap = pixmap.transformed(
                                QTransform().rotate(-angle))
                            image = image.rotate(angle, expand=True)
                            image.save(img_path)
                            image.close()
                    except (AttributeError, KeyError, IndexError):
                        # cases: image don't have getexif
                        pass

                    max_h = self.ui.img_show_label.height()
                    max_w = self.ui.img_show_label.width()
                    if max_h > self.configurator.using_conf_dict[
                            'image default display size'][0]:
                        max_h = self.configurator.using_conf_dict[
                            'image default display size'][0]
                    if max_w > self.configurator.using_conf_dict[
                            'image default display size'][1]:
                        max_w = self.configurator.using_conf_dict[
                            'image default display size'][1]
                    self.ui.img_show_label.setPixmap(
                        pixmap.scaled(max_w,
                                      max_h,
                                      aspectMode=Qt.KeepAspectRatio))
                    # QApplication.processEvents()
                    self.infos_dict['fd_info'] = "%d/%d: %s" % (
                        self.idx_curr_file, len(self.file_paths),
                        self.file_paths[self.idx_curr_file])
                    self.ui.status_bar.showMessage(self.infos_dict['fd_info'])

                    break
                elif not undo_op:
                    self.idx_curr_file = self.idx_curr_file + 1
                else:
                    self.idx_curr_file = self.idx_curr_file - 1
                    if self.idx_curr_file < 0:
                        self.idx_curr_file = 0
                        break