예제 #1
0
class LabelledSlider(QWidget):
    '''
    This class holds QSlider, budded to QLabel
    This is used only to simplify GUI creation 
    '''
    def __init__(self, labelText=QString(), orientation=Qt.Horizontal,
                 topLeftTuple=LEFT, parent=None):
        super(LabelledSlider, self).__init__(parent)
        
        self.labelText = labelText
        self.slider = QSlider(orientation)
        self.valueChanged = self.slider.valueChanged
        self.label = QLabel(self.labelText + ' ' + str(self.slider.value()))
        self.label.setBuddy(self.slider)
        self.slider.valueChanged.connect(self.sliderMove)
        layout = QBoxLayout(QBoxLayout.LeftToRight
                if topLeftTuple == LEFT else QBoxLayout.TopToBottom)
        layout.addWidget(self.label)
        layout.addWidget(self.slider)
        self.setLayout(layout)
        # Creating links to functions
        self.value = self.slider.value
        self.setValue = self.slider.setValue
        self.setMaximum = self.slider.setMaximum
        self.setMinimum = self.slider.setMinimum
        self.setText = self.label.setText
        self.text = self.label.text
    
    def sliderMove(self, value):
        self.label.setText(self.labelText + ' ' + str(value))
예제 #2
0
    def __init__(self, main_combo=False):
        super(ActionBar, self).__init__()
        self.setObjectName("actionbar")
        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(1, 1, 1, 1)
        hbox.setSpacing(1)

        self.lbl_checks = QLabel('')
        self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.lbl_checks.setFixedWidth(48)
        self.lbl_checks.setVisible(False)
        hbox.addWidget(self.lbl_checks)

        self.combo = QComboBox()
        self.combo.setIconSize(QSize(16, 16))
        #model = QStandardItemModel()
        #self.combo.setModel(model)
        #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove)
        self.combo.setMaximumWidth(300)
        self.combo.setObjectName("combotab")
        self.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
            self.current_changed)
        self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP)
        self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.combo, SIGNAL(
            "customContextMenuRequested(const QPoint &)"),
            self._context_menu_requested)
        hbox.addWidget(self.combo)

        self.symbols_combo = QComboBox()
        self.symbols_combo.setIconSize(QSize(16, 16))
        self.symbols_combo.setObjectName("combo_symbols")
        self.connect(self.symbols_combo, SIGNAL("activated(int)"),
            self.current_symbol_changed)
        hbox.addWidget(self.symbols_combo)

        self.code_navigator = CodeNavigator()
        hbox.addWidget(self.code_navigator)

        self._pos_text = "Line: %d, Col: %d"
        self.lbl_position = QLabel(self._pos_text % (0, 0))
        self.lbl_position.setObjectName("position")
        self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.lbl_position)

        self.btn_close = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btn_close.setIconSize(QSize(16, 16))
        if main_combo:
            self.btn_close.setObjectName('navigation_button')
            self.btn_close.setToolTip(translations.TR_CLOSE_FILE)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.about_to_close_file)
        else:
            self.btn_close.setObjectName('close_split')
            self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.close_split)
        self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.btn_close)
예제 #3
0
    def build_form(self, parameters):
        """Build a form from impact functions parameter.

        .. note:: see http://tinyurl.com/pyqt-differences

        :param parameters: Parameters to be edited
        """
        scroll_layout = QVBoxLayout()
        scroll_widget = QWidget()
        scroll_widget.setLayout(scroll_layout)
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(scroll_widget)
        self.configLayout.addWidget(scroll)

        for key, value in parameters.items():
            if key == 'postprocessors':
                self.build_post_processor_form(value)
            elif key == 'minimum needs':
                self.build_minimum_needs_form(value)
            else:
                self.build_widget(scroll_layout, key, value)

        if scroll_layout.count() == 0:
            # Rizky: in case empty impact function, let's show some messages
            label = QLabel()
            message = tr('This impact function does not have any options to '
                         'configure')
            label.setText(message)
            scroll_layout.addWidget(label)

        scroll_layout.addStretch()
예제 #4
0
 def _setupUi(self):
     self.setWindowTitle(tr("Error Report"))
     self.resize(553, 349)
     self.verticalLayout = QVBoxLayout(self)
     self.label = QLabel(self)
     self.label.setText(tr("Something went wrong. How about reporting the error?"))
     self.label.setWordWrap(True)
     self.verticalLayout.addWidget(self.label)
     self.errorTextEdit = QPlainTextEdit(self)
     self.errorTextEdit.setReadOnly(True)
     self.verticalLayout.addWidget(self.errorTextEdit)
     msg = tr(
         "Error reports should be reported as Github issues. You can copy the error traceback "
         "above and paste it in a new issue (bonus point if you run a search to make sure the "
         "issue doesn't already exist). What usually really helps is if you add a description "
         "of how you got the error. Thanks!"
         "\n\n"
         "Although the application should continue to run after this error, it may be in an "
         "unstable state, so it is recommended that you restart the application."
     )
     self.label2 = QLabel(msg)
     self.label2.setWordWrap(True)
     self.verticalLayout.addWidget(self.label2)
     self.horizontalLayout = QHBoxLayout()
     self.horizontalLayout.addItem(horizontalSpacer())
     self.dontSendButton = QPushButton(self)
     self.dontSendButton.setText(tr("Close"))
     self.dontSendButton.setMinimumSize(QSize(110, 0))
     self.horizontalLayout.addWidget(self.dontSendButton)
     self.sendButton = QPushButton(self)
     self.sendButton.setText(tr("Go to Github"))
     self.sendButton.setMinimumSize(QSize(110, 0))
     self.sendButton.setDefault(True)
     self.horizontalLayout.addWidget(self.sendButton)
     self.verticalLayout.addLayout(self.horizontalLayout)
예제 #5
0
    def __init__(self):
        QDockWidget.__init__(self, "Help")
        self.setObjectName("HelpDock")

        widget = QWidget()
        widget.setStyleSheet("background-color: #ffffe0")
        layout = QVBoxLayout()
        widget.setLayout(layout)

        self.link_widget = QLabel()
        self.link_widget.setStyleSheet("font-weight: bold")
        self.link_widget.setMinimumHeight(20)

        self.help_widget = QLabel(HelpDock.default_help_string)
        self.help_widget.setWordWrap(True)
        self.help_widget.setTextFormat(Qt.RichText)

        self.validation_widget = QLabel("")
        self.validation_widget.setWordWrap(True)
        self.validation_widget.setScaledContents(True)
        self.validation_widget.setAlignment(Qt.AlignHCenter)
        self.validation_widget.setTextFormat(Qt.RichText)


        layout.addWidget(self.link_widget)
        layout.addWidget(self.help_widget)
        layout.addStretch(1)
        layout.addWidget(self.validation_widget)

        self.setWidget(widget)

        self.help_messages = {}

        MessageCenter().addHelpMessageListeners(self)
예제 #6
0
파일: aboutdialog.py 프로젝트: agiz/orange3
    def __setupUi(self):
        layout = QVBoxLayout()
        label = QLabel(self)

        pixmap, _ = config.splash_screen()

        label.setPixmap(pixmap)

        layout.addWidget(label, Qt.AlignCenter)

        try:
            from Orange.version import version
            from Orange.version import hg_revision
        except ImportError:
            dist = pkg_resources.get_distribution("Orange")
            version = dist.version
            hg_revision = "Unknown"

        text = ABOUT_TEMPLATE.format(version=version,
                                     hg_revision=hg_revision)
        # TODO: Also list all known add-on versions.
        text_label = QLabel(text)
        layout.addWidget(text_label, Qt.AlignCenter)

        buttons = QDialogButtonBox(QDialogButtonBox.Close,
                                   Qt.Horizontal,
                                   self)
        layout.addWidget(buttons)
        buttons.rejected.connect(self.accept)
        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.setLayout(layout)
예제 #7
0
    def __init__(self, parent=None):
        super(aboutWidget, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle('LoL Server Status - About')
        self.setMinimumWidth(parent.width())
        self.move(parent.pos())
        self.setFocus(False)

        #label_title
        label_title = QLabel('LoL Server Status')
        label_title.setObjectName('label_title')
        label_title.setAlignment(Qt.AlignCenter)

        #label_source
        label_source = QLabel(
            'Source: <a style="color:#0073de" href="%s">Github repository</a>' %
            __source__)
        label_source.setToolTip('Github repository')
        label_source.setOpenExternalLinks(True)

        #btn_about_qt
        btn_about_qt = QPushButton('About Qt')

        #General layout
        vbox = QVBoxLayout(self)
        vbox.addWidget(label_title)
        vbox.addWidget(QLabel('Version: %s' % __version__))
        vbox.addWidget(QLabel('Author: %s' % __author__))
        vbox.addWidget(QLabel('License: %s' % __license__))
        vbox.addWidget(label_source)
        vbox.addWidget(btn_about_qt)

        #CONNECT SGNALS
        self.connect(btn_about_qt, SIGNAL('clicked()'), self.open_about_qt)
예제 #8
0
    def __init__(self, text_items, abstract, menu, parent=None):
        QWidget.__init__(self, parent)
        self.row_layout = QHBoxLayout(self)
        self.row_layout.setMargin(0)
        self.row_layout.setAlignment(Qt.AlignLeft)
        self.details_button = DetailsButton()
        self.row_layout.addWidget(self.details_button)

        for widget in (self.details_button, self):
            self.connect(widget, SIGNAL('clicked()'), self.updateView)

        for text in text_items:
            label = QLabel()
            label.setText("<h2>%s</h2>" % text)
            self.row_layout.addWidget(label)

        self.abstract = abstract

        if abstract is None:
            return

        self.row_layout.addWidget(abstract)
        self.row_layout.addStretch()

        self.edit_button = EditButton(menu)
        self.row_layout.addWidget(self.edit_button)
    def settings(self, parent):
        # CRIANDO O GRUPOBOXTEMPS PARA POR OS LABELS E LCD'S
        self.groupBoxTemps = QGroupBox(parent)

        # CRIANDO O LABEL PARA INFORMAR O QUE O LCD ESTÁ MOSTRANDO
        self.lbTemp1 = QLabel(self.groupBoxTemps)
        self.lbTemp1.setGeometry(QRect(70, 10, 127, 10))
        self.lbTemp1.setMaximumSize(QSize(16777215, 10))
        self.lbTemp1.setText("Termometro 1")
        self.lbTemp1.setAlignment(Qt.AlignCenter)

        # CRIANDO O LABEL PARA INFORMAR O QUE O LCD ESTÁ MOSTRANDO
        self.lbTemp2 = QLabel(self.groupBoxTemps)
        self.lbTemp2.setGeometry(QRect(330, 10, 130, 10))
        self.lbTemp2.setMaximumSize(QSize(16777215, 10))
        self.lbTemp2.setText("Termometro 2")
        self.lbTemp2.setAlignment(Qt.AlignCenter)

        # CRIANDO O LCD PARA INFORMAR A TEMPERATURA DO TERMOMETRO 1
        self.lcdTemp1 = QLCDNumber(self.groupBoxTemps)
        self.lcdTemp1.setGeometry(QRect(30, 30, 211, 71))
        self.lcdTemp1.display("00.00")
        self.lcdTemp1.setDigitCount(6)

        # CRIANDO O LCD PARA INFORMAR A TEMPERATURA DO TERMOMETRO 2
        self.lcdTemp2 = QLCDNumber(self.groupBoxTemps)
        self.lcdTemp2.setGeometry(QRect(290, 30, 211, 71))
        self.lcdTemp2.display("00.00")
        self.lcdTemp2.setDigitCount(6)

        # COLOCANDO LAYOUT NO GRUPOBOXTEMPS
        self.addWidget(self.groupBoxTemps)
예제 #10
0
class Organ(KeyboardPart):
    @staticmethod
    def title(_=__builtin__._):
        return _("Organ")
    
    @staticmethod
    def short(_=__builtin__._):
        return _("abbreviation for Organ", "Org.")
    
    midiInstrument = 'church organ'

    def createWidgets(self, layout):
        super(Organ, self).createWidgets(layout)
        grid = layout.itemAt(layout.count() - 1).layout()
        self.pedalVoices = QSpinBox(minimum=0, maximum=4, value=1)
        self.pedalVoicesLabel = QLabel()
        self.pedalVoicesLabel.setBuddy(self.pedalVoices)
        grid.addWidget(self.pedalVoicesLabel, 2, 0)
        grid.addWidget(self.pedalVoices)
        
    def translateWidgets(self):
        super(Organ, self).translateWidgets()
        self.pedalVoicesLabel.setText(_("Pedal:"))
        self.pedalVoices.setToolTip(_(
            "Set to 0 to disable the pedal altogether."))
    
    def build(self, data, builder):
        super(Organ, self).build(data, builder)
        if self.pedalVoices.value():
            data.nodes.append(self.buildStaff(data, builder,
                'pedal', -1, self.pedalVoices.value(), clef="bass"))
예제 #11
0
    def __init__(self, page):
        super(Printing, self).__init__(page)
        
        layout = QGridLayout(spacing=1)
        self.setLayout(layout)
        
        self.messageLabel = QLabel(wordWrap=True)
        self.printCommandLabel = QLabel()
        self.printCommand = widgets.urlrequester.UrlRequester()
        self.printCommand.setFileMode(QFileDialog.ExistingFile)
        self.printCommand.changed.connect(page.changed)
        self.printDialogCheck = QCheckBox(toggled=page.changed)
        self.resolutionLabel = QLabel()
        self.resolution = QComboBox(editable=True, editTextChanged=page.changed)
        self.resolution.addItems("300 600 1200".split())
        self.resolution.lineEdit().setInputMask("9000")

        layout.addWidget(self.messageLabel, 0, 0, 1, 2)
        layout.addWidget(self.printCommandLabel, 1, 0)
        layout.addWidget(self.printCommand, 1, 1)
        layout.addWidget(self.printDialogCheck, 2, 0, 1, 2)
        layout.addWidget(self.resolutionLabel, 3, 0)
        layout.addWidget(self.resolution, 3, 1)
        
        app.translateUI(self)
예제 #12
0
    def show(self, webPages):
        settings = Settings()
        server = xmlrpclib.Server(settings.serverAddress)

        self.setWindowTitle('updates')

        layout = self.layout()
        if layout == None:
            layout = QVBoxLayout()

        label = QLabel('Some Web Pages have changed:')
        layout.addWidget(label)

        for webPage in webPages:
            label = QLabel('<a href=' + webPage + '>' + self._truncate(webPage) + '</a>' )
            label.setOpenExternalLinks(True)
            layout.addWidget(label)

        #buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        moreButton = QPushButton('More...')
        moreButton.setMaximumWidth(60)
        self.connect(moreButton, SIGNAL('clicked()'), self.showDiffWindow)
        layout.addWidget(moreButton)

        self.setLayout(layout)

        if debug.verbose:
            print('DEBUG: Showing notification dialog')
        QDialog.show(self)

        QTimer.singleShot(0, self.fixPosition)
        QTimer.singleShot(self._timeout, self.hide)
예제 #13
0
 def __init__(self, page):
     super(TypographicalQuotes, self).__init__(page)
     
     layout = QGridLayout(spacing=1)
     self.setLayout(layout)
     l = self.languageLabel = QLabel()
     c = self.languageCombo = QComboBox(currentIndexChanged=self.languageChanged)
     l.setBuddy(c)
     
     self.primaryLabel = QLabel()
     self.secondaryLabel = QLabel()
     self.primaryLeft = QLineEdit(textEdited=self.changed)
     self.primaryRight = QLineEdit(textEdited=self.changed)
     self.secondaryLeft = QLineEdit(textEdited=self.changed)
     self.secondaryRight = QLineEdit(textEdited=self.changed)
     
     self._langs = ["current", "custom"]
     self._langs.extend(lang for lang in lasptyqu.available() if lang != "C")
     c.addItems(['' for i in self._langs])
     
     layout.addWidget(self.languageLabel, 0, 0)
     layout.addWidget(self.primaryLabel, 1, 0)
     layout.addWidget(self.secondaryLabel, 2, 0)
     layout.addWidget(self.languageCombo, 0, 1, 1, 2)
     layout.addWidget(self.primaryLeft, 1, 1)
     layout.addWidget(self.primaryRight, 1, 2)
     layout.addWidget(self.secondaryLeft, 2, 1)
     layout.addWidget(self.secondaryRight, 2, 2)
     
     app.translateUI(self)
    def _initInputUI(self, layout):
        self.setWindowTitle(self._title)
        messageLabel = QLabel(self._message, self)
        messageLabel.setWordWrap(True)
        layout.addWidget(messageLabel)

        inputWidget = QWidget(self)
        inputLayout = QHBoxLayout(inputWidget)
        inputLayout.setContentsMargins(0, 0, 0, 0)
                
        if type(self._initialBegin) != QTime:
            initialBegin = QTime.fromString(self._initialBegin, lunch_settings.LUNCH_TIME_FORMAT_QT)
        if type(self._initialEnd) != QTime:
            initialEnd = QTime.fromString(self._initialEnd, lunch_settings.LUNCH_TIME_FORMAT_QT)
                
        inputLayout.addWidget(QLabel("From", self))
        self.beginEdit = QTimeEdit(self)
        self.beginEdit.setDisplayFormat("HH:mm")
        self.beginEdit.setTime(initialBegin)
        inputLayout.addWidget(self.beginEdit)
        
        inputLayout.addWidget(QLabel("to", self))
        self.endEdit = QTimeEdit(self)
        self.endEdit.setDisplayFormat("HH:mm")
        self.endEdit.setTime(initialEnd)
        inputLayout.addWidget(self.endEdit)
        
        layout.addWidget(inputWidget, 0, Qt.AlignLeft)
예제 #15
0
파일: legend.py 프로젝트: Ensembles/ert
class Legend(QWidget):
    """Combines a LegendMarker with a label"""
    def __init__(self, legend, color):
        QWidget.__init__(self)

        self.setMinimumWidth(140)
        self.setMaximumHeight(25)

        self.legend = legend

        layout = QHBoxLayout()
        layout.setMargin(0)

        self.legend_marker = LegendMarker(color)
        self.legend_marker.setToolTip(legend)

        layout.addWidget(self.legend_marker)
        self.legend_label = QLabel(legend)
        layout.addWidget(self.legend_label)
        layout.addStretch()

        self.setLayout(layout)

    def setLegend(self, legend):
        self.legend_label.setText(legend)

    def updateLegend(self, *args):
        legend_text = self.legend % args
        self.legend_label.setText(legend_text)
        self.legend_marker.setToolTip(legend_text)

    def setColor(self, color):
        self.legend_marker.color = color
        self.legend_marker.update()
예제 #16
0
 def __init__(self, style, parentView, backgroundColor, foregroundColor, width, height):
     QLabel.__init__(self)
     self.setColors(backgroundColor, foregroundColor)
     self.setPixmapSize(width, height)
     self.setIcon(style)
     self._swapped = False
     self._rotation = 0
예제 #17
0
파일: utils.py 프로젝트: albfan/mikidown
    def __init__(self, path, parent=None):
        super(LineEditDialog, self).__init__(parent)
        self.path = path

        # newPage/newSubpage
        if parent.objectName() in ["mikiWindow", "notesTree"]:
            editorLabel = QLabel("Page Name:")
            self.extNames = [".md", ".markdown", ".mkd"]
        # Copy Image to notesEdit
        elif parent.objectName() == "notesEdit":
            editorLabel = QLabel("File Name:")
            self.extNames = ["", ".jpg"]
        else:
            return

        self.editor = QLineEdit()
        editorLabel.setBuddy(self.editor)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        layout = QGridLayout()
        layout.addWidget(editorLabel, 0, 0)
        layout.addWidget(self.editor, 0, 1)
        layout.addWidget(self.buttonBox, 1, 1)
        self.setLayout(layout)

        self.editor.textEdited.connect(self.updateUi)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
예제 #18
0
    def __init__( self, parent = None ):
        QWidget.__init__( self, parent )

        self.__reportUUID = ""
        self.__reportFileName = ""
        self.__reportOption = -1
        self.__reportShown = False
        self.__report = None

        self.__widgets = []

        # Prepare members for reuse
        if GlobalData().pylintAvailable:
            self.__noneLabel = QLabel( "\nNo results available" )
        else:
            self.__noneLabel = QLabel( "\nPylint is not available" )
        self.__noneLabel.setAutoFillBackground( True )
        noneLabelPalette = self.__noneLabel.palette()
        noneLabelPalette.setColor( QPalette.Background,
                                   GlobalData().skin.nolexerPaper )
        self.__noneLabel.setPalette( noneLabelPalette )

        self.__noneLabel.setFrameShape( QFrame.StyledPanel )
        self.__noneLabel.setAlignment( Qt.AlignHCenter )
        self.__headerFont = self.__noneLabel.font()
        self.__headerFont.setPointSize( self.__headerFont.pointSize() + 4 )
        self.__noneLabel.setFont( self.__headerFont )

        self.__createLayout( parent )

        self.__updateButtonsStatus()
        self.resizeEvent()
        return
예제 #19
0
class ProgressDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.resize(300, 75)
        self.setWindowTitle("Updating")
        self.vw = QWidget(self)
        self.vl = QVBoxLayout(self.vw)
        self.vl.setMargin(10)
        self.label = QLabel(self.vw)
        self.label.setText("<b>Downloading:</b> library.zip")
        self.vl.addWidget(self.label)
        self.horizontalLayoutWidget = QWidget()
        self.horizontalLayout = QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)
        self.progressbar = QProgressBar(self.horizontalLayoutWidget)
        self.progressbar.setFixedWidth(260)
        self.progressbar.setMinimum(0)
        self.progressbar.setMaximum(100)
        self.stopButton = QPushButton(self.horizontalLayoutWidget)
        self.stopButton.setFlat(True)
        self.stopButton.setIcon(Icons.stop)
        self.stopButton.setFixedSize(16,16)
        self.horizontalLayout.addWidget(self.progressbar)
        self.horizontalLayout.addWidget(self.stopButton)
        self.vl.addWidget(self.horizontalLayoutWidget)
        self.stopButton.clicked.connect(self.forceStop)
        
    def setValue(self,val):
        self.progressbar.setValue(val)
    def forceStop(self):
        self.emit(SIGNAL("forceStop"))
