Esempio n. 1
0
 def _add_to_internal_dict(self, element, parent, num_row):
     QueueModel._add_to_internal_dict(self, element, parent, num_row)
     if element.tag == "item":
         # TODO: check if file exists and if so, initialize percentage
         progressbar = QProgressBar()
         progressbar.setValue(0)
         self.progress_bars[element] = progressbar
         selected_extension = element.get("selected")
         if selected_extension is None:
             element.attrib["status"] = "Error: No Extension selected"
             return
         selected_format = element.find("format[@extension='%s']" % selected_extension)
         if selected_format is None:
             element.attrib["status"] = "Error: No Quality selected"
             return
         selected_quality = selected_format.get("selected")
         option = element.find(
             "format[@extension='%s']/option[@quality='%s']" % (selected_extension, selected_quality)
         )
         self.option_elements[element] = option
         # fill remaining filename template, extension and quality shall not change within DownloadModel
         mapping = dict(
             title=element.get("title"),
             url=element.get("url"),
             host=element.get("host"),
             extension=selected_extension,
             quality=selected_quality,
         )
         element.attrib["filename"] = fill_filename_template(element.attrib["filename"], mapping)
Esempio n. 2
0
    def __init__(self, parent=None):
        super(StatusArea, self).__init__(parent)
        self.setStyleSheet('StatusArea {background: yellow}')
        self.msg = QLabel(self)
        self.file = QLabel(self)
        self.progress = QProgressBar(self)

        self.msg.setFont(View.labelsFont())
        self.file.setFont(View.editsFont())

        self.progress.setMaximum(100)
        self.progress.setMinimum(0)
        self.progress.setTextVisible(False)
        self.progress.setStyleSheet(""" 
            QProgressBar {
                 border: 2px solid grey;
                 border-radius: 5px;
                 width: 60px;
                 height: 10px;
             }

             QProgressBar::chunk {
                 background-color: #05B8CC;
                 width: 5px;
             }""")

        layout = QHBoxLayout()
        layout.addWidget(self.msg, 0, Qt.AlignLeft)
        layout.addWidget(self.file, 0, Qt.AlignLeft)
        layout.addWidget(self.progress, 0, Qt.AlignRight)

        self.setLayout(layout)
Esempio n. 3
0
    def __init__(self, parent=None, statusBarService=None):
        """
        Creates a QProgressBar and adds it to the given status bar (for
        threads that can provide accurate progress information).

        Note: The status bar can either be a QStatusBar or the StatusBarService. In the default
        BioPARKIN use, it is the StatusBarService instance.

        @todo: A throbber is created and also added to the status bar (for
        threads that can only provide start/stop information).
        """
        #        super(ProgressBarService, self).__init__(parent)   # done in __new__

        if statusBarService is not None:
            self.statusBarService = statusBarService
            self.progressBar = QProgressBar(None)  # used for showing progress
            self.progressBarMutex = QMutex()
            self.progressBar.hide()
            self.statusBarService.addPermanentWidget(self.progressBar)
            self.progressRunning = False

            self.throbber = QLabel()
            self.throbberRunning = False
            self.throbberMutex = QMutex()
            self.statusBarService.addPermanentWidget(self.throbber)
            self.throbber.show()
            self.throbber.hide()

            throbberImage = QMovie(":/images/Spinning_wheel_throbber.gif",
                                   parent=self.throbber)
            throbberImage.setScaledSize(QSize(24, 24))
            throbberImage.setCacheMode(QMovie.CacheAll)
            throbberImage.start()
            self.throbber.setMovie(throbberImage)
            self.throbber.setFixedSize(24, 24)
Esempio n. 4
0
    def __init__(self, p_steps=None):

        QProgressBar.__init__(self)

        self.__steps = 1 if p_steps is None else p_steps
        self.__length = 100 / self.__steps
        self.__value = 0

        self.setValue(0)
    def _init_statusbar(self):

        self._progressbar = QProgressBar()

        self._progressbar.setMinimum(0)
        self._progressbar.setMaximum(100)
        self._progressbar.hide()

        self.statusBar().addPermanentWidget(self._progressbar)
Esempio n. 6
0
 def __init__(self):
     """ Constructo FUnction
     """
     QMainWindow.__init__(self)
     self.setWindowTitle("Application Title Here")
     self.setGeometry(300, 250, 400, 300)
     self.statusLabel = QLabel('Showing Progress')
     self.progressBar = QProgressBar()
     self.progressBar.setMinimum(0)
     self.progressBar.setMaximum(1000000)
Esempio n. 7
0
 def showProgressbar(self):
     if self.progressText:
         if not self.pb_widget:
             self.pb_widget = QDialog(self.parent())
             self.pb_widget.setWindowFlags(Qt.SplashScreen)
             self.pb_widget.setModal(True)
         hl = QHBoxLayout()
         pb = QProgressBar()
         pb.setRange(0, 0)
         hl.addWidget(pb)
         hl.addWidget(QLabel(self.progressText))
         self.pb_widget.setLayout(hl)
         self.pb_widget.show()
Esempio n. 8
0
 def setupStatusBar(self):
     """Ajoute une barre de status"""
     self.progressBar = QProgressBar()
     self.statusLabel = QLabel('Progression ...')
     self.progressBar.setMaximum(100)
     self.progressBar.setMinimum(0)
     self.statusBar = QStatusBar()
     # # Affiche un message durant 2 sec après ouverture de l'application
     # self.statusBar.showMessage('Please Wait ...', 2000)
     self.progressBar.setValue(10)
     self.statusBar.addWidget(self.statusLabel, 1)
     self.statusBar.addWidget(self.progressBar, 2)
     self.setStatusBar(self.statusBar)
Esempio n. 9
0
 def modSB(self):
     if self.PPbar is None:
         self.PPbar = True
         self.statusb.clear()
         self.pbar = QProgressBar()
         self.pbar.setMaximum(100)
         self.pbar.setMinimum(0)
         self.plabel = QLabel()
         self.statusb.addWidget(self.plabel, 0.5)
         self.statusb.addWidget(self.pbar, 3)
     else:
         self.PPbar = None
         self.statusb.removeWidget(self.plabel)
         self.statusb.removeWidget(self.pbar)
         self.statusb.clear()
Esempio n. 10
0
    def __init__(self, parent=None):
        super(StatusArea, self).__init__(parent)
        self.setStyleSheet('StatusArea {background: yellow}')
        self.msg = QLabel(self)
        self.file = QLabel(self)
        self.progress = QProgressBar(self)
   
        self.msg.setFont(View.labelsFont())
        self.file.setFont(View.editsFont())

        self.progress.setMaximum(100)
        self.progress.setMinimum(0)
        self.progress.setTextVisible(False)
        self.progress.setStyleSheet(""" 
            QProgressBar {
                 border: 2px solid grey;
                 border-radius: 5px;
                 width: 60px;
                 height: 10px;
             }

             QProgressBar::chunk {
                 background-color: #05B8CC;
                 width: 5px;
             }""")
 
        layout = QHBoxLayout()
        layout.addWidget(self.msg, 0, Qt.AlignLeft)
        layout.addWidget(self.file, 0, Qt.AlignLeft)
        layout.addWidget(self.progress, 0, Qt.AlignRight)

        self.setLayout(layout)
Esempio n. 11
0
    def __init__(self, parent=None, statusBarService=None):
        """
        Creates a QProgressBar and adds it to the given status bar (for
        threads that can provide accurate progress information).

        Note: The status bar can either be a QStatusBar or the StatusBarService. In the default
        BioPARKIN use, it is the StatusBarService instance.

        @todo: A throbber is created and also added to the status bar (for
        threads that can only provide start/stop information).
        """
        #        super(ProgressBarService, self).__init__(parent)   # done in __new__

        if statusBarService is not None:
            self.statusBarService = statusBarService
            self.progressBar = QProgressBar(None)  # used for showing progress
            self.progressBarMutex = QMutex()
            self.progressBar.hide()
            self.statusBarService.addPermanentWidget(self.progressBar)
            self.progressRunning = False

            self.throbber = QLabel()
            self.throbberRunning = False
            self.throbberMutex = QMutex()
            self.statusBarService.addPermanentWidget(self.throbber)
            self.throbber.show()
            self.throbber.hide()

            throbberImage = QMovie(":/images/Spinning_wheel_throbber.gif", parent=self.throbber)
            throbberImage.setScaledSize(QSize(24, 24))
            throbberImage.setCacheMode(QMovie.CacheAll)
            throbberImage.start()
            self.throbber.setMovie(throbberImage)
            self.throbber.setFixedSize(24, 24)
	def __init__(self, parent, message):
		super(ExportProgressDialog, self).__init__(parent)

		self.setModal(True)
		self.setWindowTitle(message)

		indicator = QProgressBar()
		indicator.setMinimum(0)
		indicator.setMaximum(0)

		messageLabel = QLabel(message)

		layout = QGridLayout()
		layout.addWidget(messageLabel)
		layout.addWidget(indicator)
		self.setLayout(layout)
Esempio n. 13
0
 def __init__(self):
     super(STMainWindow, self).__init__()
     self.createActions()
     self.createMenus()
     layout = QVBoxLayout()
     self.tabs = QTabWidget()
     self.tabs.setTabPosition(QTabWidget.West)
     self.tabs.currentChanged[int].connect(self.tabChanged)
     self.sessiontab = sweattrails.qt.sessiontab.SessionTab(self)
     self.tabs.addTab(self.sessiontab, "Sessions")
     self.tabs.addTab(sweattrails.qt.fitnesstab.FitnessTab(self),
                      "Fitness")
     self.tabs.addTab(sweattrails.qt.profiletab.ProfileTab(self),
                      "Profile")
     self.usertab = sweattrails.qt.usertab.UserTab(self)
     self.tabs.addTab(self.usertab, "Users")
     self.usertab.hide()
     layout.addWidget(self.tabs)
     w = QWidget(self)
     w.setLayout(layout)
     self.setCentralWidget(w)
     self.statusmessage = QLabel()
     self.statusmessage.setMinimumWidth(200)
     self.statusBar().addPermanentWidget(self.statusmessage)
     self.progressbar = QProgressBar()
     self.progressbar.setMinimumWidth(100)
     self.progressbar.setMinimum(0)
     self.progressbar.setMaximum(100)
     self.statusBar().addPermanentWidget(self.progressbar)
     self.setWindowTitle("SweatTrails")
     self.setWindowIconText("SweatTrails")
     icon = QPixmap("image/sweatdrops.png")
     self.setWindowIcon(QIcon(icon))
     QCoreApplication.instance().refresh.connect(self.userSet)
Esempio n. 14
0
    def setupUI(self):

        self.pushButton = QPushButton(u"Search", self)
        #self.testButton = QPushButton(u"Test", self)
        self.lineEdit = QLineEdit(self)
        self.textEdit = QTextEdit(self)
        self.comboBox = QComboBox(self)
        self.label = QLabel(u"DB:", self)
        self.progressBar = QProgressBar(self)
        self.progressBar.setRange(0,1)
        
        self.textEdit.setReadOnly(True)

        self.layout = QVBoxLayout()
        self.topLayout = QHBoxLayout()
        
        self.topLayout.addWidget(self.label)
        self.topLayout.addWidget(self.comboBox)
        self.topLayout.addWidget(self.lineEdit)
        self.topLayout.addWidget(self.pushButton)
        #self.topLayout.addWidget(self.testButton)

        #self.testButton.clicked.connect(self.onTestButtonClicked)

        self.layout.addLayout(self.topLayout)
        self.layout.addWidget(self.textEdit)
        self.layout.addWidget(self.progressBar)

        self.setLayout(self.layout)

        self.resize(600, 700)
        self.setWindowTitle(u"Search Data for NCBI")
 def __init__(self):
     QMainWindow.__init__(self)
     self.setWindowTitle("Main Window")
     self.setGeometry(300, 250, 400, 300)
     self.statusLabel = QLabel('Showing Progress')
     self.progressBar = QProgressBar()
     self.progressBar.setMinimum(0)
     self.progressBar.setMaximum(100)
Esempio n. 16
0
 def _createLayout(self):
     'Create the Widget Layout'
     
     self._txtLogbook = QLineEdit()
     self._txtLogbook.setReadOnly(True)
     self._lblLogbook = QLabel(self.tr('&Logbook File:'))
     self._lblLogbook.setBuddy(self._txtLogbook)
     self._btnBrowse = QPushButton('...')
     self._btnBrowse.clicked.connect(self._btnBrowseClicked)
     self._btnBrowse.setStyleSheet('QPushButton { min-width: 24px; max-width: 24px; }')
     self._btnBrowse.setToolTip(self.tr('Browse for a Logbook'))
     
     self._cbxComputer = QComboBox()
     self._lblComputer = QLabel(self.tr('Dive &Computer:'))
     self._lblComputer.setBuddy(self._cbxComputer)
     self._btnAddComputer = QPushButton(QPixmap(':/icons/list-add.png'), self.tr(''))
     self._btnAddComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }')
     self._btnAddComputer.clicked.connect(self._btnAddComputerClicked)
     self._btnRemoveComputer = QPushButton(QPixmap(':/icons/list-remove.png'), self.tr(''))
     self._btnRemoveComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }')
     self._btnRemoveComputer.clicked.connect(self._btnRemoveComputerClicked)
     
     hbox = QHBoxLayout()
     hbox.addWidget(self._btnAddComputer)
     hbox.addWidget(self._btnRemoveComputer)
     
     gbox = QGridLayout()
     gbox.addWidget(self._lblLogbook, 0, 0)
     gbox.addWidget(self._txtLogbook, 0, 1)
     gbox.addWidget(self._btnBrowse, 0, 2)
     gbox.addWidget(self._lblComputer, 1, 0)
     gbox.addWidget(self._cbxComputer, 1, 1)
     gbox.addLayout(hbox, 1, 2)
     gbox.setColumnStretch(1, 1)
     
     self._pbTransfer = QProgressBar()
     self._pbTransfer.reset()
     self._txtStatus = QTextEdit()
     self._txtStatus.setReadOnly(True)
     
     self._btnTransfer = QPushButton(self.tr('&Transfer Dives'))
     self._btnTransfer.clicked.connect(self._btnTransferClicked)
     
     self._btnExit = QPushButton(self.tr('E&xit'))
     self._btnExit.clicked.connect(self.close)
     
     hbox = QHBoxLayout()
     hbox.addWidget(self._btnTransfer)
     hbox.addStretch()
     hbox.addWidget(self._btnExit)
     
     vbox = QVBoxLayout()
     vbox.addLayout(gbox)
     vbox.addWidget(self._pbTransfer)
     vbox.addWidget(self._txtStatus)
     vbox.addLayout(hbox)
     
     self.setLayout(vbox)
Esempio n. 17
0
    def _create_control(self, parent):
        layout = QVBoxLayout()
        pb = QProgressBar()

        self._message_control = QLabel()
        self._message_control.setText('     ')
        layout.addWidget(self._message_control)
        layout.addWidget(pb)

        return pb
Esempio n. 18
0
 def initInterface(self, kwargs):
   layout = QGridLayout()
   self._data_table = SearchTable(name=kwargs.get("name"))
   self._progress_spider = QProgressBar()
   self._label_count = QLabel(self.tr("0 items scraped"))
   # make it a busy indicator. you don't know when it'll finish 
   self._progress_spider.setMinimum(0); self._progress_spider.setMaximum(0)
   self._progress_spider.setTextVisible(False)
   self._btn_stop_spider = QPushButton(self.tr("Stop Spider"))
   self._btn_stop_spider.clicked.connect(self.stop_spider)
   row = 0; col = 0;
   layout.addWidget(self._data_table, row, col, 1, 4)
   row += 1;
   layout.addWidget(self._progress_spider, row, col, 1, 1)
   col += 1
   layout.addWidget(self._label_count, row, col, 1, 2)
   col += 2
   layout.addWidget(self._btn_stop_spider, row, col, 1, 1)
   self.setLayout(layout)
Esempio n. 19
0
 def __init__(self,inQueue,outQueue,*args,**kwargs):
     QtGui.QProgressDialog.__init__(self,*args,**kwargs)
     self.progress = QProgressBar(self)
     self.progress.setFormat("%p%")
     self.setBar(self.progress)
     self.inQueue = inQueue
     self.outQueue = outQueue
     self.timer = QtCore.QTimer(self)
     self.timer.timeout.connect(self.dispatcher)
     self.timer.start(50)
     self.center()
Esempio n. 20
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        Ui_MainWindow.__init__(self, parent)
        self.setupUi(self)

        self.progressBar = QProgressBar()
        self.progressBar.setMaximumWidth(100)
        self.statusbar.addPermanentWidget(self.progressBar)

        self.initData()

        self.connects()
Esempio n. 21
0
    def showProgressbar(self):
        if self.progressText:

            # generate widget if not given in init
            if not self.pb_widget:
                self.pb_widget = QDialog(self.parent())
                self.pb_widget.setWindowFlags(Qt.SplashScreen)
                self.pb_widget.setModal(True)

            # add button
            delete_button = QPushButton('X')
            delete_button.clicked.connect(self.exit)
            hl = QHBoxLayout()
            pb = QProgressBar()
            pb.setRange(0, 0)
            hl.addWidget(pb)
            hl.addWidget(QLabel(self.progressText))
            if self.abortButton:
                hl.addWidget(delete_button)
            self.pb_widget.setLayout(hl)
            self.pb_widget.show()
Esempio n. 22
0
	def __init__(self,progress=None,parent=None):
		QWidget.__init__(self,parent)
		self.progressBar=QProgressBar()
		self.abortButton=QPushButton()
		
		layout=QHBoxLayout()
		layout.addWidget(self.progressBar)
		layout.addWidget(self.abortButton)
		self.setLayout(layout)
		
		if progress:
			self.setProgress(progress)
Esempio n. 23
0
    class ControlledProgressDialog(QtGui.QProgressDialog):
        """
        QProgressDialog controlled by pipe
        """
        def __init__(self,inQueue,outQueue,*args,**kwargs):
            QtGui.QProgressDialog.__init__(self,*args,**kwargs)
            self.progress = QProgressBar(self)
            self.progress.setFormat("%p%")
            self.setBar(self.progress)
            self.inQueue = inQueue
            self.outQueue = outQueue
            self.timer = QtCore.QTimer(self)
            self.timer.timeout.connect(self.dispatcher)
            self.timer.start(50)
            self.center()

        def setTextVisible(self,visible):
            self.progress.setTextVisible(visible)

        def center(self):
            screen = QtGui.QDesktopWidget().screenGeometry()
            size = self.geometry()
            self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

        @QtCore.Slot()
        def dispatcher(self):
            """
            Dispatcher called by 50ms
            """
            while not self.inQueue.empty():
                cmd,args,ret = self.inQueue.get()
                if cmd == "quit":
                    self.timer.stop()
                    self.close()
                else:
                    res = getattr(self,cmd)(*args)
                    if ret:
                        self.outQueue.put(res)
                    self.center()
Esempio n. 24
0
 def setupStatusBar(self):
     """Ajoute une barre de status"""
     self.progressBar = QProgressBar()
     self.statusLabel = QLabel('Progression ...')
     self.progressBar.setMaximum(100)
     self.progressBar.setMinimum(0)
     self.statusBar = QStatusBar()
     # # Affiche un message durant 2 sec après ouverture de l'application
     # self.statusBar.showMessage('Please Wait ...', 2000)
     self.progressBar.setValue(10)
     self.statusBar.addWidget(self.statusLabel, 1)
     self.statusBar.addWidget(self.progressBar, 2)
     self.setStatusBar(self.statusBar)
Esempio n. 25
0
class ProgressView(QWidget):
	def __init__(self,progress=None,parent=None):
		QWidget.__init__(self,parent)
		self.progressBar=QProgressBar()
		self.abortButton=QPushButton()
		
		layout=QHBoxLayout()
		layout.addWidget(self.progressBar)
		layout.addWidget(self.abortButton)
		self.setLayout(layout)
		
		if progress:
			self.setProgress(progress)
	
	def setProgress(self,progress):
		self.progress=progress
		self.progress.progressSetup.connect(self.progressBar.setMaximum)
		self.progress.progressNotified.connect(self.progressBar.setValue)
		self.progress.progressCompleted.connect(self.progressCompleted)
		self.abortButton.clicked.connect(self.progress.abort)
	
	def progressCompleted(self):
		self.progressBar.setValue(self.progress.maximum)
Esempio n. 26
0
    def __init__(self):
        super(CompareSequences, self).__init__()

        self.setWindowTitle('Compare Sequences')
        self.setFixedHeight(125)

        self._ledit1 = QLineEdit()
        self._btn_pick_1 = QPushButton('...')
        self._ledit2 = QLineEdit()
        self._btn_pick_2 = QPushButton('...')
        self._btn_compare = QPushButton('Compare')
        self._progress_bar = QProgressBar(self.statusBar())

        self._setup_ui()
        self._set_connections()
Esempio n. 27
0
    def createRotableGroupBox(self):
        self.rotableGroupBox = QGroupBox("Rotable Widgets")
        
        self.rotableWidgets.append(QSpinBox())
        self.rotableWidgets.append(QSlider())
        self.rotableWidgets.append(QDial())
        self.rotableWidgets.append(QProgressBar())
        count = len(self.rotableWidgets)
        for i in range(count):
            self.rotableWidgets[i].valueChanged[int].\
                connect(self.rotableWidgets[(i+1) % count].setValue)

        self.rotableLayout = QGridLayout()    
        self.rotableGroupBox.setLayout(self.rotableLayout)

        self.rotateWidgets()