예제 #20
0
파일: mainwindow.py 프로젝트: daffodil/enki
class _StatusBar(QStatusBar):
    """Extended status bar. Supports HTML messages
    """
    def __init__(self, *args):
        QStatusBar.__init__(self, *args)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setSizeGripEnabled(False)
        self.setStyleSheet("QStatusBar {border: 0} QStatusBar::item {border: 0}")
        self._label = QLabel(self)
        self._label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self._label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self._label.setStyleSheet("color: red")
        self.addWidget(self._label)
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        self._timer.timeout.connect(self.clearMessage)
    
    def showMessage(self, text, timeout=0):
        """QStatusBar.showMessage()
        """
        self._label.setText(text)
        self._timer.stop()
        if timeout > 0:
            self._timer.start(timeout)
    
    def clearMessage(self):
        """QStatusBar.clearMessage()
        """
        self._label.clear()
예제 #21
0
    def __createScoreLabel( self, score, previousScore,
                            showFileName, fileName ):
        " Creates the score label "

        txt = "Score: " + str( score )
        if previousScore != "":
            txt += " / Previous score: " + str( previousScore )
        if not showFileName:
            txt += " for " + os.path.basename( fileName )

        scoreLabel = QLabel( txt )
        scoreLabel.setFrameShape( QFrame.StyledPanel )
        scoreLabel.setFont( self.__headerFont )
        scoreLabel.setAutoFillBackground( True )
        palette = scoreLabel.palette()

        if score < self.BadLimit:
            palette.setColor( QPalette.Background, QColor( 255, 127, 127 ) )
            palette.setColor( QPalette.Foreground, QColor( 0, 0, 0 ) )
        elif score > self.GoodLimit:
            palette.setColor( QPalette.Background, QColor( 220, 255, 220 ) )
            palette.setColor( QPalette.Foreground, QColor( 0, 0, 0 ) )
        else:
            palette.setColor( QPalette.Background, QColor( 255, 255, 127 ) )
            palette.setColor( QPalette.Foreground, QColor( 0, 0, 0 ) )

        scoreLabel.setPalette( palette )
        return scoreLabel
예제 #22
0
 def pix(self, pix):
     self.ui.imageView.setEnabled(True)
     self._pix = pix
     if self.pix_item is not None:
         self.scene.removeItem(self.pix_item)
     self.pix_item = self.scene.addPixmap(QPixmap.fromImage(pix))
     self.scene.setSceneRect(QRectF(self.pix.rect()))
     if self.show_pic_w:
         self.show_pic_w.close()
         self.show_pic_w = None
     if self.pic_w:
         self.show_pic_w = QLabel(self, Qt.Window)
         #self.show_pic_w.setAttribute(Qt.WA_DeleteOnClose)
         self.show_pic_w.setPicture(self.pic_w)
         self.show_pic_w.show()
         self.show_pic_w.raise_()
     if self.show_pic_c:
         self.show_pic_c.close()
         self.show_pic_c = None
     if self.pic_c:
         self.show_pic_c = QLabel(self, Qt.Window)
         #self.show_pic_c.setAttribute(Qt.WA_DeleteOnClose)
         self.show_pic_c.setPicture(self.pic_c)
         self.show_pic_c.show()
         self.show_pic_c.raise_()
     log_debug("Received image")
예제 #23
0
class View(QWidget):

    def __init__(self, status = None, Actions = None):
        super (View, self).__init__()
        self.actions = Actions
        self.name = QLabel("Experimental")
        self.rv = RegisterView()
        self.rv.set_pressed_signal.connect(self.register_set_pressed)
        self.rv.get_pressed_signal.connect(self.register_get_pressed)
        layout = QVBoxLayout()
        layout.addWidget(self.name)
        layout.addWidget(self.rv)
        self.setLayout(layout)

    def set_name(self, name):
        self.name.setText(name)

    def add_register(self, index, name, initial_value = 0):
        self.rv.add_register(index, name, initial_value)

    def set_register(self, index, value):
        self.rv.set_register(index, value)

    def register_set_pressed(self, index, value):
        self.actions.set_pressed.emit(index, value)

    def register_get_pressed(self, index):
        self.actions.get_pressed.emit(index)
예제 #24
0
파일: termwidget.py 프로젝트: daffodil/enki
 class Edit(defaultEditorClass):
     """Text editor class, which implements good size hints
     """
     def __init__(self, *args, **kwargs):
         defaultEditorClass.__init__(self, *args, **kwargs)
         self._sizeHintLabel = QLabel("asdf")
     
     def minimumSizeHint(self):
         """QWidget.minimumSizeHint implementation
         """
         lineHeight = self._calculateLineHeight()
         return QSize(lineHeight * 2, lineHeight * 2)
     
     def sizeHint(self):
         """QWidget.sizeHint implementation
         """
         lineHeight = self._calculateLineHeight()
         return QSize(lineHeight * 6, lineHeight * 6)
     
     def _calculateLineHeight(self):
         """Calculate height of one line of text
         """
         self._sizeHintLabel.setFont(QFont(core.config()["Editor"]["DefaultFont"],
                                           core.config()["Editor"]["DefaultFontSize"]))
         return self._sizeHintLabel.sizeHint().height()
예제 #25
0
 def getText(cls,
             parent=None,
             windowTitle='Get Text',
             label='',
             text='',
             plain=True,
             wrapped=True):
     """
     Prompts the user for a text entry using the text edit class.
     
     :param      parent | <QWidget>
                 windowTitle | <str>
                 label       | <str>
                 text        | <str>
                 plain       | <bool> | return plain text or not
     
     :return     (<str> text, <bool> accepted)
     """
     # create the dialog
     dlg = QDialog(parent)
     dlg.setWindowTitle(windowTitle)
     
     # create the layout
     layout = QVBoxLayout()
     
     # create the label
     if label:
         lbl = QLabel(dlg)
         lbl.setText(label)
         layout.addWidget(lbl)
     
     # create the widget
     widget = cls(dlg)
     widget.setText(text)
     
     if not wrapped:
         widget.setLineWrapMode(XTextEdit.NoWrap)
     
     layout.addWidget(widget)
     
     # create the buttons
     btns = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
                             Qt.Horizontal,
                             dlg)
     layout.addWidget(btns)
     
     dlg.setLayout(layout)
     dlg.adjustSize()
     
     # create connections
     btns.accepted.connect(dlg.accept)
     btns.rejected.connect(dlg.reject)
     
     if dlg.exec_():
         if plain:
             return (widget.toPlainText(), True)
         else:
             return (widget.toHtml(), True)
     else:
         return ('', False)
예제 #26
0
class ProgressDialog(QDialog):


    def __init__(self, title, description, parent):

        super(ProgressDialog, self).__init__(parent)

        self.setWindowTitle(title)


        self.label = QLabel(description, self)
        self.label.setContentsMargins(2, 0, 0, 0)
        self.progress = QProgressBar(self)

        self._createlayout()

    def _createlayout(self):


        l = QVBoxLayout()

        l.addWidget(self.label)
        l.addWidget(self.progress)


        self.setLayout(l)
예제 #27
0
    def  __init__(self, image_width, image_height, parent=None):
        super(UserButtonMenu, self).__init__(parent)
        
        self.image_width = image_width
        self.image_height = image_height

        self.label = QLabel(self)
        self.label.setScaledContents(True)
        self.label.setSizePolicy(
                QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored))

        self.imageLabel = QLabel(self)
        self.imageLabel.setScaledContents(True)
        self.imageLabel.setSizePolicy(
                QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        self.setSizePolicy(
                QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        self.userMenu = QMenu('user accounts menu') # TODO Remove magic

        hbox = QHBoxLayout()
        hbox.addWidget(self.imageLabel)
        hbox.addWidget(self.label)
        self.setLayout(hbox)
        self.setMenu(self.userMenu)
예제 #28
0
    def __createLayout( self ):
        " Creates the layout "
        self.setFixedHeight( 24 )
        self.__layout = QHBoxLayout( self )
        self.__layout.setMargin( 0 )
        self.__layout.setContentsMargins( 0, 0, 0, 0 )

        # Create info icon
        self.__infoIcon = QLabel()
        self.__infoIcon.setPixmap( getPixmap( 'cfunknown.png' ) )
        self.__layout.addWidget( self.__infoIcon )
        self.__spacer = QWidget()
        self.__spacer.setSizePolicy( QSizePolicy.Fixed, QSizePolicy.Expanding )
        self.__spacer.setMinimumWidth( 0 )
        self.__layout.addWidget( self.__spacer )
#        self.__pathLabel = FitLabel( self )
        self.__pathLabel = QLabel( self )
        self.__pathLabel.setTextFormat( Qt.PlainText )
        self.__pathLabel.setAlignment( Qt.AlignLeft )
        self.__pathLabel.setWordWrap( False )
        self.__pathLabel.setFrameStyle( QFrame.StyledPanel )
        self.__pathLabel.setTextInteractionFlags( Qt.NoTextInteraction )
        self.__pathLabel.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )
        self.__layout.addWidget( self.__pathLabel )
        return
예제 #29
0
    def __init__(self, parent=None, icon=QIcon(), text="", wordWrap=False,
                 textFormat=Qt.AutoText, standardButtons=NoButton, **kwargs):
        super().__init__(parent, **kwargs)
        self.__text = text
        self.__icon = QIcon()
        self.__wordWrap = wordWrap
        self.__standardButtons = MessageWidget.NoButton
        self.__buttons = []

        layout = QHBoxLayout()
        layout.setContentsMargins(8, 0, 8, 0)

        self.__iconlabel = QLabel(objectName="icon-label")
        self.__iconlabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.__textlabel = QLabel(objectName="text-label", text=text,
                                  wordWrap=wordWrap, textFormat=textFormat)

        if sys.platform == "darwin":
            self.__textlabel.setAttribute(Qt.WA_MacSmallSize)

        layout.addWidget(self.__iconlabel)
        layout.addWidget(self.__textlabel)

        self.setLayout(layout)
        self.setIcon(icon)
        self.setStandardButtons(standardButtons)
예제 #30
0
파일: about.py 프로젝트: debianitram/side
    def __init__(self, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("About SIDE-C"))
        self.setMaximumSize(QSize(0, 0))
        

        vbox = QVBoxLayout(self)

        #Create an icon for the Dialog
        # pixmap = QPixmap(":img/icon")
        # self.lblIcon = QLabel()
        # self.lblIcon.setPixmap(pixmap)

        hbox = QHBoxLayout()
        # hbox.addWidget(self.lblIcon)

        lblTitle = QLabel(
                '<h1>SIDE - C</h1>\n<i>Simple Integrated Development Environment for C<i>')
        lblTitle.setTextFormat(Qt.RichText)
        lblTitle.setAlignment(Qt.AlignLeft)
        hbox.addWidget(lblTitle)
        vbox.addLayout(hbox)
        #Add description
        vbox.addWidget(QLabel(
self.tr("""ALGO ACA""")))
        vbox.addWidget(QLabel("Hola"))
        link_ninja = QLabel(
            self.tr('Website: '))
        vbox.addWidget(link_ninja)
        link_source = QLabel(
            self.tr('Source Code'))
        vbox.addWidget(link_source)
class NumberBoxPanel(QWidget):
    def __init__(self, parent, resoution="0.0000"):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("NumberBoxPanel" +
                           str(len(parent.findChildren(NumberBoxPanel))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        if resoution != None:
            self.numberBox = QLineEdit(self.frameBoxPanel)
            self.numberBox.setEnabled(True)
            font = QFont()
            font.setBold(False)
            font.setWeight(50)
            self.numberBox.setFont(font)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setText("0.0")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)
            self.numberBox.textChanged.connect(self.numberBoxChanged)
            self.numberBox.editingFinished.connect(
                self.numberBoxEditingFinished)
        else:
            self.numberBox = QSpinBox(self.frameBoxPanel)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.numberBox.setMinimum(-100000000)
            self.numberBox.setMaximum(100000000)
            self.numberBox.setValue(1)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)

        self.imageButton = QPushButton(self.frameBoxPanel)

        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)

        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.numberResolution = resoution
        str0 = String.Number2String(6.6788, "0.0000")
        self.Value = 0
        self.captionUnits = ""

    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_1"), self)

    def method_6(self, string_0):
        return "%s%s\t%f %s" % (string_0, self.Caption, self.Value,
                                self.CaptionUnits)

    def numberBoxEditingFinished(self):
        self.emit(SIGNAL("editingFinished"), self)

    def numberBoxChanged(self):
        try:
            test = float(self.numberBox.text())
            self.emit(SIGNAL("Event_0"), self)
        except:
            if self.numberBox.text() == "" or self.numberBox.text(
            ) == "-" or self.numberBox.text() == "+":
                return
            str0 = "You must input the float type in \"%s\"." % (self.Caption)
            QMessageBox.warning(self, "Warning", str0)
            self.numberBox.setText("0.0")

    def get_CaptionUnits(self):
        return self.captionUnits

    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption

    def set_Caption(self, captionStr):
        if self.CaptionUnits != "" and self.CaptionUnits != None:
            self.captionLabel.setText(
                QString(captionStr + "(") + self.CaptionUnits + QString("):"))
        else:
            self.captionLabel.setText(captionStr + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def get_Value(self):
        try:
            if self.numberResolution != None:
                return float(self.numberBox.text())
            else:
                return self.numberBox.value()
        except:
            return 0.0

    def set_Value(self, valueFloat):
        if self.numberResolution != None:
            if valueFloat == None or valueFloat == "":
                rStr = String.Number2String(0, self.numberResolution)
                self.numberBox.setText(rStr)
                return
            try:
                test = float(valueFloat)
                rStr = String.Number2String(test, self.numberResolution)
                self.numberBox.setText(rStr)
            except:
                str0 = "You must put the float type in \"%s\"." % (
                    self.Caption)
                QMessageBox.warning(self, "Warning", str0)
                rStr = String.Number2String(0, self.numberResolution)
                self.numberBox.setText(rStr)
        else:
            try:
                test = int(valueFloat)
                self.numberBox.setValue(test)
            except:
                str0 = "You must put the float type in \"%s\"." % (
                    self.Caption)
                QMessageBox.warning(self, "Warning", str0)
                self.numberBox.setValue(0)

    Value = property(get_Value, set_Value, None, None)

    # def get_IsEmpty(self):
    #     return self.numberBox.text() == "" or self.numberBox.text() == None
    # IsEmpty = property(get_IsEmpty, None, None, None)

    def get_ReadOnly(self):
        return self.numberBox.isReadOnly()

    def set_ReadOnly(self, bool):
        self.numberBox.setReadOnly(bool)

    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def set_Width(self, width):
        self.numberBox.setMinimumSize(QSize(width, 0))
        self.numberBox.setMaximumSize(QSize(width, 16777215))

    Width = property(None, set_Width, None, None)

    def get_Enabled(self):
        return self.isEnabled()

    def set_Enabled(self, bool):
        self.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)

    Button = property(None, set_Button, None, None)