Esempio n. 28
0
class MainWindow(QMainWindow):
    """ Our Main Window """
    def __init__(self):
        """ Constructor Fucntion
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.statusLabel = QLabel('Showing Progress')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)

    def createStatusBar(self):
        """ Function to create the status bar
        """
        self.myStatusBar = QStatusBar()
        self.myStatusBar.showMessage('', 2000)
        self.setStatusBar(self.myStatusBar)
        """
        self.progressBar.setValue(10)
        self.myStatusBar.addWidget(self.statusLabel, 1)
        self.myStatusBar.addWidget(self.progressBar, 2)
        self.setStatusBar(self.myStatusBar)
        """

    def showProgress(self):
        """ Function to show progress
        """
        while(self.progressBar.value() < self.progressBar.maximum()):
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1)

        self.statusLabel.setText('Ready')

    def setupComponents(self):
        """ Setting the central widget
        """
        textEdit = QTextEdit()
        self.setCentralWidget(textEdit)
Esempio n. 29
0
 def InitUI(self):        
     """ Initialize user created UI elements """
     self.qlVidsDone         = QLabel('0', self)
     self.qlVidsInProgress   = QLabel('0', self)
     self.qlStartTime        = QLabel(datetime.now().strftime("%a, %d %b %Y %H:%M:%S"), self)
     self.qlEndTime          = QLabel('', self)
     self.qlTimeLeft         = QLabel('', self)
     self.qlDestinationSpace = QLabel('', self)
     self.qlArcSpace         = QLabel('', self)
     self.qlProcessingSpeed  = QLabel('', self)
     
     self.qleSourceDir       = QLineEditDirectoriesOnly()
     self.qleArchiveDir      = QLineEditDirectoriesOnly()
     self.qleDestinationDir  = QLineEditDirectoriesOnly()
     self.qleMaxVidsCap      = QLineEditIntsOnly()
     self.qleVideoTypes      = QLineEditNoPeriodsOrCommas()
     self.qleVideoTypes.installEventFilter(self)
     
     self.qpbSourceDir       = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForSourceDirectory)
     self.qpbArchiveDir      = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForArchiveDirectory)
     self.qpbTargetDir       = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForTargetDirectory)
     self.qpbRun             = self.__CreateButton(None,"Run", 75, self.Process)        
     
     self.setWindowTitle("Manage HD Video")
     self.videoExtensionFileFilter = "Video (*.mkv *.mp4 *.avi)"
     self.qleVideoTypes.setText("mkv mp4 avi")
     self.statusLabel = QLabel('Showing Progress')
     self.progressBar = QProgressBar()
     self.progressBar.setMinimum(0)
     self.progressBar.setMaximum(100)
     self.__CreateActions()
     self.__CreateMenus()
     self.fileMenu.addAction(self.stdAction)
     self.fileMenu.addAction(self.altAction)
     if Progress.runPlatform == 'win':
         self.stdAction.setIcon(QIcon('checked.jpg'))
     self.stdAction.setChecked(True)
     self.fileMenu.addSeparator()
     self.fileMenu.addAction(self.exitAction)
     self.fileMenu.addSeparator()
     self.helpMenu.addAction(self.aboutAction)
     self.__SetIcon()
     self.__CenterWindow()
     self.__CreateGrid()       
    def __init__(self, parent, message):
        super(ExportProgressDialog, self).__init__(parent)

        self.setModal(True)
        self.setWindowTitle(message)

        indicator = QProgressBar()
        indicator.setMinimum(0)
        indicator.setMaximum(0)

        messageLabel = QLabel(message)

        layout = QGridLayout()
        layout.addWidget(messageLabel)
        layout.addWidget(indicator)
        self.setLayout(layout)
Esempio n. 31
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        Ui_MainWindow.__init__(self, parent)
        self.setupUi(self)

        self.progressBar = QProgressBar()
        self.progressBar.setMaximumWidth(100)
        self.statusbar.addPermanentWidget(self.progressBar)

        self.initData()

        self.connects()

    def connects(self):
        self.checkThread.checkComplete.connect(self.updateView)
        self.checkThread.versionChecked.connect(self.progressCheck)

    #        self.actionQuit.triggered.connect(self.close)

    def initData(self):
        WowPath = os.path.normpath("D:\World of Warcraft")
        WowPath = os.path.join(WowPath, "Interface", "AddOns")

        self.addons = getAddOnList(WowPath)

        self.progressBar.setRange(0, len(self.addons))
        self.progressBar.setValue(0)
        self.progressBar.show()

        self.a = 0

        self.checkThread = QCheckThread(self.addons)
        self.checkThread.start()

        self.statusbar.showMessage("Checking for update")

    @Slot(list)
    def updateView(self, latestVersions):
        self.statusbar.showMessage("Checking complete", 30000)
        self.tableViewAddOn.setModel(AddOnModel(self.addons, latestVersions))
        self.tableViewAddOn.resizeColumnsToContents()
        self.progressBar.hide()
        self.checkThread.quit()

    @Slot()
    def progressCheck(self):
        self.progressBar.setValue(self.progressBar.value() + 1)

    @Slot()
    def closeEvent(self, *args, **kwargs):
        self.checkThread.quit()
        return QMainWindow.closeEvent(self, *args, **kwargs)
Esempio n. 32
0
class ProgressBarService(QObject):
    """
    This service is initialized with a status bar upon which it sets
    a progress bar. Consumers of the service can then show/hide
    the progress bar and set values.

    The __new__ method is overridden to make this class a singleton.
    Every time it is instantiated somewhere in code, the same instance will be
    returned. In this way, it can serve like a static class.

    @param statusbar: The status bar on which to display progress.
    @type statusbar: QStatusBar (I think)

    @since: 2010-03-02
    """

    __author__ = "Moritz Wade"
    __contact__ = "*****@*****.**"
    __copyright__ = "Zuse Institute Berlin 2010"

    _instance = None

    def __new__(cls, *args, **kwargs
                ):  # making this a Singleton, always returns the same instance
        if not cls._instance:
            cls._instance = super(ProgressBarService,
                                  cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self, parent=None, statusBarService=None):
        """
        Creates a QProgressBar and adds it to the given status bar (for
        threads that can provide accurate progress information).

        Note: The status bar can either be a QStatusBar or the StatusBarService. In the default
        BioPARKIN use, it is the StatusBarService instance.

        @todo: A throbber is created and also added to the status bar (for
        threads that can only provide start/stop information).
        """
        #        super(ProgressBarService, self).__init__(parent)   # done in __new__

        if statusBarService is not None:
            self.statusBarService = statusBarService
            self.progressBar = QProgressBar(None)  # used for showing progress
            self.progressBarMutex = QMutex()
            self.progressBar.hide()
            self.statusBarService.addPermanentWidget(self.progressBar)
            self.progressRunning = False

            self.throbber = QLabel()
            self.throbberRunning = False
            self.throbberMutex = QMutex()
            self.statusBarService.addPermanentWidget(self.throbber)
            self.throbber.show()
            self.throbber.hide()

            throbberImage = QMovie(":/images/Spinning_wheel_throbber.gif",
                                   parent=self.throbber)
            throbberImage.setScaledSize(QSize(24, 24))
            throbberImage.setCacheMode(QMovie.CacheAll)
            throbberImage.start()
            self.throbber.setMovie(throbberImage)
            self.throbber.setFixedSize(24, 24)

    def getStatusBar(self):
        """
        Gets the internal status bar (or StatusBarService)
        """
        return self.statusBarService

    def connect_to_thread(self, thread):
        """
        Connects standard BioParkinThreadBase SIGNALs to update methods.

        @param thread: Thread whose Signals to handle
        @type thread: BioParkinThreadBase
        """
        if thread is not None:
            self.thread = thread
            self.thread.startWithoutProgressSignal.connect(self.start_throbber)
            self.thread.startWithProgressSignal.connect(self.start_progress)
            self.thread.finishedSignal.connect(self.finish)
            self.thread.progressMinimumSignal.connect(
                self.setProgressBarMinimum)
            self.thread.progressMaximumSignal.connect(
                self.setProgressBarMaximum)
            self.thread.progressValueSignal.connect(self.setProgressBarValue)
            self.thread.progressTextSignal.connect(self.showMessage)

    def setProgressBarMinimum(self, min):
        """
        Uses a QMutexLocker to set the minimum value for the progress bar.
        """
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.setMinimum(min)

    def setProgressBarMaximum(self, max):
        """
        Uses a QMutexLocker to set the maximum value for the progress bar.
        """
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.setMaximum(max)

    def setProgressBarValue(self, value):
        """
        Uses a QMutexLocker to set the minimum value for the progress bar.

        This also implicitely "starts" the progress, e.g. show the ProgressBar.
        """
        self.progressRunning = True
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.setValue(value)
            self.progressBar.show()

    def update(self, value, min=None, max=None, text=None):
        """
        Updates the progress bar with the given information.

        @param value: current value
        @type value: int

        @param min: Value that represents 0%
        @type min: int

        @param max: Value that represents 100%
        @type max: int

        @param text: Text to display on status bar
        @type text: str
        """
        #
        self.progressRunning = True
        with QMutexLocker(self.progressBarMutex):
            if min and max:
                self.progressBar.setRange(min, max)
            self.progressBar.setValue(value)
            self.progressBar.show()

        if text is not None:
            self.statusBarService.showMessage(text)

#    @Slot("QString")

    def finish(self, text=None):
        """
        This is a slot. It's called when a thread emits its "finished" Signal.

        The given text is posted to the status bar.

        @param text: Text for status bar
        @type text: str
        """
        if self.progressRunning:
            with QMutexLocker(self.progressBarMutex):
                self.progressBar.hide()
        if self.throbberRunning:
            with QMutexLocker(self.throbberMutex):
                self.throbber.hide()

        if text is None:
            self.statusBarService.showMessage("Finished", 1000)
        else:
            self.statusBarService.showMessage(
                text, 3000)  # show finish message for 3 seconds

        self.thread = None  # release reference to thread

    def start_throbber(self, text=None):
        """
        This is a slot. It starts (the progress-state-less) throbber
        animation.

        The given text is posted to the status bar.

        @param text: Text for status bar
        @type text: str
        """
        with QMutexLocker(self.throbberMutex):
            self.throbber.show()
            self.throbberRunning = True

        if text is None:
            self.statusBarService.showMessage("Computing...")
        else:
            self.statusBarService.showMessage(text)


#    @Slot("QString")

    def start_progress(self, text=None):
        """
        This is a slot. It starts the progress animation.

        The given text is posted to the status bar.

        @param text: Text for status bar
        @type text: str
        """
        self.progressRunning = True
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.show()

        if text is None:
            self.statusBarService.showMessage("Computing...", 1000)
        else:
            self.statusBarService.showMessage(text)

    def showMessage(self, text):
        if self.statusBarService:
            self.statusBarService.showMessage(text)
Esempio n. 33
0
class STMainWindow(QMainWindow):
    def __init__(self):
        super(STMainWindow, self).__init__()
        self.createActions()
        self.createMenus()
        layout = QVBoxLayout()
        self.tabs = QTabWidget()
        self.tabs.setTabPosition(QTabWidget.West)
        self.tabs.currentChanged[int].connect(self.tabChanged)
        self.sessiontab = sweattrails.qt.sessiontab.SessionTab(self)
        self.tabs.addTab(self.sessiontab, "Sessions")
        self.tabs.addTab(sweattrails.qt.fitnesstab.FitnessTab(self),
                         "Fitness")
        self.tabs.addTab(sweattrails.qt.profiletab.ProfileTab(self),
                         "Profile")
        self.usertab = sweattrails.qt.usertab.UserTab(self)
        self.tabs.addTab(self.usertab, "Users")
        self.usertab.hide()
        layout.addWidget(self.tabs)
        w = QWidget(self)
        w.setLayout(layout)
        self.setCentralWidget(w)
        self.statusmessage = QLabel()
        self.statusmessage.setMinimumWidth(200)
        self.statusBar().addPermanentWidget(self.statusmessage)
        self.progressbar = QProgressBar()
        self.progressbar.setMinimumWidth(100)
        self.progressbar.setMinimum(0)
        self.progressbar.setMaximum(100)
        self.statusBar().addPermanentWidget(self.progressbar)
        self.setWindowTitle("SweatTrails")
        self.setWindowIconText("SweatTrails")
        icon = QPixmap("image/sweatdrops.png")
        self.setWindowIcon(QIcon(icon))
        QCoreApplication.instance().refresh.connect(self.userSet)


    def createActions(self):
        self.switchUserAct = QAction("&Switch User", self, shortcut = "Ctrl+U", statusTip = "Switch User", triggered = self.switch_user)
        self.importFileAct = QAction("&Import", self, shortcut = "Ctrl+I", statusTip = "Import Session", triggered = self.file_import)
        self.downloadAct = QAction("&Download", self, shortcut = "Ctrl+D",
                                   statusTip = "Download activities from device",
                                   triggered = QCoreApplication.instance().download)
        self.downloadAct = QAction("&Withings", self,
                                   statusTip = "Download Withings data",
                                   triggered = QCoreApplication.instance().withings)
        self.exitAct = QAction("E&xit", self, shortcut = "Ctrl+Q", statusTip = "Exit SweatTrails", triggered = self.close)

        self.aboutAct = QAction("&About", self, triggered = self.about)
        self.aboutQtAct = QAction("About &Qt", self, triggered = QApplication.aboutQt)


    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
        self.fileMenu.addAction(self.switchUserAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.importFileAct)
        self.fileMenu.addAction(self.downloadAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)

        self.menuBar().addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)
        self.helpMenu.addAction(self.aboutQtAct)


    def show(self):
        super(QMainWindow, self).show()
        if self.select_user():
            t = sweattrails.qt.imports.BackgroundThread.get_thread()
            t.jobStarted.connect(self.status_message)
            t.jobFinished.connect(self.status_message)
            t.jobError.connect(self.status_message)
        else:
            self.close()

    def switch_user(self):
        pass

    def select_user(self):
        ret = False
        if QCoreApplication.instance().user:
            return True
        elif QCoreApplication.instance().has_users():
            dialog = SelectUser(self)
            dialog.select()
            ret = QCoreApplication.instance().is_authenticated()
            if ret:
                self.refresh()
        else:
            dialog = CreateUser(self)
            dialog.exec_()
            ret = QCoreApplication.instance().is_authenticated()
            if ret:
                self.refresh()
        return ret

    #
    # FILE IMPORT
    #

    def file_import(self):
        (fileNames, _) = QFileDialog.getOpenFileNames(self,
                               "Open Activity File",
                               "",
                               "Activity Files (*.tcx *.fit *.csv)")
        if fileNames:
            QCoreApplication.instance().import_files(*fileNames)

    def file_import_started(self, filename):
        self.switchUserAct.setEnabled(False)

    def file_imported(self, filename):
        self.switchUserAct.setEnabled(True)
        self.refresh()

    def file_import_error(self, filename, msg):
        self.switchUserAct.setEnabled(True)
        self.refresh()

    #
    # END FILE IMPORT
    #

    # =====================================================================
    # S I G N A L  H A N D L E R S
    # =====================================================================

    def refresh(self):
        QCoreApplication.instance().refresh.emit()
        self.status_message("")

    def tabChanged(self, tabix):
        w = self.tabs.currentWidget()
        if hasattr(w, "activate"):
            w.activate(0)
        if hasattr(w, "setValues"):
            w.setValues()

    def setSession(self, session):
        self.tabs.setCurrentIndex(0)
        self.sessiontab.setSession(session)

    def setTab(self, tab):
        t = self.tabs.currentWidget()
        if t and hasattr(t, "setTab"):
            t.setTab(tab)

    def userSet(self):
        user = QCoreApplication.instance().user
        if user.is_admin():
            self.usertab.show()

    def status_message(self, msg, *args):
        self.statusmessage.setText(msg.format(*args))

    def progress_init(self, msg, *args):
        self.progressbar.setValue(0)
        self.status_message(msg, *args)

    def progress(self, percentage):
        self.progressbar.setValue(percentage)

    def progress_done(self):
        self.progressbar.reset()

    def about(self):
        QMessageBox.about(self, "About SweatTrails",
                          "SweatTrails is a training log application")
Esempio n. 34
0
    def __init__(self, parent=None):
        """Initialize the parent class of this instance."""
        super(window, self).__init__(parent)
        app.aboutToQuit.connect(self.myExitHandler)

        self.style_sheet = self.styleSheet('style')
        # app.setStyle(QStyleFactory.create('Macintosh'))
        #app.setStyleSheet(self.style_sheet)
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0,0,0,0)

        app.setOrganizationName("Eivind Arvesen")
        app.setOrganizationDomain("https://github.com/eivind88/raskolnikov")
        app.setApplicationName("Raskolnikov")
        app.setApplicationVersion("0.0.1")
        settings = QSettings()

        self.data_location = QDesktopServices.DataLocation
        self.temp_location = QDesktopServices.TempLocation
        self.cache_location = QDesktopServices.CacheLocation

        self.startpage = "https://duckduckgo.com/"
        self.new_tab_behavior = "insert"

        global bookmarks

        global saved_tabs
        print "Currently saved_tabs:\n", saved_tabs

        global menubar
        menubar = QMenuBar()

        # Initialize a statusbar for the window
        self.statusbar = self.statusBar()
        self.statusbar.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.statusbar.setStyleSheet(self.style_sheet)
        self.statusbar.setMinimumHeight(15)

        self.pbar = QProgressBar()
        self.pbar.setMaximumWidth(100)
        self.statusbar.addPermanentWidget(self.pbar)

        self.statusbar.hide()

        self.setMinimumSize(504, 235)
        # self.setWindowModified(True)
        # app.alert(self, 0)
        self.setWindowTitle("Raskolnikov")
        # toolbar = self.addToolBar('Toolbar')
        # toolbar.addAction(exitAction)
        # self.setUnifiedTitleAndToolBarOnMac(True)
        self.setWindowIcon(QIcon(""))

        # Create input widgets
        self.bbutton = QPushButton(u"<")
        self.fbutton = QPushButton(u">")
        self.hbutton = QPushButton(u"⌂")
        self.edit = QLineEdit("")
        self.edit.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
        self.edit.setPlaceholderText("Enter URL")
        # self.edit.setMinimumSize(400, 24)
        self.rbutton = QPushButton(u"↻")
        self.dbutton = QPushButton(u"☆")
        self.tbutton = QPushButton(u"⁐")
        # ↆ ⇧ √ ⌘ ⏎ ⏏ ⚠ ✓ ✕ ✖ ✗ ✘ ::: ❤ ☮ ☢ ☠ ✔ ☑ ♥ ✉ ☣ ☤ ✘ ☒ ♡ ツ ☼ ☁ ❅ ✎
        self.nbutton = QPushButton(u"+")
        self.nbutton.setObjectName("NewTab")
        self.nbutton.setMinimumSize(35, 30)
        self.nbutton.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        self.edit.setTextMargins(2, 1, 2, 0)

        # create a horizontal layout for the input
        input_layout = QHBoxLayout()
        input_layout.setSpacing(4)
        input_layout.setContentsMargins(0, 0, 0, 0)

        # add the input widgets to the input layout
        input_layout.addWidget(self.bbutton)
        input_layout.addWidget(self.fbutton)
        input_layout.addWidget(self.hbutton)
        input_layout.addWidget(self.edit)
        input_layout.addWidget(self.rbutton)
        input_layout.addWidget(self.dbutton)
        input_layout.addWidget(self.tbutton)

        # create a widget to hold the input layout
        self.input_widget = QFrame()
        self.input_widget.setObjectName("InputWidget")
        self.input_widget.setStyleSheet(self.style_sheet)

        # set the layout of the widget
        self.input_widget.setLayout(input_layout)
        self.input_widget.setVisible(True)

        # CREATE BOOKMARK-LINE HERE
        self.bookmarks_layout = QHBoxLayout()
        self.bookmarks_layout.setSpacing(0)
        self.bookmarks_layout.setContentsMargins(0, 0, 0, 0)

        for i in bookmarks:
            link = QToolButton()
            link.setDefaultAction(QAction(unicode(i), link))
            link.setObjectName(unicode(i))
            link.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
            link.clicked.connect(self.handleBookmarks)

            self.bookmarks_layout.addWidget(link)

        self.bookmarks_widget = QFrame()
        self.bookmarks_widget.setObjectName("BookmarkWidget")
        self.bookmarks_widget.setStyleSheet(self.style_sheet)
        self.bookmarks_widget.setLayout(self.bookmarks_layout)

        if not bookmarks:
            self.bookmarks_widget.hide()

        # Task list
        self.tasklist = QStandardItemModel()
        #parentItem = self.tasklist.invisibleRootItem()
        #self.tasklist.header().hide()
        self.tasklist.setHorizontalHeaderItem(0, QStandardItem('Tasks'))
        parentItem = QStandardItem("Parent")
        self.tasklist.appendRow(parentItem)
        for i in range(4):
            item = QStandardItem("Item %d" % i)
            parentItem.appendRow(item)
            #parentItem = item

        #self.list.activated[str].connect(self.handleBookmarks)
        #self.list.view().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        # create tabs
        self.tabs = QTabWidget()
        self.tabs.setDocumentMode(True)
        self.tabs.setTabsClosable(True)
        self.tabs.setMovable(True)
        self.tabs.tabBar().hide()
        self.tabs.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.tabs.setCornerWidget(self.nbutton)
        self.tabs.cornerWidget().setObjectName("CornerWidget")
        self.tabs.cornerWidget().setMinimumSize(10, 24)
        self.tabs.cornerWidget().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        if saved_tabs:
            for tab in saved_tabs['tabs']:
                tasklist = QTreeView()
                tasklist.hide()
                tasklist.setObjectName('taskList')
                tasklist.setMinimumWidth(100)
                tasklist.setMaximumWidth(250)

                new_tab = QWebView()
                new_tab.setObjectName('webView')

                inspector = QWebInspector(self)
                inspector.setObjectName('webInspector')
                inspector.hide()

                page_layout = QVBoxLayout()
                page_layout.setSpacing(0)
                page_layout.setContentsMargins(0, 0, 0, 0)
                page_layout.addWidget(new_tab)
                page_layout.addWidget(inspector)
                page_widget = QFrame()
                page_widget.setObjectName('pageWidget')
                page_widget.setLayout(page_layout)

                complete_tab_layout = QHBoxLayout()
                complete_tab_layout.setSpacing(0)
                complete_tab_layout.setContentsMargins(0, 0, 0, 0)
                complete_tab_layout.addWidget(tasklist)
                complete_tab_layout.addWidget(page_widget)
                complete_tab_widget = QFrame()
                complete_tab_widget.setLayout(complete_tab_layout)

                #for page in tab['history']:
                #    new_tab.load(QUrl(page['url']))
                #print tab['current_history']
                #for item in new_tab.history().items():
                #    print item
                #new_tab.history().goToItem(new_tab.history().itemAt(tab['current_history']))
                new_tab.load(QUrl(tab['history'][tab['current_history']]['url']))
                tab['current_history']
                self.tabs.setUpdatesEnabled(False)
                if self.new_tab_behavior == "insert":
                    self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget,
                                        unicode(new_tab.title()))
                elif self.new_tab_behavior == "append":
                    self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title()))
                self.tabs.setUpdatesEnabled(True)
                new_tab.titleChanged.connect(self.change_tab)
                new_tab.urlChanged.connect(self.change_tab)
                new_tab.loadStarted.connect(self.load_start)
                new_tab.loadFinished.connect(self.load_finish)
                new_tab.loadProgress.connect(self.pbar.setValue)
                new_tab.page().linkHovered.connect(self.linkHover)
                inspector.setPage(new_tab.page())

            for index, tab in enumerate(saved_tabs['tabs']):
                self.tabs.setTabText(index, tab['history'][tab['current_history']]['title'])

            self.tabs.setCurrentIndex(saved_tabs['current_tab'])
        else:
            self.new_tab()

        tabs_layout = QVBoxLayout()
        tabs_layout.setSpacing(0)
        tabs_layout.setContentsMargins(0, 0, 0, 0)
        tabs_layout.addWidget(self.tabs)

        self.tabs_widget = QFrame()
        self.tabs_widget.setObjectName("TabLine")
        self.tabs_widget.setStyleSheet(self.style_sheet)
        self.tabs_widget.setLayout(tabs_layout)
        self.tabs_widget.setVisible(True)

        # Webkit settings
        gsettings = self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).settings().globalSettings()
        # Basic settings
        gsettings.setAttribute(QWebSettings.AutoLoadImages, True)
        gsettings.setAttribute(QWebSettings.JavascriptEnabled, True)
        gsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False)
        gsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, False)
        gsettings.setAttribute(QWebSettings.PluginsEnabled, False) # Flash isn't stable at present
        gsettings.setAttribute(QWebSettings.JavaEnabled, False) # Java applet's aren't supported by PySide
        gsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled,
            True)
        # Performace settings
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True)
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        # Other settings
        gsettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False)

        # Create a vertical layout and add widgets
        vlayout = QVBoxLayout()
        vlayout.setSpacing(0)
        vlayout.setContentsMargins(0, 0, 0, 0)
        # toolbar.addWidget(self.input_widget)
        vlayout.addWidget(self.input_widget)
        vlayout.addWidget(self.bookmarks_widget)
        vlayout.addWidget(self.tabs_widget)

        # create a widget to hold the vertical layout
        wrapper_widget = QWidget()
        wrapper_widget.setLayout(vlayout)
        self.setCentralWidget(wrapper_widget)

        self.bbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).back)
        self.fbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).forward)
        self.hbutton.clicked.connect(self.goHome)
        self.edit.returnPressed.connect(self.set_url)
        # Add button signal to "go" slot
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)
        self.dbutton.clicked.connect(self.bookmark)
        self.tbutton.clicked.connect(self.toggleTaskBar)
        self.nbutton.clicked.connect(self.new_tab)
        self.tabs.tabCloseRequested.connect(self.tabs.removeTab)
        self.tabs.currentChanged.connect(self.change_tab)

        widgets = (input_layout.itemAt(i).widget() for i in range(
            input_layout.count()))
        for widget in widgets:
            if isinstance(widget, QPushButton):
                widget.setFixedSize(33, 21)
                widget.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
                widget.pressed.connect(self.press_button)
                widget.released.connect(self.release_button)

        # make a ctrl+q quit
        sequence = QKeySequence(Qt.CTRL + Qt.Key_Q)
        QShortcut(sequence, self, SLOT("close()"))

        # make an accelerator to toggle fullscreen
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F)
        QShortcut(sequence, self, self.toggle_fullscreen)

        # make an accelerator to toggle input visibility
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_L)
        QShortcut(sequence, self, self.toggle_input)

        # make an accelerator to focus adress-bar
        sequence = QKeySequence(Qt.CTRL + Qt.Key_L)
        QShortcut(sequence, self, self.focus_adress)

        # make an accelerator to reload page
        sequence = QKeySequence(Qt.CTRL + Qt.Key_R)
        QShortcut(sequence, self, self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)

        # make an accelerator to create new tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_T)
        QShortcut(sequence, self, self.new_tab)

        # make an accelerator to close tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_W)
        QShortcut(sequence, self, self.close_tab)

        # make an accelerator to navigate tabs
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left)
        QShortcut(sequence, self, self.previous_tab)
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right)
        QShortcut(sequence, self, self.next_tab)

        # make an accelerator to toggle inspector
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_U)
        QShortcut(sequence, self, self.handleShowInspector)

        # make an accelerator to toggle bookmark
        sequence = QKeySequence(Qt.CTRL + Qt.Key_D)
        QShortcut(sequence, self, self.bookmark)

        # make an accelerator to toggle task/project-list
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_L)
        QShortcut(sequence, self, self.toggleTaskBar)

        # finally set the attribute need to rotate
        # try:
        #     self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
        # except:
        #     print "not maemo"

        self.statusbar.show()
Esempio n. 35
0
    def __init__(self):
        QMainWindow.__init__(self)

        # the user interface, consisting of a progress bar above a plain
        # text edit, which logs all actions.
        container = QWidget(self)
        container.setLayout(QVBoxLayout(container))
        self.setCentralWidget(container)
        progressbar = QProgressBar(container)
        container.layout().addWidget(progressbar)
        log = QPlainTextEdit(container)
        container.layout().addWidget(log)

        # the actual worker thread
        counter = Counter(100, self)

        # an action to quit the windows
        exit = QAction(QIcon.fromTheme('application-exit'), 'exit', self)

        # add two actions to start and stop the worker to the toolbar of the
        # main window
        start_counting = QAction(QIcon.fromTheme('media-playback-start'),
                                 'Start counting', self)
        stop_counting = QAction(QIcon.fromTheme('media-playback-stop'),
                                'Stop counting', self)
        # initially no counter runs, so we can disable the stop action
        stop_counting.setEnabled(False)

        # add all actions to a toolbar
        actions = self.addToolBar('Actions')
        actions.addAction(exit)
        actions.addSeparator()
        actions.addAction(start_counting)
        actions.addAction(stop_counting)

        # quit the application, if the quit action is triggered
        exit.triggered.connect(QApplication.instance().quit)

        # start and stop the counter, if the corresponding actions are
        # triggered.
        start_counting.triggered.connect(counter.start)
        stop_counting.triggered.connect(counter.stop)

        # adjust the minimum and the maximum of the progress bar, if
        # necessary.  Not really required in this snippet, but added for the
        # purpose of demonstrating it
        counter.minimumChanged.connect(progressbar.setMinimum)
        counter.maximumChanged.connect(progressbar.setMaximum)

        # switch the enabled states of the actions according to whether the
        # worker is running or not
        counter.started.connect(partial(start_counting.setEnabled, False))
        counter.started.connect(partial(stop_counting.setEnabled, True))
        counter.finished.connect(partial(start_counting.setEnabled, True))
        counter.finished.connect(partial(stop_counting.setEnabled, False))

        # update the progess bar continuously
        counter.progress.connect(progressbar.setValue)

        # log all actions in our logging widget
        counter.started.connect(
            partial(self.statusBar().showMessage, 'Counting'))
        counter.finished.connect(partial(self.statusBar().showMessage, 'Done'))
        # log a forced stop
        stop_counting.triggered.connect(partial(log.appendPlainText,
                                                'Stopped'))
        # log all counted values
        counter.progress.connect(lambda v: log.appendPlainText(str(v)))

        # and finally show the current state in the status bar.
        counter.started.connect(partial(log.appendPlainText, 'Counting'))
        counter.finished.connect(partial(log.appendPlainText, 'Done'))
Esempio n. 36
0
class MainWindow(QMainWindow):
    """ Create the Application Main Window CLass
    """
    def __init__(self):
        """ Constructo FUnction
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("Application Title Here")
        self.setGeometry(300, 250, 400, 300)
        self.statusLabel = QLabel('Showing Progress')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(1000000)

    def CreateStatusBar(self):
        """ Funtion to Create Status Bar
        """
        self.myStatusBar = QStatusBar()
        self.progressBar.setValue(10)
        self.myStatusBar.addWidget(self.statusLabel, 1)
        self.myStatusBar.addWidget(self.progressBar, 2)
        self.setStatusBar(self.myStatusBar)

    def ShowProgress(self):
        """ Function to Show Progress
        """
        while self.progressBar.value() < self.progressBar.maximum():
            self.progressBar.setValue(self.progressBar.value() + 1)
        self.statusLabel.setText('Ready')
Esempio n. 37
0
class StatusArea(QWidget):
    def __init__(self, parent=None):
        super(StatusArea, self).__init__(parent)
        self.setStyleSheet('StatusArea {background: yellow}')
        self.msg = QLabel(self)
        self.file = QLabel(self)
        self.progress = QProgressBar(self)

        self.msg.setFont(View.labelsFont())
        self.file.setFont(View.editsFont())

        self.progress.setMaximum(100)
        self.progress.setMinimum(0)
        self.progress.setTextVisible(False)
        self.progress.setStyleSheet(""" 
            QProgressBar {
                 border: 2px solid grey;
                 border-radius: 5px;
                 width: 60px;
                 height: 10px;
             }

             QProgressBar::chunk {
                 background-color: #05B8CC;
                 width: 5px;
             }""")

        layout = QHBoxLayout()
        layout.addWidget(self.msg, 0, Qt.AlignLeft)
        layout.addWidget(self.file, 0, Qt.AlignLeft)
        layout.addWidget(self.progress, 0, Qt.AlignRight)

        self.setLayout(layout)

    @Slot(str)
    @Slot(str, str, str)
    def setMessage(self, msg, file='', progress=None):
        if not progress:
            self.progress.hide()
            self.progress.setValue(0)
        else:
            self.progress.setValue(progress)
            self.progress.show()

        self.msg.setText(msg)
        self.file.setText(file)

    def paintEvent(self, event):
        p = QPainter()
        p.begin(self)
        p.fillRect(self.rect(), QBrush(QColor(240, 200, 0)))
        p.end()
class MainWindow(QMainWindow):
    """ Our main window class
    """
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.statusLabel = QLabel('Showing Progress')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
    
    def CreateStatusBar(self):
        self.myStatusBar = QStatusBar()
        self.progressBar.setValue(10)
        self.myStatusBar.addWidget(self.statusLabel, 1)
        self.myStatusBar.addWidget(self.progressBar, 2)
        #self.myStatusBar.showMessage('Ready', 2000)
        self.setStatusBar(self.myStatusBar)
    
    def showProgress(self):
        while(self.progressBar.value() < self.progressBar.maximum()):
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1)
        self.statusLabel.setText('Ready')
Esempio n. 39
0
class SpiderTab(QWidget):
  """Has handlers for spider data and events. It houses the results table of the
     spider, controls for the spider and progress indication
     It implicitly conforms to IEventHandler interface"""
  TIMER_CHECK_INTERVAL = 3000
  favicon_received = Signal(str) # send the url or path to the handler, which should be the tab widget
  stop_spider_signal = Signal(int)
  became_current = Signal(bool) # tell the table it has become active. it's an interesting property for producers!
  
  def __init__(self, parent=None, **kwargs):
    super(SpiderTab, self).__init__(parent)
    self._event_queue = None
    self._data_queue = None
    self._engine = None
    self._favicon_received = False
    self._spider_id = None
    self._item_count = 0
    self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu)
    self.initInterface(kwargs)
    self._context_menu = None
    self._setupContextMenu()
    self.became_current.connect(self._set_table_activity)
    self._queue_check_timer = QTimer()
    self._queue_check_timer.setInterval(self.TIMER_CHECK_INTERVAL)
    self._queue_check_timer.timeout.connect(self._checkQueues)
    self._queue_check_timer.start()
    
  def initInterface(self, kwargs):
    layout = QGridLayout()
    self._data_table = SearchTable(name=kwargs.get("name"))
    self._progress_spider = QProgressBar()
    self._label_count = QLabel(self.tr("0 items scraped"))
    # make it a busy indicator. you don't know when it'll finish 
    self._progress_spider.setMinimum(0); self._progress_spider.setMaximum(0)
    self._progress_spider.setTextVisible(False)
    self._btn_stop_spider = QPushButton(self.tr("Stop Spider"))
    self._btn_stop_spider.clicked.connect(self.stop_spider)
    row = 0; col = 0;
    layout.addWidget(self._data_table, row, col, 1, 4)
    row += 1;
    layout.addWidget(self._progress_spider, row, col, 1, 1)
    col += 1
    layout.addWidget(self._label_count, row, col, 1, 2)
    col += 2
    layout.addWidget(self._btn_stop_spider, row, col, 1, 1)
    self.setLayout(layout)
    
  def _setupContextMenu(self):
    from visualscrape.lib.data import ActionStore
    self._context_menu = QMenu(self)
    # get the export action from the action store
    action_store = ActionStore.get_instance()
    for action in action_store:
      if action.get_name() == "export":
        export_action = action
        break
    self._context_menu.addAction(export_action)
    
  def export_table(self):
    export_dialog = ExportDialog()
    export_dialog.exec_()
    export_info = export_dialog.data()
    if export_info:
      data = self._data_table.get_visible_data()
      FileExporter.export(data, self._data_table.name.lower(), export_info.location, export_info.format)
  
  def set_event_queue(self, eq):
    self._event_queue = eq
    
  def set_data_queue(self, dq):
    self._data_queue = dq
    
  def stop_spider(self):
    if self._spider_id is None: # do not stop the the spider before receiving data
      pass
    else:
      if self._queue_check_timer.isActive():
        confirm_stop = QMessageBox(self)
        confirm_stop.setIcon(QMessageBox.Warning)
        confirm_stop.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        confirm_stop.setText(self.tr("Scraping process still running"))
        confirm_stop.setDetailedText(self.tr("Are you sure you want to stop it?"))
        confirm_stop.setWindowTitle(self.tr("Spider still running"))
        ret = confirm_stop.exec_()
        if ret == QMessageBox.Yes:
          self.stop_spider_signal.emit(self._spider_id)
          return True
        else: return False # I won't whip you if you stop it accidentally
      else: return True # already over
      
  def configure_searchlineedit(self, lineEdit):
    self._data_table.configure_search_lineedit(lineEdit)
    
  def _checkQueues(self):
    while not self._event_queue.empty():
      event = self._event_queue.get(block=False, timeout=0)
      if isinstance(event, SpiderClosed):
        self._queue_check_timer.stop()
        self._progress_spider.setMinimum(0)
        self._progress_spider.setMaximum(100)
        self._progress_spider.setValue(100)
        self._btn_stop_spider.setEnabled(False)
    while not self._data_queue.empty():
      item = self._data_queue.get(block=False, timeout=0)
      if not self._favicon_received: # the first item on the data queue should be the favicon
        favicon_data = item["images"][0]
        self.favicon_received.emit(favicon_data["path"]) # note that icons are not guaranteed to have a path. Not everybody wants to save images
        self._favicon_received = True
        self._spider_id = item["_id"]
      else:
        item.pop("_id") # the table has nothing to do with spider ids
        self._data_table.addItem(item)
      self._item_count += 1
      self._label_count.setText(self.tr("{0:n} items scraped".format(self._item_count)))
      
  def _set_table_activity(self, state):
    self._data_table.set_active(state)
Esempio n. 40
0
class SafeLock(QWidget):
    def __init__(self):
        super(SafeLock, self).__init__()
        main_layout = QVBoxLayout(self)
        self.Version = '0.5 beta'
        self.s_error = "QStatusBar{color:red;font-weight:1000;}"
        self.s_loop = "QStatusBar{color:black;font-weight:1000;}"
        self.s_norm = "QStatusBar{color:blue;font-style:italic;"
        self.s_norm += "font-weight:500;}"
        self.Processing = None
        self.CP = None
        self.PPbar = None
        self.key = None
        self.DFiles = []

        self.picon = r_path("images/favicon.png")
        self.plogo = r_path("images/logo.png")
        if name == 'nt':
            self.picon = r_path("images\\favicon.png")
            self.plogo = r_path("images\\logo.png")
        self.icon = QIcon(self.picon)
        self.logo = QIcon(self.plogo)
        self.center()
        self.setStyle()
        self.setMW(main_layout)
        self.setSB(main_layout)
        self.show()

    def db(self, password="******", dbname="untitled.sld", dc=True):
        eng = create_engine("sqlite:///%s" % dbname,
                            connect_args={'check_same_thread': False})
        Base = declarative_base(bind=eng)
        Session = sessionmaker(bind=eng)
        session = Session()

        class Identifier(Base):
            __tablename__ = "identifier"
            id = Column(Integer, primary_key=True)
            version = Column(Binary)
            kvd = Column(Binary)

            def __init__(self, version, kvd):
                self.id = 0
                self.version = version
                self.kvd = kvd

        class Folder(Base):
            __tablename__ = 'folders'
            id = Column(Integer, primary_key=True)
            path = Column(Unicode)

            def __init__(self, path="Empty"):
                self.path = path

        class File(Base):
            __tablename__ = 'files'
            id = Column(Integer, primary_key=True)
            name = Column(String)
            f_id = Column(Integer, ForeignKey('folders.id'), nullable=True)
            bb = Column(Binary)

            def __init__(self, name="empty", f_id=0, bb=1010):
                self.name = name
                self.f_id = f_id
                self.bb = bb
        if dc:
            Base.metadata.create_all()
            enc = encryptit(sha256(self.Version).digest(),
                            sha256(password).digest())
            session.add(Identifier(enc[0], enc[1]))
            session.commit()

        return [eng, Base, session, File, Folder, Identifier, password]

    def checkP(self, db):
        try:
            d = db[2].query(db[5]).filter_by(id=0).first()
            if d is not None:
                if isenct(self.Version, d.version, db[6], d.kvd):
                    return True
        except:
            pass
        return False

    def setStyle(self):
        self.setMaximumWidth(410)
        self.setMinimumWidth(410)
        self.setMaximumHeight(370)
        self.setMinimumHeight(370)
        self.setWindowIcon(self.icon)
        self.activateWindow()
        self.setWindowTitle("safelock " + self.Version)
        self.setToolTip(
            u"단순히 끌어다 놓는 것으로 파일이나 폴더를 암호화하거나" +
            u" .sld 파일을 복호화할 수 있습니다.")
        self.setAcceptDrops(True)
        self.show()

    def center(self):
        qrect = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qrect.moveCenter(cp)
        self.move(qrect.topLeft())

    def setMW(self, ml):
        ll = QVBoxLayout()
        self.mIcon = QLabel()
        self.mIcon.setAlignment(Qt.AlignCenter)
        mmicon = self.logo.pixmap(250, 230, QIcon.Active, QIcon.On)
        self.mIcon.setPixmap(mmicon)
        self.mInst = QLabel(
         #   u"<center>(Drag and drop files or folders to encrypt them)<br>" +
            u"<center>(마우스로 끌어다 놓으십시오)<br>" +
            u"<u>최대 2GB 파일 또는 디렉토리만 가능</u></center>")
        font = QFont()
        font.setPointSize(13)
        font.setBold(True)
        font.setWeight(75)
        self.fInst = QLabel('<center></center>')
        self.mInst.setFont(font)
        ll.addWidget(self.mIcon)
        ll.addWidget(self.mInst)
        ll.addWidget(self.fInst)
        ml.addLayout(ll)

    def setSB(self, ml):
        self.statusb = QStatusBar()
        ml.addWidget(self.statusb)

    def modSB(self):
        if self.PPbar is None:
            self.PPbar = True
            self.statusb.clear()
            self.pbar = QProgressBar()
            self.pbar.setMaximum(100)
            self.pbar.setMinimum(0)
            self.plabel = QLabel()
            self.statusb.addWidget(self.plabel, 0.5)
            self.statusb.addWidget(self.pbar, 3)
        else:
            self.PPbar = None
            self.statusb.removeWidget(self.plabel)
            self.statusb.removeWidget(self.pbar)
            self.statusb.clear()

    # def searchF(self, dirname):
    #     filelist = []
    #     try:
    #         filenames = listdir(dirname)
    #         for filename in filenames:
    #             full_filename = path.join(dirname, filename)
    #             if path.isdir(full_filename):
    #                 tmplist = self.searchF(full_filename)
    #                 for tmpfile in tmplist:
    #                     filelist.append(tmpfile)
    #             else:
    #                 tmp = full_filename.replace('\\','/')
    #                 filelist.append(tmp)
    #     except PermissionError:
    #         pass
    #     return filelist

    def saveFile(self, fl):
        fname, _ = QFileDialog.getSaveFileName(self,
                                               u"암호화 경로 설정",
                                               fl,
                                               "Safelock file (*.sld)")
        if '.' in fname:
            tm = fname.split('.')
            tm = tm[len(tm) - 1]
            if tm == "sld":
                try:
                    if path.isfile(fname):
                        remove(fname)
                except:
                    pass
                return fname
        if len(fname) <= 0:
            return None
        fname += ".sld"
        try:
            if path.isfile(fname):
                remove(fname)
        except:
            pass
        return fname

    def extTo(self, fl):
        fname = QFileDialog.getExistingDirectory(self, u"복호화 경로 설정",
                                                 fl)
        if len(fname) <= 0:
            return None
        return fname

    def getPass(self):
        passwd, re = QInputDialog.getText(self, u"비밀번호", u"입력하신 비밀번호 :",
                                          QLineEdit.Password)
        if len(passwd) > 0 :
            passwd2, re = QInputDialog.getText(self, u"비밀번호", u"다시한번 입력하세요 :",
                                          QLineEdit.Password)
            if passwd != passwd2:
                self.errorMsg(u"비밀번호가 맞지 않습니다")
                return False
            else:
                if not re:
                    return False
                if len(passwd) <= 0:
                    return None
                return passwd
        else:
            if not re:
                return False
            else:
                return None

    def getPass2(self):
        passwd, re = QInputDialog.getText(self, u"비밀번호", u"입력하신 비밀번호 :",
                                          QLineEdit.Password)
        if not re:
            return False
        if len(passwd) <= 0:
            return None
        return passwd

    def errorMsg(self, msg=u"에러 발생 !"):
        QMessageBox.critical(self, "Error", msg)
        return True

    def aboutMsgg(self):
        Amsg = u"<center>SafeLock %s " % self.Version
        Amsg += u"은 Mozilla Public License 버전 2.0에 "
        Amsg += u"따라 허가된 무료 오픈소스 프로젝트 입니다.<br><br>"
        Amsg += u" 본 프로그램에 대한 더 많은 정보를 원하시면:<br> "
        Amsg += u"<b><a href='https://github.com/mjuc4/safelock'> "
        Amsg += u"https://github.com/mjuc4/safelock/ </a> </b></center>"
        QMessageBox.about(self, "About", Amsg)
        return True

    def getSession(self):
        self.eng = eng(self.password, self.dbname)
        Session = sessionmaker(bind=self.eng)
        self.Base = declarative_base(bind=self.eng)
        self.Base.metadata.create_all()
        self.session = Session()
        return self.session

    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dragMoveEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        if e.mimeData().hasUrls:
            e.setDropAction(Qt.CopyAction)
            e.accept()
            self.DFiles = []
            for url in e.mimeData().urls():
                try:
                    if sysname == 'darwin':
                        from Foundation import NSURL
                        fname = NSURL.URLWithString_(
                            url.toString()).filePathURL().path()
                    else:
                        fname = url.toLocalFile()
                    self.DFiles.append(fname)
                except:
                    pass
            self.dealD(self.DFiles)
        else:
            event.ignore()

    def in_loop(self):
        if self.Processing is None:
            self.Processing = True
            self.setAcceptDrops(False)
            self.mIcon.setEnabled(False)
            self.mInst.setEnabled(False)
            self.fInst.setText(u"<center>| 취소는 더블 클릭 |</center>")
            self.setToolTip("Double-Click anywhere to cancel")
        else:
            self.Processing = None
            self.setAcceptDrops(True)
            self.mIcon.setEnabled(True)
            self.mInst.setEnabled(True)
            self.fInst.setText(u"<center>| 취소는 더블 클릭 |</center>")
            self.setToolTip(
                u"단순히 끌어다 놓는 것으로 파일이나 폴더를 암호화하거나" +
                u" .sld 파일을 복호화할 수 있습니다.")

    def dealD(self, files):
        def tpp(inp):
            a = path.basename(inp)
            return inp.replace(a, '')
        if len(files) < 1:
            return False
        elif len(files) >= 1:
            if len(files) == 1:
                tf = files[0].split('.')
                tf = tf[len(tf) - 1]
                if tf == 'sld':
                    pw = self.getPass2()
                    if pw is None:
                        self.errorMsg(u"비밀번호 입력하십쇼!")
                        return False
                    elif not pw:
                        return False
                    if not self.checkP(self.db(sha256(pw).digest(), files[0],
                                               dc=False)):
                        self.errorMsg(
                            u"비밀번호가 맞지 않습니다. 다시 시도하세요")
                        return False
                    else:
                        fold = self.extTo(tpp(files[0]))
                        if fold is not None:
                            self.CP = fold
                            self.in_loop()
                            self.P = DecryptTH(fold, self.db(pw,
                                                             files[0],
                                                             dc=False),
                                               sha256(pw).digest())
                            self.P.start()
                            self.P.somesignal.connect(self.handleStatusMessage)
                            self.P.setTerminationEnabled(True)
                            return True
            pw = self.getPass()
            if pw is None:
                self.errorMsg(u"비밀번호 입력하십시오 !")
            elif not pw:
                pass
            else:
                fil = self.saveFile(tpp(files[0]))
                if fil is not None:
                    if path.isfile(fil):
                        try:
                            remove(fil)
                        except:
                            pass
                    self.CP = fil
                    self.in_loop()
                    self.P = EncryptTH(files, self.db(pw, fil),
                                       sha256(pw).digest())
                    self.P.start()
                    self.P.somesignal.connect(self.handleStatusMessage)
                    self.P.setTerminationEnabled(True)
        return True

    @Slot(object)
    def handleStatusMessage(self, message):
        self.statusb.setStyleSheet(self.s_loop)

        def getIT(f, o):
            return int((f / o) * 100)
        mm = message.split('/')
        if mm[len(mm) - 1] == '%':
            if self.PPbar is None:
                self.modSB()
            self.pbar.setValue(getIT(int(mm[0]), int(mm[1])))
            self.setWindowTitle("Processing : " + str(getIT(int(mm[0]),
                                                            int(mm[1]))) + "%")
            self.plabel.setText(mm[0] + '/' + mm[1])
        else:
            self.unsetCursor()
            if self.PPbar is not None:
                self.modSB()
            if message[:7] == '# Error':
                if self.Processing:
                    self.in_loop()
                self.statusb.setStyleSheet(self.s_error)
                self.cleanup()
            elif message[:6] == '# Stop':
                self.statusb.setStyleSheet(self.s_error)
            elif message[:6] == '# Done':
                if self.Processing:
                    self.in_loop()
                self.statusb.setStyleSheet(self.s_norm)
                if message.find('encrypted')>=0 :
                    QMessageBox.question(None,'success',"Encrypted succes")
                else:    
                    QMessageBox.question(None,'success',"Decrypted succes")
            elif message == "# Loading":
                self.setCursor(Qt.BusyCursor)
                self.statusb.setStyleSheet(self.s_norm)
            self.setWindowTitle('safelock ' + self.Version)
            self.statusb.showMessage(message)

    def mousePressEvent(self, event):
        if event.type() == QEvent.Type.MouseButtonDblClick:
            if self.Processing is None:
                self.aboutMsgg()
            else:
                self.closeEvent()

    def closeEvent(self, event=None):
        if self.Processing is not None:
            if event is not None:
                r = QMessageBox.question(
                    self,
                    "Making sure",
                    "Are you sure you want to exit, during an active" +
                    " process ?",
                    QMessageBox.Yes | QMessageBox.No)
            else:
                r = QMessageBox.question(
                    self,
                    "Making sure",
                    "Are you sure, you to cancel ?",
                    QMessageBox.Yes | QMessageBox.No)
            if r == QMessageBox.Yes:
                self.P.stop()
                self.cleanup()
                if event is not None:
                    self.in_loop()
                    event.accept()
                else:
                    self.in_loop()
            else:
                if event is not None:
                    event.ignore()
        else:
            if self.CP is not None:
                try:
                    if path.isfile(self.CP + '-journal'):
                        remove(self.CP + '-journal')
                except:
                    pass
            if event is not None:
                event.accept()

    def cleanup(self):
        if self.CP is not None:
            try:
                if path.isfile(self.CP + '-journal'):
                    remove(self.CP + '-journal')
                if path.isfile(self.CP):
                        remove(self.CP)
            except:
                pass