예제 #32
0
class RecordingWidget(QWidget):
    """Widget containing main recording UI for Freeseer"""
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.resize(400, 400)

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.setStyleSheet("""
            QToolButton {
                background-color: #D1D1D1;
                border-style: solid;
                border-width: 1px;
                border-radius: 10px;
                border-color: #969696;
                padding: 6px;
            }

            QToolButton:pressed {
                background-color: #A3A2A2;
                border-width: 2px;
                border-color: #707070;
            }

            QToolButton:checked {
                background-color: #A3A2A2;
                border-width: 2px;
                border-color: #707070;
            }

            QToolButton:disabled {
                background-color: #EDEDED;
                border-color: #BFBDBD;
            }

            QToolButton:hover {
                border-width: 2px;
            }
        """)

        boldFont = QFont()
        boldFont.setBold(True)

        fontSize = self.font().pixelSize()
        fontUnit = "px"
        if fontSize == -1:  # Font is set as points, not pixels.
            fontUnit = "pt"
            fontSize = self.font().pointSize()

        # Control bar
        self.controlRow = QHBoxLayout()
        self.mainLayout.addLayout(self.controlRow)

        self.recordIcon = QIcon(":/multimedia/record.png")
        self.stopIcon = QIcon(":/multimedia/stop.png")
        pauseIcon = QIcon(":/multimedia/pause.png")
        playIcon = QIcon(":/multimedia/play.png")
        self.headphoneIcon = QIcon()
        self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"),
                                     QIcon.Normal, QIcon.Off)

        self.is_recording = False
        self.recordButton = QToolButton()
        self.recordButton.setToolTip("Record")
        self.recordButton.setFixedSize(QSize(60, 40))
        self.recordButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.recordButton.setIcon(self.recordIcon)
        self.recordButton.setEnabled(False)
        self.recordButton.setObjectName("recordButton")
        self.controlRow.addWidget(self.recordButton, 0, Qt.AlignLeft)
        self.connect(self.recordButton, SIGNAL("clicked()"),
                     self.setRecordIcon)

        self.playButton = QToolButton()
        self.playButton.setToolTip("Play last recorded Video")
        self.playButton.setFixedSize(QSize(60, 40))
        self.playButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.playButton.setIcon(playIcon)
        self.playButton.setEnabled(False)
        self.controlRow.addWidget(self.playButton, 0, Qt.AlignLeft)

        self.pauseButton = QToolButton()
        self.pauseButton.setToolTip("Pause")
        self.pauseButton.setIcon(pauseIcon)
        self.pauseButton.setFixedSize(QSize(60, 40))
        self.pauseButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.pauseButton.setEnabled(False)
        self.pauseButton.setCheckable(True)
        self.controlRow.addWidget(self.pauseButton, 0, Qt.AlignLeft)

        self.controlRow.addSpacerItem(QSpacerItem(30, 40))
        self.controlRow.addStretch(1)

        self.standbyButton = QPushButton("Standby")
        self.standbyButton.setStyleSheet("""
            QPushButton {{
                color: white;
                background-color: #47a447;
                border-style: solid;
                border-width: 0px;
                border-radius: 10px;
                border-color: #398439;
                font: bold {}{};
                padding: 6px;
            }}

            QPushButton:pressed {{
                background-color: #3E8A3E;
                border-color: #327532;
            }}

            QPushButton:hover {{
                border-width: 2px;
            }}
        """.format(fontSize + 3, fontUnit))
        self.standbyButton.setToolTip("Standby")
        self.standbyButton.setFixedSize(QSize(180, 40))
        self.standbyButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.standbyButton.setCheckable(True)
        self.standbyButton.setObjectName("standbyButton")
        self.controlRow.addWidget(self.standbyButton)

        self.disengageButton = QPushButton("Leave record-mode")
        self.disengageButton.setStyleSheet("""
            QPushButton {{
                color: white;
                background-color: #D14343;
                border-style: solid;
                border-width: 0px;
                border-radius: 10px;
                border-color: #B02C2C;
                font: bold {}{};
                padding: 6px;
            }}

            QPushButton:pressed {{
                background-color: #AD2B2B;
                border-color: #8C2929;
            }}

            QPushButton:hover {{
                border-width: 2px;
            }}

            QPushButton:disabled {{
                background-color: #B89E9E;
        }}
        """.format(fontSize + 3, fontUnit))
        self.disengageButton.setToolTip("Leave record-mode")
        self.disengageButton.setFixedSize(QSize(180, 40))
        self.disengageButton.setSizePolicy(QSizePolicy.Fixed,
                                           QSizePolicy.Fixed)
        self.disengageButton.setHidden(True)
        self.disengageButton.setObjectName("disengageButton")
        self.controlRow.addWidget(self.disengageButton)

        # Filter bar
        self.filterBarLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.filterBarLayout)

        self.filterBarLayoutRow_1 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_1)
        self.eventLabel = QLabel("Event")
        self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.eventComboBox = QComboBox()
        self.eventLabel.setBuddy(self.eventComboBox)
        self.roomLabel = QLabel("Room")
        self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.roomComboBox = QComboBox()
        self.roomLabel.setBuddy(self.roomComboBox)
        self.dateLabel = QLabel("Date")
        self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.dateComboBox = QComboBox()
        self.dateLabel.setBuddy(self.dateComboBox)
        self.filterBarLayoutRow_1.addWidget(self.eventLabel)
        self.filterBarLayoutRow_1.addWidget(self.eventComboBox)
        self.filterBarLayoutRow_1.addWidget(self.roomLabel)
        self.filterBarLayoutRow_1.addWidget(self.roomComboBox)
        self.filterBarLayoutRow_1.addWidget(self.dateLabel)
        self.filterBarLayoutRow_1.addWidget(self.dateComboBox)

        self.filterBarLayoutRow_2 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_2)
        self.talkLabel = QLabel("Talk ")
        self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.talkComboBox = QComboBox()
        self.talkComboBox.setFont(boldFont)
        self.talkComboBox.setSizePolicy(QSizePolicy.Minimum,
                                        QSizePolicy.Maximum)
        self.talkComboBox.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLength)
        self.filterBarLayoutRow_2.addWidget(self.talkLabel)
        self.filterBarLayoutRow_2.addWidget(self.talkComboBox)

        # Preview Layout
        self.previewLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.previewLayout)

        self.previewWidget = QWidget()
        self.audioSlider = QSlider()
        self.audioSlider.setSizePolicy(QSizePolicy.Fixed,
                                       QSizePolicy.Expanding)
        self.audioSlider.setEnabled(False)
        self.previewLayout.addWidget(self.previewWidget)
        self.previewLayout.addWidget(self.audioSlider)

        self.statusLabel = QLabel()
        self.mainLayout.addWidget(self.statusLabel)

        # Audio Feedback Checkbox
        self.audioFeedbackCheckbox = QCheckBox()
        self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft)
        self.audioFeedbackCheckbox.setIcon(self.headphoneIcon)
        self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback")
        self.mainLayout.addWidget(self.audioFeedbackCheckbox)

    def setRecordIcon(self):
        self.is_recording = not self.is_recording
        if self.is_recording:
            self.recordButton.setIcon(self.stopIcon)
        else:
            self.recordButton.setIcon(self.recordIcon)
 def __init__(self, parent, item):
     QWidget.__init__(self, parent)
     self.gridLayout_2 = QGridLayout(self)
     self.gridLayout_2.setObjectName(("gridLayout_2"))
     self.mMapPositionFixedCheckBox = QCheckBox(self)
     self.mMapPositionFixedCheckBox.setObjectName(("mMapPositionFixedCheckBox"))
     self.gridLayout_2.addWidget(self.mMapPositionFixedCheckBox, 0, 0, 1, 1)
     self.gridLayout = QGridLayout()
     self.gridLayout.setObjectName(("gridLayout"))
     self.mFrameColorButton = QgsColorButton(self)
     self.mFrameColorButton.setText((""))
     self.mFrameColorButton.setObjectName(("mFrameColorButton"))
     self.gridLayout.addWidget(self.mFrameColorButton, 3, 1, 1, 1)
     self.mFrameColorButton.colorChanged.connect(self.on_mFrameColorButton_colorChanged)
     self.mBackgroundColorLabel = QLabel(self)
     self.mBackgroundColorLabel.setObjectName(("mBackgroundColorLabel"))
     self.gridLayout.addWidget(self.mBackgroundColorLabel, 2, 0, 1, 1)
     self.mMapMarkerLabel = QLabel(self)
     self.mMapMarkerLabel.setObjectName(("mMapMarkerLabel"))
     self.gridLayout.addWidget(self.mMapMarkerLabel, 0, 0, 1, 1)
     self.mBackgroundColorButton = QgsColorButton(self)
     self.mBackgroundColorButton.setText((""))
     self.mBackgroundColorButton.setObjectName(("mBackgroundColorButton"))
     self.gridLayout.addWidget(self.mBackgroundColorButton, 2, 1, 1, 1)
     self.mBackgroundColorButton.colorChanged.connect(self.on_mBackgroundColorButton_colorChanged)
     self.mMapMarkerButton = QPushButton(self)
     self.mMapMarkerButton.setText((""))
     self.mMapMarkerButton.setObjectName(("mMapMarkerButton"))
     self.gridLayout.addWidget(self.mMapMarkerButton, 0, 1, 1, 1)
     self.mMapMarkerButton.clicked.connect(self.on_mMapMarkerButton_clicked)
     self.mFrameWidthLabel = QLabel(self)
     self.mFrameWidthLabel.setObjectName(("mFrameWidthLabel"))
     self.gridLayout.addWidget(self.mFrameWidthLabel, 1, 0, 1, 1)
     self.mFrameWidthSpinBox = QDoubleSpinBox(self)
     self.mFrameWidthSpinBox.setObjectName(("mFrameWidthSpinBox"))
     self.gridLayout.addWidget(self.mFrameWidthSpinBox, 1, 1, 1, 1)
     self.mFrameColorLabel = QLabel(self)
     self.mFrameColorLabel.setObjectName(("mFrameColorLabel"))
     self.gridLayout.addWidget(self.mFrameColorLabel, 3, 0, 1, 1)
     self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1)
     self.mMapMarkerLabel.setBuddy(self.mMapMarkerButton)
     self.mFrameWidthLabel.setBuddy(self.mFrameWidthSpinBox)
             
     self.setWindowTitle("QgsAnnotationWidgetBase")
     self.mMapPositionFixedCheckBox.setText("Fixed map position")
     self.mBackgroundColorLabel.setText("Background color")
     self.mMapMarkerLabel.setText("Map marker")
     self.mFrameWidthLabel.setText( "Frame width")
     self.mFrameColorLabel.setText( "Frame color")
     self.setLayout(self.gridLayout_2)
     self.mItem = item
     if ( self.mItem != None ):
         self.blockAllSignals( True )
         
         if ( self.mItem.mapPositionFixed() ):
             self.mMapPositionFixedCheckBox.setCheckState( Qt.Checked )
         else:
             self.mMapPositionFixedCheckBox.setCheckState( Qt.Unchecked )
         
         self.mFrameWidthSpinBox.setValue( self.mItem.frameBorderWidth() )
         self.mFrameColorButton.setColor( self.mItem.frameColor() )
         self.mFrameColorButton.setColorDialogTitle(  "Select frame color" )
         self.mFrameColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
         self.mBackgroundColorButton.setColor( self.mItem.frameBackgroundColor() )
         self.mBackgroundColorButton.setColorDialogTitle(  "Select background color"  )
         self.mBackgroundColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
         self.symbol = self.mItem.markerSymbol()
         if ( self.symbol != None ):
             self.mMarkerSymbol =  self.symbol.clone() 
             self.updateCenterIcon()
         self.blockAllSignals( False )
class QgsAnnotationWidget(QWidget):
    def __init__(self, parent, item):
        QWidget.__init__(self, parent)
        self.gridLayout_2 = QGridLayout(self)
        self.gridLayout_2.setObjectName(("gridLayout_2"))
        self.mMapPositionFixedCheckBox = QCheckBox(self)
        self.mMapPositionFixedCheckBox.setObjectName(("mMapPositionFixedCheckBox"))
        self.gridLayout_2.addWidget(self.mMapPositionFixedCheckBox, 0, 0, 1, 1)
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName(("gridLayout"))
        self.mFrameColorButton = QgsColorButton(self)
        self.mFrameColorButton.setText((""))
        self.mFrameColorButton.setObjectName(("mFrameColorButton"))
        self.gridLayout.addWidget(self.mFrameColorButton, 3, 1, 1, 1)
        self.mFrameColorButton.colorChanged.connect(self.on_mFrameColorButton_colorChanged)
        self.mBackgroundColorLabel = QLabel(self)
        self.mBackgroundColorLabel.setObjectName(("mBackgroundColorLabel"))
        self.gridLayout.addWidget(self.mBackgroundColorLabel, 2, 0, 1, 1)
        self.mMapMarkerLabel = QLabel(self)
        self.mMapMarkerLabel.setObjectName(("mMapMarkerLabel"))
        self.gridLayout.addWidget(self.mMapMarkerLabel, 0, 0, 1, 1)
        self.mBackgroundColorButton = QgsColorButton(self)
        self.mBackgroundColorButton.setText((""))
        self.mBackgroundColorButton.setObjectName(("mBackgroundColorButton"))
        self.gridLayout.addWidget(self.mBackgroundColorButton, 2, 1, 1, 1)
        self.mBackgroundColorButton.colorChanged.connect(self.on_mBackgroundColorButton_colorChanged)
        self.mMapMarkerButton = QPushButton(self)
        self.mMapMarkerButton.setText((""))
        self.mMapMarkerButton.setObjectName(("mMapMarkerButton"))
        self.gridLayout.addWidget(self.mMapMarkerButton, 0, 1, 1, 1)
        self.mMapMarkerButton.clicked.connect(self.on_mMapMarkerButton_clicked)
        self.mFrameWidthLabel = QLabel(self)
        self.mFrameWidthLabel.setObjectName(("mFrameWidthLabel"))
        self.gridLayout.addWidget(self.mFrameWidthLabel, 1, 0, 1, 1)
        self.mFrameWidthSpinBox = QDoubleSpinBox(self)
        self.mFrameWidthSpinBox.setObjectName(("mFrameWidthSpinBox"))
        self.gridLayout.addWidget(self.mFrameWidthSpinBox, 1, 1, 1, 1)
        self.mFrameColorLabel = QLabel(self)
        self.mFrameColorLabel.setObjectName(("mFrameColorLabel"))
        self.gridLayout.addWidget(self.mFrameColorLabel, 3, 0, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1)
        self.mMapMarkerLabel.setBuddy(self.mMapMarkerButton)
        self.mFrameWidthLabel.setBuddy(self.mFrameWidthSpinBox)
                
        self.setWindowTitle("QgsAnnotationWidgetBase")
        self.mMapPositionFixedCheckBox.setText("Fixed map position")
        self.mBackgroundColorLabel.setText("Background color")
        self.mMapMarkerLabel.setText("Map marker")
        self.mFrameWidthLabel.setText( "Frame width")
        self.mFrameColorLabel.setText( "Frame color")
        self.setLayout(self.gridLayout_2)
        self.mItem = item
        if ( self.mItem != None ):
            self.blockAllSignals( True )
            
            if ( self.mItem.mapPositionFixed() ):
                self.mMapPositionFixedCheckBox.setCheckState( Qt.Checked )
            else:
                self.mMapPositionFixedCheckBox.setCheckState( Qt.Unchecked )
            
            self.mFrameWidthSpinBox.setValue( self.mItem.frameBorderWidth() )
            self.mFrameColorButton.setColor( self.mItem.frameColor() )
            self.mFrameColorButton.setColorDialogTitle(  "Select frame color" )
            self.mFrameColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
            self.mBackgroundColorButton.setColor( self.mItem.frameBackgroundColor() )
            self.mBackgroundColorButton.setColorDialogTitle(  "Select background color"  )
            self.mBackgroundColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
            self.symbol = self.mItem.markerSymbol()
            if ( self.symbol != None ):
                self.mMarkerSymbol =  self.symbol.clone() 
                self.updateCenterIcon()
            self.blockAllSignals( False )
        
    def apply(self):
        if ( self.mItem != None ):
            self.mItem.setMapPositionFixed( self.mMapPositionFixedCheckBox.checkState() == Qt.Checked )
            self.mItem.setFrameBorderWidth( self.mFrameWidthSpinBox.value() )
            self.mItem.setFrameColor( self.mFrameColorButton.color() )
            self.mItem.setFrameBackgroundColor( self.mBackgroundColorButton.color() )
            self.mItem.setMarkerSymbol( self.mMarkerSymbol )
            self.mMarkerSymbol = None  #//item takes ownership
            self.mItem.update()
        
    def blockAllSignals(self, block ):
        self.mMapPositionFixedCheckBox.blockSignals( block )
        self.mMapMarkerButton.blockSignals( block )
        self.mFrameWidthSpinBox.blockSignals( block )
        self.mFrameColorButton.blockSignals( block )
    def on_mMapMarkerButton_clicked(self):
        if ( self.mMarkerSymbol == None ):
            return
        markerSymbol = self.mMarkerSymbol.clone() 
        dlg = QgsSymbolV2SelectorDialog ( markerSymbol, QgsStyleV2.defaultStyle(), None, self )
        if ( dlg.exec_()!= QDialog.Rejected ):
            self.mMarkerSymbol = markerSymbol
            self.updateCenterIcon()
    def on_mFrameColorButton_colorChanged(self, color ):
        if ( self.mItem == None):
            return
        self.mItem.setFrameColor( color )
        
    def updateCenterIcon(self):
        if ( self.mMarkerSymbol == None ):
            return
        icon = QgsSymbolLayerV2Utils.symbolPreviewIcon( self.mMarkerSymbol, self.mMapMarkerButton.iconSize() )
        self.mMapMarkerButton.setIcon( icon )
    def on_mBackgroundColorButton_colorChanged(self, color ):
        if ( self.mItem == None ):
            return
        self.mItem.setFrameBackgroundColor( color )
예제 #35
0
    def __init__(self,
                 parent=None,
                 signalManager=None,
                 name="Databases update",
                 domains=None):
        OWWidget.__init__(self,
                          parent,
                          signalManager,
                          name,
                          wantMainArea=False)

        self.searchString = ""
        self.accessCode = ""
        self.domains = domains or DOMAINS
        self.serverFiles = serverfiles.ServerFiles()

        fbox = gui.widgetBox(self.controlArea, "Filter")

        # The completer model token strings
        self.completertokens = []
        # A 'dynamic' completer item model will be updated with
        # 'prefix {token}' where prefix is current 'active' filter list
        # (the QCompleter only completes on one item in the model)
        self.completermodel = QStringListModel(self)
        self.completer = QCompleter(self.completermodel,
                                    self,
                                    caseSensitivity=Qt.CaseInsensitive)

        self.lineEditFilter = QLineEdit(textChanged=self.SearchUpdate)

        self.lineEditFilter.setCompleter(self.completer)

        fbox.layout().addWidget(self.lineEditFilter)

        box = gui.widgetBox(self.controlArea, "Files")

        self.filesView = QTreeWidget(self)
        self.filesView.setHeaderLabels(
            ["", "Data Source", "Update", "Last Updated", "Size"])

        self.filesView.setRootIsDecorated(False)
        self.filesView.setUniformRowHeights(True)
        self.filesView.setSelectionMode(QAbstractItemView.NoSelection)
        self.filesView.setSortingEnabled(True)
        self.filesView.sortItems(1, Qt.AscendingOrder)
        self.filesView.setItemDelegateForColumn(
            0, UpdateOptionsItemDelegate(self.filesView))

        self.filesView.model().layoutChanged.connect(self.SearchUpdate)

        box.layout().addWidget(self.filesView)

        box = gui.widgetBox(self.controlArea, orientation="horizontal")
        self.updateButton = gui.button(
            box,
            self,
            "Update all",
            callback=self.UpdateAll,
            tooltip="Update all updatable files",
        )

        self.downloadButton = gui.button(
            box,
            self,
            "Download all",
            callback=self.DownloadFiltered,
            tooltip="Download all filtered files shown")

        self.cancelButton = gui.button(
            box,
            self,
            "Cancel",
            callback=self.Cancel,
            tooltip="Cancel scheduled downloads/updates.")

        self.retryButton = gui.button(box,
                                      self,
                                      "Reconnect",
                                      callback=self.RetrieveFilesList)
        self.retryButton.hide()

        gui.rubber(box)

        gui.lineEdit(box,
                     self,
                     "accessCode",
                     "Access Code",
                     orientation="horizontal",
                     callback=self.RetrieveFilesList)

        self.warning(0)

        box = gui.widgetBox(self.controlArea, orientation="horizontal")
        gui.rubber(box)

        self.infoLabel = QLabel()
        self.infoLabel.setAlignment(Qt.AlignCenter)

        self.controlArea.layout().addWidget(self.infoLabel)
        self.infoLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        self.updateItems = []

        self.resize(800, 600)

        self.progress = ProgressState(self, maximum=3)
        self.progress.valueChanged.connect(self._updateProgress)
        self.progress.rangeChanged.connect(self._updateProgress)
        self.executor = ThreadExecutor(threadPool=QThreadPool(
            maxThreadCount=2))

        task = Task(self, function=self.RetrieveFilesList)
        task.exceptionReady.connect(self.HandleError)
        task.start()

        self._tasks = []
        self._haveProgress = False