Esempio n. 41
0
 def __init__(self, *args):
     QProgressBar.__init__(self, *args)
     with open("QProgressBar.qss") as f:
         self.setStyleSheet(f.read())
Esempio n. 42
0
class SafeLock(QWidget):
    def __init__(self):
        super(SafeLock, self).__init__()
        main_layout = QVBoxLayout(self)
        self.Version = '0.5 beta'
        self.s_error = "QStatusBar{color:red;font-weight:1000;}"
        self.s_loop = "QStatusBar{color:black;font-weight:1000;}"
        self.s_norm = "QStatusBar{color:blue;font-style:italic;"
        self.s_norm += "font-weight:500;}"
        self.Processing = None
        self.CP = None
        self.PPbar = None
        self.key = None
        self.DFiles = []

        self.picon = r_path("images/favicon.png")
        self.plogo = r_path("images/logo.png")
        if name == 'nt':
            self.picon = r_path("images\\favicon.png")
            self.plogo = r_path("images\\logo.png")
        self.icon = QIcon(self.picon)
        self.logo = QIcon(self.plogo)
        self.center()
        self.setStyle()
        self.setMW(main_layout)
        self.setSB(main_layout)
        self.show()

    def db(self, password="******", dbname="untitled.sld", dc=True):
        eng = create_engine("sqlite:///%s" % dbname,
                            connect_args={'check_same_thread': False})
        Base = declarative_base(bind=eng)
        Session = sessionmaker(bind=eng)
        session = Session()

        class Identifier(Base):
            __tablename__ = "identifier"
            id = Column(Integer, primary_key=True)
            version = Column(Binary)
            kvd = Column(Binary)

            def __init__(self, version, kvd):
                self.id = 0
                self.version = version
                self.kvd = kvd

        class Folder(Base):
            __tablename__ = 'folders'
            id = Column(Integer, primary_key=True)
            path = Column(String)

            def __init__(self, path="Empty"):
                self.path = path

        class File(Base):
            __tablename__ = 'files'
            id = Column(Integer, primary_key=True)
            name = Column(String)
            f_id = Column(Integer, ForeignKey('folders.id'), nullable=True)
            bb = Column(Binary)

            def __init__(self, name="empty", f_id=0, bb=1010):
                self.name = name
                self.f_id = f_id
                self.bb = bb

        if dc:
            Base.metadata.create_all()
            enc = encryptit(
                sha256(self.Version).digest(),
                sha256(password).digest())
            session.add(Identifier(enc[0], enc[1]))
            session.commit()

        return [eng, Base, session, File, Folder, Identifier, password]

    def checkP(self, db):
        try:
            d = db[2].query(db[5]).filter_by(id=0).first()
            if d is not None:
                if isenct(self.Version, d.version, db[6], d.kvd):
                    return True
        except:
            pass
        return False

    def setStyle(self):
        self.setMaximumWidth(410)
        self.setMinimumWidth(410)
        self.setMaximumHeight(370)
        self.setMinimumHeight(370)
        self.setWindowIcon(self.icon)
        self.activateWindow()
        self.setWindowTitle("safelock " + self.Version)
        self.setToolTip("Just drag and drop any files or folders" +
                        " to ecrypt or a .sld file to decrypt")
        self.setAcceptDrops(True)
        self.show()

    def center(self):
        qrect = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qrect.moveCenter(cp)
        self.move(qrect.topLeft())

    def setMW(self, ml):
        ll = QVBoxLayout()
        self.mIcon = QLabel()
        self.mIcon.setAlignment(Qt.AlignCenter)
        mmicon = self.logo.pixmap(250, 230, QIcon.Active, QIcon.On)
        self.mIcon.setPixmap(mmicon)
        self.mInst = QLabel(
            "<center>(Drag and drop files or folders to encrypt them)<br>" +
            "(Drap and drop .sld file to decrypt it)<br>" +
            "<u>2GB max single file size to encrypt</u></center>")
        font = QFont()
        font.setPointSize(13)
        font.setBold(True)
        font.setWeight(75)
        self.fInst = QLabel('<center>| Double-Click for about |</center>')
        self.mInst.setFont(font)
        ll.addWidget(self.mIcon)
        ll.addWidget(self.mInst)
        ll.addWidget(self.fInst)
        ml.addLayout(ll)

    def setSB(self, ml):
        self.statusb = QStatusBar()
        ml.addWidget(self.statusb)

    def modSB(self):
        if self.PPbar is None:
            self.PPbar = True
            self.statusb.clear()
            self.pbar = QProgressBar()
            self.pbar.setMaximum(100)
            self.pbar.setMinimum(0)
            self.plabel = QLabel()
            self.statusb.addWidget(self.plabel, 0.5)
            self.statusb.addWidget(self.pbar, 3)
        else:
            self.PPbar = None
            self.statusb.removeWidget(self.plabel)
            self.statusb.removeWidget(self.pbar)
            self.statusb.clear()

    def saveFile(self, fl):
        fname, _ = QFileDialog.getSaveFileName(self, "Save encrypted file", fl,
                                               "Safelock file (*.sld)")
        if '.' in fname:
            tm = fname.split('.')
            tm = tm[len(tm) - 1]
            if tm == "sld":
                try:
                    if path.isfile(fname):
                        remove(fname)
                except:
                    pass
                return fname
        if len(fname) <= 0:
            return None
        fname += ".sld"
        try:
            if path.isfile(fname):
                remove(fname)
        except:
            pass
        return fname

    def extTo(self, fl):
        fname = QFileDialog.getExistingDirectory(self, "Extract files to", fl)
        if len(fname) <= 0:
            return None
        return fname

    def getPass(self):
        passwd, re = QInputDialog.getText(self, "Password", "Enter password :"******"Something went wrong !"):
        QMessageBox.critical(self, "Error", msg)
        return True

    def aboutMsgg(self):
        Amsg = "<center>All credit reserved to the author of "
        Amsg += "safelock %s " % self.Version
        Amsg += ", This work is a free, open-source project licensed "
        Amsg += " under Mozilla Public License version 2.0 . <br><br>"
        Amsg += " visit for more info or report:<br> "
        Amsg += "<b><a href='https://safe-lock.github.io'> "
        Amsg += "https://safe-lock.github.io/ </a> </b></center>"
        QMessageBox.about(self, "About", Amsg)
        return True

    def getSession(self):
        self.eng = eng(self.password, self.dbname)
        Session = sessionmaker(bind=self.eng)
        self.Base = declarative_base(bind=self.eng)
        self.Base.metadata.create_all()
        self.session = Session()
        return self.session

    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dragMoveEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        if e.mimeData().hasUrls:
            e.setDropAction(Qt.CopyAction)
            e.accept()
            self.DFiles = []
            for url in e.mimeData().urls():
                try:
                    if sysname == 'darwin':
                        from Foundation import NSURL
                        fname = NSURL.URLWithString_(
                            url.toString()).filePathURL().path()
                    else:
                        fname = url.toLocalFile()
                    self.DFiles.append(fname)
                except:
                    pass
            self.dealD(self.DFiles)
        else:
            event.ignore()

    def in_loop(self):
        if self.Processing is None:
            self.Processing = True
            self.setAcceptDrops(False)
            self.mIcon.setEnabled(False)
            self.mInst.setEnabled(False)
            self.fInst.setText("<center>| Double-Click to cancel |</center>")
            self.setToolTip("Double-Click anywhere to cancel")
        else:
            self.Processing = None
            self.setAcceptDrops(True)
            self.mIcon.setEnabled(True)
            self.mInst.setEnabled(True)
            self.fInst.setText("<center>| Double-Click for about |</center>")
            self.setToolTip("Just drag and drop any files or folders" +
                            " to ecrypt or a .sld file to decrypt")

    def dealD(self, files):
        def tpp(inp):
            a = path.basename(inp)
            return inp.replace(a, '')

        if len(files) < 1:
            return False
        elif len(files) >= 1:
            if len(files) == 1:
                tf = files[0].split('.')
                tf = tf[len(tf) - 1]
                if tf == 'sld':
                    pw = self.getPass()
                    if pw is None:
                        self.errorMsg("You can't set an empty password !")
                        return False
                    elif not pw:
                        return False
                    if not self.checkP(
                            self.db(sha256(pw).digest(), files[0], dc=False)):
                        self.errorMsg("Wrong password entered, try again.")
                        return False
                    else:
                        fold = self.extTo(tpp(files[0]))
                        if fold is not None:
                            self.CP = fold
                            self.in_loop()
                            self.P = DecryptTH(fold,
                                               self.db(pw, files[0], dc=False),
                                               sha256(pw).digest())
                            self.P.start()
                            self.P.somesignal.connect(self.handleStatusMessage)
                            self.P.setTerminationEnabled(True)
                            return True
            pw = self.getPass()
            if pw is None:
                self.errorMsg("You can't set an empty password !")
            elif not pw:
                pass
            else:
                fil = self.saveFile(tpp(files[0]))
                if fil is not None:
                    if path.isfile(fil):
                        try:
                            remove(fil)
                        except:
                            pass
                    self.CP = fil
                    self.in_loop()
                    self.P = EncryptTH(files, self.db(pw, fil),
                                       sha256(pw).digest())
                    self.P.start()
                    self.P.somesignal.connect(self.handleStatusMessage)
                    self.P.setTerminationEnabled(True)
        return True

    @Slot(object)
    def handleStatusMessage(self, message):
        self.statusb.setStyleSheet(self.s_loop)

        def getIT(f, o):
            return int((f / o) * 100)

        mm = message.split('/')
        if mm[len(mm) - 1] == '%':
            if self.PPbar is None:
                self.modSB()
            self.pbar.setValue(getIT(int(mm[0]), int(mm[1])))
            self.setWindowTitle("Processing : " +
                                str(getIT(int(mm[0]), int(mm[1]))) + "%")
            self.plabel.setText(mm[0] + '/' + mm[1])
        else:
            self.unsetCursor()
            if self.PPbar is not None:
                self.modSB()
            if message[:7] == '# Error':
                if self.Processing:
                    self.in_loop()
                self.statusb.setStyleSheet(self.s_error)
                self.cleanup()
            elif message[:6] == '# Stop':
                self.statusb.setStyleSheet(self.s_error)
            elif message[:6] == '# Done':
                if self.Processing:
                    self.in_loop()
                self.statusb.setStyleSheet(self.s_norm)
            elif message == "# Loading":
                self.setCursor(Qt.BusyCursor)
                self.statusb.setStyleSheet(self.s_norm)
            self.setWindowTitle('safelock ' + self.Version)
            self.statusb.showMessage(message)

    def mousePressEvent(self, event):
        if event.type() == QEvent.Type.MouseButtonDblClick:
            if self.Processing is None:
                self.aboutMsgg()
            else:
                self.closeEvent()

    def closeEvent(self, event=None):
        if self.Processing is not None:
            if event is not None:
                r = QMessageBox.question(
                    self, "Making sure",
                    "Are you sure you want to exit, during an active" +
                    " process ?", QMessageBox.Yes | QMessageBox.No)
            else:
                r = QMessageBox.question(self, "Making sure",
                                         "Are you sure, you to cancel ?",
                                         QMessageBox.Yes | QMessageBox.No)
            if r == QMessageBox.Yes:
                self.P.stop()
                self.cleanup()
                if event is not None:
                    self.in_loop()
                    event.accept()
                else:
                    self.in_loop()
            else:
                if event is not None:
                    event.ignore()
        else:
            if self.CP is not None:
                try:
                    if path.isfile(self.CP + '-journal'):
                        remove(self.CP + '-journal')
                except:
                    pass
            if event is not None:
                event.accept()

    def cleanup(self):
        if self.CP is not None:
            try:
                if path.isfile(self.CP + '-journal'):
                    remove(self.CP + '-journal')
                if path.isfile(self.CP):
                    remove(self.CP)
            except:
                pass
Esempio n. 43
0
 def _create_gauge ( self, dialog, layout ):
     self.progress_bar = QProgressBar( dialog )
     self.progress_bar.setRange( self.min, self.max )
     layout.addWidget( self.progress_bar )
Esempio n. 44
0
class MainWindow(QMainWindow):
    """Fenêtre principale du programme"""
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.setWindowIcon(QIcon('Stock/appicon.png'))

    def setupComponent(self):
        """Initialise l'ensemble des éléments de l'application"""
        self.setupStatusBar()
        self.setupZoneText()
        self.setupMenu()
        self.setupToolBar()

    def setupStatusBar(self):
        """Ajoute une barre de status"""
        self.progressBar = QProgressBar()
        self.statusLabel = QLabel('Progression ...')
        self.progressBar.setMaximum(100)
        self.progressBar.setMinimum(0)
        self.statusBar = QStatusBar()
        # # Affiche un message durant 2 sec après ouverture de l'application
        # self.statusBar.showMessage('Please Wait ...', 2000)
        self.progressBar.setValue(10)
        self.statusBar.addWidget(self.statusLabel, 1)
        self.statusBar.addWidget(self.progressBar, 2)
        self.setStatusBar(self.statusBar)

    def setupZoneText(self):
        """Ajout du widget central (zone de texte)"""
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

    def setupMenu(self):
        """Ajout de menus contextuels"""
        self.createActions()
        self.createMenu()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    def setupToolBar(self):
        """Ajout de la barre d'outils"""
        self.mainToolBar = self.addToolBar('Main')
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

    def showProgress(self):
        """Avancement de la barre de progression"""
        while self.progressBar.value() < self.progressBar.maximum():
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1 / 10)
        # self.statusBar.showMessage('Ready', 2000)
        self.statusLabel.setText('Ready !!')

    def createMenu(self):
        """Création de la barre de menu avec 3 menus"""
        self.fileMenu = self.menuBar().addMenu('&Fichier')
        self.editMenu = self.menuBar().addMenu('&Edition')
        self.helpMenu = self.menuBar().addMenu('&About')

    def createActions(self):
        """Création des différentes actions du menu
           '&' permet de surligner une lettre pour acès rapide Alt+lettre
           'shortcut' permet de définir le raccourci de l'action du menu
           'statusTip' permet de modifier l'affichage dans la barre de status
           'triggered' permet de définir l'action à réaliser"""
        self.newAction = QAction('&New',
                                 self,
                                 shortcut=QKeySequence.New,
                                 statusTip="Créer un nouveau fichier",
                                 triggered=self.newFile)
        self.exitAction = QAction('&Exit',
                                  self,
                                  shortcut="Ctrl+Q",
                                  statusTip="Quitter l'application",
                                  triggered=self.exitFile)
        self.copyAction = QAction('&Copy',
                                  self,
                                  shortcut="Ctrl+C",
                                  statusTip="Copier",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction('&Paste',
                                   self,
                                   shortcut="Ctrl+V",
                                   statusTip="Coller",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction('&About',
                                   self,
                                   statusTip="Infos à propos de l'éditeur",
                                   triggered=self.aboutHelp)

    def newFile(self):
        """Efface le contenu du widget de text"""
        self.textEdit.setText('')

    def exitFile(self):
        """Ferme le programme"""
        self.close()

    def aboutHelp(self):
        """Affiche des renseignements sur le logiciel"""
        QMessageBox.about(self, "About this application",
                          "Just a simple text editor using Menu Bar")
Esempio n. 45
0
class ProgressDialog ( MProgressDialog, Window ):
    """ A simple progress dialog window which allows itself to be updated

        FIXME: buttons are not set up correctly yet
    """

    #-- Facet Definitions ------------------------------------------------------

    progress_bar    = Instance( QProgressBar )
    title           = Unicode
    message         = Unicode
    min             = Int
    max             = Int
    margin          = Int( 5 )
    can_cancel      = Bool( False )
    show_time       = Bool( False )
    show_percent    = Bool( False )
    _user_cancelled = Bool( False )
    dialog_size     = Instance( QRect )

    # Label for the 'cancel' button
    cancel_button_label = Unicode( 'Cancel' )

    #-- Public Methods ---------------------------------------------------------

    def open ( self ):
        super( ProgressDialog, self ).open()
        self._start_time = time.time()


    def close ( self ):
        self.progress_bar.destroy()
        self.progress_bar = None

        super( ProgressDialog, self ).close()


    def update ( self, value ):
        """
        Updates the progress bar to the desired value. If the value is >=
        the maximum and the progress bar is not contained in another panel
        the parent window will be closed

        """

        if self.progress_bar is None:
            return ( None, None )

        self.progress_bar.setValue( value )

        percent = (float( value ) - self.min) / (self.max - self.min)

        if self.show_time and (percent != 0):
            current_time = time.time()
            elapsed      = current_time - self._start_time
            estimated    = elapsed / percent
            remaining    = estimated - elapsed

            self._set_time_label( elapsed,   self._elapsed_control )
            self._set_time_label( estimated, self._estimated_control )
            self._set_time_label( remaining, self._remaining_control )
            self._message_control.setText( self.message )

        if self.show_percent:
            self._percent_control = "%3f" % ((percent * 100) % 1)

        if (value >= self.max) or self._user_cancelled:
            self.close()

        return ( not self._user_cancelled, False )


    def reject ( self, event ):
        self._user_cancelled = True
        self.close()


    def _set_time_label ( self, value, control ):
        hours   = value / 3600
        minutes = (value % 3600) / 60
        seconds = value % 60
        label   = "%1u:%02u:%02u" % ( hours, minutes, seconds )

        control.setText( control.text()[:-7] + label )


    def _create_buttons ( self, dialog, layout ):
        """ Creates the buttons.
        """
        # Create the button:
        buttons = QDialogButtonBox()

        if self.can_cancel:
            buttons.addButton( self.cancel_button_label,
                               QDialogButtonBox.RejectRole )

        buttons.addButton( QDialogButtonBox.Ok )

        # TODO: hookup the buttons to our methods, this may involve subclassing
        # from QDialog

        if self.can_cancel:
            buttons.connect( buttons, SIGNAL( 'rejected()' ), dialog,
                             SLOT( 'reject() ' ) )
        buttons.connect( buttons, SIGNAL( 'accepted()' ), dialog,
                         SLOT( 'accept()' ) )

        layout.addWidget( buttons )


    def _create_label ( self, dialog, layout, text ):
        dummy = QLabel( text, dialog )
        dummy.setAlignment( Qt.AlignTop | Qt.AlignLeft )

        label = QLabel( "unknown", dialog )
        label.setAlignment( Qt.AlignTop | Qt.AlignLeft | Qt.AlignRight )

        sub_layout = QHBoxLayout()

        sub_layout.addWidget( dummy )
        sub_layout.addWidget( label )

        layout.addLayout( sub_layout )

        return label


    def _create_gauge ( self, dialog, layout ):
        self.progress_bar = QProgressBar( dialog )
        self.progress_bar.setRange( self.min, self.max )
        layout.addWidget( self.progress_bar )


    def _create_message ( self, dialog, layout ):
        label = QLabel( self.message, dialog )
        label.setAlignment( Qt.AlignTop | Qt.AlignLeft )
        layout.addWidget( label )
        self._message_control = label


    def _create_percent ( self, dialog, layout ):
        #not an option with the QT progress bar
        return


    def _create_timer ( self, dialog, layout ):
        if not self.show_time:
            return

        self._elapsed_control   = self._create_label( dialog, layout,
                                                      "Elapsed time : " )
        self._estimated_control = self._create_label( dialog, layout,
                                                      "Estimated time : " )
        self._remaining_control = self._create_label( dialog, layout,
                                                      "Remaining time : " )


    def _create_control ( self, parent ):
        control = QDialog( parent )
        control.setWindowTitle( self.title )

        return control


    def _create ( self ):
        super( ProgressDialog, self )._create()

        contents = self._create_contents( self.control )


    def _create_contents ( self, parent ):
        dialog = parent
        layout = QVBoxLayout( dialog )

        # The 'guts' of the dialog:
        self._create_message( dialog, layout )
        self._create_gauge(   dialog, layout )
        self._create_percent( dialog, layout )
        self._create_timer(   dialog, layout )
        self._create_buttons( dialog, layout )

        parent.setLayout( layout )

#-- EOF ------------------------------------------------------------------------
Esempio n. 46
0
class window(QMainWindow):

    """Main window."""

    def __init__(self, parent=None):
        """Initialize the parent class of this instance."""
        super(window, self).__init__(parent)
        app.aboutToQuit.connect(self.myExitHandler)

        self.style_sheet = self.styleSheet('style')
        # app.setStyle(QStyleFactory.create('Macintosh'))
        #app.setStyleSheet(self.style_sheet)
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0,0,0,0)

        app.setOrganizationName("Eivind Arvesen")
        app.setOrganizationDomain("https://github.com/eivind88/raskolnikov")
        app.setApplicationName("Raskolnikov")
        app.setApplicationVersion("0.0.1")
        settings = QSettings()

        self.data_location = QDesktopServices.DataLocation
        self.temp_location = QDesktopServices.TempLocation
        self.cache_location = QDesktopServices.CacheLocation

        self.startpage = "https://duckduckgo.com/"
        self.new_tab_behavior = "insert"

        global bookmarks

        global saved_tabs
        print "Currently saved_tabs:\n", saved_tabs

        global menubar
        menubar = QMenuBar()

        # Initialize a statusbar for the window
        self.statusbar = self.statusBar()
        self.statusbar.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.statusbar.setStyleSheet(self.style_sheet)
        self.statusbar.setMinimumHeight(15)

        self.pbar = QProgressBar()
        self.pbar.setMaximumWidth(100)
        self.statusbar.addPermanentWidget(self.pbar)

        self.statusbar.hide()

        self.setMinimumSize(504, 235)
        # self.setWindowModified(True)
        # app.alert(self, 0)
        self.setWindowTitle("Raskolnikov")
        # toolbar = self.addToolBar('Toolbar')
        # toolbar.addAction(exitAction)
        # self.setUnifiedTitleAndToolBarOnMac(True)
        self.setWindowIcon(QIcon(""))

        # Create input widgets
        self.bbutton = QPushButton(u"<")
        self.fbutton = QPushButton(u">")
        self.hbutton = QPushButton(u"⌂")
        self.edit = QLineEdit("")
        self.edit.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
        self.edit.setPlaceholderText("Enter URL")
        # self.edit.setMinimumSize(400, 24)
        self.rbutton = QPushButton(u"↻")
        self.dbutton = QPushButton(u"☆")
        self.tbutton = QPushButton(u"⁐")
        # ↆ ⇧ √ ⌘ ⏎ ⏏ ⚠ ✓ ✕ ✖ ✗ ✘ ::: ❤ ☮ ☢ ☠ ✔ ☑ ♥ ✉ ☣ ☤ ✘ ☒ ♡ ツ ☼ ☁ ❅ ✎
        self.nbutton = QPushButton(u"+")
        self.nbutton.setObjectName("NewTab")
        self.nbutton.setMinimumSize(35, 30)
        self.nbutton.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        self.edit.setTextMargins(2, 1, 2, 0)

        # create a horizontal layout for the input
        input_layout = QHBoxLayout()
        input_layout.setSpacing(4)
        input_layout.setContentsMargins(0, 0, 0, 0)

        # add the input widgets to the input layout
        input_layout.addWidget(self.bbutton)
        input_layout.addWidget(self.fbutton)
        input_layout.addWidget(self.hbutton)
        input_layout.addWidget(self.edit)
        input_layout.addWidget(self.rbutton)
        input_layout.addWidget(self.dbutton)
        input_layout.addWidget(self.tbutton)

        # create a widget to hold the input layout
        self.input_widget = QFrame()
        self.input_widget.setObjectName("InputWidget")
        self.input_widget.setStyleSheet(self.style_sheet)

        # set the layout of the widget
        self.input_widget.setLayout(input_layout)
        self.input_widget.setVisible(True)

        # CREATE BOOKMARK-LINE HERE
        self.bookmarks_layout = QHBoxLayout()
        self.bookmarks_layout.setSpacing(0)
        self.bookmarks_layout.setContentsMargins(0, 0, 0, 0)

        for i in bookmarks:
            link = QToolButton()
            link.setDefaultAction(QAction(unicode(i), link))
            link.setObjectName(unicode(i))
            link.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
            link.clicked.connect(self.handleBookmarks)

            self.bookmarks_layout.addWidget(link)

        self.bookmarks_widget = QFrame()
        self.bookmarks_widget.setObjectName("BookmarkWidget")
        self.bookmarks_widget.setStyleSheet(self.style_sheet)
        self.bookmarks_widget.setLayout(self.bookmarks_layout)

        if not bookmarks:
            self.bookmarks_widget.hide()

        # Task list
        self.tasklist = QStandardItemModel()
        #parentItem = self.tasklist.invisibleRootItem()
        #self.tasklist.header().hide()
        self.tasklist.setHorizontalHeaderItem(0, QStandardItem('Tasks'))
        parentItem = QStandardItem("Parent")
        self.tasklist.appendRow(parentItem)
        for i in range(4):
            item = QStandardItem("Item %d" % i)
            parentItem.appendRow(item)
            #parentItem = item

        #self.list.activated[str].connect(self.handleBookmarks)
        #self.list.view().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        # create tabs
        self.tabs = QTabWidget()
        self.tabs.setDocumentMode(True)
        self.tabs.setTabsClosable(True)
        self.tabs.setMovable(True)
        self.tabs.tabBar().hide()
        self.tabs.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.tabs.setCornerWidget(self.nbutton)
        self.tabs.cornerWidget().setObjectName("CornerWidget")
        self.tabs.cornerWidget().setMinimumSize(10, 24)
        self.tabs.cornerWidget().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        if saved_tabs:
            for tab in saved_tabs['tabs']:
                tasklist = QTreeView()
                tasklist.hide()
                tasklist.setObjectName('taskList')
                tasklist.setMinimumWidth(100)
                tasklist.setMaximumWidth(250)

                new_tab = QWebView()
                new_tab.setObjectName('webView')

                inspector = QWebInspector(self)
                inspector.setObjectName('webInspector')
                inspector.hide()

                page_layout = QVBoxLayout()
                page_layout.setSpacing(0)
                page_layout.setContentsMargins(0, 0, 0, 0)
                page_layout.addWidget(new_tab)
                page_layout.addWidget(inspector)
                page_widget = QFrame()
                page_widget.setObjectName('pageWidget')
                page_widget.setLayout(page_layout)

                complete_tab_layout = QHBoxLayout()
                complete_tab_layout.setSpacing(0)
                complete_tab_layout.setContentsMargins(0, 0, 0, 0)
                complete_tab_layout.addWidget(tasklist)
                complete_tab_layout.addWidget(page_widget)
                complete_tab_widget = QFrame()
                complete_tab_widget.setLayout(complete_tab_layout)

                #for page in tab['history']:
                #    new_tab.load(QUrl(page['url']))
                #print tab['current_history']
                #for item in new_tab.history().items():
                #    print item
                #new_tab.history().goToItem(new_tab.history().itemAt(tab['current_history']))
                new_tab.load(QUrl(tab['history'][tab['current_history']]['url']))
                tab['current_history']
                self.tabs.setUpdatesEnabled(False)
                if self.new_tab_behavior == "insert":
                    self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget,
                                        unicode(new_tab.title()))
                elif self.new_tab_behavior == "append":
                    self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title()))
                self.tabs.setUpdatesEnabled(True)
                new_tab.titleChanged.connect(self.change_tab)
                new_tab.urlChanged.connect(self.change_tab)
                new_tab.loadStarted.connect(self.load_start)
                new_tab.loadFinished.connect(self.load_finish)
                new_tab.loadProgress.connect(self.pbar.setValue)
                new_tab.page().linkHovered.connect(self.linkHover)
                inspector.setPage(new_tab.page())

            for index, tab in enumerate(saved_tabs['tabs']):
                self.tabs.setTabText(index, tab['history'][tab['current_history']]['title'])

            self.tabs.setCurrentIndex(saved_tabs['current_tab'])
        else:
            self.new_tab()

        tabs_layout = QVBoxLayout()
        tabs_layout.setSpacing(0)
        tabs_layout.setContentsMargins(0, 0, 0, 0)
        tabs_layout.addWidget(self.tabs)

        self.tabs_widget = QFrame()
        self.tabs_widget.setObjectName("TabLine")
        self.tabs_widget.setStyleSheet(self.style_sheet)
        self.tabs_widget.setLayout(tabs_layout)
        self.tabs_widget.setVisible(True)

        # Webkit settings
        gsettings = self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).settings().globalSettings()
        # Basic settings
        gsettings.setAttribute(QWebSettings.AutoLoadImages, True)
        gsettings.setAttribute(QWebSettings.JavascriptEnabled, True)
        gsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False)
        gsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, False)
        gsettings.setAttribute(QWebSettings.PluginsEnabled, False) # Flash isn't stable at present
        gsettings.setAttribute(QWebSettings.JavaEnabled, False) # Java applet's aren't supported by PySide
        gsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled,
            True)
        # Performace settings
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True)
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        # Other settings
        gsettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False)

        # Create a vertical layout and add widgets
        vlayout = QVBoxLayout()
        vlayout.setSpacing(0)
        vlayout.setContentsMargins(0, 0, 0, 0)
        # toolbar.addWidget(self.input_widget)
        vlayout.addWidget(self.input_widget)
        vlayout.addWidget(self.bookmarks_widget)
        vlayout.addWidget(self.tabs_widget)

        # create a widget to hold the vertical layout
        wrapper_widget = QWidget()
        wrapper_widget.setLayout(vlayout)
        self.setCentralWidget(wrapper_widget)

        self.bbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).back)
        self.fbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).forward)
        self.hbutton.clicked.connect(self.goHome)
        self.edit.returnPressed.connect(self.set_url)
        # Add button signal to "go" slot
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)
        self.dbutton.clicked.connect(self.bookmark)
        self.tbutton.clicked.connect(self.toggleTaskBar)
        self.nbutton.clicked.connect(self.new_tab)
        self.tabs.tabCloseRequested.connect(self.tabs.removeTab)
        self.tabs.currentChanged.connect(self.change_tab)

        widgets = (input_layout.itemAt(i).widget() for i in range(
            input_layout.count()))
        for widget in widgets:
            if isinstance(widget, QPushButton):
                widget.setFixedSize(33, 21)
                widget.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
                widget.pressed.connect(self.press_button)
                widget.released.connect(self.release_button)

        # make a ctrl+q quit
        sequence = QKeySequence(Qt.CTRL + Qt.Key_Q)
        QShortcut(sequence, self, SLOT("close()"))

        # make an accelerator to toggle fullscreen
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F)
        QShortcut(sequence, self, self.toggle_fullscreen)

        # make an accelerator to toggle input visibility
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_L)
        QShortcut(sequence, self, self.toggle_input)

        # make an accelerator to focus adress-bar
        sequence = QKeySequence(Qt.CTRL + Qt.Key_L)
        QShortcut(sequence, self, self.focus_adress)

        # make an accelerator to reload page
        sequence = QKeySequence(Qt.CTRL + Qt.Key_R)
        QShortcut(sequence, self, self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)

        # make an accelerator to create new tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_T)
        QShortcut(sequence, self, self.new_tab)

        # make an accelerator to close tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_W)
        QShortcut(sequence, self, self.close_tab)

        # make an accelerator to navigate tabs
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left)
        QShortcut(sequence, self, self.previous_tab)
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right)
        QShortcut(sequence, self, self.next_tab)

        # make an accelerator to toggle inspector
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_U)
        QShortcut(sequence, self, self.handleShowInspector)

        # make an accelerator to toggle bookmark
        sequence = QKeySequence(Qt.CTRL + Qt.Key_D)
        QShortcut(sequence, self, self.bookmark)

        # make an accelerator to toggle task/project-list
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_L)
        QShortcut(sequence, self, self.toggleTaskBar)

        # finally set the attribute need to rotate
        # try:
        #     self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
        # except:
        #     print "not maemo"

        self.statusbar.show()

    def press_button(self):
        """On button press. Connected."""
        self.sender().setStyleSheet('background-color: rgba(228, 228, 228)')

    def release_button(self):
        """On button release. Connected."""
        self.sender().setStyleSheet('background-color: rgba(252, 252, 252)')

    def goHome(self):
        """Go to startpage."""
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setUrl(QUrl(self.startpage))

    def handleShowInspector(self):
        """Toggle web inspector."""
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).setShown(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden())

    def toggleTaskBar(self):
        """Toggle task bar."""
        if self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden():
            self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setModel(self.tasklist)
        self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setShown(self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden())
        #self.tasklist.setShown(self.tasklist.isHidden())

    def focus_adress(self):
        """Focus adress bar."""
        self.edit.selectAll()
        self.edit.setFocus()

    def toggle_input(self):
        """Toggle input visibility."""
        if self.input_widget.isVisible():
            visible = False
        else:
            visible = True
        self.input_widget.setVisible(visible)

    def toggle_fullscreen(self):
        """Toggle fullscreen."""
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()
        self.change_tab()

    def linkHover(self, l):
        """Show link adress in status bar on mouse hover."""
        self.statusbar.showMessage(l)

    def new_tab(self):
        """Open new tab."""
        tasklist = QTreeView()
        tasklist.hide()
        tasklist.setObjectName('taskList')
        tasklist.setMinimumWidth(100)
        tasklist.setMaximumWidth(250)

        new_tab = QWebView()
        new_tab.setObjectName('webView')

        inspector = QWebInspector(self)
        inspector.setObjectName('webInspector')
        inspector.hide()

        page_layout = QVBoxLayout()
        page_layout.setSpacing(0)
        page_layout.setContentsMargins(0, 0, 0, 0)
        page_layout.addWidget(new_tab)
        page_layout.addWidget(inspector)
        page_widget = QFrame()
        page_widget.setObjectName('pageWidget')
        page_widget.setLayout(page_layout)

        complete_tab_layout = QHBoxLayout()
        complete_tab_layout.setSpacing(0)
        complete_tab_layout.setContentsMargins(0, 0, 0, 0)
        complete_tab_layout.addWidget(tasklist)
        complete_tab_layout.addWidget(page_widget)
        complete_tab_widget = QFrame()
        complete_tab_widget.setLayout(complete_tab_layout)

        new_tab.load(QUrl(self.startpage))
        self.tabs.setUpdatesEnabled(False)
        if self.new_tab_behavior == "insert":
            self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget,
                                    unicode(new_tab.title()))
        elif self.new_tab_behavior == "append":
            self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title()))
        self.tabs.setCurrentWidget(complete_tab_widget)
        self.tabs.setTabText(self.tabs.currentIndex(),
                             unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title()))
        self.tabs.setUpdatesEnabled(True)
        # tab.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        # tab.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        new_tab.titleChanged.connect(self.change_tab)
        new_tab.urlChanged.connect(self.change_tab)
        new_tab.loadStarted.connect(self.load_start)
        new_tab.loadFinished.connect(self.load_finish)
        new_tab.loadProgress.connect(self.pbar.setValue)
        new_tab.page().linkHovered.connect(self.linkHover)
        inspector.setPage(new_tab.page())

    def change_tab(self):
        """Change active tab."""
        if self.tabs.count() <= 1:
            self.tabs.tabBar().hide()
        else:
            self.tabs.tabBar().show()

        try:
            self.edit.setText(str(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()))
            self.tabs.setTabText(self.tabs.currentIndex(),
                                 unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title()))
            self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus()
        except Exception:
            self.tabs.tabBar().hide()
            self.new_tab()

        #print (self.tabs.widget(self.tabs.currentIndex()).size().width()-10), self.tabs.count()
        self.tabs_widget.setStyleSheet(self.style_sheet +
                                       "QTabBar::tab { width:" + str(
                                        (self.tabs.widget(
                                            self.tabs.currentIndex()
                                            ).size().width()-26-self.tabs.count()*2)/self.tabs.count()
                                        ) + "px; }")

    def previous_tab(self):
        """Previous tab."""
        try:
            if self.tabs.currentIndex() > 0:
                self.tabs.setCurrentIndex(self.tabs.currentIndex()-1)
            else:
                self.tabs.setCurrentIndex(self.tabs.count()-1)

            self.change_tab()
        except Exception:
            pass

    def next_tab(self):
        """Next tab."""
        try:
            if self.tabs.currentIndex() < self.tabs.count()-1:
                self.tabs.setCurrentIndex(self.tabs.currentIndex()+1)
            else:
                self.tabs.setCurrentIndex(0)

            self.change_tab()
        except Exception: #, e
            pass

    def close_tab(self):
        """Close tab."""
        self.tabs.removeTab(self.tabs.currentIndex())

    def close(self):
        """Close app."""
        Qapplication.quit()

    def set_url(self):
        """Set url."""
        url = self.edit.text()
        # does the url start with http://?
        if "." not in url:
            url = "http://www.google.com/search?q="+url
        elif not url.startswith("http://"):
            url = "http://" + url
        qurl = QUrl(url)
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(qurl)
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus()

    def load_start(self):
        """Update view values, called upon started page load."""
        self.rbutton.setText(u"╳")
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).stop)
        self.pbar.show()

    def load_finish(self):
        """Update view values, called upon finished page load."""
        if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoBack()):
            self.bbutton.setEnabled(True)
        else:
            self.bbutton.setEnabled(False)
        if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoForward()):
            self.fbutton.setEnabled(True)
        else:
            self.fbutton.setEnabled(False)

        self.rbutton.setText(u"↻")
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)
        self.pbar.hide()

        global bookmarks
        if unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) in bookmarks:
            self.dbutton.setText(u"★")
        else:
            self.dbutton.setText(u"☆")

        if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden():
            self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).hide()
            self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).show()

    def bookmark(self):
        """Toggle bookmark."""
        global bookmarks
        if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded() in bookmarks:
            bookmarks.append(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())
            pickle.dump(bookmarks, open(bookFile, "wb"))
            link = QToolButton()
            link.setDefaultAction(QAction(unicode(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())), link))
            link.setObjectName(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()))
            link.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
            link.clicked.connect(self.handleBookmarks)
            self.bookmarks_layout.addWidget(link)

            if self.bookmarks_widget.isHidden():
                self.bookmarks_widget.show()

            self.dbutton.setText(u"★")

        else:
            bookmarks.remove(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())
            pickle.dump(bookmarks, open(bookFile, "wb"))
            link = self.bookmarks_widget.findChild(QToolButton, unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()))
            self.bookmarks_layout.removeWidget(link)
            link.deleteLater()
            link = None

            if not bookmarks:
                self.bookmarks_widget.hide()

            self.dbutton.setText(u"☆")

    def handleBookmarks(self):

        self.gotoLink(self.sender().objectName())
        #self.gotoLink(unicode())

    def gotoLink(self, url):

        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(QUrl(url))

    def styleSheet(self, style_sheet):
        """Load stylesheet."""
        try:
            with open(os.path.join
                      (basedir, 'assets', 'style.qss'), 'r') as file:
                return file.read()
        except Exception:
            # print e
            return ''

    def resizeEvent(self, evt=None):
        """Called on window resize."""
        self.change_tab()

    def myExitHandler(self):
        """Exiting."""
        pass
        global tabFile

    # {current_tab: 1, tabs:[0: {current_history:3, history:[{title, url}]]}
        pb = {'current_tab': self.tabs.currentIndex()}
        pb['tabs'] = list()
        for tab in range(self.tabs.count()):
            pb['tabs'].append(dict(current_history=self.tabs.widget(
                tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().currentItemIndex(), history=list(dict(
                    title=item.title(), url=item.url()
                    ) for item in self.tabs.widget(tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().items())))

        # print pb
        pickle.dump(pb, open(tabFile, "wb"))
Esempio n. 47
0
class StatusArea(QWidget):
    def __init__(self, parent=None):
        super(StatusArea, self).__init__(parent)
        self.setStyleSheet('StatusArea {background: yellow}')
        self.msg = QLabel(self)
        self.file = QLabel(self)
        self.progress = QProgressBar(self)
   
        self.msg.setFont(View.labelsFont())
        self.file.setFont(View.editsFont())

        self.progress.setMaximum(100)
        self.progress.setMinimum(0)
        self.progress.setTextVisible(False)
        self.progress.setStyleSheet(""" 
            QProgressBar {
                 border: 2px solid grey;
                 border-radius: 5px;
                 width: 60px;
                 height: 10px;
             }

             QProgressBar::chunk {
                 background-color: #05B8CC;
                 width: 5px;
             }""")
 
        layout = QHBoxLayout()
        layout.addWidget(self.msg, 0, Qt.AlignLeft)
        layout.addWidget(self.file, 0, Qt.AlignLeft)
        layout.addWidget(self.progress, 0, Qt.AlignRight)

        self.setLayout(layout)

    @Slot(str)
    @Slot(str, str, str)
    def setMessage(self, msg, file='', progress=None):
        if not progress:
            self.progress.hide()
            self.progress.setValue(0)
        else:
            self.progress.setValue(progress)
            self.progress.show()

        self.msg.setText(msg)
        self.file.setText(file)

    def paintEvent(self, event):
        p = QPainter()
        p.begin(self)
        p.fillRect(self.rect(), QBrush(QColor(240, 200, 0)))
        p.end()
Esempio n. 48
0
class ProgressBarService(QObject):
    """
    This service is initialized with a status bar upon which it sets
    a progress bar. Consumers of the service can then show/hide
    the progress bar and set values.

    The __new__ method is overridden to make this class a singleton.
    Every time it is instantiated somewhere in code, the same instance will be
    returned. In this way, it can serve like a static class.

    @param statusbar: The status bar on which to display progress.
    @type statusbar: QStatusBar (I think)

    @since: 2010-03-02
    """

    __author__ = "Moritz Wade"
    __contact__ = "*****@*****.**"
    __copyright__ = "Zuse Institute Berlin 2010"

    _instance = None

    def __new__(cls, *args, **kwargs): # making this a Singleton, always returns the same instance
        if not cls._instance:
            cls._instance = super(ProgressBarService, cls).__new__(cls, *args, **kwargs)
        return cls._instance
    
    def __init__(self, parent=None, statusBarService = None):
        """
        Creates a QProgressBar and adds it to the given status bar (for
        threads that can provide accurate progress information).

        Note: The status bar can either be a QStatusBar or the StatusBarService. In the default
        BioPARKIN use, it is the StatusBarService instance.

        @todo: A throbber is created and also added to the status bar (for
        threads that can only provide start/stop information).
        """
#        super(ProgressBarService, self).__init__(parent)   # done in __new__

        if statusBarService is not None:
            self.statusBarService = statusBarService
            #self.progressBar = QProgressBar(self.statusBarService) # used for showing progress
            self.progressBar = QProgressBar(None) # used for showing progress
            self.progressBarMutex = QMutex()
            self.progressBar.hide()
            self.statusBarService.addPermanentWidget(self.progressBar)
            self.progressRunning = False
    
    
            self.throbber = QLabel()
            self.throbberRunning = False
            self.throbberMutex = QMutex()
            self.statusBarService.addPermanentWidget(self.throbber)
            self.throbber.show()
            self.throbber.hide()

            throbberImage = QMovie(":/images/Spinning_wheel_throbber.gif", parent=self.throbber)
            throbberImage.setScaledSize(QSize(24, 24))
            throbberImage.setCacheMode(QMovie.CacheAll)
            throbberImage.start()
            self.throbber.setMovie(throbberImage)
            self.throbber.setFixedSize(24,24)


#    def __call__(self):
#        """
#        Quick'n'dirty way to make a Singleton out of this class.
#        """
#        return self

#    def setStatusBar(self, statusbar):
#        """
#        Sets the internal status bar (or StatusBarService)
#        """
#        self.statusbar = statusbar
        
    def getStatusBar(self):
        """
        Gets the internal status bar (or StatusBarService)
        """
        return self.statusBarService
    
    def connect_to_thread(self, thread):
        """
        Connects standard BioParkinThreadBase SIGNALs to update methods.

        @param thread: Thread whose Signals to handle
        @type thread: BioParkinThreadBase
        """
        if thread is not None:
            self.thread = thread
            #thread.finished.connect(self.threadFinished)
            #print "in connect_to_thread"
            self.thread.startWithoutProgressSignal.connect(self.start_throbber)
            self.thread.startWithProgressSignal.connect(self.start_progress)
            self.thread.finishedSignal.connect(self.finish)
            self.thread.progressMinimumSignal.connect(self.setProgressBarMinimum)
            self.thread.progressMaximumSignal.connect(self.setProgressBarMaximum)
            self.thread.progressValueSignal.connect(self.setProgressBarValue)
            self.thread.progressTextSignal.connect(self.showMessage)
    
    #  def threadFinished(self, bool):
    #    self.hide("Action finished.")

    def setProgressBarMinimum(self, min):
        """
        Uses a QMutexLocker to set the minimum value for the progress bar.
        """
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.setMinimum(min)

    def setProgressBarMaximum(self, max):
        """
        Uses a QMutexLocker to set the maximum value for the progress bar.
        """
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.setMaximum(max)

    def setProgressBarValue(self, value):
        """
        Uses a QMutexLocker to set the minimum value for the progress bar.

        This also implicitely "starts" the progress, e.g. show the ProgressBar.
        """
        self.progressRunning = True
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.setValue(value)
            self.progressBar.show()
    
    def update(self, value, min=None, max=None, text = None):
        """
        Updates the progress bar with the given information.

        @param value: current value
        @type value: int

        @param min: Value that represents 0%
        @type min: int

        @param max: Value that represents 100%
        @type max: int

        @param text: Text to display on status bar
        @type text: str
        """
        #
        self.progressRunning = True
        #QApplication.processEvents()
        with QMutexLocker(self.progressBarMutex):
            if min and max:
                self.progressBar.setRange(min, max)
            self.progressBar.setValue(value)
            self.progressBar.show()

        if text is not None:
            self.statusBarService.showMessage(text)
    
    
#    @Slot("QString")
    def finish(self, text = None):
        """
        This is a slot. It's called when a thread emits its "finished" Signal.

        The given text is posted to the status bar.

        @param text: Text for status bar
        @type text: str
        """
        #print "in finish()"
        #logging.info("Finishing Progress Service")
        
        if self.progressRunning:
            with QMutexLocker(self.progressBarMutex):
                self.progressBar.hide()
        if self.throbberRunning:
            with QMutexLocker(self.throbberMutex):
                self.throbber.hide()
        
        
        if text is None:
            self.statusBarService.showMessage("Finished", 1000)
        else:
            self.statusBarService.showMessage(text, 3000) # show finish message for 3 seconds
        
        
        self.thread = None  # release reference to thread
    
#    @Slot("QString")
    def start_throbber(self, text = None):
        """
        This is a slot. It starts (the progress-state-less) throbber
        animation.

        The given text is posted to the status bar.

        @param text: Text for status bar
        @type text: str
        """
        #print "Starting progress throbber...."
        #logging.info("Starting progress throbber....")
        with QMutexLocker(self.throbberMutex):
            self.throbber.show()
            self.throbberRunning = True

        if text is None:
            self.statusBarService.showMessage("Computing...")
        else:
            self.statusBarService.showMessage(text)
    
    
#    @Slot("QString")
    def start_progress(self, text = None):
        """
        This is a slot. It starts the progress animation.

        The given text is posted to the status bar.

        @param text: Text for status bar
        @type text: str
        """
        self.progressRunning = True
        with QMutexLocker(self.progressBarMutex):
            self.progressBar.show()
        
        if text is None:
            self.statusBarService.showMessage("Computing...", 1000)
        else:
            self.statusBarService.showMessage(text)

    def showMessage(self, text):
        if self.statusBarService:
            self.statusBarService.showMessage(text)
Esempio n. 49
0
class MainWindow(QMainWindow):
    """ Starting point of the GUI based application """
    isMyProgressTimer = False
    def __init__(self):        
        """ MainWindow Constructor Function"""
        super(MainWindow, self).__init__()
        wdgt = QWidget()
        wdgt.setWindowTitle = "ManageHD"
        self.setCentralWidget(wdgt)
        self.InitUI()
        self.GetParameterFileInfo()        
    
    def InitUI(self):        
        """ Initialize user created UI elements """
        self.qlVidsDone         = QLabel('0', self)
        self.qlVidsInProgress   = QLabel('0', self)
        self.qlStartTime        = QLabel(datetime.now().strftime("%a, %d %b %Y %H:%M:%S"), self)
        self.qlEndTime          = QLabel('', self)
        self.qlTimeLeft         = QLabel('', self)
        self.qlDestinationSpace = QLabel('', self)
        self.qlArcSpace         = QLabel('', self)
        self.qlProcessingSpeed  = QLabel('', self)
        
        self.qleSourceDir       = QLineEditDirectoriesOnly()
        self.qleArchiveDir      = QLineEditDirectoriesOnly()
        self.qleDestinationDir  = QLineEditDirectoriesOnly()
        self.qleMaxVidsCap      = QLineEditIntsOnly()
        self.qleVideoTypes      = QLineEditNoPeriodsOrCommas()
        self.qleVideoTypes.installEventFilter(self)
        
        self.qpbSourceDir       = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForSourceDirectory)
        self.qpbArchiveDir      = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForArchiveDirectory)
        self.qpbTargetDir       = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForTargetDirectory)
        self.qpbRun             = self.__CreateButton(None,"Run", 75, self.Process)        
        
        self.setWindowTitle("Manage HD Video")
        self.videoExtensionFileFilter = "Video (*.mkv *.mp4 *.avi)"
        self.qleVideoTypes.setText("mkv mp4 avi")
        self.statusLabel = QLabel('Showing Progress')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.__CreateActions()
        self.__CreateMenus()
        self.fileMenu.addAction(self.stdAction)
        self.fileMenu.addAction(self.altAction)
        if Progress.runPlatform == 'win':
            self.stdAction.setIcon(QIcon('checked.jpg'))
        self.stdAction.setChecked(True)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.fileMenu.addSeparator()
        self.helpMenu.addAction(self.aboutAction)
        self.__SetIcon()
        self.__CenterWindow()
        self.__CreateGrid()       

    def eventFilter(self, source, event): #Override
        """ Override the QMainWindow eventFilter method to add File Mask Validation. """
        if (event.type() == QEvent.FocusOut and
            source is self.qleVideoTypes):
            self.ValidateFileMask()
        return QMainWindow.eventFilter(self, source, event)
    
    def DisableGuiElements(self):
        """ Change the setEnabled property of the main GUI elements to False. """
        self.qleArchiveDir.setEnabled(False)
        self.qleDestinationDir.setEnabled(False)
        self.qleMaxVidsCap.setEnabled(False)
        self.qleSourceDir.setEnabled(False)
        self.qleVideoTypes.setEnabled(False)

        self.qpbArchiveDir.setEnabled(False)
        self.qpbSourceDir.setEnabled(False)
        self.qpbTargetDir.setEnabled(False)
        self.qpbRun.setEnabled(False)

    def EnableGuiElements(self):
        """ Change the setEnabled property of the main GUI elements to True. """
        self.qleArchiveDir.setEnabled(True)
        self.qleDestinationDir.setEnabled(True)
        self.qleMaxVidsCap.setEnabled(True)
        self.qleSourceDir.setEnabled(True)
        self.qleVideoTypes.setEnabled(True)
        
        self.qpbArchiveDir.setEnabled(True)
        self.qpbSourceDir.setEnabled(True)
        self.qpbTargetDir.setEnabled(True)
        self.qpbRun.setEnabled(True)

    def __AddGridLabel(self, grid, lblText, custFont, row, column, justification):
        sd = QLabel(lblText, self)
        sd.setFont(custFont)
        grid.addWidget(sd, row, column, alignment = justification)        

    def SelectSingleFileForSourceDirectory(self):
        self.qleSourceDir.setText( self.InvokeSingleSelectionDirectoryDialog() )
        self.ValidateFileMask()

    def SelectSingleFileForArchiveDirectory(self):
        self.qleArchiveDir.setText( self.InvokeSingleSelectionDirectoryDialog() )
    
    def SelectSingleFileForTargetDirectory(self):
        self.qleDestinationDir.setText( self.InvokeSingleSelectionDirectoryDialog() )

    def InvokeSingleSelectionFileDialog(self):
        """ Prompts the user to select a single file from a file dialog window. """
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setFilter(self.videoExtensionFileFilter)        
        ret = dialog.exec_()
        FileNames = dialog.selectedFiles()
        if len(FileNames) == 0:
            FileNames.append(None)
        return FileNames[0]
    
    def InvokeSingleSelectionDirectoryDialog(self):
        """ Prompts the user to select a single directory from a directory dialog window. """
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.DirectoryOnly)        
        DirectoryName = dialog.getExistingDirectory()
        if len(DirectoryName) == 0:
            DirectoryName = None
        return DirectoryName

    def ValidateFileMask(self):
        """ Function to validate that the entered file mask is valid. """
        extensionList = ""
        if len(self.qleVideoTypes.text().split(" ")) > 0:
            for videoExtension in self.qleVideoTypes.text().split(" "):
                extensionList += ("*." + videoExtension + " ")
            extensionList = extensionList[:-1]
        self.videoExtensionFileFilter = "Video ({})".format(extensionList)        
        
    def __CreateGrid(self):
        g1 = QGridLayout()
        self.centralWidget().setLayout(g1)

        g1.setSpacing(5)

        bold = QFont()
        bold.setBold(True)
        self.__AddGridLabel(g1, 'Source Directory:', QFont(), 0, 0, -1)
        self.__AddGridLabel(g1, 'Archive Directory:', QFont(), 1, 0, -1)
        self.__AddGridLabel(g1, 'Target Directory:', QFont(), 2, 0, -1)
        self.__AddGridLabel(g1, 'Max Number of Videos:', QFont(), 3, 0, -1)
        self.__AddGridLabel(g1, 'Video File Types:', QFont(), 3, 2, -1)
        #self.__AddGridLabel(g1, 'Max Run Time in Hours:', QFont(), 4, 2, -1)

        g1.addWidget(self.qleSourceDir, 0, 1, 1, 3)
        g1.addWidget(self.qleArchiveDir, 1, 1, 1, 3)
        g1.addWidget(self.qleDestinationDir, 2, 1, 1, 3)
        g1.addWidget(self.qleMaxVidsCap, 3, 1)
        g1.addWidget(self.qleVideoTypes, 3, 3)
        #g1.addWidget(self.qleRunTimeMax, 4, 3)
        
        g1.addWidget(self.qpbRun, 10, 3, alignment = -1)
        
        g1.addWidget(QLabel('', self), 4, 0,) # Empty Column As Separator
        g1.addWidget(QLabel('', self), 5, 0,) # Empty Column As Separator
        
        self.__AddGridLabel(g1, 'Videos Completed:',   bold, 5, 0, -1)
        self.__AddGridLabel(g1, 'Start Time:',         bold, 5, 2, -1)
        self.__AddGridLabel(g1, 'Videos In Progress:', bold, 6, 0, -1)
        self.__AddGridLabel(g1, 'Time Remaining:',     bold, 7, 2, -1)
        self.__AddGridLabel(g1, 'Target Space Left:',  bold, 7, 0, -1)
        self.__AddGridLabel(g1, 'Archive Space Left:', bold, 8, 0, -1)
        self.__AddGridLabel(g1, 'End Time:',           bold, 6, 2, -1)
        self.__AddGridLabel(g1, 'Processing Speed:',   bold, 8, 2, -1)
        
        g1.addWidget(self.qlVidsDone,        5, 1,) 
        g1.addWidget(self.qlVidsInProgress,  6, 1)
        g1.addWidget(self.qlStartTime,       5, 3,) 
        g1.addWidget(self.qlEndTime,         6, 3,) 
        g1.addWidget(self.qlTimeLeft,        7, 3,) 
        g1.addWidget(self.qlDestinationSpace,     7, 1,) 
        g1.addWidget(self.qlArcSpace,        8, 1,)
        g1.addWidget(self.qlProcessingSpeed, 8, 3,)
        
        g1.addWidget(self.qpbSourceDir,      0, 4,)
        g1.addWidget(self.qpbArchiveDir,     1, 4,)
        g1.addWidget(self.qpbTargetDir,      2, 4,)        
        self.show
        
    def GetParameterFileInfo(self):
        Progress.DeterminePlatform()
        fm = FileManip()
        #params = Progress.cliParams.copy()
        params = fm.ReadSettingsFile()
        self.qlProcessingSpeed.setText(str(Progress.cliParams['ProcessingSpeedInGBperHour']))
        self.qleSourceDir.setText(params['sourceDir'])
        self.qleArchiveDir.setText(params['archiveDir'])
        self.qleDestinationDir.setText(params['destinationDir'])
        
    def GetDriveSpace(self, path):
        """ Call the GetDriveSpace() method using an instance of the FileManip class. """
        fm = FileManip() 
        return fm.GetDriveSpace(path)

    def ResetStats(self):
        """ Change statistical data displays back to their original initialized values. """
        Progress.ResetStatuses()
        self.qlVidsDone.setText( '0')
        self.qlVidsInProgress.setText('0')
        self.qlStartTime.setText(datetime.now().strftime("%a, %d %b %Y %H:%M:%S"))
        self.qlTimeLeft.setText("")
        if self.qleDestinationDir.text() != "":
            self.qlDestinationSpace.setText(str(self.GetDriveSpace(self.qleDestinationDir.text())))
        if self.qleArchiveDir.text() != "":
            self.qlArcSpace.setText(str(self.GetDriveSpace(self.qleArchiveDir.text())))
        self.qlEndTime.setText("")
        self.qlProcessingSpeed.setText("")
    
    def VerifyRequiredFieldsFilled(self):
        """ Cancels the RUN functionality and informs the user via Message Box if the required fields are not all completed. """
        if self.qleSourceDir.text() == "" or \
            self.qleVideoTypes.text() == "" or \
            self.qleDestinationDir.text() == "":
            QMessageBox.critical(self, "Required Field Error", 
                                 "You have not filled out the three required fields. "
                                 "'Source Directory', "
                                 "'Target Directory' and "
                                 "'Video File Types' "
                                 "are all required Fields.", QMessageBox.Ok)
            return 0
        return True        

    def Process(self):
        """ Batch processing of the source video files begins here. """
        result = self.VerifyRequiredFieldsFilled()
        if result != True:
            return
        self.ResetStats()
        
        Progress.statuses['ProcessingComplete'] = False
        self.DisableGuiElements()
        Params = Progress.cliParams.copy() 
        Params['sourceDir']      = self.qleSourceDir.text()
        Params['archiveDir']     = self.qleArchiveDir.text()
        Params['destinationDir'] = self.qleDestinationDir.text()

        maximumNumVids = ""
        for idx in range(0, len(self.qleMaxVidsCap.text())):
            if self.qleMaxVidsCap.text()[idx] != '.':
                maximumNumVids = maximumNumVids + self.qleMaxVidsCap.text()[idx]

        if maximumNumVids.isnumeric():
            Params['maxNumberOfVideosToProcess']  = '%1.f' % float(self.qleMaxVidsCap.text())

        if len(self.qleVideoTypes.text().split(" ")) > 0:
            extensionList = ""
            for videoExtension in self.qleVideoTypes.text().split(" "):
                extensionList += (videoExtension + ",")
        else:
            extensionList = None

        Params['videoTypes']     = extensionList
        
        #Create and instance of the processing class
        pm = ProcessMovies()

        #Disable applicable GUI elements
        self.DisableGuiElements

        #Spawn a thread to run this
        Thread(target=pm.StartWithGUI, args=(Params,)).start()

        sleep(1)
        self.qlTimeLeft.setText(Progress.CalculateTimeRemaining())
        Progress.statuses['StatusesHaveChanged'] = True
        return

    def __CreateButton(self, folderIcon, txt, pxSize, actionFunction):
        """ Function to add a button """
        if folderIcon != None:
            folderIcon = QIcon('folder.png')
            myButton = QPushButton(folderIcon, "")
        else:
            myButton = QPushButton(txt)
        myButton.setMaximumWidth(pxSize)
        myButton.clicked.connect(actionFunction)
        return myButton

    def aboutHelp(self):
        """ Displays the ABOUT box and sets its content. """
        QMessageBox.about(self, "About ManageHD",
                          "Program written in Python v3.4 \n\n"
                          "ManageHD allows you to select an entire "
                          "directory of HD video files and lower their "
                          "resolution from 1080 HD to 720 HD, in batch. "
                          "It calls the HandBrake Command Line Interface "
                          "(CLI) in order to re-encode each video. \n\nYou must "
                          "have the Handbrake CLI installed to use this "
                          "software. "
                          "The CLI (command line interface) can be downloaded at:\n\n "
                          "     http://handbrake.fr/downloads2.php \n\n"
                          "The average video file at 720 HD "
                          "is generally one fourth to one sixth the size "
                          "of its 1080 HD source file. \n\n"
                          "Coding was done by InfanteLabz. \n\n"
                          "This sofware is released under GPL v3 "
                          "licensing. \n\n Developed on Wing IDE")

    def exitFile(self):
        """ Exits the Main Window, ending the program. """
        self.close()

    def __CreateActions(self):
        """ Function to create actions for menus """
        self.stdAction = QAction(QIcon('convert.png'), 
                                'Create MKV files',
                                self, shortcut = "Ctrl+K",
                                statusTip = "File format set to MKV container",
                                triggered = self.stdConversion,
                                checkable = True)

        self.altAction = QAction(QIcon('convert.png'), 
                                'Create MP4 files',
                                self, shortcut = "Ctrl+P",
                                statusTip = "File format set to MP4 file",
                                triggered = self.altConversion,
                                checkable = True)

        self.exitAction = QAction(QIcon('exit.png'),
                                  '&Quit',
                                  self, shortcut="Ctrl+Q",
                                  statusTip = "Exit the Application",
                                  triggered=self.exitFile)

        #self.copyAction = QAction(QIcon('copy.png'), 'C&opy',
                                  #self, shortcut="Ctrl+C",
                                  #statusTip="Copy",
                                  #triggered=self.CopyFunction)

        self.aboutAction = QAction(QIcon('about.png'), 'A&bout',
                                   self, statusTip="Displays info about ManageHD",
                                   triggered=self.aboutHelp)

    def __CreateMenus(self):
        """ Function to create actual menu bar """
        self.fileMenu = self.menuBar().addMenu("&File")
        self.helpMenu = self.menuBar().addMenu("&Help")
        
    def __CenterWindow(self):
        """ Function to center the window """
        qRect = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())
    
    def __SetAboutBox(self):
        """ Function to position and wire the ABOUT box """
        self.aboutButton = QPushButton("About", self)
        self.aboutButton.move(200, 100)
        self.aboutButton.clicked.connect(self.ShowAbout)
        
    def __SetIcon(self):
        """ Function to set Icon """
        appIcon = QIcon('ManageHD_Icon.png')
        self.setWindowIcon(appIcon)

    def DisplayAbnormalTerminationStatus(self, status): # Not Implemented
        pass

    def GetArchiveDirectory(self): # Not Implemented
        pass
    
    def stdConversion(self):
        """ Called by the STANDARD menu item under FILE. Sets ManageHD to perform the standard Handbrake conversion. """
        Progress.statuses['HandbrakeOptionsString'] = str(" -i {0} -o {1} -f mkv --width 1280 --crop 0:0:0:0 --decomb -s 1 -N eng -m --large-file --encoder x264 -q 19 -E ffac3")
        Progress.statuses['OutputExtension'] = 'mkv'
        self.altAction.setChecked(False)
        if Progress.runPlatform == "win":
            self.altAction.setIcon(QIcon('convert.png'))
            self.stdAction.setIcon(QIcon('checked.jpg'))
        self.stdAction.setChecked(True)
    
    def altConversion(self):
        """ Called by the ALTERNATE menu item under FILE. Sets ManageHD to perform Handbrake conversions using an alternate series of settings. """
        Progress.statuses['HandbrakeOptionsString'] = str(" -i {0} -o {1} -f mp4 --width 1280 --crop 0:0:0:0 --decomb -s 1 -N eng -m --large-file --encoder x264 -q 19 -E ffac3")
        Progress.statuses['OutputExtension'] = 'mp4'
        self.stdAction.setChecked(False)
        if Progress.runPlatform == "win":
            self.altAction.setIcon(QIcon('checked.jpg'))
            self.stdAction.setIcon(QIcon('convert.png'))
        self.altAction.setChecked(True)

    def CopyFunction(): # Not Implemented
        pass
        
    def ValidateAndRun(self): # Not Implemented
        pass