예제 #36
0
class OWDatabasesUpdate(OWWidget):

    name = "Databases Update"
    description = "Update local systems biology databases."
    icon = "../widgets/icons/Databases.svg"
    priority = 10

    inputs = []
    outputs = []

    want_main_area = False

    def __init__(self,
                 parent=None,
                 signalManager=None,
                 name="Databases update",
                 domains=None):
        OWWidget.__init__(self,
                          parent,
                          signalManager,
                          name,
                          wantMainArea=False)

        self.searchString = ""
        self.accessCode = ""
        self.domains = domains or DOMAINS
        self.serverFiles = serverfiles.ServerFiles()

        fbox = gui.widgetBox(self.controlArea, "Filter")

        # The completer model token strings
        self.completertokens = []
        # A 'dynamic' completer item model will be updated with
        # 'prefix {token}' where prefix is current 'active' filter list
        # (the QCompleter only completes on one item in the model)
        self.completermodel = QStringListModel(self)
        self.completer = QCompleter(self.completermodel,
                                    self,
                                    caseSensitivity=Qt.CaseInsensitive)

        self.lineEditFilter = QLineEdit(textChanged=self.SearchUpdate)

        self.lineEditFilter.setCompleter(self.completer)

        fbox.layout().addWidget(self.lineEditFilter)

        box = gui.widgetBox(self.controlArea, "Files")

        self.filesView = QTreeWidget(self)
        self.filesView.setHeaderLabels(
            ["", "Data Source", "Update", "Last Updated", "Size"])

        self.filesView.setRootIsDecorated(False)
        self.filesView.setUniformRowHeights(True)
        self.filesView.setSelectionMode(QAbstractItemView.NoSelection)
        self.filesView.setSortingEnabled(True)
        self.filesView.sortItems(1, Qt.AscendingOrder)
        self.filesView.setItemDelegateForColumn(
            0, UpdateOptionsItemDelegate(self.filesView))

        self.filesView.model().layoutChanged.connect(self.SearchUpdate)

        box.layout().addWidget(self.filesView)

        box = gui.widgetBox(self.controlArea, orientation="horizontal")
        self.updateButton = gui.button(
            box,
            self,
            "Update all",
            callback=self.UpdateAll,
            tooltip="Update all updatable files",
        )

        self.downloadButton = gui.button(
            box,
            self,
            "Download all",
            callback=self.DownloadFiltered,
            tooltip="Download all filtered files shown")

        self.cancelButton = gui.button(
            box,
            self,
            "Cancel",
            callback=self.Cancel,
            tooltip="Cancel scheduled downloads/updates.")

        self.retryButton = gui.button(box,
                                      self,
                                      "Reconnect",
                                      callback=self.RetrieveFilesList)
        self.retryButton.hide()

        gui.rubber(box)

        gui.lineEdit(box,
                     self,
                     "accessCode",
                     "Access Code",
                     orientation="horizontal",
                     callback=self.RetrieveFilesList)

        self.warning(0)

        box = gui.widgetBox(self.controlArea, orientation="horizontal")
        gui.rubber(box)

        self.infoLabel = QLabel()
        self.infoLabel.setAlignment(Qt.AlignCenter)

        self.controlArea.layout().addWidget(self.infoLabel)
        self.infoLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        self.updateItems = []

        self.resize(800, 600)

        self.progress = ProgressState(self, maximum=3)
        self.progress.valueChanged.connect(self._updateProgress)
        self.progress.rangeChanged.connect(self._updateProgress)
        self.executor = ThreadExecutor(threadPool=QThreadPool(
            maxThreadCount=2))

        task = Task(self, function=self.RetrieveFilesList)
        task.exceptionReady.connect(self.HandleError)
        task.start()

        self._tasks = []
        self._haveProgress = False

    def RetrieveFilesList(self):
        self.retryButton.hide()
        self.warning(0)
        self.progress.setRange(0, 3)
        self.serverFiles = serverfiles.ServerFiles(access_code=self.accessCode)

        task = Task(
            function=partial(retrieveFilesList, self.serverFiles, self.domains,
                             methodinvoke(self.progress, "advance")))

        task.resultReady.connect(self.SetFilesList)
        task.exceptionReady.connect(self.HandleError)

        self.executor.submit(task)

        self.setEnabled(False)

    def SetFilesList(self, serverInfo):
        """
        Set the files to show.
        """
        self.setEnabled(True)

        domains = serverInfo.keys()
        if not domains:
            if self.domains:
                domains = self.domains
            else:
                domains = serverfiles.listdomains()

        localInfo = dict([(dom, serverfiles.allinfo(dom)) for dom in domains])

        all_tags = set()

        self.filesView.clear()
        self.updateItems = []

        for item in join_info_dict(localInfo, serverInfo):
            tree_item = UpdateTreeWidgetItem(item)
            options_widget = UpdateOptionsWidget(item.state)
            options_widget.item = item

            options_widget.installClicked.connect(
                partial(self.SubmitDownloadTask, item.domain, item.filename))
            options_widget.removeClicked.connect(
                partial(self.SubmitRemoveTask, item.domain, item.filename))

            self.updateItems.append((item, tree_item, options_widget))
            all_tags.update(item.tags)

        self.filesView.addTopLevelItems(
            [tree_item for _, tree_item, _ in self.updateItems])

        for item, tree_item, options_widget in self.updateItems:
            self.filesView.setItemWidget(tree_item, 0, options_widget)

            # Add an update button if the file is updateable
            if item.state == OUTDATED:
                button = QToolButton(None,
                                     text="Update",
                                     maximumWidth=120,
                                     minimumHeight=20,
                                     maximumHeight=20)

                if sys.platform == "darwin":
                    button.setAttribute(Qt.WA_MacSmallSize)

                button.clicked.connect(
                    partial(self.SubmitDownloadTask, item.domain,
                            item.filename))

                self.filesView.setItemWidget(tree_item, 2, button)

        self.progress.advance()

        self.filesView.setColumnWidth(0, self.filesView.sizeHintForColumn(0))

        for column in range(1, 4):
            contents_hint = self.filesView.sizeHintForColumn(column)
            header_hint = self.filesView.header().sectionSizeHint(column)
            width = max(min(contents_hint, 400), header_hint)
            self.filesView.setColumnWidth(column, width)

        hints = [hint for hint in sorted(all_tags) if not hint.startswith("#")]
        self.completertokens = hints
        self.completermodel.setStringList(hints)

        self.SearchUpdate()
        self.UpdateInfoLabel()
        self.toggleButtons()
        self.cancelButton.setEnabled(False)

        self.progress.setRange(0, 0)

    def buttonCheck(self, selected_items, state, button):
        for item in selected_items:
            if item.state != state:
                button.setEnabled(False)
            else:
                button.setEnabled(True)
                break

    def toggleButtons(self):
        selected_items = [
            item for item, tree_item, _ in self.updateItems
            if not tree_item.isHidden()
        ]
        self.buttonCheck(selected_items, OUTDATED, self.updateButton)
        self.buttonCheck(selected_items, AVAILABLE, self.downloadButton)

    def HandleError(self, exception):
        if isinstance(exception, ConnectionError):
            self.warning(
                0, "Could not connect to server! Check your connection "
                "and try to reconnect.")
            self.SetFilesList({})
            self.retryButton.show()
        else:
            sys.excepthook(type(exception), exception.args, None)
            self.progress.setRange(0, 0)
            self.setEnabled(True)

    def UpdateInfoLabel(self):
        local = [
            item for item, tree_item, _ in self.updateItems
            if item.state != AVAILABLE and not tree_item.isHidden()
        ]
        size = sum(float(item.size) for item in local)

        onServer = [
            item for item, tree_item, _ in self.updateItems
            if not tree_item.isHidden()
        ]
        sizeOnServer = sum(float(item.size) for item in onServer)

        text = ("%i items, %s (on server: %i items, %s)" %
                (len(local), sizeof_fmt(size), len(onServer),
                 sizeof_fmt(sizeOnServer)))

        self.infoLabel.setText(text)

    def UpdateAll(self):
        self.warning(0)
        for item, tree_item, _ in self.updateItems:
            if item.state == OUTDATED and not tree_item.isHidden():
                self.SubmitDownloadTask(item.domain, item.filename)

    def DownloadFiltered(self):
        # TODO: submit items in the order shown.
        for item, tree_item, _ in self.updateItems:
            if not tree_item.isHidden() and item.state in \
                    [AVAILABLE, OUTDATED]:
                self.SubmitDownloadTask(item.domain, item.filename)

    def _updateCompleterPrefix(self, prefix, seperator=" "):
        prefix = str(self.completer.completionPrefix())

        tokens = self.completertokens
        model = self.completer.model()

        if not prefix.endswith(seperator) and seperator in prefix:
            prefix, _ = prefix.rsplit(seperator, 1)
            items = [prefix + seperator + item for item in tokens]
        else:
            items = tokens
        old = set(str(item) for item in model.stringList())

        if old != set(items):
            model.setStringList(items)

    def SearchUpdate(self, searchString=None):
        self._updateCompleterPrefix(searchString)
        strings = str(self.lineEditFilter.text()).split()
        for item, tree_item, _ in self.updateItems:
            hide = not all(
                UpdateItem_match(item, string) for string in strings)
            tree_item.setHidden(hide)
        self.UpdateInfoLabel()
        self.toggleButtons()

    def SubmitDownloadTask(self, domain, filename):
        """
        Submit the (domain, filename) to be downloaded/updated.
        """
        self.cancelButton.setEnabled(True)

        index = self.updateItemIndex(domain, filename)
        _, tree_item, opt_widget = self.updateItems[index]

        if self.accessCode:
            sf = serverfiles.ServerFiles(access_code=self.accessCode)
        else:
            sf = serverfiles.ServerFiles()

        task = DownloadTask(domain, filename, sf)

        self.progress.adjustRange(0, 100)

        pb = ItemProgressBar(self.filesView)
        pb.setRange(0, 100)
        pb.setTextVisible(False)

        task.advanced.connect(pb.advance)
        task.advanced.connect(self.progress.advance)
        task.finished.connect(pb.hide)
        task.finished.connect(self.onDownloadFinished, Qt.QueuedConnection)
        task.exception.connect(self.onDownloadError, Qt.QueuedConnection)

        self.filesView.setItemWidget(tree_item, 2, pb)

        # Clear the text so it does not show behind the progress bar.
        tree_item.setData(2, Qt.DisplayRole, "")
        pb.show()

        # Disable the options widget
        opt_widget.setEnabled(False)
        self._tasks.append(task)

        self.executor.submit(task)

    def EndDownloadTask(self, task):
        future = task.future()
        index = self.updateItemIndex(task.domain, task.filename)
        item, tree_item, opt_widget = self.updateItems[index]

        self.filesView.removeItemWidget(tree_item, 2)
        opt_widget.setEnabled(True)

        if future.cancelled():
            # Restore the previous state
            tree_item.setUpdateItem(item)
            opt_widget.setState(item.state)

        elif future.exception():
            tree_item.setUpdateItem(item)
            opt_widget.setState(item.state)

            # Show the exception string in the size column.
            self.warning(
                0, "Error while downloading. Check your connection "
                "and retry.")

            # recreate button for download
            button = QToolButton(None,
                                 text="Retry",
                                 maximumWidth=120,
                                 minimumHeight=20,
                                 maximumHeight=20)

            if sys.platform == "darwin":
                button.setAttribute(Qt.WA_MacSmallSize)

            button.clicked.connect(
                partial(self.SubmitDownloadTask, item.domain, item.filename))

            self.filesView.setItemWidget(tree_item, 2, button)

        else:
            # get the new updated info dict and replace the the old item
            self.warning(0)
            info = serverfiles.info(item.domain, item.filename)
            new_item = update_item_from_info(item.domain, item.filename, info,
                                             info)

            self.updateItems[index] = (new_item, tree_item, opt_widget)

            tree_item.setUpdateItem(new_item)
            opt_widget.setState(new_item.state)

            self.UpdateInfoLabel()

    def SubmitRemoveTask(self, domain, filename):
        serverfiles.remove(domain, filename)
        index = self.updateItemIndex(domain, filename)
        item, tree_item, opt_widget = self.updateItems[index]

        if item.info_server:
            new_item = item._replace(state=AVAILABLE,
                                     local=None,
                                     info_local=None)
        else:
            new_item = item._replace(local=None, info_local=None)
            # Disable the options widget. No more actions can be performed
            # for the item.
            opt_widget.setEnabled(False)

        tree_item.setUpdateItem(new_item)
        opt_widget.setState(new_item.state)
        self.updateItems[index] = (new_item, tree_item, opt_widget)

        self.UpdateInfoLabel()

    def Cancel(self):
        """
        Cancel all pending update/download tasks (that have not yet started).
        """
        for task in self._tasks:
            task.future().cancel()

    def onDeleteWidget(self):
        self.Cancel()
        self.executor.shutdown(wait=False)
        OWWidget.onDeleteWidget(self)

    def onDownloadFinished(self):
        # on download completed/canceled/error
        assert QThread.currentThread() is self.thread()
        for task in list(self._tasks):
            future = task.future()
            if future.done():
                self.EndDownloadTask(task)
                self._tasks.remove(task)

        if not self._tasks:
            # Clear/reset the overall progress
            self.progress.setRange(0, 0)
            self.cancelButton.setEnabled(False)

    def onDownloadError(self, exc_info):
        sys.excepthook(*exc_info)
        self.warning(
            0, "Error while downloading. Check your connection and "
            "retry.")

    def updateItemIndex(self, domain, filename):
        for i, (item, _, _) in enumerate(self.updateItems):
            if item.domain == domain and item.filename == filename:
                return i
        raise ValueError("%r, %r not in update list" % (domain, filename))

    def _updateProgress(self, *args):
        rmin, rmax = self.progress.range()
        if rmin != rmax:
            if not self._haveProgress:
                self._haveProgress = True
                self.progressBarInit()

            self.progressBarSet(self.progress.ratioCompleted() * 100,
                                processEvents=None)
        if rmin == rmax:
            self._haveProgress = False
            self.progressBarFinished()
    def __init__(self, parent, resoution="0.0000"):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("NumberBoxPanel" +
                           str(len(parent.findChildren(NumberBoxPanel))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        if resoution != None:
            self.numberBox = QLineEdit(self.frameBoxPanel)
            self.numberBox.setEnabled(True)
            font = QFont()
            font.setBold(False)
            font.setWeight(50)
            self.numberBox.setFont(font)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setText("0.0")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)
            self.numberBox.textChanged.connect(self.numberBoxChanged)
            self.numberBox.editingFinished.connect(
                self.numberBoxEditingFinished)
        else:
            self.numberBox = QSpinBox(self.frameBoxPanel)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.numberBox.setMinimum(-100000000)
            self.numberBox.setMaximum(100000000)
            self.numberBox.setValue(1)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)

        self.imageButton = QPushButton(self.frameBoxPanel)

        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)

        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.numberResolution = resoution
        str0 = String.Number2String(6.6788, "0.0000")
        self.Value = 0
        self.captionUnits = ""
예제 #38
0
class EncryptDialog(QDialog):
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("CryptoSystems")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('Select All')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('write your password'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.techniquesGroup = QGroupBox(self)
        self.tecniquesform = QFormLayout()
        self.techniquesGroup.setLayout(self.tecniquesform)

        self.techniquesScroll = QScrollArea(self)
        self.techniquesScroll.setGeometry(QRect(770, 100, 230, 300))
        self.techniquesScroll.setWidget(self.techniquesGroup)
        self.techniquesScroll.setWidgetResizable(True)

        self.rowsTechiques = []
        for i in list(range(8)):
            horizontalLayout = QHBoxLayout()
            self.tecniquesform.addRow(horizontalLayout)
            self.rowsTechiques.append(horizontalLayout)

        techniquesCombo = QComboBox()
        techniquesCombo.setGeometry(QRect(10, 50, 171, 22))
        techniquesCombo.addItems(self.techniquesClass.keys())
        self.techniques.append(techniquesCombo)
        self.rowsTechiques[0].addWidget(techniquesCombo)
        self.techniquesNumber = 1

        self.addTechnique = QPushButton()
        self.addTechnique.setGeometry(QRect(90, 90, 31, 21))
        self.addTechnique.setFixedSize(31, 21)
        self.addTechnique.setText('+')
        self.connect(self.addTechnique, SIGNAL("clicked()"),
                     self.__eventAddTechnique)
        self.rowsTechiques[len(self.rowsTechiques) - 1].addWidget(
            self.addTechnique)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Start...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitEncryption)

    def __eventAddTechnique(self):
        techniquesCombo = QComboBox()
        techniquesCombo.setGeometry(QRect(10, 50, 171, 22))
        techniquesCombo.addItems(self.techniquesClass.keys())
        self.techniques.append(techniquesCombo)
        self.rowsTechiques[self.techniquesNumber].addWidget(techniquesCombo)
        self.techniquesNumber = self.techniquesNumber + 1
        if ((len(self.rowsTechiques) - 1) == self.techniquesNumber):
            self.addTechnique.setEnabled(False)

    def __eventDirectoryChanged(self):
        index = self.treeView.currentIndex()
        self.__changeDirectory(self.fileSystemModel.filePath(index))

    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])

    def __selectAllFiles(self):
        for o in self.filesview:
            o.setChecked(self.checkBox_2.isChecked())

    def __deselectFile(self):
        #print 'deselect'
        self.checkBox_2.setChecked(False)

    def __arrozconpollo(self):
        self.__obtainSelectedFIles()

    def __obtainSelectedFIles(self):
        files = []
        for o in self.filesview:
            if o.isChecked():
                files.append(str(o.title()))
                self.progressBars[str(o.title())].setVisible(True)
        return files

    def __getFiles(self, path):
        from os import listdir
        from os.path import isfile

        f = []

        for base in listdir(path):
            try:
                if isfile(path + '/' + base):
                    f.append(base)
            except ValueError:
                pass
        f.sort()
        return f

    def __eventInitEncryption(self):
        if len(self.__obtainSelectedFIles()) == 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("You must specify the files you want to encrypt")
            msg.setWindowTitle("CryptoSystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        if str(self.lineEdit.text()).strip() == '':
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("You must specify a key")
            msg.setWindowTitle("CryptoSystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        self.okButton.setEnabled(False)
        self.techniquesGroup.setEnabled(False)
        self.lineEdit.setEnabled(False)

        index = self.treeView.currentIndex()

        path = self.fileSystemModel.filePath(index)
        selectedFiles = self.__obtainSelectedFIles()

        from os.path import getsize
        blockSize = 4096

        from hashlib import md5
        Hash = md5()
        Hash.update(str(self.lineEdit.text()))
        key = Hash.hexdigest()

        for f in selectedFiles:

            f_in = open(path + '/' + f, 'rb')
            f_out = open(
                path + '/' + reduceMd5(checksum(path + '/' + f)) + '.cry',
                'wb')

            f_out.write('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' +
                        unhexlify('01'))

            header_list = ''
            techniquesObjects = []
            for t in self.techniques:
                header_list = header_list + t.currentText() + ':'
                techniquesObjects.append(self.techniquesClass[str(
                    t.currentText())](key))

            file_header = str('header|' + str(f_in.name.split('/')[-1]) + '|' +
                              str(header_list) + '|' +
                              str(checksum(path + '/' + f)))

            aes = AES(key)
            f_out.write(aes.encrypt(file_header))
            f_out.write(unhexlify('02'))

            in_size = getsize(path + '/' + f)
            in_progress = 0.0

            block = f_in.read(blockSize)
            while (block):
                block_c = block
                for t in techniquesObjects:
                    block_c = t.encrypt(block_c)
                f_out.write(block_c)
                in_progress = in_progress + blockSize

                progress = (in_progress / in_size) * 100
                #print progress
                self.progressBars[str(f)].setProperty("value", int(progress))
                self.progressBars[str(f)].setToolTip(str(progress) + '%')
                block = f_in.read(blockSize)

            f_in.close()
            f_out.close()

        msg = QMessageBox()

        msg.setIcon(QMessageBox.Information)

        msg.setText("Encryption has successfully concluded")
        msg.setWindowTitle("CryptoSystems")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()

        self.hide()
예제 #39
0
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        #self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("Desencriptador de Cryogenesis Systems.")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('seleccionar todos')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('escriba su contraseña'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Iniciar...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitDecryption)
예제 #40
0
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("CryptoSystems")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('Select All')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('write your password'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.techniquesGroup = QGroupBox(self)
        self.tecniquesform = QFormLayout()
        self.techniquesGroup.setLayout(self.tecniquesform)

        self.techniquesScroll = QScrollArea(self)
        self.techniquesScroll.setGeometry(QRect(770, 100, 230, 300))
        self.techniquesScroll.setWidget(self.techniquesGroup)
        self.techniquesScroll.setWidgetResizable(True)

        self.rowsTechiques = []
        for i in list(range(8)):
            horizontalLayout = QHBoxLayout()
            self.tecniquesform.addRow(horizontalLayout)
            self.rowsTechiques.append(horizontalLayout)

        techniquesCombo = QComboBox()
        techniquesCombo.setGeometry(QRect(10, 50, 171, 22))
        techniquesCombo.addItems(self.techniquesClass.keys())
        self.techniques.append(techniquesCombo)
        self.rowsTechiques[0].addWidget(techniquesCombo)
        self.techniquesNumber = 1

        self.addTechnique = QPushButton()
        self.addTechnique.setGeometry(QRect(90, 90, 31, 21))
        self.addTechnique.setFixedSize(31, 21)
        self.addTechnique.setText('+')
        self.connect(self.addTechnique, SIGNAL("clicked()"),
                     self.__eventAddTechnique)
        self.rowsTechiques[len(self.rowsTechiques) - 1].addWidget(
            self.addTechnique)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Start...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitEncryption)
예제 #41
0
class cryoGUI(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("Crypto App")
        self.resize(500, 260)
        self.setMinimumSize(QSize(500, 260))
        self.setMaximumSize(QSize(500, 260))
        self.label = QLabel(self)
        self.label.setGeometry(QRect(66, 55, 150, 150))
        self.label.setPixmap(QPixmap("images/padlock.png"))
        self.label.setScaledContents(True)
        self.label.setToolTip('Encrypt files and folders')

        self.label_2 = QLabel(self)
        self.label_2.setGeometry(QRect(282, 55, 150, 150))
        self.label_2.setPixmap(QPixmap("images/unlock.png"))
        self.label_2.setScaledContents(True)
        self.label_2.setToolTip('Decrypt files and folders')
        self.label_2.mousePressEvent = self.__initDecrypter

        self.label_3 = QLabel(self)
        self.label_3.setGeometry(QRect(66, 180, 150, 16))
        self.label_3.setAlignment(Qt.AlignCenter)
        self.label_3.setText('<b style="color: white">ENCRYPT</b>')

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(282, 180, 150, 16))
        self.label_4.setAlignment(Qt.AlignCenter)
        self.label_4.setText('<b style="color: white">DECRYPT</b>')

        self.label_3.mousePressEvent = self.label.mousePressEvent = self.__initEncrypter
        self.label_4.mousePressEvent = self.label_2.mousePressEvent = self.__initDecrypter

    def __initEncrypter(self, e):
        E = EncryptDialog()
        E.exec_()

    def __initDecrypter(self, e):
        E = DecryptDialog()
        E.exec_()
예제 #42
0
    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])
예제 #43
0
class PreviewBrowser(QWidget):
    """A Preview Browser for recent/premade scheme selection.
    """
    # Emitted when the current previewed item changes
    currentIndexChanged = Signal(int)

    # Emitted when an item is double clicked in the preview list.
    activated = Signal(int)

    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.__model = None
        self.__currentIndex = -1
        self.__template = DESCRIPTION_TEMPLATE
        self.__setupUi()

    def __setupUi(self):
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        top_layout = QHBoxLayout()
        top_layout.setContentsMargins(12, 12, 12, 12)

        # Top row with full text description and a large preview
        # image.
        self.__label = QLabel(self,
                              objectName="description-label",
                              wordWrap=True,
                              alignment=Qt.AlignTop | Qt.AlignLeft)

        self.__label.setWordWrap(True)
        self.__label.setFixedSize(220, PREVIEW_SIZE[1])

        self.__image = QSvgWidget(self, objectName="preview-image")
        self.__image.setFixedSize(*PREVIEW_SIZE)

        self.__imageFrame = DropShadowFrame(self)
        self.__imageFrame.setWidget(self.__image)

        # Path text below the description and image
        path_layout = QHBoxLayout()
        path_layout.setContentsMargins(12, 0, 12, 0)
        path_label = QLabel("<b>{0!s}</b>".format(self.tr("Path:")),
                            self,
                            objectName="path-label")

        self.__path = TextLabel(self, objectName="path-text")

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.__path)

        self.__selectAction = \
            QAction(self.tr("Select"), self,
                    objectName="select-action",
                    )

        top_layout.addWidget(self.__label,
                             1,
                             alignment=Qt.AlignTop | Qt.AlignLeft)
        top_layout.addWidget(self.__image,
                             1,
                             alignment=Qt.AlignTop | Qt.AlignRight)

        vlayout.addLayout(top_layout)
        vlayout.addLayout(path_layout)

        # An list view with small preview icons.
        self.__previewList = LinearIconView(objectName="preview-list-view")
        self.__previewList.doubleClicked.connect(self.__onDoubleClicked)

        vlayout.addWidget(self.__previewList)
        self.setLayout(vlayout)

    def setModel(self, model):
        """Set the item model for preview.
        """
        if self.__model != model:
            if self.__model:
                s_model = self.__previewList.selectionModel()
                s_model.selectionChanged.disconnect(self.__onSelectionChanged)
                self.__model.dataChanged.disconnect(self.__onDataChanged)

            self.__model = model
            self.__previewList.setModel(model)

            if model:
                s_model = self.__previewList.selectionModel()
                s_model.selectionChanged.connect(self.__onSelectionChanged)
                self.__model.dataChanged.connect(self.__onDataChanged)

            if model and model.rowCount():
                self.setCurrentIndex(0)

    def model(self):
        """Return the item model.
        """
        return self.__model

    def setPreviewDelegate(self, delegate):
        """Set the delegate to render the preview images.
        """
        raise NotImplementedError

    def setDescriptionTemplate(self, template):
        self.__template = template
        self.__update()

    def setCurrentIndex(self, index):
        """Set the selected preview item index.
        """
        if self.__model is not None and self.__model.rowCount():
            index = min(index, self.__model.rowCount() - 1)
            index = self.__model.index(index, 0)
            sel_model = self.__previewList.selectionModel()
            # This emits selectionChanged signal and triggers
            # __onSelectionChanged, currentIndex is updated there.
            sel_model.select(index, sel_model.ClearAndSelect)

        elif self.__currentIndex != -1:
            self.__currentIndex = -1
            self.__update()
            self.currentIndexChanged.emit(-1)

    def currentIndex(self):
        """Return the current selected index.
        """
        return self.__currentIndex

    def __onSelectionChanged(self, *args):
        """Selected item in the preview list has changed.
        Set the new description and large preview image.

        """
        rows = self.__previewList.selectedIndexes()
        if rows:
            index = rows[0]
            self.__currentIndex = index.row()
        else:
            index = QModelIndex()
            self.__currentIndex = -1

        self.__update()
        self.currentIndexChanged.emit(self.__currentIndex)

    def __onDataChanged(self, topleft, bottomRight):
        """Data changed, update the preview if current index in the changed
        range.

        """
        if self.__currentIndex <= topleft.row() and \
                self.__currentIndex >= bottomRight.row():
            self.__update()

    def __onDoubleClicked(self, index):
        """Double click on an item in the preview item list.
        """
        self.activated.emit(index.row())

    def __update(self):
        """Update the current description.
        """
        if self.__currentIndex != -1:
            index = self.model().index(self.__currentIndex, 0)
        else:
            index = QModelIndex()

        if not index.isValid():
            description = ""
            name = ""
            path = ""
            svg = NO_PREVIEW_SVG
        else:
            description = unicode(index.data(Qt.WhatsThisRole).toString())
            if not description:
                description = "No description."

            description = escape(description)
            description = description.replace("\n", "<br/>")

            name = unicode(index.data(Qt.DisplayRole).toString())
            if not name:
                name = "Untitled"

            name = escape(name)
            path = unicode(index.data(Qt.StatusTipRole).toString())

            svg = unicode(index.data(previewmodel.ThumbnailSVGRole).toString())

        desc_text = self.__template.format(description=description, name=name)

        self.__label.setText(desc_text)

        self.__path.setText(path)

        if not svg:
            svg = NO_PREVIEW_SVG

        if svg:
            self.__image.load(QByteArray(svg.encode("utf-8")))