Esempio n. 50
0
class MainWindow(QMainWindow):
    """
    The main window of angr management.
    """
    def __init__(self, file_to_open=None, parent=None):
        super(MainWindow, self).__init__(parent)

        icon_location = os.path.join(IMG_LOCATION, 'angr.png')
        self.setWindowIcon(QIcon(icon_location))

        GlobalInfo.main_window = self

        # initialization
        self.caption = "angr Management"
        self.setMinimumSize(QSize(400, 400))
        self.setDockNestingEnabled(True)

        self.workspace = None
        self.central_widget = None

        self._file_toolbar = None  # type: FileToolbar
        self._states_toolbar = None  # type: StatesToolbar
        self._analysis_toolbar = None  # type: AnalysisToolbar
        self._progressbar = None  # type: QProgressBar

        self._status = ""
        self._progress = None

        self._init_menus()
        self._init_toolbars()
        self._init_statusbar()
        self._init_workspace()

        self.showMaximized()

        # I'm ready to show off!
        self.show()

        self.status = "Ready."

        if file_to_open is not None:
            # load a binary
            self._open_loadbinary_dialog(file_to_open)

    #
    # Properties
    #

    @property
    def caption(self):
        return self.getWindowTitle()

    @caption.setter
    def caption(self, v):
        self.setWindowTitle(v)

    @property
    def status(self):
        return self._status

    @status.setter
    def status(self, v):
        self._status = v

        self.statusBar().showMessage(v)

    @property
    def progress(self):
        return self._progress

    @progress.setter
    def progress(self, v):
        self._progress = v
        self._progressbar.show()
        self._progressbar.setValue(v)

    #
    # Dialogs
    #

    def _open_loadbinary_dialog(self, file_to_open):
        load_binary_dialog = LoadBinary(file_to_open)
        load_binary_dialog.exec_()

        if load_binary_dialog.cfg_args is not None:
            # load the binary
            self._load_binary(file_to_open,
                              load_options=load_binary_dialog.load_options,
                              cfg_args=load_binary_dialog.cfg_args
                              )

    def open_newstate_dialog(self):
        new_state_dialog = NewState(self.workspace, parent=self)
        new_state_dialog.exec_()

    #
    # Widgets
    #

    def _init_statusbar(self):

        self._progressbar = QProgressBar()

        self._progressbar.setMinimum(0)
        self._progressbar.setMaximum(100)
        self._progressbar.hide()

        self.statusBar().addPermanentWidget(self._progressbar)

    def _init_toolbars(self):

        self._file_toolbar = FileToolbar(self)
        self._states_toolbar = StatesToolbar(self)
        self._analysis_toolbar = AnalysisToolbar(self)

        self.addToolBar(Qt.TopToolBarArea, self._file_toolbar.qtoolbar())
        self.addToolBar(Qt.TopToolBarArea, self._states_toolbar.qtoolbar())
        self.addToolBar(Qt.TopToolBarArea, self._analysis_toolbar.qtoolbar())

    #
    # Menus
    #

    def _init_menus(self):
        fileMenu = FileMenu(self)
        self.menuBar().addMenu(fileMenu.qmenu())

    #
    # Workspace
    #

    def _init_workspace(self):
        self.central_widget = QMainWindow()
        self.setCentralWidget(self.central_widget)

        wk = Workspace(self)
        self.workspace = wk

        right_dockable_views = [ dock for dock in self.workspace.dockable_views
                                 if dock.widget().default_docking_position == 'right' ]

        for d0, d1 in zip(right_dockable_views, right_dockable_views[1:]):
            self.central_widget.tabifyDockWidget(d0, d1)
        right_dockable_views[0].raise_()

        self.central_widget.setTabPosition(Qt.RightDockWidgetArea, QTabWidget.North)

    #
    # Event
    #

    def resizeEvent(self, event):
        """

        :param QResizeEvent event:
        :return:
        """

        pass
        # self._recalculate_view_sizes(event.oldSize())

    def event(self, event):

        if event.type() == QEvent.User:
            # our event callback

            try:
                event.result = event.execute()
            except Exception:
                event.exception = sys.exc_info()
            event.event.set()

            return True

        return super(MainWindow, self).event(event)

    #
    # Actions
    #

    def reload(self):
        self.workspace.reload()

    def load_binary(self):

        # Open File window
        file_path, _ = QFileDialog.getOpenFileName(self, "Open a binary", ".",
                                                   "All executables (*);;Windows PE files (*.exe);;Core Dumps (*.core)",
                                                   )

        if os.path.isfile(file_path):
            self._open_loadbinary_dialog(file_path)


    def quit(self):
        self.close()

    def run_variable_recovery(self):
        self.workspace.views_by_category['disassembly'][0].variable_recovery_flavor = 'accurate'

    def run_induction_variable_analysis(self):
        self.workspace.views_by_category['disassembly'][0].run_induction_variable_analysis()

    #
    # Other public methods
    #

    def progress_done(self):
        self._progress = None
        self._progressbar.hide()

    #
    # Private methods
    #

    def _load_binary(self, file_path, load_options=None, cfg_args=None):

        if load_options is None:
            load_options = { }

        if cfg_args is None:
            cfg_args = { }

        inst = Instance(project=angr.Project(file_path, load_options=load_options))
        self.workspace.set_instance(inst)
        inst.initialize(cfg_args=cfg_args)

    def _recalculate_view_sizes(self, old_size):
        adjustable_dockable_views = [dock for dock in self.workspace.dockable_views
                                     if dock.widget().default_docking_position in ('left', 'bottom', 'right')]

        if not adjustable_dockable_views:
            return

        for dock in adjustable_dockable_views:
            widget = dock.widget()

            if old_size.width() < 0:
                dock.old_size = widget.sizeHint()
                continue

            if old_size != self.size():
                # calculate the width ratio

                if widget.default_docking_position == 'left':
                    # we want to adjust the width
                    ratio = dock.old_size.width() * 1.0 / old_size.width()
                    new_width = int(self.width() * ratio)
                    self._resize_dock_widget(dock, new_width, widget.height())
                elif widget.default_docking_position == 'bottom':
                    # we want to adjust the height
                    ratio = dock.old_size.height() * 1.0 / old_size.height()
                    new_height = int(self.height() * ratio)
                    self._resize_dock_widget(dock, widget.width(), new_height)

                dock.old_size = widget.size()


    def _resize_dock_widget(self, dock_widget, new_width, new_height):

        original_size = dock_widget.size()
        original_min = dock_widget.minimumSize()
        original_max = dock_widget.maximumSize()

        dock_widget.resize(new_width, new_height)

        if new_width != original_size.width():
            if original_size.width() > new_width:
                dock_widget.setMaximumWidth(new_width)
            else:
                dock_widget.setMinimumWidth(new_width)

        if new_height != original_size.height():
            if original_size.height() > new_height:
                dock_widget.setMaximumHeight(new_height)
            else:
                dock_widget.setMinimumHeight(new_height)

        dock_widget.original_min = original_min
        dock_widget.original_max = original_max

        QTimer.singleShot(1, dock_widget.restore_original_size)
Esempio n. 51
0
 def __init__(self, *args):
     QProgressBar.__init__(self, *args)
     with open("QProgressBar.qss") as f:
         self.setStyleSheet(f.read())