예제 #44
0
class DecryptDialog(QDialog):
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        #self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("Desencriptador de Cryogenesis Systems.")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('seleccionar todos')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('escriba su contraseña'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Iniciar...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitDecryption)

    def __eventDirectoryChanged(self):
        index = self.treeView.currentIndex()
        self.__changeDirectory(self.fileSystemModel.filePath(index))

    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])

    def __selectAllFiles(self):
        for o in self.filesview:
            o.setChecked(self.checkBox_2.isChecked())

    def __deselectFile(self):
        #print 'deselect'
        self.checkBox_2.setChecked(False)

    def __arrozconpollo(self):
        self.__obtainSelectedFIles()

    def __obtainSelectedFIles(self):
        files = []
        for o in self.filesview:
            if o.isChecked():
                files.append(str(o.title()))
                self.progressBars[str(o.title())].setVisible(True)
        return files

    def __getFiles(self, path):
        from os import listdir
        from os.path import isfile

        f = []

        for base in listdir(path):
            try:
                if isfile(path + '/' + base) and base.split('.')[-1] == 'cry':
                    f.append(base)
            except ValueError:
                pass
        f.sort()
        return f

    def __eventInitDecryption(self):
        if len(self.__obtainSelectedFIles()) == 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText(
                "Debes especificar los archivos que quieres desencriptar")
            msg.setWindowTitle("Cryosystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        if str(self.lineEdit.text()).strip() == '':
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Debes especificar una clave")
            msg.setWindowTitle("Cryosystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        self.okButton.setEnabled(False)
        self.lineEdit.setEnabled(False)

        index = self.treeView.currentIndex()

        path = self.fileSystemModel.filePath(index)
        selectedFiles = self.__obtainSelectedFIles()

        from hashlib import md5
        Hash = md5()
        Hash.update(str(self.lineEdit.text()))
        key = Hash.hexdigest()

        errors = 0

        from os.path import getsize
        blockSize = 4096
        for f in selectedFiles:

            f_in = open(path + '/' + f, 'rb')
            print path + '/' + f

            header = ''
            if (f_in.read(20) == ('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' +
                                  unhexlify('01'))):
                while (True):
                    c = f_in.read(1)
                    if c == unhexlify('02'):
                        break
                    else:
                        header = header + c
            else:
                print 'esto no es un archivo cifradodo de Cryogenesis Systems'

            #print key
            aes = AES(key)
            #print aes.decrypt(header)
            header_sections = aes.decrypt(header).split('|')

            if header_sections[0] != 'header':
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText("La clave no es correcta para el archivo:" + f)
                msg.setWindowTitle("Cryosystems")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()
                errors = errors + 1
                continue

            f_out = open(path + '/' + header_sections[1], 'wb')

            techniques = header_sections[2].split(':')[:-1]

            techniquesObjects = []

            for t in techniques:
                techniquesObjects.append(self.techniquesClass[t](key))
            techniquesObjects.reverse()

            in_size = getsize(path + '/' + f)
            in_progress = 0.0

            block = f_in.read(blockSize)
            while (block):
                block_p = block
                for t in techniquesObjects:
                    block_p = t.decrypt(block_p)
                f_out.write(block_p)
                in_progress = in_progress + blockSize
                progress = (in_progress / in_size) * 100
                self.progressBars[str(f)].setProperty("value", int(progress))
                self.progressBars[str(f)].setToolTip(str(progress) + '%')
                block = f_in.read(blockSize)

            f_in.close()
            f_out.close()

            if (checksum(path + '/' + header_sections[1]) !=
                    header_sections[3]):
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText("El archivo" + f + 'se ha corrompido')
                msg.setWindowTitle("Cryosystems")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()
                errors = errors + 1
                from os import remove
                remove(header_sections[1])

        msg = QMessageBox()
        msg.setWindowTitle("Cryosystems")
        msg.setStandardButtons(QMessageBox.Ok)

        if (errors == 0):
            msg.setIcon(QMessageBox.Information)
            msg.setText("La desencriptacion ha concluido exitosamente")
        else:
            msg.setIcon(QMessageBox.Warning)
            msg.setText("La desencriptacion ha concluido con " + str(errors) +
                        ' error(es)')

        msg.exec_()
        self.hide()
예제 #45
0
    def QTLayout(self):
        """
        Basic layout made with QT Designer
         
        """
        self.setWindowTitle("PDF Editor")
        self.setWindowFlags(self.windowFlags()
                            ^ Qt.WindowContextHelpButtonHint)  # removes the"?"
        self.layout = QVBoxLayout(self)
        self.labelH1 = QLabel("PDF Creation")
        font = QFont()
        font.setPointSize(9)
        self.labelH1.setFont(font)
        self.pathButton = QPushButton("Source PDF file")
        self.pathButton.clicked.connect(self.setSourcePath)

        self.layout.addWidget(self.pathButton)
        self.labelPagesCount = QLabel()
        self.labelPagesCount.setText("{Empty}")
        self.labelN = QLabel("\n")
        self.labelN1 = QLabel("\n")
        self.layout.addWidget(self.labelN)
        self.labelSourceFile1 = QLabel()
        self.labelSourceFile1.setText("Source file path:")
        self.layout.addWidget(self.labelSourceFile1)
        self.layout.addWidget(self.labelSourceFile1)
        self.layout.addWidget(self.labelPagesCount)
        self.labelCountPages1 = QLabel("0")
        self.layout.addWidget(self.labelPagesCount)
        self.layout.addWidget(self.labelCountPages1)
        self.layout.addWidget(self.labelN)
        self.destinationButton = QPushButton("Destination path:")
        self.layout.addWidget(self.destinationButton)
        self.destinationButton.clicked.connect(self.destinationFileSave)
        self.lavbelSave = QLabel("Selec estination path:")
        self.layout.addWidget(self.lavbelSave)
        self.labelSave2 = QLabel("{Empty}")
        self.layout.addWidget(self.labelSave2)
        self.layout.addWidget(self.labelN1)
        self.labelStr = QLabel("Input selected pages \n[separated with comma]")
        self.layout.addWidget(self.labelStr)
        self.lineEditCountOfPages = QLineEdit()
        self.layout.addWidget(self.lineEditCountOfPages)
        self.saveButton2 = QPushButton("SAVE FILE")
        self.layout.addWidget(self.saveButton2)
        self.saveButton2.clicked.connect(self.saveOutputFile)

        self.mergeButton = QPushButton("MERGE FILES")
        self.mergeButton.clicked.connect(self.mergeTwoFiles)
        self.breakLabel = QLabel()
        self.mergeTextLabel = QLabel("Button below merges two PDF files")
        self.layout.addWidget(self.breakLabel)
        self.layout.addWidget(self.breakLabel)
        self.layout.addWidget(self.mergeTextLabel)
        self.layout.addWidget(self.mergeButton)
예제 #46
0
class Entity(QWidget):
    def __init__(self, base_image, parent=None):
        super().__init__(parent)
        self._base_label = QLabel(self)
        self._base_image = base_image

        self._decor_label = None
        self._decor_pixmap = None

        self.__pixmap = None
        """:type: PyQt4.QtGui.QPixmap"""

        self.__cord_x = 0
        self.__cord_y = 0
        self.__angle = 0
        self.setAlignment(Qt.AlignCenter)
        self.updatePixmap()

        if _debugging:
            self.setStyleSheet("border: 1px solid black")

    @property
    def angle(self):
        return self.__angle

    @angle.setter
    def angle(self, angle):
        self.__angle = angle
        self.updatePixmap()

    @property
    def cord_x(self):
        return self.__cord_x

    @cord_x.setter
    def cord_x(self, cord):
        self.__cord_x = cord
        self.move(self.cord_x, self.cord_y)

    @property
    def cord_y(self):
        return self.__cord_y

    @cord_y.setter
    def cord_y(self, cord):
        self.__cord_y = cord
        self.move(self.cord_x, self.cord_y)

    def add_decoration(self, path):
        if path is None:
            self._decor_label.deleteLater()
            self._decor_label = None
        else:
            self._decor_label = QLabel(self)
            self._decor_pixmap = QPixmap(path)
            self._decor_pixmap = self._decor_pixmap.scaled(
                self._decor_pixmap.width() * _SCALE,
                self._decor_pixmap.height() * _SCALE)
            self._decor_pixmap = self._decor_pixmap.transformed(
                QTransform().rotate(self.angle))
            self._decor_label.setPixmap(self._decor_pixmap)
            self._decor_label.setAlignment(Qt.AlignCenter)
            self._decor_label.show()

    def updatePixmap(self):
        path = _PATH + os.sep + "assets" + os.sep + self._base_image
        self.__pixmap = QPixmap(path)
        self.__pixmap = self.__pixmap.scaled(self.__pixmap.width() * _SCALE,
                                             self.__pixmap.height() * _SCALE)
        self.__pixmap = self.__pixmap.transformed(QTransform().rotate(
            self.angle))
        self._base_label.setPixmap(self.__pixmap)
        self.setFixedSize(self.__pixmap.width(), self.__pixmap.height())

    def setFixedSize(self, x, y):
        super().setFixedSize(x, y)
        self._base_label.setFixedSize(x, y)

    def setAlignment(self, alignment):
        self._base_label.setAlignment(alignment)
예제 #47
0
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("WindPanel" +
                           str(len(parent.findChildren(WindPanel))))

        #         self.frame_WindIA = QFrame(parent)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Raised)
        self.setObjectName(("frame_WindIA"))
        self.hLayout = QHBoxLayout(self)
        self.hLayout.setSpacing(0)
        self.hLayout.setMargin(0)
        self.hLayout.setObjectName(("hLayout"))

        self.basicFrame = Frame(self, "HL")
        self.hLayout.addWidget(self.basicFrame)

        self.lblIA = QLabel(self.basicFrame)
        self.lblIA.setMinimumSize(QSize(200, 0))
        self.lblIA.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lblIA.setFont(font)
        self.lblIA.setObjectName(("lblIA"))
        self.basicFrame.Add = self.lblIA

        self.comboBox = QComboBox(self.basicFrame)
        # sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())
        # self.comboBox.setSizePolicy(sizePolicy)
        # self.comboBox.setMinimumSize(QSize(60, 0))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName(("comboBox"))
        self.basicFrame.Add = self.comboBox

        self.speedBox = QLineEdit(self.basicFrame)
        # sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(self.speedBox.sizePolicy().hasHeightForWidth())
        # self.speedBox.setSizePolicy(sizePolicy)
        # self.speedBox.setMinimumSize(QSize(70, 0))
        # self.speedBox.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.speedBox.setFont(font)
        self.speedBox.setObjectName(("speedBox"))
        self.speedBox.setMinimumSize(QSize(60, 0))
        self.speedBox.setMaximumSize(QSize(60, 16777215))
        self.basicFrame.Add = self.speedBox

        spacerItem = QSpacerItem(0, 0, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.basicFrame.layoutBoxPanel.addItem(spacerItem)

        self.altitude = Altitude.NaN()
        self.customValue = Speed(30).Knots
        self.comboBox.addItems(["ICAO", "UK", "Custom"])
        self.comboBox.currentIndexChanged.connect(self.changeWindType)
        self.comboBox.setCurrentIndex(0)
        self.lblIA.setText("Wind (kts):")
        self.speedBox.setEnabled(False)
예제 #48
0
        triangle = [
            QPointF(value * span, y),
            QPointF((value * span) + (2 * FractionSlider.XMARGIN), y),
            QPointF((value * span) + FractionSlider.XMARGIN, fm.height())
        ]
        painter.setPen(Qt.yellow)
        painter.setBrush(Qt.darkYellow)
        painter.drawPolygon(QPolygonF(triangle))


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    form = QDialog()
    sliderLabel = QLabel("&Fraction")
    slider = FractionSlider(denominator=12)
    sliderLabel.setBuddy(slider)
    denominatorLabel = QLabel("&Denominator")
    denominatorSpinBox = QSpinBox()
    denominatorLabel.setBuddy(denominatorSpinBox)
    denominatorSpinBox.setRange(3, 60)
    denominatorSpinBox.setValue(slider.fraction()[1])
    denominatorSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
    numeratorLabel = QLabel("Numerator")
    numeratorLCD = QLCDNumber()
    numeratorLCD.setSegmentStyle(QLCDNumber.Flat)
    layout = QGridLayout()
    layout.addWidget(sliderLabel, 0, 0)
    layout.addWidget(slider, 0, 1, 1, 5)
    layout.addWidget(numeratorLabel, 1, 0)
예제 #49
0
    def __init__(self, run_model, parent):
        QDialog.__init__(self, parent)
        self.setWindowFlags(Qt.Window)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setModal(True)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle("Simulations")

        assert isinstance(run_model, BaseRunModel)
        self._run_model = run_model

        ert = None
        if isinstance(run_model, BaseRunModel):
            ert = run_model.ert()

        self.simulations_tracker = SimulationsTracker()
        states = self.simulations_tracker.getStates()
        self.state_colors = {state.name: state.color for state in states}
        self.state_colors['Success'] = self.state_colors["Finished"]
        self.state_colors['Failure'] = self.state_colors["Failed"]

        self.total_progress = SimpleProgress()

        status_layout = QHBoxLayout()
        status_layout.addStretch()
        self.__status_label = QLabel()
        status_layout.addWidget(self.__status_label)
        status_layout.addStretch()
        status_widget_container = QWidget()
        status_widget_container.setLayout(status_layout)

        self.progress = Progress()
        self.progress.setIndeterminateColor(self.total_progress.color)
        for state in states:
            self.progress.addState(state.state, QColor(*state.color),
                                   100.0 * state.count / state.total_count)

        legend_layout = QHBoxLayout()
        self.legends = {}
        for state in states:
            self.legends[state] = Legend("%s (%d/%d)", QColor(*state.color))
            self.legends[state].updateLegend(state.name, 0, 0)
            legend_layout.addWidget(self.legends[state])

        legend_widget_container = QWidget()
        legend_widget_container.setLayout(legend_layout)

        self.running_time = QLabel("")

        self.plot_tool = PlotTool()
        self.plot_tool.setParent(None)
        self.plot_button = QPushButton(self.plot_tool.getName())
        self.plot_button.clicked.connect(self.plot_tool.trigger)
        self.plot_button.setEnabled(ert is not None)

        self.kill_button = QPushButton("Kill simulations")
        self.done_button = QPushButton("Done")
        self.done_button.setHidden(True)
        self.restart_button = QPushButton("Restart")
        self.restart_button.setHidden(True)
        self.show_details_button = QPushButton("Details")
        self.show_details_button.setCheckable(True)

        size = 20
        spin_movie = resourceMovie("ide/loading.gif")
        spin_movie.setSpeed(60)
        spin_movie.setScaledSize(QSize(size, size))
        spin_movie.start()

        self.processing_animation = QLabel()
        self.processing_animation.setMaximumSize(QSize(size, size))
        self.processing_animation.setMinimumSize(QSize(size, size))
        self.processing_animation.setMovie(spin_movie)

        button_layout = QHBoxLayout()
        button_layout.addWidget(self.processing_animation)
        button_layout.addWidget(self.running_time)
        button_layout.addStretch()
        button_layout.addWidget(self.show_details_button)
        button_layout.addWidget(self.plot_button)
        button_layout.addWidget(self.kill_button)
        button_layout.addWidget(self.done_button)
        button_layout.addWidget(self.restart_button)
        button_widget_container = QWidget()
        button_widget_container.setLayout(button_layout)

        self.detailed_progress = DetailedProgressWidget(
            self, self.state_colors)
        self.detailed_progress.setVisible(False)
        self.dummy_widget_container = QWidget(
        )  #Used to keep the other widgets from stretching

        layout = QVBoxLayout()
        layout.addWidget(self.total_progress)
        layout.addWidget(status_widget_container)
        layout.addWidget(self.progress)
        layout.addWidget(legend_widget_container)
        layout.addWidget(self.detailed_progress)
        layout.addWidget(self.dummy_widget_container)
        layout.addWidget(button_widget_container)

        layout.setStretch(0, 0)
        layout.setStretch(1, 0)
        layout.setStretch(2, 0)
        layout.setStretch(3, 0)
        layout.setStretch(4, 1)
        layout.setStretch(5, 1)
        layout.setStretch(6, 0)

        self.setLayout(layout)

        self.kill_button.clicked.connect(self.killJobs)
        self.done_button.clicked.connect(self.accept)
        self.restart_button.clicked.connect(self.restart_failed_realizations)
        self.show_details_button.clicked.connect(self.toggle_detailed_progress)

        self.__updating = False
        self.__update_queued = False
        self.__simulation_started = False

        self.__update_timer = QTimer(self)
        self.__update_timer.setInterval(500)
        self.__update_timer.timeout.connect(self.updateRunStatus)
        self._simulations_argments = {}
예제 #50
0
class PDFEditorLite(QDialog):
    """
    Main class of Editor, inherits from QDialog class
    Use Qt Designer Layout as GUI
    """
    def __init__(self, parent=None):
        super(PDFEditorLite, self).__init__(parent)
        self.QTLayout()

    def QTLayout(self):
        """
        Basic layout made with QT Designer
         
        """
        self.setWindowTitle("PDF Editor")
        self.setWindowFlags(self.windowFlags()
                            ^ Qt.WindowContextHelpButtonHint)  # removes the"?"
        self.layout = QVBoxLayout(self)
        self.labelH1 = QLabel("PDF Creation")
        font = QFont()
        font.setPointSize(9)
        self.labelH1.setFont(font)
        self.pathButton = QPushButton("Source PDF file")
        self.pathButton.clicked.connect(self.setSourcePath)

        self.layout.addWidget(self.pathButton)
        self.labelPagesCount = QLabel()
        self.labelPagesCount.setText("{Empty}")
        self.labelN = QLabel("\n")
        self.labelN1 = QLabel("\n")
        self.layout.addWidget(self.labelN)
        self.labelSourceFile1 = QLabel()
        self.labelSourceFile1.setText("Source file path:")
        self.layout.addWidget(self.labelSourceFile1)
        self.layout.addWidget(self.labelSourceFile1)
        self.layout.addWidget(self.labelPagesCount)
        self.labelCountPages1 = QLabel("0")
        self.layout.addWidget(self.labelPagesCount)
        self.layout.addWidget(self.labelCountPages1)
        self.layout.addWidget(self.labelN)
        self.destinationButton = QPushButton("Destination path:")
        self.layout.addWidget(self.destinationButton)
        self.destinationButton.clicked.connect(self.destinationFileSave)
        self.lavbelSave = QLabel("Selec estination path:")
        self.layout.addWidget(self.lavbelSave)
        self.labelSave2 = QLabel("{Empty}")
        self.layout.addWidget(self.labelSave2)
        self.layout.addWidget(self.labelN1)
        self.labelStr = QLabel("Input selected pages \n[separated with comma]")
        self.layout.addWidget(self.labelStr)
        self.lineEditCountOfPages = QLineEdit()
        self.layout.addWidget(self.lineEditCountOfPages)
        self.saveButton2 = QPushButton("SAVE FILE")
        self.layout.addWidget(self.saveButton2)
        self.saveButton2.clicked.connect(self.saveOutputFile)

        self.mergeButton = QPushButton("MERGE FILES")
        self.mergeButton.clicked.connect(self.mergeTwoFiles)
        self.breakLabel = QLabel()
        self.mergeTextLabel = QLabel("Button below merges two PDF files")
        self.layout.addWidget(self.breakLabel)
        self.layout.addWidget(self.breakLabel)
        self.layout.addWidget(self.mergeTextLabel)
        self.layout.addWidget(self.mergeButton)

    def mergeTwoFiles(self):
        firstPDF = QFileDialog.getOpenFileName(self,
                                               'Choose the first PDF file',
                                               "*.pdf")
        secondPDF = QFileDialog.getOpenFileName(self,
                                                'Choose the second PDF file ',
                                                "*.pdf")
        QMessageBox.information(self, "Select destination place",
                                "Input name of new file and path")
        merged = QFileDialog.getSaveFileName(self, 'Destination file', "*.pdf")

        if os.path.exists(firstPDF) and os.path.exists(secondPDF):
            output = PdfFileWriter()
            firstPDF = PdfFileReader(open(firstPDF, "rb"))
            for page in range(firstPDF.getNumPages()):
                output.addPage(firstPDF.getPage(page))

            secondPDF = PdfFileReader(open(secondPDF, "rb"))
            for page in range(secondPDF.getNumPages()):
                output.addPage(secondPDF.getPage(page))

            outputStream = open(merged, "wb")
            output.write(outputStream)
            outputStream.close()

    def setSourcePath(self):
        self.sourcePath = QFileDialog.getOpenFileName(
            self, 'Choose the source PDF file to add', "*.pdf")
        self.labelPagesCount.setText(self.sourcePath)
        input1 = PdfFileReader(file(self.labelPagesCount.text(), "rb"))
        self.labelCountPages1.setText("Source file page count: %s " %
                                      input1.getNumPages())

    def destinationFileSave(self):
        self.destinationPath = QFileDialog.getSaveFileName(
            self, 'Destination', "*.pdf")
        self.labelSave2.setText(self.destinationPath)

    def saveOutputFile(self):
        try:
            list1 = str(self.lineEditCountOfPages.text())
            list1 = map(int, list1.split(','))

            if str(self.labelPagesCount.text()) != "{Empty}":
                input1 = PdfFileReader(file(self.labelPagesCount.text(), "rb"))
                output = PdfFileWriter()

                self.labelCountPages1.setText("New file pages amount: %s " %
                                              input1.getNumPages())

                for b in list1:
                    if b <= int(input1.getNumPages()):
                        output.addPage(input1.getPage(b - 1))
                    else:
                        QMessageBox.information(self, "Error!",
                                                "Wrong page number")

                if str(self.labelSave2.text()) != "{Empty}":
                    outputStream = file(self.labelSave2.text(), "wb")
                    output.write(outputStream)
                    outputStream.close()
                else:
                    QMessageBox.information(self, "Error!",
                                            "Choose the save path")
                    outputStream.close()

            else:
                QMessageBox.information(self, "Error",
                                        "Choose the right source")

        except ValueError:
            QMessageBox.information(self, "Error", "Wrong pages")
예제 #51
0
class Entity(QWidget):
    def __init__(self, base_image, size, hp=100, pos=(0, 0), parent=None):
        super().__init__(parent)
        self._base_label = QLabel(self)
        self._base_image = base_image
        self._size = size
        self._decor_label = None
        self._decor_pixmap = None
        self._hp_max = hp

        self.__pixmap = None
        """:type: PyQt4.QtGui.QPixmap"""

        self.__cord_x = pos[0]
        self.__cord_y = pos[1]
        self.__angle = 0

        self.__hp_bar = QProgressBar(self)
        self.__hp_bar.setMaximum(self._hp_max)
        self.__hp_bar.setValue(self._hp_max)
        self.__hp_bar.setTextVisible(False)
        self.__hp_bar.setMaximumSize(size[0], 5)

        self.setAlignment(Qt.AlignCenter)
        self.updatePixmap()

        if _debugging:
            self.setStyleSheet("border: 1px solid black")

    @property
    def health(self):
        return self.__hp_bar.value()

    @health.setter
    def health(self, hp):
        if hp > self._hp_max:
            hp = self._hp_max
        elif hp < 0:
            hp = 0
        self.__hp_bar.setValue(hp)

    @property
    def angle(self):
        return self.__angle

    @angle.setter
    def angle(self, angle):
        self.__angle = angle
        self.updatePixmap()

    @property
    def cord_x(self):
        return self.__cord_x

    @cord_x.setter
    def cord_x(self, cord):
        self.__cord_x = cord
        self.move(self.cord_x, self.cord_y)

    @property
    def cord_y(self):
        return self.__cord_y

    @cord_y.setter
    def cord_y(self, cord):
        self.__cord_y = cord
        self.move(self.cord_x, self.cord_y)

    def hide_hp_bar(self, bool=False):
        if bool:
            self.__hp_bar.hide()
        else:
            self.__hp_bar.show()

    def add_decoration(self, path):
        if path is None:
            self._decor_label.deleteLater()
            self._decor_label = None
        else:
            self._decor_label = QLabel(self)
            self._decor_pixmap = QPixmap(path)
            # self._decor_pixmap = self._decor_pixmap.scaled(self._size[0], self._size[1])
            self._decor_pixmap = self._decor_pixmap.transformed(
                QTransform().rotate(self.angle))
            self._decor_label.setPixmap(self._decor_pixmap)
            self._decor_label.setAlignment(Qt.AlignCenter)
            self._decor_label.show()

    def updatePixmap(self):
        path = get_asset_path(self._base_image)
        self.__pixmap = QPixmap(path)
        self.__pixmap = self.__pixmap.scaled(self._size[0], self._size[1])
        self.__pixmap = self.__pixmap.transformed(QTransform().rotate(
            self.angle))
        self._base_label.setPixmap(self.__pixmap)
        self._base_label.show()
        # self.setFixedSize(self.__pixmap.width(), self.__pixmap.height())

    def setFixedSize(self, x, y):
        super().setFixedSize(x, y)
        self._base_label.setFixedSize(x, y)

    def setAlignment(self, alignment):
        self._base_label.setAlignment(alignment)
예제 #52
0
class WindPanel(QFrame):
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("WindPanel" +
                           str(len(parent.findChildren(WindPanel))))

        #         self.frame_WindIA = QFrame(parent)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Raised)
        self.setObjectName(("frame_WindIA"))
        self.hLayout = QHBoxLayout(self)
        self.hLayout.setSpacing(0)
        self.hLayout.setMargin(0)
        self.hLayout.setObjectName(("hLayout"))

        self.basicFrame = Frame(self, "HL")
        self.hLayout.addWidget(self.basicFrame)

        self.lblIA = QLabel(self.basicFrame)
        self.lblIA.setMinimumSize(QSize(200, 0))
        self.lblIA.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lblIA.setFont(font)
        self.lblIA.setObjectName(("lblIA"))
        self.basicFrame.Add = self.lblIA

        self.comboBox = QComboBox(self.basicFrame)
        # sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())
        # self.comboBox.setSizePolicy(sizePolicy)
        # self.comboBox.setMinimumSize(QSize(60, 0))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName(("comboBox"))
        self.basicFrame.Add = self.comboBox

        self.speedBox = QLineEdit(self.basicFrame)
        # sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(self.speedBox.sizePolicy().hasHeightForWidth())
        # self.speedBox.setSizePolicy(sizePolicy)
        # self.speedBox.setMinimumSize(QSize(70, 0))
        # self.speedBox.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.speedBox.setFont(font)
        self.speedBox.setObjectName(("speedBox"))
        self.speedBox.setMinimumSize(QSize(60, 0))
        self.speedBox.setMaximumSize(QSize(60, 16777215))
        self.basicFrame.Add = self.speedBox

        spacerItem = QSpacerItem(0, 0, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.basicFrame.layoutBoxPanel.addItem(spacerItem)

        self.altitude = Altitude.NaN()
        self.customValue = Speed(30).Knots
        self.comboBox.addItems(["ICAO", "UK", "Custom"])
        self.comboBox.currentIndexChanged.connect(self.changeWindType)
        self.comboBox.setCurrentIndex(0)
        self.lblIA.setText("Wind (kts):")
        self.speedBox.setEnabled(False)

    def setAltitude(self, value):
        self.altitude = value
        self.method_5()
#     def getValue(self, SpeedUnits_0 = SpeedUnits.KTS):
#         return Speed(float(self.speedBox.text()), SpeedUnits_0)

    def method_3(self, altitude_0):
        altitude = Altitude(float(self.speedBox.text()), AltitudeUnits.FT)
        if (self.comboBox.currentIndex() != 0):
            return altitude
        return Altitude(altitude.Feet - altitude_0.Feet, AltitudeUnits.FT)

    def method_5(self):
        if self.comboBox.currentIndex() == 0:
            self.speedBox.setText(
                str(round(Speed.smethod_1(self.altitude).Knots, 1)))
        elif self.comboBox.currentIndex() == 1:
            self.speedBox.setText(
                str(round(Speed.smethod_2(self.altitude).Knots, 1)))
        else:
            self.speedBox.setText(str(self.customValue))
        if self.comboBox.currentIndex() != 2:
            self.speedBox.setEnabled(False)
        else:
            self.speedBox.setEnabled(True)

    def changeWindType(self):
        self.method_5()

    def method_7(self, string_0):
        # object[] string0 = new object[] { string_0, this.captionLabel.Caption, this.speedBox.ToString(), this.comboBox.Items[this.comboBox.SelectedIndex] };
        return "%s%s\t%s (%s)" % (string_0, "Wind: ", self.speedBox.text(),
                                  self.comboBox.currentText())

    def set_LabelWidth(self, width):
        self.lblIA.setMinimumSize(QSize(width, 0))
        self.lblIA.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def get_speed(self):
        try:
            return Speed(float(self.speedBox.text()))
        except:
            return None

    Value = property(get_speed, None, None, None)

    def get_isEmpty(self):
        try:
            num = float(self.speedBox.text())
            return False
        except:
            return True

    IsEmpty = property(get_isEmpty, None, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)
예제 #53
0
    def __createLayout(self):
        " Creates the widget layout "

        verticalLayout = QVBoxLayout(self)
        verticalLayout.setContentsMargins(0, 0, 0, 0)
        verticalLayout.setSpacing(0)

        self.headerFrame = QFrame()
        self.headerFrame.setFrameStyle(QFrame.StyledPanel)
        self.headerFrame.setAutoFillBackground(True)
        headerPalette = self.headerFrame.palette()
        headerBackground = headerPalette.color(QPalette.Background)
        headerBackground.setRgb(min(headerBackground.red() + 30, 255),
                                min(headerBackground.green() + 30, 255),
                                min(headerBackground.blue() + 30, 255))
        headerPalette.setColor(QPalette.Background, headerBackground)
        self.headerFrame.setPalette(headerPalette)
        self.headerFrame.setFixedHeight(24)

        self.__stackLabel = QLabel("Stack")

        expandingSpacer = QSpacerItem(10, 10, QSizePolicy.Expanding)
        fixedSpacer = QSpacerItem(3, 3)

        self.__showHideButton = QToolButton()
        self.__showHideButton.setAutoRaise(True)
        self.__showHideButton.setIcon(PixmapCache().getIcon('less.png'))
        self.__showHideButton.setFixedSize(20, 20)
        self.__showHideButton.setToolTip("Hide frames list")
        self.__showHideButton.setFocusPolicy(Qt.NoFocus)
        self.__showHideButton.clicked.connect(self.__onShowHide)

        headerLayout = QHBoxLayout()
        headerLayout.setContentsMargins(0, 0, 0, 0)
        headerLayout.addSpacerItem(fixedSpacer)
        headerLayout.addWidget(self.__stackLabel)
        headerLayout.addSpacerItem(expandingSpacer)
        headerLayout.addWidget(self.__showHideButton)
        self.headerFrame.setLayout(headerLayout)

        self.__framesList = QTreeWidget(self)
        self.__framesList.setSortingEnabled(False)
        # I might not need that because of two reasons:
        # - the window has no focus
        # - the window has custom current indicator
        # self.__framesList.setAlternatingRowColors( True )
        self.__framesList.setRootIsDecorated(False)
        self.__framesList.setItemsExpandable(False)
        self.__framesList.setUniformRowHeights(True)
        self.__framesList.setSelectionMode(QAbstractItemView.NoSelection)
        self.__framesList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.__framesList.setItemDelegate(NoOutlineHeightDelegate(4))
        self.__framesList.setFocusPolicy(Qt.NoFocus)
        self.__framesList.setContextMenuPolicy(Qt.CustomContextMenu)

        self.__framesList.itemClicked.connect(self.__onFrameClicked)
        self.__framesList.itemDoubleClicked.connect(
            self.__onFrameDoubleClicked)
        self.__framesList.customContextMenuRequested.connect(
            self.__showContextMenu)

        self.__framesList.setHeaderLabels(
            ["", "File:line", "Function", "Full path"])

        verticalLayout.addWidget(self.headerFrame)
        verticalLayout.addWidget(self.__framesList)
        return
예제 #54
0
class RunDialog(QDialog):
    def __init__(self, run_model, parent):
        QDialog.__init__(self, parent)
        self.setWindowFlags(Qt.Window)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setModal(True)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle("Simulations")

        assert isinstance(run_model, BaseRunModel)
        self._run_model = run_model

        ert = None
        if isinstance(run_model, BaseRunModel):
            ert = run_model.ert()

        self.simulations_tracker = SimulationsTracker()
        states = self.simulations_tracker.getStates()
        self.state_colors = {state.name: state.color for state in states}
        self.state_colors['Success'] = self.state_colors["Finished"]
        self.state_colors['Failure'] = self.state_colors["Failed"]

        self.total_progress = SimpleProgress()

        status_layout = QHBoxLayout()
        status_layout.addStretch()
        self.__status_label = QLabel()
        status_layout.addWidget(self.__status_label)
        status_layout.addStretch()
        status_widget_container = QWidget()
        status_widget_container.setLayout(status_layout)

        self.progress = Progress()
        self.progress.setIndeterminateColor(self.total_progress.color)
        for state in states:
            self.progress.addState(state.state, QColor(*state.color),
                                   100.0 * state.count / state.total_count)

        legend_layout = QHBoxLayout()
        self.legends = {}
        for state in states:
            self.legends[state] = Legend("%s (%d/%d)", QColor(*state.color))
            self.legends[state].updateLegend(state.name, 0, 0)
            legend_layout.addWidget(self.legends[state])

        legend_widget_container = QWidget()
        legend_widget_container.setLayout(legend_layout)

        self.running_time = QLabel("")

        self.plot_tool = PlotTool()
        self.plot_tool.setParent(None)
        self.plot_button = QPushButton(self.plot_tool.getName())
        self.plot_button.clicked.connect(self.plot_tool.trigger)
        self.plot_button.setEnabled(ert is not None)

        self.kill_button = QPushButton("Kill simulations")
        self.done_button = QPushButton("Done")
        self.done_button.setHidden(True)
        self.restart_button = QPushButton("Restart")
        self.restart_button.setHidden(True)
        self.show_details_button = QPushButton("Details")
        self.show_details_button.setCheckable(True)

        size = 20
        spin_movie = resourceMovie("ide/loading.gif")
        spin_movie.setSpeed(60)
        spin_movie.setScaledSize(QSize(size, size))
        spin_movie.start()

        self.processing_animation = QLabel()
        self.processing_animation.setMaximumSize(QSize(size, size))
        self.processing_animation.setMinimumSize(QSize(size, size))
        self.processing_animation.setMovie(spin_movie)

        button_layout = QHBoxLayout()
        button_layout.addWidget(self.processing_animation)
        button_layout.addWidget(self.running_time)
        button_layout.addStretch()
        button_layout.addWidget(self.show_details_button)
        button_layout.addWidget(self.plot_button)
        button_layout.addWidget(self.kill_button)
        button_layout.addWidget(self.done_button)
        button_layout.addWidget(self.restart_button)
        button_widget_container = QWidget()
        button_widget_container.setLayout(button_layout)

        self.detailed_progress = DetailedProgressWidget(
            self, self.state_colors)
        self.detailed_progress.setVisible(False)
        self.dummy_widget_container = QWidget(
        )  #Used to keep the other widgets from stretching

        layout = QVBoxLayout()
        layout.addWidget(self.total_progress)
        layout.addWidget(status_widget_container)
        layout.addWidget(self.progress)
        layout.addWidget(legend_widget_container)
        layout.addWidget(self.detailed_progress)
        layout.addWidget(self.dummy_widget_container)
        layout.addWidget(button_widget_container)

        layout.setStretch(0, 0)
        layout.setStretch(1, 0)
        layout.setStretch(2, 0)
        layout.setStretch(3, 0)
        layout.setStretch(4, 1)
        layout.setStretch(5, 1)
        layout.setStretch(6, 0)

        self.setLayout(layout)

        self.kill_button.clicked.connect(self.killJobs)
        self.done_button.clicked.connect(self.accept)
        self.restart_button.clicked.connect(self.restart_failed_realizations)
        self.show_details_button.clicked.connect(self.toggle_detailed_progress)

        self.__updating = False
        self.__update_queued = False
        self.__simulation_started = False

        self.__update_timer = QTimer(self)
        self.__update_timer.setInterval(500)
        self.__update_timer.timeout.connect(self.updateRunStatus)
        self._simulations_argments = {}

    def closeEvent(self, QCloseEvent):
        if not self.checkIfRunFinished():
            #Kill jobs if dialog is closed
            if self.killJobs() != QMessageBox.Yes:
                QCloseEvent.ignore()

    def startSimulation(self, arguments):

        self._simulations_argments = arguments

        if not 'prev_successful_realizations' in self._simulations_argments:
            self._simulations_argments['prev_successful_realizations'] = 0
        self._run_model.reset()

        def run():
            self._run_model.startSimulations(self._simulations_argments)

        simulation_thread = Thread(name="ert_gui_simulation_thread")
        simulation_thread.setDaemon(True)
        simulation_thread.run = run
        simulation_thread.start()

        self.__update_timer.start()

    def checkIfRunFinished(self):
        if self._run_model.isFinished():
            self.hideKillAndShowDone()

            if self._run_model.hasRunFailed():
                error = self._run_model.getFailMessage()
                QMessageBox.critical(
                    self, "Simulations failed!",
                    "The simulation failed with the following error:\n\n%s" %
                    error)

            return True
        return False

    def updateProgress(self):

        total_count = self._run_model.getQueueSize()
        queue_status = self._run_model.getQueueStatus()
        states = self.simulations_tracker.getStates()

        for state in states:
            state.count = 0
            state.total_count = total_count

        for state in states:
            for queue_state in queue_status:
                if queue_state in state.state:
                    state.count += queue_status[queue_state]

            self.progress.updateState(state.state,
                                      100.0 * state.count / state.total_count)
            self.legends[state].updateLegend(state.name, state.count,
                                             state.total_count)

    def updateRunStatus(self):
        self.__status_label.setText(self._run_model.getPhaseName())

        if self.checkIfRunFinished():
            self.total_progress.setProgress(self._run_model.getProgress())
            self.detailed_progress.set_progress(
                *self._run_model.getDetailedProgress())
            self.updateProgress()
            return

        self.total_progress.setProgress(self._run_model.getProgress())

        if self._run_model.isIndeterminate():
            self.progress.setIndeterminate(True)
            states = self.simulations_tracker.getStates()
            for state in states:
                self.legends[state].updateLegend(state.name, 0, 0)

        else:
            if self.detailed_progress and self.detailed_progress.isVisible():
                self.detailed_progress.set_progress(
                    *self._run_model.getDetailedProgress())
            else:
                self._run_model.updateDetailedProgress(
                )  #update information without rendering

            self.progress.setIndeterminate(False)
            self.updateProgress()

        self.setRunningTime()

    def setRunningTime(self):
        days = 0
        hours = 0
        minutes = 0
        seconds = self._run_model.getRunningTime()

        if seconds >= 60:
            minutes, seconds = divmod(seconds, 60)

        if minutes >= 60:
            hours, minutes = divmod(minutes, 60)

        if hours >= 24:
            days, hours = divmod(hours, 24)

        if days > 0:
            self.running_time.setText(
                "Running time: %d days %d hours %d minutes %d seconds" %
                (days, hours, minutes, seconds))
        elif hours > 0:
            self.running_time.setText(
                "Running time: %d hours %d minutes %d seconds" %
                (hours, minutes, seconds))
        elif minutes > 0:
            self.running_time.setText("Running time: %d minutes %d seconds" %
                                      (minutes, seconds))
        else:
            self.running_time.setText("Running time: %d seconds" % seconds)

    def killJobs(self):

        msg = "Are you sure you want to kill the currently running simulations?"
        if self._run_model.getQueueStatus().get(
                JobStatusType.JOB_QUEUE_UNKNOWN, 0) > 0:
            msg += "\n\nKilling a simulation with unknown status will not kill the realizations already submitted!"
        kill_job = QMessageBox.question(self, "Kill simulations?", msg,
                                        QMessageBox.Yes | QMessageBox.No)

        if kill_job == QMessageBox.Yes:
            if self._run_model.killAllSimulations():
                self.reject()
        return kill_job

    def hideKillAndShowDone(self):
        self.__update_timer.stop()
        self.processing_animation.hide()
        self.kill_button.setHidden(True)
        self.done_button.setHidden(False)
        self.detailed_progress.set_progress(
            *self._run_model.getDetailedProgress())
        self.restart_button.setVisible(self.has_failed_realizations())
        self.restart_button.setEnabled(self._run_model.support_restart)

    def has_failed_realizations(self):
        completed = self._run_model.completed_realizations_mask
        initial = self._run_model.initial_realizations_mask
        for (index, successful) in enumerate(completed):
            if initial[index] and not successful:
                return True
        return False

    def count_successful_realizations(self):
        """
        Counts the realizations completed in the prevoius ensemble run
        :return:
        """
        completed = self._run_model.completed_realizations_mask
        return completed.count(True)

    def create_mask_from_failed_realizations(self):
        """
        Creates a BoolVector mask representing the failed realizations
        :return: Type BoolVector
        """
        completed = self._run_model.completed_realizations_mask
        initial = self._run_model.initial_realizations_mask
        inverted_mask = BoolVector(default_value=False)
        for (index, successful) in enumerate(completed):
            inverted_mask[index] = initial[index] and not successful
        return inverted_mask

    def restart_failed_realizations(self):

        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Information)
        msg.setText(
            "Note that workflows will only be executed on the restarted realizations and that this might have unexpected consequences."
        )
        msg.setWindowTitle("Restart Failed Realizations")
        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        result = msg.exec_()

        if result == QMessageBox.Ok:
            self.restart_button.setVisible(False)
            self.kill_button.setVisible(True)
            self.done_button.setVisible(False)
            active_realizations = self.create_mask_from_failed_realizations()
            self._simulations_argments[
                'active_realizations'] = active_realizations
            self._simulations_argments[
                'prev_successful_realizations'] += self.count_successful_realizations(
                )
            self.startSimulation(self._simulations_argments)

    def toggle_detailed_progress(self):

        self.detailed_progress.setVisible(not (
            self.detailed_progress.isVisible()))
        self.dummy_widget_container.setVisible(not (
            self.detailed_progress.isVisible()))
        self.adjustSize()
예제 #55
0
def buildfromauto(formconfig, base):
    widgetsconfig = copy.deepcopy(formconfig['widgets'])

    try:
        widgetsconfig = base.get_widgets(widgetsconfig)
    except AttributeError:
        pass

    newstyle = formconfig.get("newstyle", False)
    hassections = any(config['widget'] == "Section"
                      for config in widgetsconfig)

    def make_layout():
        if newstyle:
            return QVBoxLayout()
        else:
            layout = QFormLayout()
            layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
            return layout

    def make_tab(tabwidget, name):
        widget = QWidget()
        widget.setLayout(make_layout())
        tabwidget.addTab(widget, name)
        return widget, widget.layout()

    if hassections:
        outwidget = QTabWidget(base)
        outlayout = None
        base.setLayout(QVBoxLayout())
        base.layout().setContentsMargins(0, 0, 0, 0)
        base.layout().addWidget(outwidget)
    else:
        outwidget = base
        outlayout = make_layout()
        outwidget.setLayout(outlayout)

    if roam.config.settings.get("form_geom_edit", False):
        geomwidget = GeomWidget()
        geomwidget.setObjectName("__geomwidget")
        outlayout.addRow("Geometry", geomwidget)

    insection = False
    for config in widgetsconfig:
        widgettype = config['widget']

        ## Make the first tab if one isn't defined already and we have other sections in the config
        if not insection and hassections and not widgettype == "Section":
            name = formconfig['label']
            tabwidget, outlayout = make_tab(outwidget, name)
            insection = True

        if widgettype == 'Section':
            # Add a spacer to the last widget
            if outlayout:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
                outlayout.addItem(QSpacerItem(10, 500))
                outlayout.addWidget(spacer)

            name = config['name']
            tabwidget, outlayout = make_tab(outwidget, name)
            installflickcharm(tabwidget)
            insection = True
            continue

        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue

        label = QLabel(name)
        label.setObjectName(field + "_label")
        labelwidget = QWidget()
        labelwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        labelwidget.layout().addWidget(label)
        labelwidget.layout().setContentsMargins(0, 0, 0, 0)

        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        layoutwidget.layout().setContentsMargins(0, 0, 0, 10)

        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            if newstyle:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
                labelwidget.layout().addWidget(spacer)
                labelwidget.layout().addWidget(savebutton)
            else:
                layoutwidget.layout().addWidget(savebutton)

        if newstyle:
            outlayout.addWidget(labelwidget)
            outlayout.addWidget(layoutwidget)
        else:
            outlayout.addRow(labelwidget, layoutwidget)

    spacer = QWidget()
    spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
    outlayout.addWidget(spacer)
    if not hassections:
        outlayout.addItem(QSpacerItem(10, 500))
        installflickcharm(outwidget)
    return base
예제 #56
0
class StackViewer(QWidget):
    " Implements the stack viewer for a debugger "

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

        self.__debugger = debugger
        self.currentStack = None
        self.currentFrame = 0
        self.__createPopupMenu()
        self.__createLayout()

        if Settings().showStackViewer == False:
            self.__onShowHide(True)
        return

    def __createPopupMenu(self):
        " Creates the popup menu "
        self.__framesMenu = QMenu()
        self.__setCurrentMenuItem = self.__framesMenu.addAction(
            "Set current (single click)", self.__onSetCurrent)
        self.__jumpMenuItem = self.__framesMenu.addAction(
            "Set current and jump to the source (double click)",
            self.__onSetCurrentAndJump)
        return

    def __createLayout(self):
        " Creates the widget layout "

        verticalLayout = QVBoxLayout(self)
        verticalLayout.setContentsMargins(0, 0, 0, 0)
        verticalLayout.setSpacing(0)

        self.headerFrame = QFrame()
        self.headerFrame.setFrameStyle(QFrame.StyledPanel)
        self.headerFrame.setAutoFillBackground(True)
        headerPalette = self.headerFrame.palette()
        headerBackground = headerPalette.color(QPalette.Background)
        headerBackground.setRgb(min(headerBackground.red() + 30, 255),
                                min(headerBackground.green() + 30, 255),
                                min(headerBackground.blue() + 30, 255))
        headerPalette.setColor(QPalette.Background, headerBackground)
        self.headerFrame.setPalette(headerPalette)
        self.headerFrame.setFixedHeight(24)

        self.__stackLabel = QLabel("Stack")

        expandingSpacer = QSpacerItem(10, 10, QSizePolicy.Expanding)
        fixedSpacer = QSpacerItem(3, 3)

        self.__showHideButton = QToolButton()
        self.__showHideButton.setAutoRaise(True)
        self.__showHideButton.setIcon(PixmapCache().getIcon('less.png'))
        self.__showHideButton.setFixedSize(20, 20)
        self.__showHideButton.setToolTip("Hide frames list")
        self.__showHideButton.setFocusPolicy(Qt.NoFocus)
        self.__showHideButton.clicked.connect(self.__onShowHide)

        headerLayout = QHBoxLayout()
        headerLayout.setContentsMargins(0, 0, 0, 0)
        headerLayout.addSpacerItem(fixedSpacer)
        headerLayout.addWidget(self.__stackLabel)
        headerLayout.addSpacerItem(expandingSpacer)
        headerLayout.addWidget(self.__showHideButton)
        self.headerFrame.setLayout(headerLayout)

        self.__framesList = QTreeWidget(self)
        self.__framesList.setSortingEnabled(False)
        # I might not need that because of two reasons:
        # - the window has no focus
        # - the window has custom current indicator
        # self.__framesList.setAlternatingRowColors( True )
        self.__framesList.setRootIsDecorated(False)
        self.__framesList.setItemsExpandable(False)
        self.__framesList.setUniformRowHeights(True)
        self.__framesList.setSelectionMode(QAbstractItemView.NoSelection)
        self.__framesList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.__framesList.setItemDelegate(NoOutlineHeightDelegate(4))
        self.__framesList.setFocusPolicy(Qt.NoFocus)
        self.__framesList.setContextMenuPolicy(Qt.CustomContextMenu)

        self.__framesList.itemClicked.connect(self.__onFrameClicked)
        self.__framesList.itemDoubleClicked.connect(
            self.__onFrameDoubleClicked)
        self.__framesList.customContextMenuRequested.connect(
            self.__showContextMenu)

        self.__framesList.setHeaderLabels(
            ["", "File:line", "Function", "Full path"])

        verticalLayout.addWidget(self.headerFrame)
        verticalLayout.addWidget(self.__framesList)
        return

    def __onShowHide(self, startup=False):
        " Triggered when show/hide button is clicked "
        if startup or self.__framesList.isVisible():
            self.__framesList.setVisible(False)
            self.__showHideButton.setIcon(PixmapCache().getIcon('more.png'))
            self.__showHideButton.setToolTip("Show frames list")

            self.__minH = self.minimumHeight()
            self.__maxH = self.maximumHeight()

            self.setMinimumHeight(self.headerFrame.height())
            self.setMaximumHeight(self.headerFrame.height())

            Settings().showStackViewer = False
        else:
            self.__framesList.setVisible(True)
            self.__showHideButton.setIcon(PixmapCache().getIcon('less.png'))
            self.__showHideButton.setToolTip("Hide frames list")

            self.setMinimumHeight(self.__minH)
            self.setMaximumHeight(self.__maxH)

            Settings().showStackViewer = True
        return

    def clear(self):
        " Clears the content "
        self.__framesList.clear()
        self.currentStack = None
        self.__stackLabel.setText("Stack")
        return

    def __resizeColumns(self):
        " Resize the files list columns "
        self.__framesList.header().setStretchLastSection(True)
        self.__framesList.header().resizeSections(QHeaderView.ResizeToContents)
        self.__framesList.header().resizeSection(0, 22)
        self.__framesList.header().setResizeMode(0, QHeaderView.Fixed)
        return

    def populate(self, stack):
        " Sets the new call stack and selects the first item in it "
        self.clear()

        self.currentStack = stack
        self.currentFrame = 0
        frameNumber = 0
        for s in stack:
            if len(s) == 2:
                # This is when an exception comes
                funcName = ""
            else:
                funcName = s[2]
            item = StackFrameItem(s[0], s[1], funcName, frameNumber)
            self.__framesList.addTopLevelItem(item)
            frameNumber += 1
        self.__resizeColumns()
        self.__framesList.topLevelItem(0).setCurrent(True)
        self.__stackLabel.setText("Stack (total: " + str(len(stack)) + ")")
        return

    def getFrameNumber(self):
        " Provides the current frame number "
        return self.currentFrame

    def __onFrameClicked(self, item, column):
        " Triggered when a frame is clicked "
        if item.isCurrent():
            return

        # Hide the current indicator
        self.__framesList.topLevelItem(self.currentFrame).setCurrent(False)

        # Show the new indicator
        self.currentFrame = item.getFrameNumber()
        for index in xrange(self.__framesList.topLevelItemCount()):
            item = self.__framesList.topLevelItem(index)
            if item.getFrameNumber() == self.currentFrame:
                item.setCurrent(True)
        self.__debugger.remoteClientVariables(1, self.currentFrame)  # globals
        self.__debugger.remoteClientVariables(0, self.currentFrame)  # locals
        return

    def __onFrameDoubleClicked(self, item, column):
        " Triggered when a frame is double clicked "
        # The frame has been switched already because the double click
        # signal always comes after the single click one
        fileName = item.getFilename()
        lineNumber = item.getLineNumber()

        editorsManager = GlobalData().mainWindow.editorsManager()
        editorsManager.openFile(fileName, lineNumber)
        editor = editorsManager.currentWidget().getEditor()
        editor.gotoLine(lineNumber)
        editorsManager.currentWidget().setFocus()
        return

    def __showContextMenu(self, coord):
        " Shows the frames list context menu "
        self.__contextItem = self.__framesList.itemAt(coord)
        if self.__contextItem is not None:
            self.__setCurrentMenuItem.setEnabled(
                not self.__contextItem.isCurrent())
            self.__framesMenu.popup(QCursor.pos())
        return

    def __onSetCurrent(self):
        " Context menu item handler "
        self.__onFrameClicked(self.__contextItem, 0)
        return

    def __onSetCurrentAndJump(self):
        " Context menu item handler "
        self.__onFrameClicked(self.__contextItem, 0)
        self.__onFrameDoubleClicked(self.__contextItem, 0)
        return

    def switchControl(self, isInIDE):
        " Switches the UI depending where the control flow is "
        self.__framesList.setEnabled(isInIDE)
        return
예제 #57
0
class Listener(QWidget):
    def __init__(self, core_file_name):
        super(Listener, self).__init__()
        self.core_file_name = core_file_name

        self.setup_ui()
        self.setup_timers()

        port = SERIAL_PORT
        self.serial = serial.Serial(port, BAUDE_RATE, timeout=0)
        self.incoming_data = []

        self.imu = IMU(PLATFORM_SPECIFIC_QUOTIENTS['stm'])
        self.stroke = Stroke()
        self.selector = Selector(self.core_file_name)

        self.acceleration_filter = AperiodicFilter(ACCELERATION_TIME_CONST)

        self.stroke.widget = self.display
        self.stroke.on_done = self.get_stroke

        self.previous_time = None

        self.data_buffer = ''

        self.init_selector()


    def setup_ui(self):
        self.resize(500, 500)
        self.out = QLabel(self)
        self.out.setMinimumHeight(100)
        font = QFont()
        font.setPixelSize(80)
        self.out.setFont(font)
        self.grid = QGridLayout(self)
        self.display = StrokeWidget()
        self.letter_selector = QComboBox()
        self.grid.addWidget(self.display, 0, 0, 1, 1)
        self.grid.addWidget(self.letter_selector, 1, 0, 1, 1)
        self.grid.addWidget(self.out, 2, 0, 1, 1)

    def setup_timers(self):
        self.serial_timer = QTimer()
        self.serial_timer.setInterval(SERIAL_INTERVAL)
        self.serial_timer.timeout.connect(self.get_data)
        self.serial_timer.start()

        self.process_timer = QTimer()
        self.process_timer.setInterval(PROCESS_INTERVAL)
        self.process_timer.timeout.connect(self.process)
        self.process_timer.start()

        self.display_timer = QTimer()
        self.display_timer.setInterval(DISPLAY_TIMEOUT)
        self.display_timer.setSingleShot(True)
        self.display_timer.timeout.connect(self.set_background)


    def init_selector(self):
        sel_lines = self.selector.letters_dict.keys()
        sel_lines.insert(0, 'new strokes')
        sel_lines.insert(0, 'free run')
        self.letter_selector.addItems(sel_lines)
        self.letter_selector.currentIndexChanged.connect(self.set_background)

    def set_background(self):
        letter = str(self.letter_selector.currentText())
        self.display.set_background(self.core_file_name, letter)

    def store_stroke(self, key, stroke, existing=True):
        file_name = '{key}{time}.txt'.format(key=key, time=int(time()))
        file_path = os.path.join(LEARNED_FOLDER, file_name)
        np.savetxt(file_path, stroke)
        if existing:
            self.display.set_background(self.core_file_name, key, color='g')
            self.display_timer.start()        

    def get_stroke(self, data):
        stroke = data['stroke']
        dimention = data['dimention']
        if dimention < MIN_DIMENTION:
            print 'too small'
            return

        letter = str(self.letter_selector.currentText())
        if letter == 'new strokes':
            self.store_stroke('_', stroke, existing=False)
            print 'recorded'

        try:
            letters = self.selector.check_stroke(stroke)
        except: #TODO: check unify_stroke
            return

        if letters:
            self.out.setText(self.out.text()+letters[0])

        if letter == 'free run' and letters:
            self.store_stroke(letters[0], stroke)
        elif letter in letters:
            self.store_stroke(letter, stroke)

    def process(self):
        local_data_storage = deepcopy(self.incoming_data)
        self.incoming_data = []

        for data in local_data_storage:
            if self.previous_time is None:
                self.previous_time = data[0]
                continue

            data[0], self.previous_time = data[0] - self.previous_time, data[0]

            if data[0] < MAX_DATA_TIMELAPSE:
                self.imu.calc(data)
                gyro = np.linalg.norm(np.array([data[7:]]))
                accel = self.imu.get_global_acceleration()

                accel = self.acceleration_filter.set_input(accel, data[0])

                accel_magnitude = np.linalg.norm(accel)

                if accel_magnitude > ACCELERATION_RESET:
                    self.execute_spell()

                Yr = self.imu.get_y_direction()

                self.stroke.set_data(Yr, gyro)

                self.stroke.process_size(data[0], accel)

        self.setVisible(not self.imu.in_calibration)

    def execute_spell(self):
        self.out.setText('')

    def get_data(self):
        try:
            self.data_buffer += self.serial.read(self.serial.inWaiting())
            if self.data_buffer == '':
                return
            data_pieces = self.data_buffer.split(BUFFER_DELIMITER)

            # Put incomplete piece back to the buffer
            self.data_buffer = data_pieces.pop(-1)

            # If there are no complete data pieces - return from function
            if not data_pieces:
                return

            # Else - get the last of the pieces and discard the rest
            line = data_pieces[-1]

            result = [float(d) for d in line.split()]
            if len(result) != 9:
                raise ValueError('Nine pieces of data should be provided.')
            new_line = [time()] + result
            self.incoming_data.append(new_line)
        except KeyboardInterrupt:
            raise
        except Exception as e:
            # Something went wrong... nobody cares.
            print e
예제 #58
0
    def __init__(self, parent):
        super(EditorConfiguration, self).__init__()
        self._preferences, vbox = parent, QVBoxLayout(self)

        # groups
        group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_INDENT)
        group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_MARGIN)
        group3 = QGroupBox(translations.TR_LINT_DIRTY_TEXT)
        group4 = QGroupBox(translations.TR_PEP8_DIRTY_TEXT)
        group5 = QGroupBox(translations.TR_HIGHLIGHTER_EXTRAS)
        group6 = QGroupBox(translations.TR_TYPING_ASSISTANCE)
        group7 = QGroupBox(translations.TR_DISPLAY_ERRORS)

        # groups container
        container_widget_with_all_preferences = QWidget()
        formFeatures = QGridLayout(container_widget_with_all_preferences)

        # Indentation
        hboxg1 = QHBoxLayout(group1)
        hboxg1.setContentsMargins(5, 15, 5, 5)
        self._spin, self._checkUseTabs = QSpinBox(), QComboBox()
        self._spin.setRange(1, 10)
        self._spin.setValue(settings.INDENT)
        hboxg1.addWidget(self._spin)
        self._checkUseTabs.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(),
            translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize()
        ])
        self._checkUseTabs.setCurrentIndex(int(settings.USE_TABS))
        hboxg1.addWidget(self._checkUseTabs)
        formFeatures.addWidget(group1, 0, 0)

        # Margin Line
        hboxg2 = QHBoxLayout(group2)
        hboxg2.setContentsMargins(5, 15, 5, 5)
        self._checkShowMargin = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MARGIN_LINE)
        self._checkShowMargin.setChecked(settings.SHOW_MARGIN_LINE)
        hboxg2.addWidget(self._checkShowMargin)
        self._spinMargin = QSpinBox()
        self._spinMargin.setRange(50, 100)
        self._spinMargin.setSingleStep(2)
        self._spinMargin.setValue(settings.MARGIN_LINE)
        hboxg2.addWidget(self._spinMargin)
        hboxg2.addWidget(QLabel(translations.TR_CHARACTERS))
        formFeatures.addWidget(group2, 0, 1)

        # Display Errors
        hboxDisplay = QHBoxLayout(group7)
        hboxDisplay.setContentsMargins(5, 15, 5, 5)
        self._checkHighlightLine = QComboBox()
        self._checkHighlightLine.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_BACKGROUND,
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_UNDERLINE
        ])
        self._checkHighlightLine.setCurrentIndex(
            int(settings.UNDERLINE_NOT_BACKGROUND))
        hboxDisplay.addWidget(self._checkHighlightLine)
        formFeatures.addWidget(group7, 1, 0, 1, 0)

        # Find Lint Errors (highlighter)
        vboxg3 = QVBoxLayout(group3)
        self._checkErrors = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS)
        self._checkErrors.setChecked(settings.FIND_ERRORS)
        self.connect(self._checkErrors, SIGNAL("stateChanged(int)"),
                     self._disable_show_errors)
        self._showErrorsOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS)
        self._showErrorsOnLine.setChecked(settings.ERRORS_HIGHLIGHT_LINE)
        self.connect(self._showErrorsOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_errors_inline)
        vboxg3.addWidget(self._checkErrors)
        vboxg3.addWidget(self._showErrorsOnLine)
        formFeatures.addWidget(group3, 2, 0)

        # Find PEP8 Errors (highlighter)
        vboxg4 = QVBoxLayout(group4)
        vboxg4.setContentsMargins(5, 15, 5, 5)
        self._checkStyle = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8)
        self._checkStyle.setChecked(settings.CHECK_STYLE)
        self.connect(self._checkStyle, SIGNAL("stateChanged(int)"),
                     self._disable_check_style)
        vboxg4.addWidget(self._checkStyle)
        self._checkStyleOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8)
        self._checkStyleOnLine.setChecked(settings.CHECK_HIGHLIGHT_LINE)
        self.connect(self._checkStyleOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_check_inline)
        vboxg4.addWidget(self._checkStyleOnLine)
        formFeatures.addWidget(group4, 2, 1)

        # Show Python3 Migration, DocStrings and Spaces (highlighter)
        vboxg5 = QVBoxLayout(group5)
        vboxg5.setContentsMargins(5, 15, 5, 5)
        self._showMigrationTips = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MIGRATION)
        self._showMigrationTips.setChecked(settings.SHOW_MIGRATION_TIPS)
        vboxg5.addWidget(self._showMigrationTips)
        self._checkForDocstrings = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_CHECK_FOR_DOCSTRINGS)
        self._checkForDocstrings.setChecked(settings.CHECK_FOR_DOCSTRINGS)
        vboxg5.addWidget(self._checkForDocstrings)
        self._checkShowSpaces = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES)
        self._checkShowSpaces.setChecked(settings.SHOW_TABS_AND_SPACES)
        vboxg5.addWidget(self._checkShowSpaces)
        formFeatures.addWidget(group5, 3, 0)

        # End of line, Center On Scroll, Trailing space, Word wrap
        vboxg6 = QVBoxLayout(group6)
        vboxg6.setContentsMargins(5, 15, 5, 5)
        self._checkEndOfLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE)
        self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE)
        vboxg6.addWidget(self._checkEndOfLine)
        self._checkCenterScroll = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_CENTER_SCROLL)
        self._checkCenterScroll.setChecked(settings.CENTER_ON_SCROLL)
        vboxg6.addWidget(self._checkCenterScroll)
        self._checkTrailing = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING)
        self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES)
        vboxg6.addWidget(self._checkTrailing)
        self._allowWordWrap = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP)
        self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP)
        vboxg6.addWidget(self._allowWordWrap)
        formFeatures.addWidget(group6, 3, 1)

        # pack all the groups
        vbox.addWidget(container_widget_with_all_preferences)
        vbox.addItem(
            QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)
예제 #59
0
 def __init__(self):
     super(StatusBar, self).__init__()
     self.pos_cursor = "Linea: %s Columna: %s"
     self.line_column = QLabel(self.pos_cursor % (1, 0))
     self.addWidget(self.line_column)
예제 #60
0
class ListView(QStackedWidget):
    PAGE_EMPTY    = 0 
    PAGE_LISTVIEW = 1

    def __init__(self, parent = None):
        
        super(ListView, self).__init__(parent=parent)
        
        self.emptyMessage = QLabel("no elements defined yet")
        self.emptyMessage.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter )
        self.emptyMessage.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.addWidget(self.emptyMessage)
        
        self._table = QTableView()
        self.addWidget(self._table)
        self._table.clicked.connect(self.tableViewCellClicked)
        self._table.doubleClicked.connect(self.tableViewCellDoubleClicked)
        self._table.verticalHeader().sectionMoved.connect(self.rowMovedTest)
        self._table.setShowGrid(False)
    
    def resetEmptyMessage(self,pystring):
        self.emptyMessage.setText(QString(pystring))

    def tableViewCellClicked(self, modelIndex):
        '''
        Reimplemt this function to get interaction when double click
        :param modelIndex:
        '''
        
#         if (modelIndex.column() == self.model.ColumnID.Delete and
#             not self._table.model().flags(modelIndex) == Qt.NoItemFlags):
#             self._table.model().removeRow(modelIndex.row())
#     
    def tableViewCellDoubleClicked(self, modelIndex):
        '''
        Reimplement this function to get interaction when single click
        :param modelIndex:
        '''
#         if modelIndex.column() == self.model.ColumnID.Color:
#             self._colorDialog.setBrushColor(self._table.model()[modelIndex.row()].brushColor())
#             self._colorDialog.setPmapColor (self._table.model()[modelIndex.row()].pmapColor())
#             self._colorDialog.exec_()
#             #print "brush color = {}".format(self._colorDialog.brushColor().name())
#             #print "pmap color  = {}".format(self._colorDialog.pmapColor().name())
#             self._table.model().setData(modelIndex, (self._colorDialog.brushColor(),
#                                               self._colorDialog.pmapColor ()))

    def rowMovedTest(self, logicalIndex, oldVisualIndex, newVisualIndex):
        logger.debug( "{} {} {}".format(logicalIndex, oldVisualIndex, newVisualIndex) )

    def _setListViewLook(self):
        table = self._table
        #table.setDragEnabled(True)
        table.setAcceptDrops(True)
        table.setFocusPolicy(Qt.NoFocus)
        table.setShowGrid(False)
        table.horizontalHeader().hide()
        table.verticalHeader().hide()
        #table.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)
        table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
        
        
        table.setSelectionMode(QAbstractItemView.SingleSelection)
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
     
    def selectRow(self, *args, **kwargs):
        self._table.selectRow(*args, **kwargs)
        
    def _onRowsChanged(self, parent, start, end):
        model = self._table.model()
        if model and model.rowCount() > 0:
            self.setCurrentIndex(self.PAGE_LISTVIEW)
        else:
            self.setCurrentIndex(self.PAGE_EMPTY)
        if self.parent()!=None: self.parent().updateGeometry()

    def setModel(self, model):
        QTableView.setModel(self._table, model)
        self._table.setSelectionModel(model._selectionModel)
        
        if model.rowCount() > 0:
            self.setCurrentIndex(self.PAGE_LISTVIEW)
        else:
            self.setCurrentIndex(self.PAGE_EMPTY)
            
        model.rowsInserted.connect(self._onRowsChanged)
        model.rowsRemoved.connect(self._onRowsChanged)
        self.model=model
        
        self._setListViewLook()
        


    @property
    def allowDelete(self):
        return not self._table.isColumnHidden(self.model.ColumnID.Delete)

    @allowDelete.setter
    def allowDelete(self, allow):
        self._table.setColumnHidden(self.model.ColumnID.Delete, not allow)

    def minimumSizeHint(self):
        #http://www.qtcentre.org/threads/14764-QTableView-sizeHint%28%29-issues
        t = self._table
        vHeader = t.verticalHeader()
        hHeader = t.horizontalHeader()
        doubleFrame = 2 * t.frameWidth()
        w = hHeader.length() + vHeader.width() + doubleFrame;
     
        contentH = 0
        if self._table.model(): 
            for i in range(self._table.model().rowCount()):
                contentH += self._table.rowHeight(i)
        contentH = max(90, contentH) 
        
        h = hHeader.height() + contentH + doubleFrame;
        from PyQt4.QtCore import QSize
        return QSize(w,h)

    def sizeHint(self):
        return self.minimumSizeHint()
    
    def shrinkToMinimum(self):
        """
        shrink the view around the 
        labels which are currently there
        """
        t = self._table
        hHeader = t.horizontalHeader()
        doubleFrame = 2 * t.frameWidth()     
        contentH = 0
        if self._table.model(): 
            for i in range(self._table.model().rowCount()):
                contentH += self._table.rowHeight(i)
        h =  contentH+2
        self.setFixedHeight(h)