def __init__(self, opPixelClassification, parent):
        super( QDialog, self ).__init__(parent=parent)
        self._op = opPixelClassification
        classifier_listwidget = QListWidget(parent=self)
        classifier_listwidget.setSelectionMode( QListWidget.SingleSelection )

        classifier_factories = self._get_available_classifier_factories()
        for name, classifier_factory in list(classifier_factories.items()):
            item = QListWidgetItem( name )
            item.setData( Qt.UserRole, classifier_factory )
            classifier_listwidget.addItem(item)

        buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self )
        buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel )
        buttonbox.accepted.connect( self.accept )
        buttonbox.rejected.connect( self.reject )
        
        layout = QVBoxLayout()
        layout.addWidget( classifier_listwidget )
        layout.addWidget( buttonbox )

        self.setLayout(layout)
        self.setWindowTitle( "Select Classifier Type" )
        
        # Save members
        self._classifier_listwidget = classifier_listwidget
Example #2
0
    def __init__(self, node, controller):
        super().__init__()
        self.node = node

        action_label = QLabel('Action')
        object_label = QLabel('Object')
        
        self.object_list = QListWidget()
        self.object_list.setSortingEnabled(True)
        self.object_list.itemSelectionChanged.connect(self.text_update)        
        
        self.action_list = QListWidget()
        self.action_list.setSortingEnabled(True)
        self.action_list.itemSelectionChanged.connect(self.text_update)
        self.action_list.addItems(self.napalm_actions)
        
        self.properties_edit = QConsoleEdit()
        self.properties_edit.setMinimumSize(300, 300)

        layout = QGridLayout()
        layout.addWidget(object_label, 0, 0)
        layout.addWidget(self.object_list, 1, 0)
        layout.addWidget(action_label, 0, 1)
        layout.addWidget(self.action_list, 1, 1)
        layout.addWidget(self.properties_edit, 2, 0, 1, 2)
        self.setLayout(layout)
Example #3
0
class SelectLocator(QWidget):
    def doConnect(self):
        i = self.locatorW.selectedItems()

        if (i):
            item = i[0]
            addr = item.text()
            try:
                port = 15701
                self.glob.socket.connect("tcp://" + addr + ":" + str(port))
                self.glob.tabW.setTabEnabled(1, True)
                self.glob.tabW.setCurrentIndex(1)
                self.glob.Session.update()
            except Exception as e:
                print(e)

    def __init__(self, main, parent=None):
        super(SelectLocator, self).__init__(parent)
        self.glob = main
        mainLayout = QVBoxLayout()

        self.locatorW = QListWidget()
        #'127.0.0.1',
        locators = ['192.168.6.111']
        self.locatorW.insertItems(0, locators)

        btnW = QPushButton('Connect')
        btnW.clicked.connect(self.doConnect)

        mainLayout.addWidget(self.locatorW)
        mainLayout.addWidget(btnW)

        # mainLayout.addStretch(0)
        self.setLayout(mainLayout)
Example #4
0
   def initUI(self):
      self.setWindowModality(Qt.ApplicationModal)
      self.setWindowTitle("Create Chat")

      self.grid = QGridLayout(self)

      self.chat_name_label = QLabel("Chat Name:")
      self.grid.addWidget(self.chat_name_label, 0, 0, 1, 1)
      self.chat_name_field = QLineEdit()
      self.grid.addWidget(self.chat_name_field, 0, 1, 1, 3)

      self.unadded_friends = QListWidget()
      self.unadded_friends.setSortingEnabled(True)
      self.grid.addWidget(self.unadded_friends, 1, 0, 4, 2)

      self.added_friends = QListWidget()
      self.added_friends.setSortingEnabled(True)
      self.grid.addWidget(self.added_friends, 1, 3, 4, 1)

      self.add_friend_button = QPushButton(">>")
      self.add_friend_button.pressed.connect(self.addFriend)
      self.grid.addWidget(self.add_friend_button, 2, 2, 1, 1)

      self.remove_friend_button = QPushButton("<<")
      self.remove_friend_button.pressed.connect(self.removeFriend)
      self.grid.addWidget(self.remove_friend_button, 3, 2, 1, 1)

      self.create_button = QPushButton("Create")
      self.create_button.pressed.connect(self.createChat)
      self.grid.addWidget(self.create_button, 5, 0, 1, 4)

      self.cancel_button = QPushButton("Cancel")
      self.cancel_button.pressed.connect(self.cancel)
      self.grid.addWidget(self.cancel_button, 6, 0, 1, 4)
Example #5
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.createGroupBox()

        listWidget = QListWidget()

        for le in MainWindow.listEntries:
            listWidget.addItem(self.tr(le))

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.groupBox)
        mainLayout.addWidget(listWidget)
        self.centralWidget.setLayout(mainLayout)

        exitAction = QAction(self.tr("E&xit"), self,
                triggered=QApplication.instance().quit)

        fileMenu = self.menuBar().addMenu(self.tr("&File"))
        fileMenu.setPalette(QPalette(Qt.red))
        fileMenu.addAction(exitAction)

        self.setWindowTitle(self.tr("Language: %s") % self.tr("English"))
        self.statusBar().showMessage(self.tr("Internationalization Example"))

        if self.tr("LTR") == "RTL":
            self.setLayoutDirection(Qt.RightToLeft)
    def initMainUi(self):
        role_names = self.parentApplet.dataSelectionApplet.topLevelOperator.DatasetRoles.value
        self.list_widgets = []
        
        # Create a tab for each role
        for role_index, role_name in enumerate(role_names):
            select_button = QPushButton("Select " + role_name + " Files...", 
                                        clicked=partial(self.select_files, role_index) )
            clear_button = QPushButton("Clear " + role_name + " Files",
                                       clicked=partial(self.clear_files, role_index) )
            button_layout = QHBoxLayout()
            button_layout.addWidget(select_button)
            button_layout.addSpacerItem( QSpacerItem(0,0,hPolicy=QSizePolicy.Expanding) )
            button_layout.addWidget(clear_button)
            button_layout.setContentsMargins(0, 0, 0, 0)
            
            button_layout_widget = QWidget()
            button_layout_widget.setLayout(button_layout)
            button_layout_widget.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) )

            list_widget = QListWidget(parent=self)
            list_widget.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) )
            self.list_widgets.append( list_widget )

            tab_layout = QVBoxLayout()
            tab_layout.setContentsMargins(0, 0, 0, 0)
            tab_layout.addWidget( button_layout_widget )
            tab_layout.addWidget( list_widget )
            
            layout_widget = QWidget(parent=self)
            layout_widget.setLayout(tab_layout)
            self.addTab(layout_widget, role_name)
Example #7
0
 def __init__(self, parent=None):
     QListWidget.__init__(self, parent)
     self.setWindowTitle(tr("Saved Sessions"))
     self.setWindowFlags(Qt.Dialog)
     hideAction = QAction(self)
     hideAction.setShortcuts(["Esc", "Ctrl+W"])
     hideAction.triggered.connect(self.hide)
     self.addAction(hideAction)
     self.sessionList = QListWidget(self)
     self.sessionList.itemActivated.connect(self.loadSession)
     self.setCentralWidget(self.sessionList)
     self.toolBar = QToolBar(self)
     self.toolBar.setMovable(False)
     self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu)
     self.addToolBar(Qt.BottomToolBarArea, self.toolBar)
     self.loadButton = QPushButton(tr("&Load"), self)
     self.loadButton.clicked.connect(lambda: self.loadSession(self.sessionList.currentItem()))
     self.toolBar.addWidget(self.loadButton)
     self.saveButton = QPushButton(tr("&Save"), self)
     self.saveButton.clicked.connect(saveSessionManually)
     self.saveButton.clicked.connect(self.refresh)
     self.toolBar.addWidget(self.saveButton)
     deleteAction = QAction(self)
     deleteAction.setShortcut("Del")
     deleteAction.triggered.connect(self.delete)
     self.addAction(deleteAction)
Example #8
0
 def paintEvent(self, event):
     painter = QPainter(self.viewport())
     painter.drawTiledPixmap(0, 0, self.fPixmapWidth, self.height(), self.fPixmapL)
     painter.drawTiledPixmap(
         self.width() - self.fPixmapWidth - 2, 0, self.fPixmapWidth, self.height(), self.fPixmapR
     )
     QListWidget.paintEvent(self, event)
Example #9
0
    def mousePressEvent(self, event):
        if self.itemAt(event.pos()) is None and self.currentRow() != -1:
            event.accept()
            self.customClearSelection()
            return

        QListWidget.mousePressEvent(self, event)
Example #10
0
    def __init__(self, parent):
        QListWidget.__init__(self, parent)
        self.host = None
        self.fParent = None

        if False:
            # kdevelop likes this :)
            from carla_backend import CarlaHostMeta
            self.host = host = CarlaHostNull()

        exts = gCarla.utils.get_supported_file_extensions()

        self.fSupportedExtensions = tuple(("." + i) for i in exts)
        self.fLastSelectedItem    = None
        self.fWasLastDragValid    = False

        self.fPixmapL     = QPixmap(":/bitmaps/rack_interior_left.png")
        self.fPixmapR     = QPixmap(":/bitmaps/rack_interior_right.png")
        self.fPixmapWidth = self.fPixmapL.width()

        self.setMinimumWidth(RackListItem.kMinimumWidth)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setSortingEnabled(False)

        self.setDragEnabled(True)
        self.setDragDropMode(QAbstractItemView.DropOnly)
        self.setDropIndicatorShown(True)
        self.viewport().setAcceptDrops(True)

        self.setFrameShape(QFrame.NoFrame)
        self.setFrameShadow(QFrame.Plain)
Example #11
0
    def __init__(self, parent):
        QListWidget.__init__(self, parent)
        self.host = None

        if False:
            # kdevelop likes this :)
            from carla_backend import CarlaHostMeta

            host = CarlaHostMeta()
            self.host = host

        self.fSupportedExtensions = []
        self.fWasLastDragValid = False

        self.setMinimumWidth(640)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setSortingEnabled(False)

        self.setDragEnabled(True)
        self.setDragDropMode(QAbstractItemView.DropOnly)
        self.setDropIndicatorShown(True)
        self.viewport().setAcceptDrops(True)

        self.setFrameShape(QFrame.NoFrame)
        self.setFrameShadow(QFrame.Plain)

        self.fPixmapL = QPixmap(":/bitmaps/rack_interior_left.png")
        self.fPixmapR = QPixmap(":/bitmaps/rack_interior_right.png")

        self.fPixmapWidth = self.fPixmapL.width()
Example #12
0
    def __init__(self, main_window, projlist, parent=None):
        super().__init__(parent)
        self.layout = QHBoxLayout()
        self.setLayout(self.layout)

        self.tabs = QTabWidget()
        self.tabs.setObjectName('projectchoosertabs')

        self.layout.addWidget(self.tabs)

        self.projects = QListWidget()
        self.projects.currentItemChanged.connect(self.selected_project)

        self.templates = QListWidget()
        self.templates.currentItemChanged.connect(self.selected_template)

        if any(projlist):
            self.tabs.addTab(self.projects, "Existing Project")
        self.tabs.addTab(self.templates, "New Project")
        self.tabs.currentChanged.connect(self.tab_changed)

        self.detailspane = QVBoxLayout()
        self.layout.addLayout(self.detailspane)
        self.details = QLabel(DEFAULT_DETAILS)

        self.go = QPushButton("Go")
        self.go.setDisabled(True)
        self.go.clicked.connect(self.perform_action)
        self.detailspane.addWidget(self.details)
        self.detailspane.addWidget(self.go)

        self.action = None
        self.main_window = main_window
        self.projlist = projlist
        self.update_choices()
Example #13
0
 def startserver(self):
     self.setGeometry(300, 150, 500, 600)
     self.setWindowTitle('Chat')
     clearLayout(self.lay)
     online = QLabel('Online:')
     messages = QLabel('Messages:')
     self.list = QListWidget()
     self.list.setStyleSheet("QListWidget{border: none;border-radius:3px;background-color:#EEE}")
     self.active = QListWidget()
     self.active.setStyleSheet("QListWidget{border: none;border-radius:3px;background-color:#EEE;height:40}")
     self.line = QLineEdit()
     self.mesLine = QHBoxLayout()
     self.send = QPushButton('Send')
     self.send.setStyleSheet('background: #6d84b4;color: white;height:40;width:70px;border-radius:3px')
     self.mesLine.addWidget(self.line)
     self.mesLine.addWidget(self.send)
     self.send.clicked.connect(self.sendmessage)
     self.line.setStyleSheet("QLineEdit{border: none;border-radius:3px;background-color:#EEE;height:40}")
     self.line.setPlaceholderText("type something ...")
     self.startmode = QPushButton('Start typing')
     self.startmode.hide()
     self.startmode.clicked.connect(self.typeracer)
     self.lay.addWidget(online)
     self.lay.addWidget(self.active)
     self.lay.addWidget(messages)
     self.lay.addWidget(self.list)
     self.lay.addLayout(self.mesLine)
Example #14
0
    def mousePressEvent(self, event):
        if self.itemAt(event.pos()) is None:
            event.accept()
            self.setCurrentRow(-1)
            return

        QListWidget.mousePressEvent(self, event)
Example #15
0
    def __init__(self, fileInfo, parent=None):
        super(ApplicationsTab, self).__init__(parent)

        topLabel = QLabel("Open with:")

        applicationsListBox = QListWidget()
        applications = []

        for i in range(1, 31):
            applications.append("Application %d" % i)

        applicationsListBox.insertItems(0, applications)

        alwaysCheckBox = QCheckBox()

        if fileInfo.suffix():
            alwaysCheckBox = QCheckBox("Always use this application to open "
                    "files with the extension '%s'" % fileInfo.suffix())
        else:
            alwaysCheckBox = QCheckBox("Always use this application to open "
                    "this type of file")

        layout = QVBoxLayout()
        layout.addWidget(topLabel)
        layout.addWidget(applicationsListBox)
        layout.addWidget(alwaysCheckBox)
        self.setLayout(layout)
Example #16
0
    def dragEnterEvent(self, event):
        if self.isDragEventValid(event.mimeData().urls()):
            self.fWasLastDragValid = True
            event.acceptProposedAction()
            return

        self.fWasLastDragValid = False
        QListWidget.dragEnterEvent(self, event)
Example #17
0
class ListWidgetAction(QWidgetAction):
    def __init__(self, *args, **kwargs):
        super(ListWidgetAction, self).__init__(*args, **kwargs)
        self._listWidget = QListWidget()
        self._listWidget.setAlternatingRowColors(True)
        self.setDefaultWidget(self._listWidget)
    def listWidget(self):
        return self._listWidget
Example #18
0
    def __init__(self, pipe, preferences_mode=False, **kwargs):
        super().__init__(**kwargs)

        self.setWindowTitle('Edit Pipeline')
        self.setWindowModality(Qt.ApplicationModal)
        self.setLayout(QGridLayout())
        self.setMaximumSize(500, 400)
        self.setMinimumSize(500, 400)
        self.resize(500, 400)

        self._preferences_mode = preferences_mode

        # Input selection
        self.inputBox = QComboBox(self)
        self.layout().addWidget(self.inputBox, 0, 0, 1, 3)
        self.init_inputs(pipe)

        # Current plugins list
        self.currentList = QListWidget(self)
        self.currentList.setDragEnabled(True)
        self.currentList.setDragDropMode(QAbstractItemView.InternalMove)
        self.layout().addWidget(self.currentList, 1, 0, 3, 1)
        self.init_current_plugins(pipe)

        # Add/Remove plugins buttons
        self.pluginsLayout = QVBoxLayout(self)
        self.layout().addLayout(self.pluginsLayout, 2, 1)

        self.addButton = QPushButton(self)
        self.addButton.setIcon(QIcon.fromTheme('go-previous'))
        self.addButton.clicked.connect(self.__add_plugin)
        self.pluginsLayout.addWidget(self.addButton)
        self.pluginsLayout.setAlignment(self.addButton, Qt.AlignHCenter)

        self.delButton = QPushButton(self)
        self.delButton.setIcon(QIcon.fromTheme('go-next'))
        self.delButton.clicked.connect(self.__remove_plugin)
        self.pluginsLayout.addWidget(self.delButton)
        self.pluginsLayout.setAlignment(self.delButton, Qt.AlignHCenter)

        # Available plugins list
        self.availableList = QListWidget(self)
        self.layout().addWidget(self.availableList, 1, 2, 3, 1)
        self.init_available_plugins(pipe)

        # Output selection
        self.outputBox = QComboBox(self)
        self.layout().addWidget(self.outputBox, 4, 0, 1, 3)
        self.init_outputs(pipe)

        # Confirm/Cancel buttons
        self.dialogButtons = QDialogButtonBox(self)
        self.dialogButtons.setStandardButtons(QDialogButtonBox.Cancel |
                                              QDialogButtonBox.Ok)
        self.layout().addWidget(self.dialogButtons, 5, 0, 1, 3)

        self.dialogButtons.accepted.connect(self.accept)
        self.dialogButtons.rejected.connect(self.reject)
class MainWidget(QWidget):
    """
    MainWidget class
    Main widget for the main window

    """
    def __init__(self, parent):
        super(MainWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        self.load_button = QPushButton("Load data")
        self.load_button.clicked.connect(self.scrape_data)
        self.layout.addWidget(self.load_button)

        self.status_label = QLabel()
        self.layout.addWidget(self.status_label)

        self.list_widget = QListWidget()
        self.list_widget.itemClicked.connect(self.item_clicked)
        self.layout.addWidget(self.list_widget)

        # Load the data from the database
        self.load_data()

        self.setLayout(self.layout)

    def scrape_data(self):
        """
        Scrape the data and load it into the list widget

        """
        scrape_and_save()
        self.load_data()
        self.status_label.setText("Data loaded")

    def load_data(self):
        """
        Load the data from the database into the list widget

        """
        self.list_widget.clear()
        data = Database.load_data_from_db()
        for item in data:
            self.list_widget.addItem(item.date + " : " + item.title + " - " +
                                     item.image)

    def item_clicked(self, item):
        """
        When a user clicks on the item in the list widget get the url for the
        item image and open it in the browser
        :param item: List widget item

        """
        text = item.text()
        image = text.split(' - ')
        image = image[1]
        import webbrowser
        webbrowser.open(image)
Example #20
0
class LayerActionsDialog(QDialog):

    def __init__(self, currentGlyph, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Layer actions…"))
        self._workableLayers = []
        for layer in currentGlyph.layerSet:
            if layer != currentGlyph.layer:
                self._workableLayers.append(layer)

        layout = QGridLayout(self)

        copyBox = QRadioButton(self.tr("Copy"), self)
        moveBox = QRadioButton(self.tr("Move"), self)
        swapBox = QRadioButton(self.tr("Swap"), self)
        self.otherCheckBoxes = (moveBox, swapBox)
        copyBox.setChecked(True)

        self.layersList = QListWidget(self)
        self.layersList.addItems(
            layer.name for layer in self._workableLayers)
        if self.layersList.count():
            self.layersList.setCurrentRow(0)
        self.layersList.itemDoubleClicked.connect(self.accept)

        buttonBox = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        l = 0
        layout.addWidget(copyBox, l, 0, 1, 2)
        layout.addWidget(moveBox, l, 2, 1, 2)
        layout.addWidget(swapBox, l, 4, 1, 2)
        l += 1
        layout.addWidget(self.layersList, l, 0, 1, 6)
        l += 1
        layout.addWidget(buttonBox, l, 0, 1, 6)
        self.setLayout(layout)

    @classmethod
    def getLayerAndAction(cls, parent, currentGlyph):
        dialog = cls(currentGlyph, parent)
        result = dialog.exec_()
        currentItem = dialog.layersList.currentItem()
        newLayer = None
        if currentItem is not None:
            newLayerName = currentItem.text()
            for layer in dialog._workableLayers:
                if layer.name == newLayerName:
                    newLayer = layer
        action = "Copy"
        for checkBox in dialog.otherCheckBoxes:
            if checkBox.isChecked():
                action = checkBox.text()
        return (newLayer, action, result)
Example #21
0
class GanttConfigure(QDialog):
    def __init__(self, sim, start, end):
        QDialog.__init__(self)
        #self.setCaption("Gantt configuration")
        self.layout = QVBoxLayout(self)

#        self._slider = QxtSpanSliderWidget(
#            sim.observe_window[0] // sim.cycles_per_ms,
#            min(sim.now(), sim.observe_window[1]) // sim.cycles_per_ms,
#            self)
        self._slider = QxtSpanSliderWidget(
            0,
            min(sim.now(), sim.duration) // sim.cycles_per_ms,
            self)
        self._slider.setSpan(start, end)
        self.layout.addWidget(self._slider)

        self._list_elements = QListWidget(self)
        for processor in sim.processors:
            item = QListWidgetItem(processor.name, self._list_elements)
            item.setData(Qt.UserRole, processor)
            self._list_elements.addItem(item)
        for task in sim.task_list:
            item = QListWidgetItem(task.name, self._list_elements)
            item.setData(Qt.UserRole, task)
            self._list_elements.addItem(item)
        #self._list_elements.setDragDropMode(QListWidget.InternalMove)
        for row in range(0, self._list_elements.count()):
            self._list_elements.item(row).setCheckState(Qt.Checked)
        self.layout.addWidget(self._list_elements)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        self.layout.addWidget(buttons)

    def get_start_date(self):
        return self._slider.lowerValue

    def get_end_date(self):
        return self._slider.upperValue

    def get_selected_items(self):
        res = []
        for row in range(0, self._list_elements.count()):
            if self._list_elements.item(row).checkState() == Qt.Checked:
                data = self._list_elements.item(row).data(Qt.UserRole)
                res.append(data)
        return res
Example #22
0
 def __init__(self, parent):
     QListWidget.__init__(self, parent)
     self.mfile = None
     self.setAlternatingRowColors(True)
     self.setLayoutMode(QListView.Batched)
     self.setResizeMode(QListView.Adjust)
     self.setSelectionMode(QAbstractItemView.ExtendedSelection)
     self.activated.connect(self._taskActivated)
     self.setUniformItemSizes(False)
     self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
Example #23
0
    def dragEnterEvent(self, event):
        urls = event.mimeData().urls()

        for url in urls:
            if self.isDragUrlValid(url):
                self.fWasLastDragValid = True
                event.acceptProposedAction()
                return

        self.fWasLastDragValid = False
        QListWidget.dragEnterEvent(self, event)
Example #24
0
    def selectionChanged(self, selected, deselected):
        for index in deselected.indexes():
            item = self.itemFromIndex(index)
            if item is not None:
                item.setSelected(False)

        for index in selected.indexes():
            item = self.itemFromIndex(index)
            if item is not None:
                item.setSelected(True)

        QListWidget.selectionChanged(self, selected, deselected)
class CustomFieldsEditor(QDialog):

    def __init__(self, parent, fields):
        QDialog.__init__(self, parent)

        layout = QVBoxLayout(self)

        self._list_elements = QListWidget(self)
        self._fields = dict(fields)
        for field, ftype in fields.items():
            self._list_elements.addItem(field + ' (' + ftype + ')')

        self._list_elements.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

        layout.addWidget(self._list_elements)

        add_remove = AddRemoveButtonBar(self, 'Remove selected field(s)',
                                        self.remove, 'Add field', self.add)
        layout.addWidget(add_remove)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        layout.addWidget(buttons)

        self.setLayout(layout)

    def remove(self):
        res = []
        for item in self._list_elements.selectedItems():
            del self._fields[str(item.text()).split(' ')[0]]
            res.append(self._list_elements.row(item))

        for row in sorted(res, key=lambda x: -x):
            self._list_elements.takeItem(row)

    def add(self):
        dialog = AddFieldDialog(self)
        if dialog.exec_():
            self._fields[str(dialog.name)] = dialog.ftype
            self._list_elements.addItem(
                dialog.name + ' (' + dialog.ftype + ')')

    def get_fields(self):
        return self._fields
Example #26
0
    def __init__(self, parent):
        QListWidget.__init__(self, parent)

        self.files_data = []
        self.loaded_list = False
        self.loading_list = False
        self.active_index = -1
        self.infohash = None
        self.itemClicked.connect(self.on_item_clicked)
        self.itemDoubleClicked.connect(self.on_item_double_clicked)

        self.files_request_mgr = None
        self.files_request_timer = None
Example #27
0
    def dragMoveEvent(self, event):
        if not self.fWasLastDragValid:
            QListWidget.dragMoveEvent(self, event)
            return

        event.acceptProposedAction()

        tryItem = self.itemAt(event.pos())

        if tryItem is not None:
            self.setCurrentRow(tryItem.getPluginId())
        else:
            self.setCurrentRow(-1)
    def __init__(self, parent=None):
        super(NewProjectManager, self).__init__(parent, Qt.Dialog)
        self.setWindowTitle(translations.TR_NEW_PROJECT)
        self.setMinimumHeight(500)
        vbox = QVBoxLayout(self)
        vbox.addWidget(QLabel(translations.TR_CHOOSE_TEMPLATE))
        vbox.addWidget(QLabel(translations.TR_TAB_PROJECTS))

        hbox = QHBoxLayout()
        self.list_projects = QListWidget()
        self.list_projects.setProperty("wizard", True)
        hbox.addWidget(self.list_projects)

        self.list_templates = QListWidget()
        self.list_templates.setProperty("wizard", True)
        hbox.addWidget(self.list_templates)

        self.text_info = QTextBrowser()
        self.text_info.setProperty("wizard", True)
        hbox.addWidget(self.text_info)

        vbox.addLayout(hbox)

        button_box = QDialogButtonBox(
            QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        choose_button = button_box.button(QDialogButtonBox.Ok)
        choose_button.setText(translations.TR_CHOOSE)
        # hbox2 = QHBoxLayout()
        # cancel = QPushButton(translations.TR_CANCEL)
        # choose = QPushButton(translations.TR_CHOOSE)
        # hbox2.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding,
        #                    QSizePolicy.Fixed))
        # hbox2.addWidget(cancel)
        # hbox2.addWidget(choose)
        # vbox.addLayout(button_box)
        vbox.addWidget(button_box)

        self.template_registry = IDE.get_service("template_registry")
        categories = self.template_registry.list_project_categories()
        for category in categories:
            self.list_projects.addItem(category)

        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        # cancel.clicked.connect(self.close)
        # choose.clicked.connect(self._start_wizard)
        self.list_projects.itemSelectionChanged.connect(
            self._project_selected)
        self.list_templates.itemSelectionChanged.connect(
            self._template_selected)
        self.list_projects.setCurrentRow(0)
Example #29
0
 def dlgMake_DeleteColumn(self,lay=None):
     if lay is None:
         self.dlg=QDialog(self)
         self.dlg.setWindowTitle('删除列:')
     else:
         ##self.grpDeleteColumn
         self.grpDeleteColumn=QGroupBox('删除列:')
         self.grpDeleteColumn.setCheckable(True)
         self.grpDeleteColumn.setChecked(False)
         lay.addWidget(self.grpDeleteColumn)
     ###layDeleteColumn
     layDeleteColumn=QHBoxLayout()
     if lay is None:
         self.dlg.setLayout(layDeleteColumn)
     else:
         self.grpDeleteColumn.setLayout(layDeleteColumn)
     ###layColumnList
     layColumnList=QVBoxLayout()
     layDeleteColumn.addLayout(layColumnList)
     ####lblDeleteColumn
     lblDeleteColumn=QLabel('原有的所有列:')
     layColumnList.addWidget(lblDeleteColumn)
     ####self.lstColumnList
     self.lstColumnList=QListWidget()
     self.lstColumnList.addItems(self.columnsName)
     self.lstColumnList.setFixedWidth(150)
     layColumnList.addWidget(self.lstColumnList)
     ###layDeleteBtns
     layDeleteBtns=QVBoxLayout()
     layDeleteColumn.addLayout(layDeleteBtns)
     ####btnDeleteColumn_Store
     btnDeleteColumn_Store=QPushButton('>>')
     btnDeleteColumn_Store.setFixedWidth(50)
     layDeleteBtns.addWidget(btnDeleteColumn_Store)
     ####btnDeleteColumn_Unstore
     btnDeleteColumn_Unstore=QPushButton('<<')
     btnDeleteColumn_Unstore.setFixedWidth(50)
     layDeleteBtns.addWidget(btnDeleteColumn_Unstore)
     ###layColumnsToDelete
     layColumnsToDelete=QVBoxLayout()
     layDeleteColumn.addLayout(layColumnsToDelete)
     ####lblColumnsToDelete
     lblColumnsToDelete=QLabel('要删除的列:')
     layColumnsToDelete.addWidget(lblColumnsToDelete)
     ####self.lstColumnsToDelete
     self.lstColumnsToDelete=QListWidget()
     self.lstColumnsToDelete.setFixedWidth(150)
     layColumnsToDelete.addWidget(self.lstColumnsToDelete)
     if lay is None:
         self.dlg.show()
Example #30
0
class PopupThing(QWidget):

    def __init__(self, parent):
        super().__init__(parent,
                         Qt.Window |
                         Qt.WindowStaysOnTopHint |
                         Qt.X11BypassWindowManagerHint |
                         Qt.FramelessWindowHint)

        vbox = QVBoxLayout()
        self.listwidget = QListWidget()
        self.listwidget.addItem("Test")
        vbox.addWidget(self.listwidget)
        vbox.setContentsMargins(4, 4, 4, 4)
        self.setLayout(vbox)
Example #31
0
class App(QWidget):
	ChangedPositions = {}

	def __init__(self, parent):
		super(App, self).__init__(parent)
		self.title = 'PySim ZEighty'
		self.left = 0
		self.top = 0
		self.width = 1200
		self.height = 3000
		self.initUI()
		self.carga = 0

	def initUI(self):
		self.setWindowTitle(self.title)
		self.setGeometry(self.left, self.top, self.width, self.height)

		self.createTable()
		self.crearLista()
		self.crearListaDeRegistros()

		self.pila = []
		self.base = []
		vbox = QBoxLayout(3)

		for x in range(11):
			self.base.append(QLabel())
			label = self.base[x]
			label.setText("xxxxxxxxxx")
			vbox.addWidget(label)
		self.base[10].setText("")
		for x in range(256):
			self.pila.append(QLabel())
			label = self.pila[x]
			vbox.addWidget(label)
		fondoPILA = self.pila[0]
		fondoPILA.setText("FONDO")

		button = QPushButton('Trazo', self)
		button.pressed.connect(self.desensambladoTrazo)

		self.button2 = QPushButton('Paso a Paso', self)
		self.button2.pressed.connect(self.ponerPasoAPaso)

		container = QWidget()
		self.ly = QBoxLayout(0)
		self.ly.addWidget(button)
		self.ly.addWidget(self.button2)
		container.setLayout(self.ly)

		win = QWidget()
		area = QScrollArea()

		win.setLayout(vbox)
		area.setWidget(win)
		area.verticalScrollBar().setValue(area.verticalScrollBar().maximum())
		area.setStyleSheet("background-color: #90caf9")
		self.GRIDPRINCIPAL = QGridLayout()
		GRID2 = QGridLayout()
		contenedor = QWidget()

		codigo = QWidget()
		contcodigo = QBoxLayout(2)
		codigo.setStyleSheet("background-color: #f48fb1")

		desFont = QFont("Times", 14, QFont.Bold)
		self.mostrarDesensamble = []

		for x in range(9):
			self.mostrarDesensamble.append(QLabel())
			self.mostrarDesensamble[x].setFont(desFont)
			contcodigo.addWidget(self.mostrarDesensamble[x])
			self.mostrarDesensamble[x].setStyleSheet("color: #000;")

		self.mostrarDesensamble[0].setText('Código Desensamblado')
		self.mostrarDesensamble[1].setText('PC		Código		Instrucción')
		self.mostrarDesensamble[8].setStyleSheet("QLabel { color: white; background-color: black; border-radius: 23px}")

		codigo.setLayout(contcodigo)
		self.mostrarDesensamble[0].setAlignment(Qt.AlignCenter)

		#boton ir a
		containerGoTO = QWidget()
		self.goTo = QLineEdit(self)
		self.goTo.setInputMask(">HHHH")
		self.goTo.setText("0000")
		addressLabel = QLabel()
		addressLabel.setText("Ir a")
		addressLabel1 = QLabel()
		addressLabel1.setText("dirección")
		addressLabel2 = QLabel()
		addressLabel2.setText("de memoria: ")
		self.box1 = QBoxLayout(2)
		self.box1.addWidget(addressLabel)
		self.box1.addWidget(addressLabel1)
		self.box1.addWidget(addressLabel2)
		self.box1.addWidget(self.goTo)
		containerGoTO.setLayout(self.box1)

		containerCleanMemory = QWidget()
		#boton desde
		self.clean1 = QLineEdit(self)
		self.clean1.setInputMask(">HHHH")
		self.clean1.setText("0000")
		cleanTextFrom = QLabel()
		cleanTextFrom.setText("Limpiar desde")
		#boton hasta
		self.clean2 = QLineEdit(self)
		self.clean2.setInputMask(">HHHH")
		self.clean2.setText("0000")
		cleanTextTo = QLabel()
		cleanTextTo.setText("hasta")
		#boton limpiar
		self.box2 = QBoxLayout(0)
		self.box2.addWidget(cleanTextFrom)
		self.box2.addWidget(self.clean1)
		self.box2.addWidget(cleanTextTo)
		self.box2.addWidget(self.clean2)
		containerCleanMemory.setLayout(self.box2)

		#buttons to clean
		containerCleanMemory1 = QWidget()
		self.cleanButton = QPushButton("Limpiar", self)
		self.cleanAll = QPushButton("Limpiar toda la memoria", self)
		self.box3 = QBoxLayout(0)
		self.box3.addWidget(self.cleanButton)
		self.box3.addWidget(self.cleanAll)
		containerCleanMemory1.setLayout(self.box3)

		self.dSpinBoxF = QDoubleSpinBox()
		self.dSpinBoxF.setMinimum(2.5)
		self.dSpinBoxF.setMaximum(9000)
		self.dSpinBoxF.setValue(3.58)
		self.dSpinBoxF.setSingleStep(0.01)

		containerEjec = QWidget()
		timeFrecWid = QWidget()
		allTime = QWidget()

		self.timeTitle = QLabel()
		self.timeSub = QLabel()
		self.instCiclos = QLabel()
		self.instTime = QLabel()
		self.totalTime = QLabel()
		self.labelZ = QLabel()
		self.labelY = QLabel()

		self.labelZ.setFixedSize(45, 48)
		self.labelY.setFixedSize(55, 48)
		self.totalTime.setFixedSize(110, 48)
		self.instTime.setFixedSize(110, 48)
		self.instCiclos.setFixedSize(30, 30)

		self.timeTitle.setText("Tiempo de Ejecución")
		self.timeSub.setText("     Frecuencia              CiclosT    Instrucción   	    Total")
		self.instCiclos.setText("    ")
		self.instTime.setText("       ")
		self.totalTime.setText("       ")
		self.labelZ.setText("[MHz]")
		self.labelY.setText("[MicroS]")

		frecTime = QHBoxLayout()
		uneTime = QVBoxLayout()
		layTime = QVBoxLayout()

		self.timeTitle.setAlignment(Qt.AlignCenter)
		self.instTime.setAlignment(Qt.AlignCenter)
		self.totalTime.setAlignment(Qt.AlignCenter)
		self.labelZ.setAlignment(Qt.AlignCenter)
		self.labelY.setAlignment(Qt.AlignCenter)
		self.instCiclos.setAlignment(Qt.AlignCenter)

		frecTime.addWidget(self.dSpinBoxF)
		frecTime.addWidget(self.labelZ)
		frecTime.addWidget(self.instCiclos)
		frecTime.addWidget(self.instTime)
		frecTime.addWidget(self.totalTime)
		frecTime.addWidget(self.labelY)
		timeFrecWid.setLayout(frecTime)
		uneTime.addWidget(self.timeTitle)
		uneTime.addWidget(self.timeSub)
		uneTime.addWidget(timeFrecWid)
		allTime.setLayout(uneTime)

		layTime.addWidget(containerCleanMemory1)
		layTime.addWidget(allTime)
		containerEjec.setLayout(layTime)

		self.containerAdress = QWidget()
		self.textbox = QLineEdit(self)
		self.textbox.setInputMask(">HHHH")
		self.textbox.setText("0000")
		addressLabel = QLabel()
		addressLabel.setText("Dir. Ejecución")
		self.box1 = QBoxLayout(2)
		self.box1.addWidget(addressLabel)
		self.box1.addWidget(self.textbox)
		self.containerAdress.setLayout(self.box1)
		self.textbox.textEdited.connect(self.asignarPC)

		memLbl = QLabel()
		memLbl.setText('Memoria')
		memLbl.setAlignment(Qt.AlignCenter)
		pilaLbl = QLabel()
		pilaLbl.setText('Stack')
		pilaLbl.setAlignment(Qt.AlignCenter)
		memLbl.setStyleSheet("font-size: 12px;font-weight: bold")
		pilaLbl.setStyleSheet("font-size: 12px;font-weight: bold")

		GRID2.addWidget(self.win2, 0, 0)
		GRID2.addWidget(self.win3, 1, 0)
		GRID2.addWidget(self.win4, 2, 0)
		contenedor.setLayout(GRID2)
		self.GRIDPRINCIPAL.setColumnStretch(0, 5)
		self.GRIDPRINCIPAL.setColumnStretch(1, 1)
		self.GRIDPRINCIPAL.setColumnStretch(2, 4)
		self.GRIDPRINCIPAL.addWidget(memLbl, 0, 0)
		self.GRIDPRINCIPAL.addWidget(pilaLbl, 0, 1)
		self.GRIDPRINCIPAL.addWidget(self.tableWidget, 1, 0)
		self.GRIDPRINCIPAL.addWidget(area, 1, 1)
		self.GRIDPRINCIPAL.addWidget(codigo, 1, 2)
		self.GRIDPRINCIPAL.addWidget(container, 2, 0)  # Botones paso a paso y trazo
		self.GRIDPRINCIPAL.addWidget(self.containerAdress, 2, 1)  # Dir Ejecucion
		self.GRIDPRINCIPAL.addWidget(containerCleanMemory, 2, 2)  # From TO
		self.GRIDPRINCIPAL.addWidget(contenedor, 3, 0)  # Registros
		self.GRIDPRINCIPAL.addWidget(containerGoTO, 3, 1)  # IR a DIR
		self.GRIDPRINCIPAL.addWidget(containerEjec, 3, 2)

		self.goTo.textEdited.connect(self.goToPosition)
		self.goTo.editingFinished.connect(self.goToPosition)
		self.cleanButton.pressed.connect(self.LimpiarMemoria)
		self.cleanAll.pressed.connect(self.LimpiarMemoriaCompleta)
		self.dSpinBoxF.valueChanged.connect(self.changeFrec)
		self.setLayout(self.GRIDPRINCIPAL)

		#Estilos
		containerGoTO.setStyleSheet("background-color: #90caf9;color: #000;border: none; border-radius: 23px;font-size: 13px;font-weight: bold")
		self.goTo.setStyleSheet("background-color: #8bc34a;padding:10px 0;border-radius: 15px;margin: 5px")
		self.tableWidget.setStyleSheet("background-color: #f48fb1;color: #000; sans-serif;font-size: 13px;font-weight: bold;gridline-color: #fff;selection-background-color:  #c2185b;border: none")
		contenedor.setStyleSheet("background-color: #90caf9;font-size: 13px;font-weight: bold;border-radius: 23px")
		button.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")
		self.button2.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")

		self.clean1.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size: 12px;font-weight: bold;padding:15px")
		self.clean2.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size: 12px;font-weight: bold;padding:15px")
		cleanTextFrom.setStyleSheet("font-size: 12px;font-weight: bold")
		cleanTextTo.setStyleSheet("font-size: 12px;font-weight: bold")
		containerCleanMemory.setStyleSheet("background-color: #90caf9;padding: 15px; border-radius: 23px")
		self.cleanButton.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 18px;font-size: 12px;font-weight: bold;padding:15px")
		self.cleanAll.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 18px;font-size: 12px;font-weight: bold;padding:15px")
		self.containerAdress.setStyleSheet("background-color: #90caf9;color: #000;border: none; border-radius: 23px;font-size: 13px;font-weight: bold")
		self.textbox.setStyleSheet("background-color: #8bc34a;padding:10px 0;border-radius: 15px;margin: 5px")
		self.dSpinBoxF.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 18px;font-size: 12px;font-weight: bold;padding:15px")

		containerEjec.setStyleSheet("background-color: #90caf9;color: #000;border: none; border-radius: 23px;font-size: 13px;font-weight: bold")
		self.labelY.setStyleSheet("background-color: #f48fb1;font-size: 12px;font-weight: bold")
		self.labelZ.setStyleSheet("background-color: #8bc34a;font-size: 12px;font-weight: bold")
		self.instTime.setStyleSheet("background-color: #f48fb1;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")
		self.totalTime.setStyleSheet("background-color: #f48fb1;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")

	def changeFrec(self):
		if z.time == 0:
			z.frec = (self.dSpinBoxF.value()) * 1000000
		else:
			pass

	def crearListaDeRegistros(self):
		self.win2 = QWidget()

		#widget para F
		vboxAll = QGridLayout()
		self.win1 = QWidget()
		self.win3 = QWidget()
		self.registerF_BIN = []
		vboxF = QBoxLayout(0)

		self.registros1 = []
		vbox = QGridLayout()
		x = 0
		registros = ["B","C","D","E","H","L","A","F","SP","IX","IY","PC","IFF1","IFF2","I","R","B\'","C\'","D\'","E\'","H\'","L\'","A\'","F\'"]
		for cadena in registros:
			self.registros1.append(QLabel())
			label = self.registros1[x]
			label.setText(cadena + " = ")
			x+=1

		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[0].setText("S")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[1].setText("Z")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[2].setText("X")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[3].setText("H")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[4].setText("X")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[5].setText("(P/V)")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[6].setText("N")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[7].setText("C")
		self.registerF_BIN.append(QLabel())
		self.registerF_BIN[8].setText('Banderas')

		regLabel = QLabel()
		regLabel.setText('Registros')
		vbox.addWidget(regLabel, 0,4)
		vbox.addWidget(self.registros1[0],1,0)
		vbox.addWidget(self.registros1[1],1,2)
		vbox.addWidget(self.registros1[2],1,4)
		vbox.addWidget(self.registros1[3],1,6)
		vbox.addWidget(self.registros1[4],1,8)
		vbox.addWidget(self.registros1[5],2,0)
		vbox.addWidget(self.registros1[6],2,2)
		vbox.addWidget(self.registros1[7],2,4)
		vbox.addWidget(self.registros1[8],2,6)
		vbox.addWidget(self.registros1[9],2,8)
		vbox.addWidget(self.registros1[10],3,0)
		vbox.addWidget(self.registros1[11],3,2)
		vbox.addWidget(self.registros1[12],3,4)
		vbox.addWidget(self.registros1[13],3,6)
		vbox.addWidget(self.registros1[14],3,8)
		vbox.addWidget(self.registros1[15],4,0)
		vbox.addWidget(self.registros1[16],4,2)
		vbox.addWidget(self.registros1[17],4,4)
		vbox.addWidget(self.registros1[18],4,6)
		vbox.addWidget(self.registros1[19],4,8)
		vbox.addWidget(self.registros1[20],5,0)
		vbox.addWidget(self.registros1[21],5,2)
		vbox.addWidget(self.registros1[22],5,4)
		vbox.addWidget(self.registros1[23],5,6)
		vboxF.addWidget(self.registerF_BIN[8])
		vboxF.addWidget(self.registerF_BIN[0])
		vboxF.addWidget(self.registerF_BIN[1])
		vboxF.addWidget(self.registerF_BIN[2])
		vboxF.addWidget(self.registerF_BIN[3])
		vboxF.addWidget(self.registerF_BIN[4])
		vboxF.addWidget(self.registerF_BIN[5])
		vboxF.addWidget(self.registerF_BIN[6])
		vboxF.addWidget(self.registerF_BIN[7])
		self.win3.setLayout(vboxF)
		self.registros1[0].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[1].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[2].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[3].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[4].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[5].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[6].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[7].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[8].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[9].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[10].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[11].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[12].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[13].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[14].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[15].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[16].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[17].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[18].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[19].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[20].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[21].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[22].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros1[23].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registerF_BIN[0].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[1].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[2].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[3].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[4].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[5].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[6].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[7].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN[8].setStyleSheet("padding: 0; font-size: 10px")
		self.crearEntradaDeRegistros(registros, vbox)
		self.win2.setLayout(vbox)


	def crearEntradaDeRegistros(self, registros, vbox):
		reg16 = ['SP', 'PC', 'IX', 'IY']
		self.registros2 = []
		x = 0
		for cadena in registros:
			self.registros2.append(QLineEdit())
			editReg = self.registros2[x]
			editReg.setText(getattr(z, cadena.replace("\'","_")))
			if cadena in reg16:
				editReg.setInputMask(">HHHH")
			elif cadena == 'IFF1' or cadena == 'IFF2':
				editReg.setInputMask("B")
			else:
				editReg.setInputMask(">HH")
			x+=1

		self.registerF_BIN1 = []
		vboxF1 = QBoxLayout(0)
		self.win4 = QWidget()
		for i in range(8):
			self.registerF_BIN1.append(QLineEdit())
			self.registerF_BIN1[i].setText("0")
			self.registerF_BIN1[i].setInputMask('B')
		self.registerF_BIN1.append(QLineEdit())
		self.registerF_BIN1[8].setText('F =')

		vbox.addWidget(self.registros2[0],1,1)
		self.registros2[0].textChanged.connect(lambda: self.editarRegistros(0, registros, reg16))
		vbox.addWidget(self.registros2[1],1,3)
		self.registros2[1].textChanged.connect(lambda: self.editarRegistros(1, registros, reg16))
		vbox.addWidget(self.registros2[2],1,5)
		self.registros2[2].textChanged.connect(lambda: self.editarRegistros(2, registros, reg16))
		vbox.addWidget(self.registros2[3],1,7)
		self.registros2[3].textChanged.connect(lambda: self.editarRegistros(3, registros, reg16))
		vbox.addWidget(self.registros2[4],1,9)
		self.registros2[4].textChanged.connect(lambda: self.editarRegistros(4, registros, reg16))
		vbox.addWidget(self.registros2[5],2,1)
		self.registros2[5].textChanged.connect(lambda: self.editarRegistros(5, registros, reg16))
		vbox.addWidget(self.registros2[6],2,3)
		self.registros2[6].textChanged.connect(lambda: self.editarRegistros(6, registros, reg16))
		vbox.addWidget(self.registros2[7],2,5)
		self.registros2[7].textChanged.connect(lambda: self.editarRegistros(7, registros, reg16))
		vbox.addWidget(self.registros2[8],2,7)
		self.registros2[8].textChanged.connect(lambda: self.editarRegistros(8, registros, reg16))
		vbox.addWidget(self.registros2[9],2,9)
		self.registros2[9].textChanged.connect(lambda: self.editarRegistros(9, registros, reg16))
		vbox.addWidget(self.registros2[10],3,1)
		self.registros2[10].textChanged.connect(lambda: self.editarRegistros(10, registros, reg16))
		vbox.addWidget(self.registros2[11],3,3)
		self.registros2[11].textChanged.connect(lambda: self.editarRegistros(11, registros, reg16))
		vbox.addWidget(self.registros2[12],3,5)
		self.registros2[12].textChanged.connect(lambda: self.editarRegistros(12, registros, reg16))
		vbox.addWidget(self.registros2[13],3,7)
		self.registros2[13].textChanged.connect(lambda: self.editarRegistros(13, registros, reg16))
		vbox.addWidget(self.registros2[14],3,9)
		self.registros2[14].textChanged.connect(lambda: self.editarRegistros(14, registros, reg16))
		vbox.addWidget(self.registros2[15],4,1)
		self.registros2[15].textChanged.connect(lambda: self.editarRegistros(15, registros, reg16))
		vbox.addWidget(self.registros2[16],4,3)
		self.registros2[16].textChanged.connect(lambda: self.editarRegistros(16, registros, reg16))
		vbox.addWidget(self.registros2[17],4,5)
		self.registros2[17].textChanged.connect(lambda: self.editarRegistros(17, registros, reg16))
		vbox.addWidget(self.registros2[18],4,7)
		self.registros2[18].textChanged.connect(lambda: self.editarRegistros(18, registros, reg16))
		vbox.addWidget(self.registros2[19],4,9)
		self.registros2[19].textChanged.connect(lambda: self.editarRegistros(19, registros, reg16))
		vbox.addWidget(self.registros2[20],5,1)
		self.registros2[20].textChanged.connect(lambda: self.editarRegistros(20, registros, reg16))
		vbox.addWidget(self.registros2[21],5,3)
		self.registros2[21].textChanged.connect(lambda: self.editarRegistros(21, registros, reg16))
		vbox.addWidget(self.registros2[22],5,5)
		self.registros2[22].textChanged.connect(lambda: self.editarRegistros(22, registros, reg16))
		vbox.addWidget(self.registros2[23],5,7)
		self.registros2[23].textChanged.connect(lambda: self.editarRegistros(23, registros, reg16))

		vboxF1.addWidget(self.registerF_BIN1[8])
		self.registerF_BIN1[0].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[0], 7))
		vboxF1.addWidget(self.registerF_BIN1[0])
		self.registerF_BIN1[1].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[1], 6))
		vboxF1.addWidget(self.registerF_BIN1[1])
		self.registerF_BIN1[2].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[2], 5))
		vboxF1.addWidget(self.registerF_BIN1[2])
		self.registerF_BIN1[3].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[3], 4))
		vboxF1.addWidget(self.registerF_BIN1[3])
		self.registerF_BIN1[4].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[4], 3))
		vboxF1.addWidget(self.registerF_BIN1[4])
		self.registerF_BIN1[5].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[5], 2))
		vboxF1.addWidget(self.registerF_BIN1[5])
		self.registerF_BIN1[6].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[6], 1))
		vboxF1.addWidget(self.registerF_BIN1[6])
		self.registerF_BIN1[7].textEdited.connect(lambda: self.editarBanderas(self.registerF_BIN1[7], 0))
		vboxF1.addWidget(self.registerF_BIN1[7])
		self.win4.setLayout(vboxF1)

		self.registros2[0].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[1].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[2].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[3].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[4].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[5].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[6].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[7].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[8].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[9].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[10].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[11].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[12].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[13].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[14].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[15].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[16].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[17].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[18].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[19].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[20].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[21].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[22].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registros2[23].setStyleSheet("padding: 5px 0; font-size: 10px")
		self.registerF_BIN1[0].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[1].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[2].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[3].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[4].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[5].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[6].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[7].setStyleSheet("padding: 0 2px; font-size: 10px")
		self.registerF_BIN1[8].setStyleSheet("padding: 0 4px; font-size: 10px")

	def editarRegistros(self, i, registros, reg16):
		if registros[i] in reg16:
			v = self.registros2[i].text().zfill(4)
		elif registros[i] == 'IFF1' or registros[i] == 'IFF2':
			v = self.registros2[i].text().zfill(1)
		else:
			v = self.registros2[i].text().zfill(2)
		if registros[i] == "F":
			register = z.hexToBin(self.registros2[i].text().zfill(2))
			self.editarBanderasHex(register)
		setattr(z, registros[i], v)

	def editarBanderas(self, registro, t):
		registerF = registro.text()
		if len(registerF) > 0:
			z.changeFlag(t,registerF)
			self.registros2[7].setText(z.F)

	def editarBanderasHex(self,register):
		self.registerF_BIN1[0].setText(register[0])
		self.registerF_BIN1[1].setText(register[1])
		self.registerF_BIN1[2].setText(register[2])
		self.registerF_BIN1[3].setText(register[3])
		self.registerF_BIN1[4].setText(register[4])
		self.registerF_BIN1[5].setText(register[5])
		self.registerF_BIN1[6].setText(register[6])
		self.registerF_BIN1[7].setText(register[7])

	def ponerPasoAPaso(self):
		z.time = 0
		self.button2.deleteLater()
		self.button2 = QPushButton('Siguiente Instrucción', self)
		self.button2.pressed.connect(self.desensambladoPasoAPaso)
		self.button3 = QPushButton('Salir paso a paso', self)
		self.button3.pressed.connect(self.salirPasoPaso)
		self.ly.addWidget(self.button2)
		self.ly.addWidget(self.button3)
		self.button2.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size: 15px;font-weight: bold;padding:15px")
		self.button3.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size: 15px;font-weight: bold;padding:15px")
		self.disableExecutionDirection()

	def salirPasoPaso(self,):
		#Linea agregadas para reiniciar el valor del tiempo
		z.time = 0
		z.PC = "0000"
		self.button3.deleteLater()
		self.button2.deleteLater()
		self.button2 = QPushButton('Paso a paso', self)
		self.button2.pressed.connect(self.ponerPasoAPaso)
		self.ly.addWidget(self.button2)
		self.enableExecutionDirection()

	def asignarPC(self):
		z.PC = self.textbox.text().zfill(4)
		self.registros1[11].setText("PC = ")
		self.registros2[11].setText(z.PC)

	def goToPosition(self):
		self.tableWidget.clearSelection()
		position = self.goTo.text()
		lenght = len(position)
		if lenght > 3:
			position_Row = position[:3]
			position_Column = position[3:]
			position_Row = int(position_Row, 16)
			position_Column = int(position_Column, 16)
			positionCell = self.tableWidget.item(position_Row, position_Column)
			self.tableWidget.scrollToItem(positionCell)
			self.tableWidget.setRangeSelected(QTableWidgetSelectionRange(positionCell.row(), positionCell.column(), positionCell.row(), positionCell.column()), True)
		elif lenght > 0:
			position_Row = position
			position_Row = int(position_Row, 16)
			position_Column = 0
			positionCell = self.tableWidget.item(position_Row, position_Column)
			self.tableWidget.scrollToItem(positionCell)
			self.tableWidget.setRangeSelected(QTableWidgetSelectionRange(positionCell.row(), positionCell.column(), positionCell.row(), positionCell.column()), True)

	def LimpiarMemoria(self):
		limpiaDic1 = {}
		inicio = self.clean1.text().zfill(4)
		fin = self.clean2.text().zfill(4)
		for i in range(int(inicio, 16), int(fin, 16) + 1):
			limpiaDic = z.mem.cambiarContenido("00", funciones.tohex(i, 16))
			limpiaDic1.update(limpiaDic)
		self.cambiaLocalidad(limpiaDic1)

	def LimpiarMemoriaCompleta(self):
		self.carga = 0
		limpiaDic1 = {}
		for i in range(int("0000", 16), int("FFFF", 16) + 1):
			limpiaDic = z.mem.cambiarContenido("00", funciones.tohex(i, 16))
			limpiaDic1.update(limpiaDic)
		self.cambiaLocalidad(limpiaDic1)

	def enableExecutionDirection(self):
		self.containerAdress = QWidget()
		self.textbox = QLineEdit(self)
		self.textbox.setInputMask(">HHHH")
		self.textbox.setText("0000")
		addressLabel = QLabel()
		addressLabel.setText("Dir. Ejecución")
		self.box1 = QBoxLayout(2)
		self.box1.addWidget(addressLabel)
		self.box1.addWidget(self.textbox)
		self.containerAdress.setLayout(self.box1)
		self.GRIDPRINCIPAL.addWidget(self.containerAdress, 2, 1)
		self.textbox.textEdited.connect(self.asignarPC)
		self.button2.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size: 15px;font-weight: bold;padding:15px")
		self.containerAdress.setStyleSheet("background-color: #90caf9;color: #000;border: none; border-radius: 23px;font-size: 13px;font-weight: bold")
		self.textbox.setStyleSheet("background-color: #8bc34a;padding:10px 0;border-radius: 15px;margin: 5px")

	def disableExecutionDirection(self):
		self.containerAdress.deleteLater()

	def createTable(self):
	   # Create table
		self.tableWidget = QTableWidget()
		self.tableWidget.setRowCount(4096)
		self.tableWidget.setColumnCount(16)
		horizantalLabels = []
		verticalLabels = []
		for i in range(16):
			horizantalLabels.append(funciones.tohex(i, 8))
		for i in range(4096):
			verticalLabels.append(funciones.tohex(i * 16, 16))
		self.tableWidget.setHorizontalHeaderLabels(horizantalLabels)
		self.tableWidget.setVerticalHeaderLabels(verticalLabels)
		# table selection change6
		for i in range(4096):
			for j in range(16):
				self.tableWidget.setItem(i, j, QTableWidgetItem("00"))
				self.tableWidget.setColumnWidth(j, 29)

		self.tableWidget.setItemDelegate(HexDelegate())
		self.tableWidget.cellChanged.connect(self.changed)

	def crearLista(self):
			self.listWidget = QListWidget()

			l = ["B", "C", "D", "E", "H", "L", "A", "F","SP", "IX", "IY", "PC", "IFF1", "IFF2", "I", "R"]
			for i in l:
				i = i + " = " + getattr(z, i)
				self.listWidget.addItem(i)

	@pyqtSlot()
	def changed(self):
		lista = [chr(i) for i in range(65, 71)] + [str(i) for i in range(10)]
		if len(self.tableWidget.selectedItems()) != 0:
			for currentQTableWidgetItem in self.tableWidget.selectedItems():
				key_row_int = currentQTableWidgetItem.row()
				key_colum_int = currentQTableWidgetItem.column()
				key_row = hex(currentQTableWidgetItem.row())[2:]
				key_column = hex(currentQTableWidgetItem.column())[2:]

				key = key_row + key_column
				content = currentQTableWidgetItem.text()

				App.ChangedPositions[int(key, 16)] = content
				content = content.upper()
			z.mem.cambiarContenido(content, key)

	def llenaDiccionario(self):
		file = open('tablaCompleta.txt', 'r')
		self.table = {}
		for line in file.readlines():
			line = line.replace('\n', '').split('|')
			self.table[line[1]] = line[0].split(':') + line[2:]

# Funcion para cargar el contenido del archivo en la memoria
	def cargaMemoria(self, dirCarga, archivo):
		try:
			code = open(archivo, 'r')
			self.carga = 1
			for line in code.readlines():
				line = line.replace(':', '').replace("\n", "")
				# El desensamble termina al encontrar la ultima linea del codigo objeto
				if (line != '00000001FF'):
					start = line[2:6]
					line = list(map(''.join, zip(*[iter(line)] * 2)))

					# Vemos que el checksum coincida con el resultado del codigo objeto
					checksum = line[len(line) - 1]
					line = line[:len(line) - 1]
					sum = funciones.compDos(eval('+'.join([str(int(num, 16)) for num in line])))

					line = line[4:]

					if (sum == checksum):
						i = int(dirCarga, 16) + int(start, 16)
						while(len(line) > 0):
							localidad = funciones.tohex(i, 16)
							z.mem.cambiarContenido(line[0], localidad)
							row = int(localidad[:3], 16)
							column = int(localidad[3], 16)
							item = QTableWidgetItem(line[0])
							self.tableWidget.setItem(row, column, item)
							App.ChangedPositions[int(localidad, 16)] = line[0]

							line = line[1:]
							i += 1
					else:
						msgBox = QMessageBox()
						msgBox.setText("Código Alterado")
						msgBox.setStandardButtons(QMessageBox.Ok)
						msgBox.exec_()
						return
				else:
					return z.mem
		except:
			msgBox = QMessageBox()
			msgBox.setText("Error al abrir archivo")
			msgBox.setStandardButtons(QMessageBox.Ok)
			msgBox.exec_()
			return

	def desensambladoTrazo(self):
		z.time = 0
		inst = ""
		j = int(z.PC, 16)
		act = ''
		if self.carga != 0:
			while(inst != 'HALT'):
				act += z.mem.obtenerContenido(funciones.tohex(j, 8))
				j += 1
				if act == 'DDCB' or act == 'FDCB':
					des = z.mem.obtenerContenido(funciones.tohex(j, 8))
					act += 'V' + z.mem.obtenerContenido(funciones.tohex(j + 1), 8)
					j += 2
					inst = self.table.get(act)[0]
					inst = inst.replace('V', des + 'H')
					long = int(self.table.get(act)[1])
					tiempo = self.table.get(act)[2:]
					if len(tiempo) == 1:
						z.time += int(tiempo[0])
					z.PC = hex(j - 4 + long)[2:].zfill(4).upper()
					if int(z.PC, 16) >= int("10000", 16):
						z.PC = "0000"
					self.changeLabelLines(act, inst)
					self.changeTimeLbls(tiempo)
					res = self.ejecutar(act, inst)
					if res == False:
						return
					j = int(z.PC, 16)
					act = ''
				elif act in self.table:
					tem = act
					inst = self.table.get(act)[0]
					long = int(self.table.get(act)[1])
					tiempo = self.table.get(act)[2:]
					if len(tiempo) == 1:
						z.time += int(tiempo[0])
					longact = len(act)/2
					# Bandera para saber cuando poner la H en los numeros al desensamblar
					flagh = 0
					while(long != longact):
						act = z.mem.obtenerContenido(funciones.tohex(j, 8))
						tem += act
						longact += 1
						j += 1
						if inst.find('WW') != -1:
							inst = (act + 'H').join(inst.rsplit('W', 1))
							flagh = 1
						elif inst.find('V') != -1:
							inst = inst.replace('V', act + 'H')
						elif inst.find('W') != -1:
							if flagh == 1:
								inst = inst.replace('W', act)
							else:
								inst = inst.replace('W', act + 'H')
					z.PC = hex(j)[2:].zfill(4).upper()
					if int(z.PC, 16) >= int("10000", 16):
						z.PC = "0000"
					self.changeLabelLines(tem, inst)
					self.changeTimeLbls(tiempo)
					res = self.ejecutar(inst)
					if res == False:
						return
					j = int(z.PC, 16)
					act = ''
					tem = ''
			z.PC = "0000"
			#Lineas agregadas para reiniciar el valor del tiempo
			z.time = 0
		else:
			return

	def desensambladoPasoAPaso(self):
		inst = ""
		j = int(z.PC, 16)
		act = ''
		yes = 0
		while(yes != 1):
			act += z.mem.obtenerContenido(funciones.tohex(j, 8))
			j += 1
			if act == 'DDCB' or act == 'FDCB':
				des = line[j]
				act += 'V' + line[j + 1]
				j += 2
				inst = self.table.get(act)[0]
				inst = inst.replace('V', des + 'H')
				long = int(self.table.get(act)[1])
				tiempo = self.table.get(act)[2:]
				if len(tiempo) == 1:
					z.time += int(tiempo[0])
				z.PC = hex(j - 4 + long)[2:].zfill(4).upper()
				if int(z.PC, 16) >= int("10000", 16):
					z.PC = "0000"
				'''
				self.instTime.setText(str(tiempo[0]))
				self.totalTime.setText(str(z.time))'''
				self.changeLabelLines(act, inst)
				self.changeTimeLbls(tiempo)
				res = self.ejecutar(act, inst)
				yes = 1
				if res == False:
					self.salirPasoPaso()
				j = int(z.PC, 16)
				act = ''

			elif act in self.table:
				tem = act
				inst = self.table.get(act)[0]
				long = int(self.table.get(act)[1])
				longact = len(act) / 2
				tiempo = self.table.get(act)[2:]
				if len(tiempo) == 1:
					z.time += int(tiempo[0])
				# Bandera para saber cuando poner la H en los numeros al desensamblar
				flagh = 0
				while(long != longact):
					act = z.mem.obtenerContenido(funciones.tohex(j, 8))
					tem += act
					longact += 1
					j += 1
					if inst.find('WW') != -1:
						inst = (act + 'H').join(inst.rsplit('W', 1))
						flagh = 1
					elif inst.find('V') != -1:
						inst = inst.replace('V', act + 'H')
					elif inst.find('W') != -1:
						if flagh == 1:
							inst = inst.replace('W', act)
						else:
							inst = inst.replace('W', act + 'H')
				z.PC = hex(j)[2:].zfill(4).upper()
				#Para imprimir las instrucciones de desensamble:
				if int(z.PC, 16) >= int("10000", 16):
					z.PC = "0000"
				self.changeLabelLines(tem, inst)
				self.changeTimeLbls(tiempo)
				res = self.ejecutar(inst)
				tiempo = self.table.get(act)[2:]
				yes = 1
				if res == False:
					self.salirPasoPaso()
				j = int(z.PC, 16)
				act = ''
				tem = ''
			if (inst == "HALT"):
				z.time = 0
				msgBox = QMessageBox()
				msgBox.setText("Fin de programa")
				msgBox.setStandardButtons(QMessageBox.Ok)
				msgBox.exec_()
				self.salirPasoPaso()

	def changeTimeLbls(self, tiempo):
		frecuencia = z.frec
		periodosReloj = str(int(tiempo[0]))
		tiempoInst = ((int(tiempo[0]) / frecuencia) * 1000000)
		tiempoTotal = ((z.time / frecuencia) * 1000000)
		tiempoInst = str(round(tiempoInst, 5))
		tiempoTotal = str(round(tiempoTotal, 5))
		self.instCiclos.setText(periodosReloj)
		self.instTime.setText(tiempoInst)
		self.totalTime.setText(tiempoTotal)

	def changeLabelLines(self, act, inst):
		self.mostrarDesensamble[2].setText(self.mostrarDesensamble[3].text())
		self.mostrarDesensamble[3].setText(self.mostrarDesensamble[4].text())
		self.mostrarDesensamble[4].setText(self.mostrarDesensamble[5].text())
		self.mostrarDesensamble[5].setText(self.mostrarDesensamble[6].text())
		self.mostrarDesensamble[6].setText(self.mostrarDesensamble[7].text())
		self.mostrarDesensamble[7].setText(self.mostrarDesensamble[8].text())
		self.mostrarDesensamble[8].setText(str(z.PC) + ('		') + str(act) + ('		') + str(inst))

	def ejecutar(self, instrucciones):
		registros = ["B","C","D","E","H","L","A","F","SP","IX","IY","PC","IFF1","IFF2","I","R","B_","C_","D_","E_","H_","L_","A_","F_"]
		pcAdd = ['PUSH', 'CALL', 'RST']
		pcRet = ['POP', 'RET']
		inst = instrucciones.split(" ")
		if (len(inst) == 1):
			flag = z.callMethod(z, inst[0], "")
			if inst[0] in pcAdd:
				res = self.addPila()
				if res == False: return False
			elif inst[0] in pcRet:
				res = self.retPila()
				if res == False: return False
			self.cambiaLocalidad(flag)
		else:
			flag = z.callMethod(z, inst[0], inst[1])
			if inst[0] in pcAdd:
				res = self.addPila()
				if res == False: return False
			elif inst[0] in pcRet:
				res = self.retPila()
				if res == False: return False
			self.cambiaLocalidad(flag)
		for i in range(len(self.registros1)):
			self.registros2[i].setText(getattr(z,registros[i]))
		return

	def addPila(self):
		v = int(z.SP, 16)
		if v == 0:
			v = 65536
		indicePila = int((65534 - v)/2)
		if indicePila >= 255:
			msgBox = QMessageBox()
			msgBox.setText("Pila Llena")
			msgBox.setStandardButtons(QMessageBox.Ok)
			msgBox.exec_()
			return False
		label = self.pila[indicePila]
		label.setText(z.mem.obtenerContenido(funciones.tohex(int(z.SP, 16) + 1, 8)) + z.mem.obtenerContenido(z.SP))
		return

	def retPila(self):
		v = int(z.SP, 16)
		if v == 0:
			v = 65536
		indicePila = int((65536 - v)/2)
		if indicePila < 0:
			msgBox = QMessageBox()
			msgBox.setText("Pila Vacía")
			msgBox.setStandardButtons(QMessageBox.Ok)
			msgBox.exec_()
			return False
		label = self.pila[indicePila]
		label.setText("")
		return


	def cambiaLocalidad(self, flag):
		if flag != None:
			for elem in flag.keys():
				row = int(elem[:3], 16)
				column = int(elem[3], 16)
				item = QTableWidgetItem(flag[elem])
				self.tableWidget.setItem(row, column, item)
				App.ChangedPositions[int(elem, 16)] = flag[elem]
		else:
			return
Example #32
0
class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        #        self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
        #        self.setAttribute(Qt.WA_TranslucentBackground)
        self.resize(900, 700)
        self.__search_mode = {
            'fuzzy': 'fuzzy_search',
            'precise': 'precise_search',
            'reg': 'reg_search'
        }
        # self.__pbn_switch_view = None

        # 创建窗口部件
        self.__widget_frame = QLabel()

        # window title
        self.__lab_title_fram = QLabel()
        self.__lab_title = QLabel('搜索辅助工具')
        self.__lab_title.setAlignment(Qt.AlignCenter)

        self.__lab_open_tool = QLabel('打开文件方式')
        self.__ln_open_tool = QLineEdit()
        self.__pbn_open_tool = QToolButton()
        self.__pbn_open_tool.setText('选择...')
        self.__ln_open_tool.setFixedHeight(20)
        self.__ln_open_tool.setFixedWidth(150)
        self.__pbn_open_tool.setFixedSize(48, 20)
        self.__lab_title_fram.setFixedHeight(50)

        # search mode
        self.__lab_mode_fram = QLabel()
        self.__rbn_fuzzy = QRadioButton('模糊搜索')
        self.__rbn_precise = QRadioButton('精确搜索')
        self.__rbn_reg = QRadioButton('正则表达式搜索')
        self.__rbn_fuzzy.setChecked(True)
        self.__lab_mode_fram.setFixedHeight(22)

        # search pattern
        self.__lab_pattern_fram = QLabel()
        self.__ln_file_name = QLineEdit()
        self.__ln_file_name.setPlaceholderText('请输入搜索条件或正则表达式......')
        self.__rbn_reg_Iyes = QRadioButton('区分大小写')
        self.__rbn_reg_Ino = QRadioButton('不区分大小写')
        self.__lab_pattern_fram.setFixedHeight(20)

        # search path
        self.__lab_path_fram = QLabel()
        self.__ln_file_path = QLineEdit()
        self.__ln_file_path.setPlaceholderText('请选择或输入路径......')
        self.__pbn_file_path = QToolButton()
        self.__pbn_file_path.setText('浏览...')
        self.__rbn_search_file = QRadioButton('检索文件名')
        self.__rbn_search_content = QRadioButton('检索文件内容')
        self.__pbn_file_path.setFixedSize(48, 20)
        self.__lab_path_fram.setFixedHeight(20)

        # search state
        self.__lab_state_fram = QLabel()
        self.__lab_state = QLabel('状态:暂无搜索结果!')
        self.__pbn_search = QPushButton('开始')
        self.__pbn_stop = QPushButton('停止')
        self.__pbn_search.setFixedWidth(89)
        self.__pbn_stop.setFixedWidth(89)
        self.__lab_state_fram.setFixedHeight(35)

        # search result
        self.__tabView = QTabWidget()
        self.__browser_result = QListWidget()
        self.__browser_error = QTextBrowser()
        self.__tabView.addTab(self.__browser_result, '匹配结果')
        self.__tabView.addTab(self.__browser_error, '错误结果')

        self.__btn_group_type = QButtonGroup()
        self.__btn_group_type.addButton(self.__rbn_search_file)
        self.__btn_group_type.addButton(self.__rbn_search_content)
        self.__rbn_search_file.setChecked(True)

        # radiobutton group
        self.__btn_group_re_I = QButtonGroup()
        self.__btn_group_re_I.addButton(self.__rbn_reg_Iyes)
        self.__btn_group_re_I.addButton(self.__rbn_reg_Ino)
        self.__rbn_reg_Iyes.setChecked(True)

        # lines
        '''
        self.__line_1 = QFrame()
        self.__line_1.setFrameStyle(QFrame.HLine | QFrame.Sunken)
        '''

        # 布局
        # open tool
        self.__layout_tool_choose = QHBoxLayout()
        self.__layout_tool_choose.addWidget(self.__ln_open_tool)
        self.__layout_tool_choose.addWidget(self.__pbn_open_tool)
        self.__layout_tool_choose.setSpacing(0)
        self.__layout_tool_choose.setContentsMargins(0, 0, 0, 0)

        self.__layout_open_tool = QHBoxLayout()
        self.__layout_open_tool.addWidget(self.__lab_open_tool)
        self.__layout_open_tool.addLayout(self.__layout_tool_choose)
        self.__layout_open_tool.setSpacing(2)

        # window title
        self.__layout_title = QHBoxLayout()
        self.__layout_title.addStretch(5)
        self.__layout_title.addWidget(self.__lab_title)
        self.__layout_title.addStretch(1)
        self.__layout_title.addLayout(self.__layout_open_tool)
        self.__layout_title.setContentsMargins(0, 0, 0, 20)
        self.__lab_title_fram.setLayout(self.__layout_title)

        # search mode
        self.__layout_search_mode = QHBoxLayout()
        self.__layout_search_mode.addWidget(self.__rbn_fuzzy)
        self.__layout_search_mode.addStretch()
        self.__layout_search_mode.addWidget(self.__rbn_precise)
        self.__layout_search_mode.addStretch()
        self.__layout_search_mode.addWidget(self.__rbn_reg)
        self.__layout_search_mode.setContentsMargins(60, 0, 60, 0)
        self.__lab_mode_fram.setLayout(self.__layout_search_mode)

        # search pattern
        self.__layout_search_reg_I = QHBoxLayout()
        self.__layout_search_reg_I.addWidget(self.__rbn_reg_Iyes)
        self.__layout_search_reg_I.addWidget(self.__rbn_reg_Ino)

        self.__layout_pattern = QHBoxLayout()
        self.__layout_pattern.addWidget(self.__ln_file_name)
        self.__layout_pattern.addLayout(self.__layout_search_reg_I)
        self.__layout_pattern.setContentsMargins(0, 0, 0, 0)
        self.__lab_pattern_fram.setLayout(self.__layout_pattern)

        # search path
        self.__layout_choose_path = QHBoxLayout()
        self.__layout_choose_path.addWidget(self.__ln_file_path)
        self.__layout_choose_path.addWidget(self.__pbn_file_path)
        self.__layout_choose_path.setSpacing(0)

        self.__layout_path = QHBoxLayout()
        self.__layout_path.addLayout(self.__layout_choose_path)
        self.__layout_path.addWidget(self.__rbn_search_file)
        self.__layout_path.addWidget(self.__rbn_search_content)
        self.__layout_path.setContentsMargins(0, 0, 0, 0)
        self.__lab_path_fram.setLayout(self.__layout_path)

        # search state
        self.__layout_state = QHBoxLayout()
        self.__layout_state.addWidget(self.__lab_state)
        self.__layout_state.addWidget(self.__pbn_search)
        self.__layout_state.addWidget(self.__pbn_stop)
        self.__layout_state.setContentsMargins(0, 0, 0, 10)
        self.__lab_state_fram.setLayout(self.__layout_state)

        # top layout
        self.__layout_top = QVBoxLayout()
        self.__layout_top.addWidget(self.__lab_title_fram)
        self.__layout_top.addWidget(self.__lab_mode_fram)
        self.__layout_top.addWidget(self.__lab_pattern_fram)
        self.__layout_top.addWidget(self.__lab_path_fram)
        self.__layout_top.addWidget(self.__lab_state_fram)
        self.__layout_top.addWidget(self.__tabView)
        self.__layout_top.setSpacing(10)
        self.__widget_frame.setLayout(self.__layout_top)

        self.__layout_fram = QGridLayout()
        self.__layout_fram.addWidget(self.__widget_frame, 0, 0, 1, 1)
        self.__layout_fram.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.__layout_fram)

        # set object name
        self.__widget_frame.setObjectName('fram')
        self.__lab_title.setObjectName('lab_title')
        self.__ln_open_tool.setObjectName('ln_open_tool')
        self.__lab_mode_fram.setObjectName('mode_fram')
        self.__ln_file_name.setObjectName('ln_pattern')
        self.__ln_file_path.setObjectName('ln_path')
        self.__lab_state.setObjectName('state')
        self.__tabView.setObjectName('tabView')
        self.__browser_result.setObjectName('browser_result')
        self.__browser_error.setObjectName('browser_error')

        self.setStyleSheet(
            '#fram{'
            'border-image: url(Images/bg);'
            '}'
            '#lab_title{'
            'color: white;'
            'font-size: 18pt;'
            '}'
            '#open_tool{'
            'color: black;'
            '}'
            '#mode_fram{'
            # 'border-top: 1px solid rgba(20, 20, 20, 100);'
            # 'border-bottom: 1px solid rgba(20, 20, 20, 100);'
            'background: rgba(0, 0, 0, 40);'
            '}'
            '#ln_open_tool, #ln_path{'
            'border-top-left-radius:    2px;'
            'border-bottom-left-radius: 2px;'
            '}'
            '#ln_pattern{'
            'border-radius: 2px;'
            '}'
            '#state{'
            'background: rgba(0, 0, 0, 40);'
            'border-radius: 2px;'
            'padding: 1px;'
            'color: rgb(240, 240, 240);'
            '}'
            'QTabBar::tab {'
            'border: 0;'
            'width:  90px;'
            'height: 20px;'
            'margin: 0 2px 0 0;'  # top right bottom left
            # 'border-top-left-radius: 5px;'
            # 'border-top-right-radius: 5px;'
            'color: rgb(200, 255, 255;);'
            '}'
            'QTabBar::tab:selected{'
            'background: rgba(25, 0, 0, 40);'
            'border-left: 1px solid rgba(255, 255, 255, 200);'
            'border-top: 1px solid rgba(255, 255, 255, 200);'
            'border-right: 1px solid rgba(255, 255, 255, 200);'
            '}'
            'QTabWidget:pane {'
            'border: 1px solid rgba(255, 255, 255, 200);'
            'background: rgba(0, 0, 0, 80);'
            '}'
            '#browser_result, #browser_error{'
            'background: rgba(0, 0, 0, 0);'
            'border: 0;'
            '}'
            'QLineEdit{'
            'background: rgba(0, 0, 0, 40);'
            'border: 1px solid rgba(220, 220, 220, 200);'
            'color: white;'
            'height: 20px;'
            '}'
            'QPushButton{'
            'background: rgba(0, 0, 0, 100);'
            'border-radius: 5px;'
            'height: 20px;'
            'color: white;'
            '}'
            'QPushButton::hover{'
            'background: rgba(0, 0, 0, 150);'
            '}'
            'QToolButton{'
            'background: rgba(0, 0, 0, 100);'
            'color: white;'
            'border-top-right-radius:    2px;'
            'border-bottom-right-radius: 2px;'
            '}'
            'QToolButton::hover{'
            'background: rgba(0, 0, 0, 150);'
            '}')

        self.__ln_file_name.setFocus()
        self.__pbn_search.setShortcut(Qt.Key_Return)

        # 关联 信号/槽
        self.__pbn_file_path.clicked.connect(self.choose_path)
        self.__pbn_search.clicked.connect(self.pbn_search_clicked)
        self.__pbn_stop.clicked.connect(self.pbn_stop)
        self.__pbn_open_tool.clicked.connect(self.choose_open_tool)
        self.__browser_result.doubleClicked.connect(self.listitem_clicked)

        # 线程间共享数据队列
        queue_size = 10000
        self.__queue_result = Queue(queue_size)
        self.__queue_error = Queue(queue_size)

        # 标记搜索状态
        self.__searching = False

        # 强制结束子线程
        self.__thread_killer = False

    # 重写鼠标按下事件
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.offset = event.globalPos() - self.pos()

    # 重写鼠标移动事件
    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(event.globalPos() - self.offset)

    # 检测记事本程序
    def set_open_tool(self):
        if platform.architecture() == ('32bit', 'WindowsPE'):
            possible_dir = [
                'C:\\Program Files\\Sublime Text 2', 'C:\\Sublime Text 2',
                'D:\\Program Files\\Sublime Text 2', 'D:\\Sublime Text 2',
                'E:\\Program Files\\Sublime Text 2', 'E:\\Sublime Text 2',
                'F:\\Program Files\\Sublime Text 2', 'F:\\Sublime Text 2',
                'C:\\Program Files\\Notepad++', 'C:\\notepad++',
                'D:\\Program Files\\Notepad++', 'D:\\notepad++',
                'E:\\Program Files\\Notepad++', 'E:\\notepad++',
                'F:\\Program Files\\Notepad++', 'F:\\notepad++',
                'C:\\Windows\\System32'
            ]
        elif platform.architecture() == ('32bit', 'ELF'):
            possible_dir = ['/usr/bin']
        for rootdir in possible_dir:
            for root, dirs, files in walk(rootdir):
                for file in files:
                    if file == 'sublime_text.exe' or file == 'notepad++.exe' or file == 'notepad.exe':
                        self.__ln_open_tool.setText(join(root, file))
                        return

    # 搜索文件名
    def search_from_filename(self,
                             filepath,
                             filename,
                             mode='fuzzy_search',
                             I=True):
        # check arguments of searching
        if filepath == '' or not exists(filepath):
            return False
        if mode not in self.__search_mode.values():
            return False
        if filename == '':
            return False

        # count
        count = 0

        # fuzzy mode
        if mode == self.__search_mode['fuzzy']:
            for root, dirs, files in walk(filepath):
                for each_file in files:
                    # kill subThread
                    if self.__thread_killer == True:
                        return

                    if filename in each_file:
                        count += 1
                        self.__lab_state.setText('正在搜索......已搜到 %d 个文件' %
                                                 count)
                        self.__queue_result.put(join(root, each_file))
                        self.__tabView.setTabText(0, '匹配结果(%d)' % count)
        # precise mode
        elif mode == self.__search_mode['precise']:
            for root, dirs, files in walk(filepath):
                for each_file in files:
                    # kill subThread
                    if self.__thread_killer == True:
                        return

                    if filename == splitext(
                            each_file)[0] or filename == each_file:
                        count += 1
                        self.__lab_state.setText('正在搜索......已搜到 %d 个文件' %
                                                 count)
                        self.__queue_result.put(join(root, each_file))
                        self.__tabView.setTabText(0, '匹配结果(%d)' % count)
        # regular expression mode
        elif mode == self.__search_mode['reg']:
            if I:
                pattern = re.compile(r'%s' % filename)
            else:
                pattern = re.compile(r'%s' % filename, re.I)

            for root, dirs, files in walk(filepath):
                for each_file in files:
                    # kill subThread
                    if self.__thread_killer == True:
                        return

                    if re.search(pattern, each_file):
                        count += 1
                        self.__lab_state.setText('正在搜索......已搜到 %d 个文件' %
                                                 count)
                        self.__queue_result.put(join(root, each_file))
                        self.__tabView.setTabText(0, '匹配结果(%d)' % count)
        self.__lab_state.setText('搜索完毕! 共搜到 %d 个文件' % count)  # finished
        self.__searching = False  # set serching flag

    # 搜索文件内容
    def search_from_content(self, path, content, mode='fuzzy_search', I=True):
        if path == '' or not exists(path):
            return False
        if mode not in self.__search_mode.values():
            return False
        if content == '':
            return False
        pass_file_count = 0
        error_number = 0
        current_file = ''
        processing_file = ''
        match_files_count = 0
        if mode == self.__search_mode['reg']:
            if I:
                pattern = re.compile(r'%s' % content)
            else:
                pattern = re.compile(r'%s' % content, re.I)
            for root, dirs, files in walk(path):
                for each_file in [
                        file for file in files if file.endswith('.h')
                        or file.endswith('.cpp') or file.endswith('.cs')
                ]:
                    current_file = join(root, each_file)
                    pass_file_count += 1
                    self.__lab_state.setText('正在搜索......%s' % current_file)
                    try:
                        for line_number, line in enumerate(open(current_file)):
                            # kill subThread
                            if self.__thread_killer == True:
                                return

                            if re.search(pattern, line):
                                if processing_file != current_file:
                                    self.__queue_result.put('\n%s' %
                                                            current_file)
                                    processing_file = current_file
                                    match_files_count += 1
                                self.__queue_result.put(
                                    'line %s: %s' %
                                    (line_number, line.strip()))
                    except Exception as error:
                        self.__queue_error.put("%s\n(%s)\n" %
                                               (error, current_file))
                        pass_file_count -= 1
                        error_number += 1
                        continue
                    self.__tabView.setTabText(0,
                                              '匹配结果(%d)' % match_files_count)
        else:
            for root, dirs, files in walk(path):
                for each_file in [
                        file for file in files if file.endswith('.h')
                        or file.endswith('.cpp') or file.endswith('.cs')
                        or file.endswith('.txt') or file.endswith('.py')
                ]:
                    current_file = join(root, each_file)
                    pass_file_count += 1
                    self.__lab_state.setText('正在搜索......%s' % current_file)
                    try:
                        for line_number, line in enumerate(open(current_file)):
                            # kill subThread
                            if self.__thread_killer == True:
                                return

                            if content in line:  # 匹配成功
                                if processing_file != current_file:  # 如果是新文件
                                    self.__queue_result.put(
                                        '\n%s' % current_file)  # 文件名入队
                                    processing_file = current_file  # 更新文件标记
                                    match_files_count += 1
                                self.__queue_result.put(
                                    'line %s: %s' %
                                    (line_number, line.strip()))  # 匹配行入队
                    except Exception as error:
                        self.__queue_error.put("%s\n(%s)\n" %
                                               (error, current_file))
                        pass_file_count -= 1
                        error_number += 1
                        continue
                    self.__tabView.setTabText(0,
                                              '匹配结果(%d)' % match_files_count)
        # self.__queue_result.put()
        self.__lab_state.setText(
            '搜索完毕!成功匹配 %d 个文件,处理 %s 个文件,失败 %s 文件。' %
            (match_files_count, pass_file_count, error_number))
        self.__searching = False

    # 单击选择路径按钮
    def choose_path(self):
        path = QFileDialog.getExistingDirectory()
        if path != '':
            path = sep.join(path.split('/'))
            self.__ln_file_path.setText(path)

    # 选择打开文件工具
    def choose_open_tool(self):
        path = QFileDialog.getOpenFileName()
        if path[0] != '':
            self.__ln_open_tool.setText(path[0])

    # 显示搜索结果
    def show_search_result(self):
        """将搜索结果加载到界面,供用户查看和操作"""
        line_block = []  # 定义临时列表,成批加载,避免刷新频率过高造成界面闪烁
        block_size = 10  # 一次性加载的个数
        while self.__searching or self.__queue_result.qsize():
            # kill subThread
            if self.__thread_killer == True:
                return

            # if self.__searching or self.__queue_result.qsize() >= block_size:     // 永远记住这个 bug (生产者-消费者 问题)
            if self.__queue_result.qsize(
            ) >= block_size:  # 如果队列中不小于 block_size 个项
                for i in range(block_size):  # 取出 block_size 个项
                    line_block.append(self.__queue_result.get())  # 出队操作
                self.__browser_result.addItems(
                    line_block)  # 一次性添加 block_size 个条目
                line_block.clear()  # 清空临时列表
            elif self.__queue_result.qsize() >= 0:  # 如果队列中小于 block_size 各项
                item = self.__queue_result.get()  # 出队一项
                self.__browser_result.addItem(QListWidgetItem(item))  # 加载到界面
            #self.__browser.setCurrentRow(self.__browser.count()-1)                  # 设置列表中最后一项为当前项,使列表不停滚动
            sleep(0.05)  # 给界面事件循环腾出时间,避免界面冻结
        #self.__pbn_search.setEnabled(True)

    # 显示出错结果
    def show_error_result(self):
        """打印略过的文件和出错原因,多为 I/O Error"""
        count = 0
        while self.__queue_error.qsize() or self.__searching:
            # kill subThread
            if self.__thread_killer == True:
                return

            if self.__queue_error.qsize() <= 0:
                continue
            self.__browser_error.append(self.__queue_error.get())
            count += 1
            self.__tabView.setTabText(1, '错误结果(%d)' % count)

    # 单击检索按钮
    def pbn_search_clicked(self):
        """To search allow the arguments from UI"""
        # 获取 UI 数据
        file_path = self.__ln_file_path.text()
        file_name = self.__ln_file_name.text()

        # 检查参数
        if file_path == '':
            QMessageBox(QMessageBox.Warning, '缺少参数!', '请输入搜索路径!',
                        QMessageBox.Ok, self).exec_()
            return
        if file_name == '':
            QMessageBox(QMessageBox.Warning, '缺少参数!', '请输入匹配条件!',
                        QMessageBox.Ok, self).exec_()
            return

        # 判断搜索模式
        mode = self.__search_mode['fuzzy']
        if self.__rbn_reg.isChecked():
            mode = self.__search_mode['reg']
        elif self.__rbn_fuzzy.isChecked():
            mode = self.__search_mode['fuzzy']
        elif self.__rbn_precise.isChecked():
            mode = self.__search_mode['precise']

        # 大小写敏感标记
        I = True
        if self.__rbn_reg_Ino.isChecked():
            I = False

        self.__browser_result.clear()
        self.__browser_error.clear()
        self.__tabView.setTabText(0, '匹配结果(0)')
        self.__tabView.setTabText(1, '错误结果(0)')
        self.__searching = True

        # 开启子线程,后台深度遍历
        self.__thread_killer = False
        if self.__rbn_search_file.isChecked():
            self.__lab_state.setText('正在搜索......已搜索到 0 个文件')
            self.__sub_thread_search = Thread(target=self.search_from_filename,
                                              args=(file_path, file_name, mode,
                                                    I))
            self.__sub_thread_search.start()
        else:
            self.__lab_state.setText('正在搜索......')
            self.__sub_thread_search = Thread(target=self.search_from_content,
                                              args=(file_path, file_name, mode,
                                                    I))
            self.__sub_thread_search.start()

        # 开启子线程,显示搜索结果
        self.__sub_thread_show_result = Thread(target=self.show_search_result)
        self.__sub_thread_show_result.start()

        # 开启子线程,显示错误结果
        self.__sub_thread_show_error = Thread(target=self.show_error_result)
        self.__sub_thread_show_error.start()

        # self.__pbn_search_file.setEnable(False)
        # self.__pbn_search_content.setEnable(False)

    # 单击停止按钮
    def pbn_stop(self):
        if not self.__searching:
            return
        self.__thread_killer = True
        while self.__queue_result.qsize():
            self.__queue_result.get()
        while self.__queue_error.qsize():
            self.__queue_error.get()
        self.__lab_state.setText('搜索已停止!')
        self.__searching = False

    # 双击搜索结果
    def listitem_clicked(self):
        """Double click to open the file from search result"""
        file_path = self.__browser_result.currentItem().text().strip()
        read_tool = self.__ln_open_tool.text()
        if not exists(file_path):
            QMessageBox.warning(self, '错误!',
                                '请双击文件名\n%s 不是文件或打不开!' % file_path,
                                QMessageBox.Ok)
            return
        if splitext(file_path)[1] in ['.jpg', '.png', '.jpeg', '.gif']:
            file_path = r'%s'.replace(' ', r'\ ') % file_path
            system('%s' % file_path)
        else:
            system('"%s" %s' % (read_tool, file_path))
Example #33
0
    def initUI(self):
        grid_layout = QGridLayout()
        grid_layout.setObjectName("grid_layout")
        grid_layout.setContentsMargins(10, 10, 10, 10)

        grp_input = QGroupBox()
        grp_input.setObjectName("grp_input")
        grp_input.setTitle("Input images")

        self.lst_images = QListWidget(grp_input)
        self.lst_images.setObjectName("lst_images")
        self.lst_images.setSelectionMode(QAbstractItemView.NoSelection)

        self.btn_load = QPushButton()
        self.btn_load.setObjectName("btn_load")
        self.btn_load.setText("1. Load images")
        self.btn_load.clicked.connect(self.load_files)

        input_layout = QGridLayout()
        input_layout.setContentsMargins(0, 0, 0, 0)
        # Set the stretch
        input_layout.setColumnStretch(0, 0)  # row, stretch
        input_layout.setColumnStretch(3, 0)
        input_layout.setRowStretch(0, 0)
        input_layout.setRowStretch(3, 0)
        # Add widgets
        input_layout.addWidget(self.lst_images, 2, 2)
        input_layout.addWidget(self.btn_load, 3, 2)
        grp_input.setLayout(input_layout)

        grid_layout.addWidget(grp_input, 0, 0, 3, 1)

        grp_detectors = QGroupBox()
        grp_detectors.setObjectName("grp_detectors")
        grp_detectors_layout = QVBoxLayout()

        chk_thresh = QCheckBox(grp_detectors)
        chk_thresh.setObjectName("chk_thresh")
        chk_thresh.setText("ThresholdBlurDetector")
        chk_thresh.setChecked(True)
        self.detector_checks.append(chk_thresh)
        self.detector_map[chk_thresh] = ThresholdBlurDetector
        grp_detectors_layout.addWidget(chk_thresh)

        chk_canny = QCheckBox(grp_detectors)
        chk_canny.setObjectName("chk_canny")
        chk_canny.setText("CannyDetector")
        self.detector_checks.append(chk_canny)
        self.detector_map[chk_canny] = CannyDetector
        grp_detectors_layout.addWidget(chk_canny)

        chk_morphology = QCheckBox(grp_detectors)
        chk_morphology.setObjectName("chk_morphology")
        chk_morphology.setText("MorphologyTransformDetector")
        self.detector_checks.append(chk_morphology)
        self.detector_map[chk_morphology] = MorphologyTransformDetector
        grp_detectors_layout.addWidget(chk_morphology)

        grp_detectors.setLayout(grp_detectors_layout)
        grid_layout.addWidget(grp_detectors, 3, 0, 1, 1)

        self.btn_process = QPushButton()
        self.btn_process.setObjectName("btn_process")
        self.btn_process.setText("2. Process")
        self.btn_process.setEnabled(False)
        self.btn_process.clicked.connect(self.process_files)

        # addWidget(*Widget, row, column, rowspan, colspan)
        grid_layout.addWidget(self.btn_process, 4, 0, 1, 1)

        self.setLayout(grid_layout)
        self.setToolTip('This is a <b>QWidget</b> widget')
        self.setGeometry(300, 300, 400, 400)
        self.setWindowTitle('License Plate Number Recognition')
        self.center()
        self.show()
Example #34
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()
        self.createDockWindows()

        self.setWindowTitle("Dock Widgets")

        self.newLetter()

    def newLetter(self):
        self.textEdit.clear()

        cursor = self.textEdit.textCursor()
        cursor.movePosition(QTextCursor.Start)
        topFrame = cursor.currentFrame()
        topFrameFormat = topFrame.frameFormat()
        topFrameFormat.setPadding(16)
        topFrame.setFrameFormat(topFrameFormat)

        textFormat = QTextCharFormat()
        boldFormat = QTextCharFormat()
        boldFormat.setFontWeight(QFont.Bold)
        italicFormat = QTextCharFormat()
        italicFormat.setFontItalic(True)

        tableFormat = QTextTableFormat()
        tableFormat.setBorder(1)
        tableFormat.setCellPadding(16)
        tableFormat.setAlignment(Qt.AlignRight)
        cursor.insertTable(1, 1, tableFormat)
        cursor.insertText("The Firm", boldFormat)
        cursor.insertBlock()
        cursor.insertText("321 City Street", textFormat)
        cursor.insertBlock()
        cursor.insertText("Industry Park")
        cursor.insertBlock()
        cursor.insertText("Some Country")
        cursor.setPosition(topFrame.lastPosition())
        cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"),
                          textFormat)
        cursor.insertBlock()
        cursor.insertBlock()
        cursor.insertText("Dear ", textFormat)
        cursor.insertText("NAME", italicFormat)
        cursor.insertText(",", textFormat)
        for i in range(3):
            cursor.insertBlock()
        cursor.insertText("Yours sincerely,", textFormat)
        for i in range(3):
            cursor.insertBlock()
        cursor.insertText("The Boss", textFormat)
        cursor.insertBlock()
        cursor.insertText("ADDRESS", italicFormat)

    def print_(self):
        document = self.textEdit.document()
        printer = QPrinter()

        dlg = QPrintDialog(printer, self)
        if dlg.exec_() != QDialog.Accepted:
            return

        document.print_(printer)

        self.statusBar().showMessage("Ready", 2000)

    def save(self):
        filename, _ = QFileDialog.getSaveFileName(self, "Choose a file name",
                                                  '.', "HTML (*.html *.htm)")
        if not filename:
            return

        file = QFile(filename)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, "Dock Widgets",
                "Cannot write file %s:\n%s." % (filename, file.errorString()))
            return

        out = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        out << self.textEdit.toHtml()
        QApplication.restoreOverrideCursor()

        self.statusBar().showMessage("Saved '%s'" % filename, 2000)

    def undo(self):
        document = self.textEdit.document()
        document.undo()

    def insertCustomer(self, customer):
        if not customer:
            return
        customerList = customer.split(', ')
        document = self.textEdit.document()
        cursor = document.find('NAME')
        if not cursor.isNull():
            cursor.beginEditBlock()
            cursor.insertText(customerList[0])
            oldcursor = cursor
            cursor = document.find('ADDRESS')
            if not cursor.isNull():
                for i in customerList[1:]:
                    cursor.insertBlock()
                    cursor.insertText(i)
                cursor.endEditBlock()
            else:
                oldcursor.endEditBlock()

    def addParagraph(self, paragraph):
        if not paragraph:
            return
        document = self.textEdit.document()
        cursor = document.find("Yours sincerely,")
        if cursor.isNull():
            return
        cursor.beginEditBlock()
        cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.MoveAnchor,
                            2)
        cursor.insertBlock()
        cursor.insertText(paragraph)
        cursor.insertBlock()
        cursor.endEditBlock()

    def about(self):
        QMessageBox.about(
            self, "About Dock Widgets",
            "The <b>Dock Widgets</b> example demonstrates how to use "
            "Qt's dock widgets. You can enter your own text, click a "
            "customer to add a customer name and address, and click "
            "standard paragraphs to add them.")

    def createActions(self):
        self.newLetterAct = QAction(QIcon(':/images/new.png'),
                                    "&New Letter",
                                    self,
                                    shortcut=QKeySequence.New,
                                    statusTip="Create a new form letter",
                                    triggered=self.newLetter)

        self.saveAct = QAction(QIcon(':/images/save.png'),
                               "&Save...",
                               self,
                               shortcut=QKeySequence.Save,
                               statusTip="Save the current form letter",
                               triggered=self.save)

        self.printAct = QAction(QIcon(':/images/print.png'),
                                "&Print...",
                                self,
                                shortcut=QKeySequence.Print,
                                statusTip="Print the current form letter",
                                triggered=self.print_)

        self.undoAct = QAction(QIcon(':/images/undo.png'),
                               "&Undo",
                               self,
                               shortcut=QKeySequence.Undo,
                               statusTip="Undo the last editing action",
                               triggered=self.undo)

        self.quitAct = QAction("&Quit",
                               self,
                               shortcut="Ctrl+Q",
                               statusTip="Quit the application",
                               triggered=self.close)

        self.aboutAct = QAction("&About",
                                self,
                                statusTip="Show the application's About box",
                                triggered=self.about)

        self.aboutQtAct = QAction("About &Qt",
                                  self,
                                  statusTip="Show the Qt library's About box",
                                  triggered=QApplication.instance().aboutQt)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.newLetterAct)
        self.fileMenu.addAction(self.saveAct)
        self.fileMenu.addAction(self.printAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.quitAct)

        self.editMenu = self.menuBar().addMenu("&Edit")
        self.editMenu.addAction(self.undoAct)

        self.viewMenu = self.menuBar().addMenu("&View")

        self.menuBar().addSeparator()

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

    def createToolBars(self):
        self.fileToolBar = self.addToolBar("File")
        self.fileToolBar.addAction(self.newLetterAct)
        self.fileToolBar.addAction(self.saveAct)
        self.fileToolBar.addAction(self.printAct)

        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.undoAct)

    def createStatusBar(self):
        self.statusBar().showMessage("Ready")

    def createDockWindows(self):
        dock = QDockWidget("Customers", self)
        dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
        self.customerList = QListWidget(dock)
        self.customerList.addItems(
            ("John Doe, Harmony Enterprises, 12 Lakeside, Ambleton",
             "Jane Doe, Memorabilia, 23 Watersedge, Beaton",
             "Tammy Shea, Tiblanka, 38 Sea Views, Carlton",
             "Tim Sheen, Caraba Gifts, 48 Ocean Way, Deal",
             "Sol Harvey, Chicos Coffee, 53 New Springs, Eccleston",
             "Sally Hobart, Tiroli Tea, 67 Long River, Fedula"))
        dock.setWidget(self.customerList)
        self.addDockWidget(Qt.RightDockWidgetArea, dock)
        self.viewMenu.addAction(dock.toggleViewAction())

        dock = QDockWidget("Paragraphs", self)
        self.paragraphsList = QListWidget(dock)
        self.paragraphsList.addItems(
            ("Thank you for your payment which we have received today.",
             "Your order has been dispatched and should be with you within "
             "28 days.",
             "We have dispatched those items that were in stock. The rest of "
             "your order will be dispatched once all the remaining items "
             "have arrived at our warehouse. No additional shipping "
             "charges will be made.",
             "You made a small overpayment (less than $5) which we will keep "
             "on account for you, or return at your request.",
             "You made a small underpayment (less than $1), but we have sent "
             "your order anyway. We'll add this underpayment to your next "
             "bill.",
             "Unfortunately you did not send enough money. Please remit an "
             "additional $. Your order will be dispatched as soon as the "
             "complete amount has been received.",
             "You made an overpayment (more than $5). Do you wish to buy more "
             "items, or should we return the excess to you?"))
        dock.setWidget(self.paragraphsList)
        self.addDockWidget(Qt.RightDockWidgetArea, dock)
        self.viewMenu.addAction(dock.toggleViewAction())

        self.customerList.currentTextChanged.connect(self.insertCustomer)
        self.paragraphsList.currentTextChanged.connect(self.addParagraph)
Example #35
0
    def initIF(self):
        self.layout = QGridLayout(self)
        self.setLayout(self.layout)
        icon = QIcon()
        icon.addPixmap(QPixmap("./style/logo3.png"))
        self.setWindowIcon(icon)
        self.setWindowTitle("语音录制与分析")
        self.list_LW = QListWidget(self)
        self.list_LW.setMaximumWidth(160)
        class WaveSpectrum(QWidget):
            def __init__(self, parent=None, maindlg=None):
                super(WaveSpectrum, self).__init__(parent)
                self.main_Dlg = maindlg
                #self.pg_PL = pg.PlotWidget(enableMenu=False)
                self.audio = self.main_Dlg.audio
                self.layout = QGridLayout(self)
                self.setLayout(self.layout)
                self.pg_PL = pg.PlotWidget() #pg.plot(title="Three plot curves")
                self.pg_PL.hideButtons()
                self.layout.addWidget(self.pg_PL)               
                self.item = self.pg_PL.getPlotItem()
                self.item.hideButtons()
                self.item.setMouseEnabled(y=False)
                self.item.setYRange(0,20000)
                range = self.audio.rate/2
                self.item.setXRange(-range,range, padding=0)
                self.axis = self.item.getAxis("bottom")
                self.axis.setLabel("频率(赫兹)")
                
            def updatePlot(self):
               try:
                   data = np.fromstring(self.audio.block, 'int16')
                   #print(data)
                   T = 1.0/self.audio.rate
                   N = data.shape[0]
                   Fx = (1./N) * np.fft.fft(data) # 万一N==0
               except Exception as e:
                   print("??",e)
               else:
                   f = np.fft.fftfreq(N, T)
                   Fx = np.fft.fftshift(Fx)
                   f = np.fft.fftshift(f)
                   self.item.plot(x=f.tolist(), y=(np.absolute(Fx)).tolist(), clear=True)    
    
        self.wave_spectrum_PG = WaveSpectrum(maindlg=self)
        self.result_LB = QLabel(self)
        self.result_LB.setText("欢迎使用")
        self.running_SL = QSlider(Qt.Horizontal)
        self.running_SL.setMinimum(0)
        self.running_SL.setMaximum(100)
        self.running_SL.setStyleSheet("QSlider::handle:horizontal {background-color: #d91900;}")
        self.save_BT = QPushButton(self)
        self.save_BT.setText("保存与分析")
        self.save_BT.setMinimumSize(128,32)
        self.record_BT = QPushButton(self)
        self.record_BT.setText("开始录音")
        self.record_BT.setMinimumSize(144,32)
        self.play_BT = QPushButton(self)
        self.play_BT.setText("开始播放")
        self.play_BT.setMinimumSize(144,32)
        self.reset_BT = QPushButton(self)
        self.reset_BT.setText("停止")
        self.reset_BT.setMinimumSize(128,32)
               
        self.layout.addWidget(self.list_LW, 0,0,1,1)
        self.layout.addWidget(self.wave_spectrum_PG, 0,1, 1,3)
        self.layout.addWidget(self.result_LB, 1,0, 1,4)
        self.layout.addWidget(self.running_SL, 2,0, 1,4)
        self.layout.addWidget(self.save_BT, 3,0, 2,1)
        self.layout.addWidget(self.record_BT, 3,1, 2,1)
        self.layout.addWidget(self.play_BT, 3,2, 2,1)
        self.layout.addWidget(self.reset_BT, 3,3, 2,1)
        

        self.list_LW.itemClicked.connect(self.sel2Play)
        self.record_BT.clicked.connect(self.click2Record)
        self.running_SL.sliderReleased.connect(self.dragPosPlay) 
        # 注意这里得是用户主动的动作哟 另外如果需要点击位置定位的话还必须要重写mousePressEvent,这里就不弄了
        self.play_BT.clicked.connect(self.click2Play)
        self.reset_BT.clicked.connect(self.click2Reset)
        self.save_BT.clicked.connect(self.click2Save)
Example #36
0
    def __init__(self):
        super().__init__()
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        row_hight = 30
        margins = self.layout.contentsMargins()
        margins.setTop(row_hight)
        margins.setRight(20)
        self.layout.setContentsMargins(margins)

        # Initializing GUI elements
        self.settings_label = QLabel('Settings')
        self.platform_var_list = QComboBox()
        self.thread_var_list = QComboBox()

        self.intel64 = QCheckBox('Intel 64')
        self.IA32 = QCheckBox('IA32')
        self.TL = QCheckBox('Threading layer')
        self.omp = QRadioButton('OpenMP')
        self.tbb = QRadioButton('TBB')

        self.lib_name = QLineEdit()
        self.functions_list = QListWidget()
        self.save_build_script = QPushButton('Save build script')
        self.functions_names = []
        self.status_receiver = None

        self.lib_name.setPlaceholderText('Library name...')

        # Preparing elements by giving initial values and etc
        self.settings_label.setAlignment(Qt.AlignBottom)
        self.save_build_script.setDisabled(True)

        self.save_build_script.clicked.connect(self.on_save_build_script)
        self.IA32.clicked.connect(self.on_block)
        self.intel64.clicked.connect(self.on_block)
        self.TL.clicked.connect(self.set_tl)
        self.lib_name.textEdited.connect(self.on_block)
        self.platform_var_list.currentIndexChanged.connect(
            self.on_target_system_selection)

        # Setting all widgets in their places
        self.layout.addWidget(self.settings_label, 0, 0)

        self.layout.addWidget(self.TL, 1, 0)
        self.layout.addWidget(self.omp, 2, 0)
        self.layout.addWidget(self.tbb, 3, 0)

        self.layout.addWidget(self.intel64, 2, 1)
        self.layout.addWidget(self.IA32, 3, 1)
        self.layout.addWidget(self.platform_var_list, 2, 2, 1, 2)
        self.layout.addWidget(self.thread_var_list, 3, 2, 1, 2)

        self.layout.addWidget(self.lib_name, 4, 0, 1, 4)
        self.layout.addWidget(self.functions_list, 5, 0, 1, 4)
        self.layout.addWidget(self.save_build_script, 6, 0, 1, 4)

        self.settings_label.setFixedHeight(row_hight)
        self.TL.setFixedHeight(row_hight)
        self.platform_var_list.setFixedHeight(row_hight)
        self.thread_var_list.setFixedHeight(row_hight)

        self.__post_check()
Example #37
0
def init_map_modes_list(list_widget: QListWidget, list_of_modes: list):
    list_widget.addItems(list_of_modes)
    list_widget.setCurrentRow(1)
Example #38
0
class NdiUi(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('ANDY - NGS data interpreter')
        self.setFixedSize(700, 480)

        self.generalLayout = QVBoxLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)

        self.buttonsModesLayout = QHBoxLayout()
        self.buttonMode1 = QPushButton('CHECK/IMPORT')
        self.buttonMode1.clicked.connect(self.setMode1)
        # self.buttonMode1 = QPushButton('Mode1', clicked=self.setMode1)
        self.buttonMode2 = QPushButton('RELATIONSHIP_ESTIMATION')
        self.buttonMode2.clicked.connect(self.setMode2)
        self.buttonMode3 = QPushButton('PRINT_SAMPLES')
        self.buttonMode3.clicked.connect(self.setMode3)
        self.buttonMode4 = QPushButton('DELETE_SAMPLES')
        self.buttonMode4.clicked.connect(self.setMode4)
        self.buttonsModesLayout.addWidget(self.buttonMode1)
        self.buttonsModesLayout.addWidget(self.buttonMode2)
        self.buttonsModesLayout.addWidget(self.buttonMode3)
        self.buttonsModesLayout.addWidget(self.buttonMode4)

        self.generalLayout.addLayout(self.buttonsModesLayout)

        self.modeWidget = QStackedWidget()
        self.generalLayout.addWidget(self.modeWidget)
        self.generateDbPasswWidget()

        self.mode1set = False
        self.mode2set = False
        self.mode3set = False
        self.mode4set = False

    def generateDbPasswWidget(self):
        self.dbPasswWidget = QWidget()

        self.dbPassw = QLineEdit(parent=self.dbPasswWidget)
        self.dbPassw.setEchoMode(QLineEdit.Password)
        self.dbPassw.setFixedSize(150, 20)
        self.dbPassw.setPlaceholderText("DB Password")

        self.dbTryConnection = QPushButton("Try DB connection",
                                           parent=self.dbPasswWidget)
        self.dbTryConnection.move(170, 0)
        self.dbTryConnection.clicked.connect(self.tryDbConnection)

        self.tryResult = QLabel(parent=self.dbPasswWidget)
        self.tryResult.setFixedSize(160, 20)
        self.tryResult.move(280, 2)

        self.modeWidget.addWidget(self.dbPasswWidget)
        self.modeWidget.setCurrentWidget(self.dbPasswWidget)

    def tryDbConnection(self):
        try:
            db = connect("localhost", "root", self.dbPassw.text(),
                         "NGS_FORENSIC")
        except:
            self.tryResult.setText('Connection failed')
            return
        self.tryResult.setText('Connection OK')
        db.close()

    def getBrowseDirName(self, label):
        dir = QFileDialog.getExistingDirectory()
        label.setText(dir)


###todo - open file ad to mode 3

    def getBrowseFileName(self, label):
        file = QFileDialog.getOpenFileName()
        label.setText(file[0])

    def setDefaultModeButtonText(self):
        self.buttonMode1.setText('CHECK/IMPORT')
        self.buttonMode2.setText('RELATIONSHIP_ESTIMATION')
        self.buttonMode3.setText('PRINT_SAMPLES')
        self.buttonMode4.setText('DELETE_SAMPLES')

    def setMode1(self):
        if not self.mode1set:
            self.generateMode1Widget()
            self.modeWidget.addWidget(self.mode1Widget)
            self.mode1set = True
        self.modeWidget.setCurrentWidget(self.mode1Widget)
        self.setDefaultModeButtonText()
        self.buttonMode1.setText('<CHECK/IMPORT>')

    def generateMode1Widget(self):
        self.mode1Widget = QWidget()
        self.mode1Layout = QGridLayout()

        self.mode1buttonDir1 = QPushButton("in_directory Illumina")
        self.mode1labelDir1 = QLabel(
            os.path.normpath('C:/NGS_forensic_database/xlsx_detail_reports'))
        self.mode1buttonDir1.clicked.connect(
            partial(self.getBrowseDirName, self.mode1labelDir1))
        # self.mode1buttonDir1.clicked.connect(lambda: self.getBrowseDirName(self.mode1labelDir1))

        self.mode1buttonDir2 = QPushButton("out_directory")
        self.mode1labelDir2 = QLabel(
            os.path.normpath('C:/NGS_forensic_database/csv_output'))
        self.mode1buttonDir2.clicked.connect(
            partial(self.getBrowseDirName, self.mode1labelDir2))

        self.mode1buttonDir3 = QPushButton("xml_CE_directory")
        self.mode1labelDir3 = QLabel(
            os.path.normpath('C:/NGS_forensic_database/xml_CE'))
        self.mode1buttonDir3.clicked.connect(
            partial(self.getBrowseDirName, self.mode1labelDir3))

        self.mode1buttonDir4 = QPushButton("CSV_CE_directory")
        self.mode1labelDir4 = QLabel(
            os.path.normpath('C:/NGS_forensic_database/csv_CE'))
        self.mode1buttonDir4.clicked.connect(
            partial(self.getBrowseDirName, self.mode1labelDir4))

        self.mode1buttonDir5 = QPushButton("report_directory")
        self.mode1labelDir5 = QLabel()
        self.mode1buttonDir5.clicked.connect(
            partial(self.getBrowseDirName, self.mode1labelDir5))

        self.mode1labelNumber = QLabel("no_reads_for_validation:")
        self.mode1inputNumber = QLineEdit("150")
        self.onlyInt = QIntValidator()
        self.mode1inputNumber.setValidator(self.onlyInt)

        self.mode1booleanCheckBox = QCheckBox("CheckIfSampleInDatabase")
        self.mode1booleanCheckBox.setChecked(True)

        self.mode1scriptSelector = QComboBox()
        self.mode1scriptSelector.addItems([
            "AutoSTR_check_no_mismatches", "AutoSTR_import2db",
            "Y-STR_check_no_mismatches", "Y-STR_import2db"
        ])

        self.mode1buttonRun = QPushButton("run")
        self.mode1buttonRun.clicked.connect(self.runMode1)

        self.mode1labelState = QLabel("")

        self.mode1Layout.addWidget(self.mode1buttonDir1, 0, 0)
        self.mode1Layout.addWidget(self.mode1labelDir1, 0, 1)
        self.mode1Layout.addWidget(self.mode1buttonDir2, 1, 0)
        self.mode1Layout.addWidget(self.mode1labelDir2, 1, 1)
        self.mode1Layout.addWidget(self.mode1buttonDir3, 2, 0)
        self.mode1Layout.addWidget(self.mode1labelDir3, 2, 1)
        self.mode1Layout.addWidget(self.mode1buttonDir4, 3, 0)
        self.mode1Layout.addWidget(self.mode1labelDir4, 3, 1)
        self.mode1Layout.addWidget(self.mode1buttonDir5, 4, 0)
        self.mode1Layout.addWidget(self.mode1labelDir5, 4, 1)
        self.mode1Layout.addWidget(self.mode1labelNumber, 5, 0)
        self.mode1Layout.addWidget(self.mode1inputNumber, 5, 1)
        self.mode1Layout.addWidget(self.mode1booleanCheckBox, 6, 0)
        self.mode1Layout.addWidget(self.mode1scriptSelector, 7, 0)
        self.mode1Layout.addWidget(self.mode1buttonRun, 7, 1)
        self.mode1Layout.addWidget(self.mode1labelState, 8, 1)
        self.mode1Widget.setLayout(self.mode1Layout)

    def runMode1(self):

        self.mode1labelState.setText("running")
        self.mode1labelState.repaint()

        dir1 = self.mode1labelDir1.text()
        dir2 = self.mode1labelDir2.text()
        dir3 = self.mode1labelDir3.text()
        dir4 = self.mode1labelDir4.text()
        dir5 = self.mode1labelDir5.text()
        number = int(self.mode1inputNumber.text())
        boolean = self.mode1booleanCheckBox.isChecked()
        script = self.mode1scriptSelector.currentIndex()

        #in_directory, out_directory, xml_directory, CSV_CE_directory, no_reads_for_validation, CheckIfSampleInDatabase
        if script == 0:
            autoSTR_FR_check_no_mismatches(dir1, dir2, dir3, dir4,
                                           dir5, number, boolean,
                                           self.dbPassw.text())
            self.mode1labelState.setText("finished")
        elif script == 1:
            autoSTR_FR_import2db(dir1, dir2, dir3, dir4, dir5, number, boolean,
                                 self.dbPassw.text())
            self.mode1labelState.setText("finished")
        elif script == 2:
            Y_STR_FR_check_no_mismatches(dir1, dir2, dir3, dir4, dir5, number,
                                         boolean, self.dbPassw.text())
            self.mode1labelState.setText("finished")
        elif script == 3:
            Y_STR_FR_import2db(dir1, dir2, dir3, dir4, dir5, number, boolean,
                               self.dbPassw.text())
            self.mode1labelState.setText("finished")

    def setMode2(self):
        if not self.mode2set:
            self.generateMode2Widget()
            self.modeWidget.addWidget(self.mode2Widget)
            self.mode2set = True
        self.modeWidget.setCurrentWidget(self.mode2Widget)
        self.setDefaultModeButtonText()
        self.buttonMode2.setText('<RELATIONSHIP_ESTIMATION>')

    def generateMode2Widget(self):
        self.mode2Widget = QWidget()
        self.mode2Layout = QGridLayout()

        self.mode2sampleName1Label = QLabel("Sample name 1:")
        self.mode2sampleName1Input = QLineEdit()

        self.mode2sampleName2Label = QLabel("Sample name 2:")
        self.mode2sampleName2Input = QLineEdit()

        self.mode2boolean1CheckBox = QCheckBox(
            "length_polymorphism_estimation")

        self.mode2boolean2CheckBox = QCheckBox(
            "use_external_file_for_missing_markers")

        self.mode2buttonDir1 = QPushButton("CE_profiles_directory")
        self.mode2labelDir1 = QLabel(
            "C:/NGS_forensic_database/relationship_LR_estimation/STR_lenght_profiles"
        )
        self.mode2buttonDir1.clicked.connect(
            partial(self.getBrowseDirName, self.mode2labelDir1))

        self.mode2buttonDir2 = QPushButton("CE_frequencies_directory")
        self.mode2labelDir2 = QLabel(
            "C:/NGS_forensic_database/relationship_LR_estimation/STR_lenght_frequencies"
        )
        self.mode2buttonDir2.clicked.connect(
            partial(self.getBrowseDirName, self.mode2labelDir2))

        self.mode2buttonDir3 = QPushButton("reports_directory")
        self.mode2labelDir3 = QLabel(
            "C:/NGS_forensic_database/relationship_LR_estimation/reports")
        self.mode2buttonDir3.clicked.connect(
            partial(self.getBrowseDirName, self.mode2labelDir3))

        self.mode2buttonRun = QPushButton("run")
        self.mode2buttonRun.clicked.connect(self.runMode2)

        self.mode2labelState = QLabel("")

        self.mode2Layout.addWidget(self.mode2sampleName1Label, 0, 0)
        self.mode2Layout.addWidget(self.mode2sampleName1Input, 0, 1)
        self.mode2Layout.addWidget(self.mode2sampleName2Label, 1, 0)
        self.mode2Layout.addWidget(self.mode2sampleName2Input, 1, 1)
        self.mode2Layout.addWidget(self.mode2boolean1CheckBox, 2, 0)
        self.mode2Layout.addWidget(self.mode2boolean2CheckBox, 3, 0)
        self.mode2Layout.addWidget(self.mode2buttonDir1, 4, 0)
        self.mode2Layout.addWidget(self.mode2labelDir1, 4, 1)
        self.mode2Layout.addWidget(self.mode2buttonDir2, 5, 0)
        self.mode2Layout.addWidget(self.mode2labelDir2, 5, 1)
        self.mode2Layout.addWidget(self.mode2buttonDir3, 6, 0)
        self.mode2Layout.addWidget(self.mode2labelDir3, 6, 1)
        self.mode2Layout.addWidget(self.mode2buttonRun, 7, 0)
        self.mode2Layout.addWidget(self.mode2labelState, 8, 1)

        self.mode2Widget.setLayout(self.mode2Layout)

    def addSamples(self):
        sample1 = self.mode2sampleName1Input.text()
        sample2 = self.mode2sampleName2Input.text()
        sampleList = list()
        sampleList.append(sample1)
        sampleList.append(sample2)
        return sampleList

    def runMode2(self):
        self.mode2labelState.setText("running")
        self.mode2labelState.repaint()

        samples = self.addSamples()
        dir1 = self.mode2labelDir1.text()
        dir2 = self.mode2labelDir2.text()
        dir3 = self.mode2labelDir3.text()
        boolean1 = self.mode2boolean1CheckBox.isChecked()
        boolean2 = self.mode2boolean2CheckBox.isChecked()
        relationship_LR_estimation(samples, boolean1, boolean2, dir1, dir2,
                                   dir3, self.dbPassw.text())
        self.mode2labelState.setText("finished")

    def setMode3(self):
        if not self.mode3set:
            self.generateMode3Widget()
            self.modeWidget.addWidget(self.mode3Widget)
            self.mode3set = True
        self.modeWidget.setCurrentWidget(self.mode3Widget)
        self.setDefaultModeButtonText()
        self.buttonMode3.setText('<PRINT_SAMPLES>')

    def generateMode3Widget(self):
        self.mode3Widget = QWidget()
        self.mode3Layout = QGridLayout()

        self.mode3buttonFile1 = QPushButton("sample_list")
        self.mode3labelFile1 = QLabel(
            "C:/NGS_forensic_database/print_samples/print_sample.txt")
        self.mode3buttonFile1.clicked.connect(
            partial(self.getBrowseFileName, self.mode3labelFile1))

        self.mode3buttonFile2 = QPushButton("locus_order")
        self.mode3labelFile2 = QLabel(
            "C:/NGS_forensic_database/print_samples/locus_order.txt")
        self.mode3buttonFile2.clicked.connect(
            partial(self.getBrowseFileName, self.mode3labelFile2))

        self.mode3buttonDir3 = QPushButton("reports_directory")
        self.mode3labelDir3 = QLabel(
            "C:/NGS_forensic_database/print_samples/prints")
        self.mode3buttonDir3.clicked.connect(
            partial(self.getBrowseDirName, self.mode3labelDir3))

        self.mode3categoriesList = QListWidget()
        self.mode3categoriesList.addItems(["AutoSTR", "Y-STR"])
        self.mode3categoriesList.setSelectionMode(
            QAbstractItemView.MultiSelection)

        #columns = ['allele', 'seq_name', 'PubMed_ID', 'sequence', 'no_reads', 'CE_validation', 'head_id', 'avg_no_reads', 'count_seq', 'frequency']
        self.mode3columnsList = QListWidget()
        self.mode3columnsList.addItems([
            "allele", "seq_name", "PubMed_ID", "sequence", "no_reads",
            "CE_validation", "head_id", "avg_no_reads", "count_seq",
            "frequency"
        ])
        self.mode3columnsList.setSelectionMode(
            QAbstractItemView.MultiSelection)

        self.mode3buttonRun = QPushButton("run")
        self.mode3buttonRun.clicked.connect(self.runMode3)

        self.mode3labelState = QLabel("")

        self.mode3Layout.addWidget(self.mode3buttonFile1, 0, 0)
        self.mode3Layout.addWidget(self.mode3labelFile1, 0, 1)
        self.mode3Layout.addWidget(self.mode3buttonFile2, 1, 0)
        self.mode3Layout.addWidget(self.mode3labelFile2, 1, 1)
        self.mode3Layout.addWidget(self.mode3buttonDir3, 2, 0)
        self.mode3Layout.addWidget(self.mode3labelDir3, 2, 1)
        self.mode3Layout.addWidget(self.mode3categoriesList, 3, 0)
        self.mode3Layout.addWidget(self.mode3columnsList, 3, 1)
        self.mode3Layout.addWidget(self.mode3buttonRun, 4, 0)
        self.mode3Layout.addWidget(self.mode3labelState, 5, 1)

        self.mode3Widget.setLayout(self.mode3Layout)

    def SelectedItems(self, item):
        if item == "columns":
            selectedItems = self.mode3columnsList.selectedItems()
        if item == "category_mode3":
            selectedItems = self.mode3categoriesList.selectedItems()
        if item == "category_mode4":
            selectedItems = self.mode4categoriesList.selectedItems()
        selectedItemsTextList = list()
        for selectedItem in selectedItems:
            selectedItemsTextList.append(selectedItem.text())
        return selectedItemsTextList

    def runMode3(self):
        self.mode3labelState.setText("running")
        self.mode3labelState.repaint()
        file1 = self.mode3labelFile1.text()
        file2 = self.mode3labelFile2.text()
        dir3 = self.mode3labelDir3.text()
        categoriesList = self.SelectedItems("category_mode3")
        columnsList = self.SelectedItems("columns")
        print_samples(file1, file2, dir3, categoriesList, columnsList,
                      self.dbPassw.text())
        self.mode3labelState.setText("finished")

    def setMode4(self):
        if not self.mode4set:
            self.generateMode4Widget()
            self.modeWidget.addWidget(self.mode4Widget)
            self.mode4set = True
        self.modeWidget.setCurrentWidget(self.mode4Widget)
        self.setDefaultModeButtonText()
        self.buttonMode4.setText('<DELETE_SAMPLES>')

    def generateMode4Widget(self):
        self.mode4Widget = QWidget()
        self.mode4Layout = QGridLayout()

        self.mode4buttonFile1 = QPushButton("sample_list")
        self.mode4labelFile1 = QLabel(
            "C:/NGS_forensic_database/delete_samples/delete_sample.txt")
        self.mode4buttonFile1.clicked.connect(
            partial(self.getBrowseFileName, self.mode4labelFile1))

        self.mode4categoriesList = QListWidget()
        self.mode4categoriesList.addItems(["AutoSTR", "Y-STR"])
        self.mode4categoriesList.setSelectionMode(
            QAbstractItemView.MultiSelection)

        self.mode4buttonRun = QPushButton("run")
        self.mode4buttonRun.clicked.connect(self.runMode4)

        self.mode4labelState = QLabel("")

        self.mode4Layout.addWidget(self.mode4buttonFile1, 0, 0)
        self.mode4Layout.addWidget(self.mode4labelFile1, 0, 1)
        self.mode4Layout.addWidget(self.mode4categoriesList, 1, 0)
        self.mode4Layout.addWidget(self.mode4buttonRun, 2, 0)
        self.mode4Layout.addWidget(self.mode4labelState, 1, 1)

        self.mode4Widget.setLayout(self.mode4Layout)

    def runMode4(self):
        self.mode4labelState.setText("running")
        self.mode4labelState.repaint()
        file1 = self.mode4labelFile1.text()
        categoriesList = self.SelectedItems("category_mode4")
        delete_samples(file1, categoriesList, self.dbPassw.text())
        self.mode4labelState.setText("finished")
Example #39
0
class FileGui(QWidget):

    logginn = pyqtSignal(str, str, int)

    def __init__(self):
        super(FileGui, self).__init__()
        self.cl = QVBoxLayout()
        self.loggin = Logger('FileGui', self.logginn)

        tt = QHBoxLayout()
        self.local = QLabel('Local: ', self)
        self.pathbar = QLineEdit(self)
        folder = qta.icon('fa5s.folder-open',
                          color='orange',
                          color_active='red')
        self.pathbtn = QPushButton(folder, "", self)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbar)
        tt.addWidget(self.pathbtn)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.other = QLabel('Otro: ', self)
        self.pathbar2 = QLineEdit(self)
        folder = qta.icon('fa5s.folder-open',
                          color='orange',
                          color_active='red')
        self.pathbtn2 = QPushButton(folder, "", self)
        tt.addWidget(self.other)
        tt.addWidget(self.pathbar2)
        tt.addWidget(self.pathbtn2)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.local = QLabel('Folders: ')
        self.pathbarftp = QLineEdit(self)
        self.pathbarftp.setReadOnly(True)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbarftp)
        self.cl.addLayout(tt)

        self.li = QListWidget(self)
        self.cl.addWidget(self.li)
        self.li.itemDoubleClicked.connect(self.ftp_move_to)

        tt = QHBoxLayout()
        find = qta.icon('fa5s.search', color='orange', color_active='red')
        self.proc = QPushButton(find, "", self)
        tt.addWidget(self.proc)
        tt.addStretch()
        self.move = QButtonGroup()
        tt1 = QRadioButton("Todos")
        tt2 = QRadioButton("Último")
        tt2.setChecked(True)
        self.move.addButton(tt1, 2)
        self.move.addButton(tt2, 1)
        self.move.setExclusive(True)
        tt.addWidget(tt1)
        tt.addWidget(tt2)
        self.cl.addLayout(tt)

        tt = QVBoxLayout()
        tt3 = QHBoxLayout()
        self.namelabel = QLabel(self)
        tt3.addWidget(self.namelabel)
        tt2 = QHBoxLayout()
        self.progresslabel = QLabel(self)
        self.speedlabel = QLabel(self)
        tt2.addWidget(self.progresslabel)
        tt2.addWidget(self.speedlabel)
        self.progress = QProgressBar(self)
        self.progress.setMinimum(0)
        self.progress.setMaximum(100)
        tt.addLayout(tt3)
        tt.addLayout(tt2)
        tt.addWidget(self.progress)
        self.cl.addLayout(tt)

        self.setLayout(self.cl)
        self.pathbtn.clicked.connect(self.set_path)
        self.proc.clicked.connect(self.procces)
        self.pathbtn2.clicked.connect(self.set_path2)
        self.ftpm = None
        self.in_progress = False

    @pyqtSlot()
    def set_path2(self):
        dirr = self.get_path()
        if dirr is None or dirr == '':
            return
        self.pathbar2.setText(dirr)
        if self.ftpm:
            self.ftpm.close()
            reconnect(self.ftpm.copier.worker.names)
            reconnect(self.ftpm.copier.worker.progress)
            reconnect(self.ftpm.copier.worker.finish)
            reconnect(self.ftpm.copier.finish)
        try:
            self.ftpm = FileManager(dirr, self.loggin)
            reconnect(self.ftpm.copier.worker.names, self.change_names)
            reconnect(self.ftpm.copier.worker.progress, self.update)
            reconnect(self.ftpm.copier.worker.finish, self.copy_finish2)
            reconnect(self.ftpm.copier.finish, self.copy_finish)
            self.pathbarftp.setText('/')
        except Exception as e:
            self.loggin.emit(str(e), ERROR)
            return
        self.li.clear()
        for i in self.ftpm.list_dir('/'):
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), i, self.li)
            self.li.addItem(item)

    @pyqtSlot()
    def ftp_move_to(self, item):
        txt = item.text()
        txt2 = normpath(join(self.pathbarftp.text(), txt))
        self.li.clear()
        if txt2 != '/':
            normpath(join(txt2, '..'))
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), '..', self.li)
            self.li.addItem(item)
        for i in self.ftpm.list_dir(txt2):
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), i, self.li)
            self.li.addItem(item)
        self.pathbarftp.setText(txt2)

    def get_path(self):
        txt = self.pathbar.text()
        if txt is None or txt == "":
            txt = ""
        dirr = QFileDialog.getExistingDirectory(
            self, "Selecionar Directorio", txt, QFileDialog.ShowDirsOnly
            | QFileDialog.DontResolveSymlinks)
        # print(dirr)
        return dirr

    @pyqtSlot()
    def set_path(self):
        dirr = self.get_path()
        if dirr is None or dirr == '':
            return
        self.pathbar.setText(dirr)

    def download(self):
        base = self.pathbar.text()
        if base == '':
            self.in_progress = False
            return
        if not self.ftpm:
            self.in_progress = False
            return
        if self.move.checkedId() == 1:
            self.ftpm.last(base)
        else:
            self.ftpm.last2(base)
        self.loggin.emit('Buscando capítulos', INFORMATION)
        if self.move.checkedId() == 1:
            self.ftpm.find_nexts(self.pathbarftp.text())
        else:
            self.ftpm.find_nexts2(self.pathbarftp.text())
        r = self.ftpm.results
        for i in r:
            # ftpp = join(i[2],i[1])
            self.ftpm.download(i[2], i[1], base, i[3])

    @pyqtSlot(str, str)
    def change_names(self, src, dst):
        self.namelabel.setText(src + '    ' + dst)
        self.loggin.emit('Descargando ' + src + '  para  ' + dst, INFORMATION)

    @pyqtSlot(int, int, float)
    def update(self, total, count, speed):
        val = int(count / max(total, 1e-12) * 100)
        self.progress.setValue(val)
        self.speedlabel.setText(str(speed / (1024)) + ' Kb/s')

    @pyqtSlot()
    def copy_finish2(self):
        self.progress.setValue(100)
        self.loggin.emit('Descarga de archivo finalizada', INFORMATION)

    @pyqtSlot()
    def copy_finish(self):
        self.progress.setValue(0)
        self.speedlabel.clear()
        self.namelabel.clear()
        self.loggin.emit('Descarga finalizada', INFORMATION)
        self.in_progress = False

    @pyqtSlot()
    def procces(self):
        if self.in_progress:
            self.loggin.emit('Hay un proceso en este momento, espere.',
                             WARNING)
            return
        self.download()
Example #40
0
File: gui.py Project: LucMiaz/nupdf
 def __init__(self, parent=None):
     super(Form, self).__init__(parent)
     window = QWidget()
     main = QVBoxLayout()
     main.addWidget(QLabel('PDF manip'))
     layout = QVBoxLayout()
     """self.filetypes=QCheckBox('Get other file types?')
     self.filetypes.setChecked(False)
     main.addWidget(self.filetypes)"""
     self.selectFiles = QPushButton("Insert files")
     self.selectFiles.clicked.connect(self.getfiles)
     self.selectFiles.setFont(normalfont)
     main.addWidget(self.selectFiles)
     self.selectFolder = QPushButton("Insert folder")
     self.selectFolder.clicked.connect(self.getfolder)
     self.selectFolder.setFont(normalfont)
     main.addWidget(self.selectFolder)
     self.boxmerge = QCheckBox('Merge multiple files?')
     self.boxmerge.setChecked(True)
     self.boxmerge.setFont(normalfont)
     main.addWidget(self.boxmerge)
     self.bookmark = QCheckBox('Add bookmarks using file title?')
     self.bookmark.setChecked(True)
     self.bookmark.setFont(normalfont)
     main.addWidget(self.bookmark)
     self.recto_verso = QCheckBox('Recto verso ?')
     self.recto_verso.setChecked(False)
     self.recto_verso.setFont(normalfont)
     main.addWidget(self.recto_verso)
     self.same_file = QCheckBox(
         'If recto verso, are they in two separate files?')
     self.same_file.setChecked(False)
     self.same_file.setFont(normalfont)
     main.addWidget(self.same_file)
     main.addWidget(QLabel('Rotation angle (clockwise)'))
     self.angle = QLineEdit('0')
     self.angle.setValidator(QIntValidator())
     self.angle.setAlignment(Qt.AlignRight)
     self.angle.setFont(normalfont)
     main.addWidget(self.angle)
     main.addWidget(
         QLabel(
             'Pages to rotate (use - for range and ; for single pages, e.g. 1-2;5)'
         ))
     self.pages = QLineEdit('')
     self.pages.setAlignment(Qt.AlignRight)
     self.pages.setFont(normalfont)
     main.addWidget(self.pages)
     self.setLayout(main)
     self.setWindowTitle('nuPDF')
     self.filenames = []
     self.listWidget = QListWidget()
     self.listWidget.setAcceptDrops(True)
     #Resize width and height
     self.listWidget.resize(300, 120)
     self.listWidget.setWindowTitle('Files paths')
     self.listWidget.show()
     self.upBtn = QPushButton('Up', self)
     self.downBtn = QPushButton('Down', self)
     self.buttonLayout = QHBoxLayout()
     self.buttonLayout.addWidget(self.upBtn)
     self.buttonLayout.addWidget(self.downBtn)
     main.addLayout(self.buttonLayout)
     main.addWidget(self.listWidget)
     self.runbutton = QPushButton('Start')
     self.runbutton.setFont(normalfont)
     self.runbutton.clicked.connect(self.run)
     self.savingpath = QLineEdit()
     self.savingpath.setFont(normalfont)
     self.setsavingpath = QPushButton("Select saving path")
     self.setsavingpath.setFont(normalfont)
     self.setsavingpath.clicked.connect(self.savefile)
     self.empty = QPushButton('empty files list')
     self.empty.setFont(normalfont)
     self.empty.clicked.connect(self.empty_file_list)
     main.addWidget(self.empty)
     main.addWidget(self.setsavingpath)
     main.addWidget(self.savingpath)
     main.addWidget(self.runbutton)
     self.status = QLabel(
         "Please select the files to work on and where to save the output")
     self.status.setFont(normalfont)
     self.upBtn.clicked.connect(self.upButton)
     self.downBtn.clicked.connect(self.downButton)
     main.addWidget(self.status)
Example #41
0
File: gui.py Project: LucMiaz/nupdf
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        window = QWidget()
        main = QVBoxLayout()
        main.addWidget(QLabel('PDF manip'))
        layout = QVBoxLayout()
        """self.filetypes=QCheckBox('Get other file types?')
        self.filetypes.setChecked(False)
        main.addWidget(self.filetypes)"""
        self.selectFiles = QPushButton("Insert files")
        self.selectFiles.clicked.connect(self.getfiles)
        self.selectFiles.setFont(normalfont)
        main.addWidget(self.selectFiles)
        self.selectFolder = QPushButton("Insert folder")
        self.selectFolder.clicked.connect(self.getfolder)
        self.selectFolder.setFont(normalfont)
        main.addWidget(self.selectFolder)
        self.boxmerge = QCheckBox('Merge multiple files?')
        self.boxmerge.setChecked(True)
        self.boxmerge.setFont(normalfont)
        main.addWidget(self.boxmerge)
        self.bookmark = QCheckBox('Add bookmarks using file title?')
        self.bookmark.setChecked(True)
        self.bookmark.setFont(normalfont)
        main.addWidget(self.bookmark)
        self.recto_verso = QCheckBox('Recto verso ?')
        self.recto_verso.setChecked(False)
        self.recto_verso.setFont(normalfont)
        main.addWidget(self.recto_verso)
        self.same_file = QCheckBox(
            'If recto verso, are they in two separate files?')
        self.same_file.setChecked(False)
        self.same_file.setFont(normalfont)
        main.addWidget(self.same_file)
        main.addWidget(QLabel('Rotation angle (clockwise)'))
        self.angle = QLineEdit('0')
        self.angle.setValidator(QIntValidator())
        self.angle.setAlignment(Qt.AlignRight)
        self.angle.setFont(normalfont)
        main.addWidget(self.angle)
        main.addWidget(
            QLabel(
                'Pages to rotate (use - for range and ; for single pages, e.g. 1-2;5)'
            ))
        self.pages = QLineEdit('')
        self.pages.setAlignment(Qt.AlignRight)
        self.pages.setFont(normalfont)
        main.addWidget(self.pages)
        self.setLayout(main)
        self.setWindowTitle('nuPDF')
        self.filenames = []
        self.listWidget = QListWidget()
        self.listWidget.setAcceptDrops(True)
        #Resize width and height
        self.listWidget.resize(300, 120)
        self.listWidget.setWindowTitle('Files paths')
        self.listWidget.show()
        self.upBtn = QPushButton('Up', self)
        self.downBtn = QPushButton('Down', self)
        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addWidget(self.upBtn)
        self.buttonLayout.addWidget(self.downBtn)
        main.addLayout(self.buttonLayout)
        main.addWidget(self.listWidget)
        self.runbutton = QPushButton('Start')
        self.runbutton.setFont(normalfont)
        self.runbutton.clicked.connect(self.run)
        self.savingpath = QLineEdit()
        self.savingpath.setFont(normalfont)
        self.setsavingpath = QPushButton("Select saving path")
        self.setsavingpath.setFont(normalfont)
        self.setsavingpath.clicked.connect(self.savefile)
        self.empty = QPushButton('empty files list')
        self.empty.setFont(normalfont)
        self.empty.clicked.connect(self.empty_file_list)
        main.addWidget(self.empty)
        main.addWidget(self.setsavingpath)
        main.addWidget(self.savingpath)
        main.addWidget(self.runbutton)
        self.status = QLabel(
            "Please select the files to work on and where to save the output")
        self.status.setFont(normalfont)
        self.upBtn.clicked.connect(self.upButton)
        self.downBtn.clicked.connect(self.downButton)
        main.addWidget(self.status)

    def upButton(self):
        currentRow = self.listWidget.currentRow()
        currentItem = self.listWidget.takeItem(currentRow)
        self.listWidget.insertItem(currentRow - 1, currentItem)

    def downButton(self):
        currentRow = self.listWidget.currentRow()
        currentItem = self.listWidget.takeItem(currentRow)
        self.listWidget.insertItem(currentRow + 1, currentItem)

    def empty_file_list(self):
        self.listWidget.clear()
        self.filenames = []

    def update_qlist(self):
        self.listWidget.clear()
        self.listWidget.addItems(self.filenames)

    def update_status(self):
        if len(self.filenames) > 0 and self.savingpath != '':
            self.status.setText('Ready')
        elif len(self.filenames) > 0 and self.savingpath == '':
            self.status.setText('Please insert a saving path')
        elif len(self.filenames) == 0 and self.savingpath != '':
            self.status.setText('Please enter at least one file to work on')
        else:
            self.status.setText('Unknown error')

    def getfilesinfolder(self, folderpath):
        return [
            path.join(root, name) for root, dirs, files in walk(folderpath)
            for name in files
            if name.endswith((".pdf", ".PDF", ".jpg", ".jpeg", ".gif", ".GIF",
                              ".JPG", ".JPEG", ".raw", ".RAW", ".PNG", ".png"))
        ]

    def savefile(self):
        self.setsavingpath.setText("Select saving path")
        self.setsavingpath.setFont(normalfont)
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        if dlg.exec_():
            path = dlg.selectedFiles()[0]
            self.savingpath.setText(path)
            if self.savingpath.text()[-4:] != '.pdf':
                path = self.savingpath.text() + ".pdf"
                self.savingpath.setText(path)
        self.update_status()

    def getfiles(self):
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.ExistingFiles)
        if dlg.exec_():
            self.filenames += dlg.selectedFiles()
        self.update_qlist()

    def getfolder(self):
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.Directory)
        if dlg.exec_():
            filesInFolder = self.getfilesinfolder(dlg.selectedFiles()[0])
            self.filenames += filesInFolder
        self.update_qlist()

    def run(self):
        self.status.setText('Processing...')
        if self.savingpath.text() != "":
            self.runbutton.toggle()
            self.runbutton.setCheckable(False)
            if self.boxmerge.isChecked():
                merge = True
                path = self.savingpath.text()
            else:
                merge = False
                path = self.filenames[0]
            if self.bookmark.isChecked():
                bookmark = True
            else:
                bookmark = False
            pages_num = []
            if self.angle.text() and int(self.angle.text()) != 0:
                angle = int(self.angle.text())
            else:
                angle = 0
            pages = self.pages.text()
            same_file = None
            if self.recto_verso.isChecked():
                recto_verso = True
                if self.same_file.isChecked():
                    same_file = True
            else:
                recto_verso = False
            if pages != "":
                from re import findall
                string = r'(([0-9]*)-([0-9]*))|([0-9]*(?![-]))'
                matches = findall(string, pages)
                for m in matches:
                    print(m)
                    if (m[1] != '' and m[2] != ''):
                        try:
                            pages_num += range(int(m[1]) - 1, int([m[2]]))
                        except:
                            pass
                    elif m[3] != '':
                        try:
                            pages_num.append(int(m[3]) - 1)
                        except:
                            pass
            if merge:
                self.status.setText('Merging files...')
                merge_pdfs(self.filenames,
                           self.savingpath.text(),
                           recto_verso=recto_verso,
                           same_file=same_file,
                           bookmark=bookmark)
            if angle != 0:
                print(pages)
                print(pages_num)
                if len(pages_num) > 0:
                    self.status.setText('Rotating pages %s ...' %
                                        ";".join([str(i) for i in pages_num]))
                    rotate_pages(path,
                                 self.savingpath.text(),
                                 pages=pages_num,
                                 angle=angle)
                else:
                    self.status.setText('Rotating all pages ...')
                    rotate_pages(path, self.savingpath.text(), angle=angle)
            self.status.setText('Done. File saved at %s' %
                                self.savingpath.text())
            self.runbutton.toggle()
            self.runbutton.setCheckable(True)
            return self.runbutton
        else:
            self.setsavingpath.setText("**Select saving path**")
            self.setsavingpath.setFont(boldfont)
            self.update_status()
Example #42
0
    def __init__(self):
        self.genes_dict = {}
        self.stop_condition = ()

        self.app = QApplication([])
        self.window = QWidget()
        self.window.resize(100, 800)  #initial window size
        grid = QGridLayout()
        self.window.setLayout(grid)

        self.window.setWindowTitle("Simulation Builder")

        grid.addWidget(QLabel("concentration file: "), 0, 0)
        selected_concentration_label = QLabel("      ")
        selected_concentration_label.setObjectName(
            "selected_concentration_label")
        grid.addWidget(selected_concentration_label, 0, 1)

        concentration_file_open_button = QPushButton('Open file')
        concentration_file_open_button.setToolTip('Open concentration file')
        concentration_file_open_button.clicked.connect(
            self.open_concentrations_file)
        grid.addWidget(concentration_file_open_button, 0, 2)

        grid.addWidget(QLabel("Pre-populate: "), 1, 0)
        pre_populate_check_box = QCheckBox()
        pre_populate_check_box.setObjectName("pre_populate_check_box")
        grid.addWidget(pre_populate_check_box, 1, 1)

        grid.addWidget(QLabel("Add FASTA file :"), 2, 0)
        add_fasta_file_button = QPushButton("Add FASTA file")
        add_fasta_file_button.setToolTip(\
            "Reads FASTA file and make its genes available for simulation")
        add_fasta_file_button.clicked.connect(self.open_fasta_file)
        grid.addWidget(add_fasta_file_button, 2, 1)

        load_batch_file_button = QPushButton("Load batch CSV file")
        load_batch_file_button.setToolTip(
            "load a CSV file with a list of Genes, copy number, initiation and termination rates."
        )
        load_batch_file_button.clicked.connect(self.load_batch_file)
        grid.addWidget(load_batch_file_button, 2, 3)

        grid.addWidget(QLabel("Loaded FASTA files:"), 3, 0)
        fasta_files_listbox = QListWidget()
        fasta_files_listbox.setObjectName("fasta_files_listbox")
        fasta_files_listbox.clicked.connect(self.onselect_fasta_file)
        grid.addWidget(fasta_files_listbox, 3, 1)

        grid.addWidget(QLabel("Genes:"), 3, 2)
        genes_listbox = QListWidget()
        genes_listbox.setObjectName("genes_listbox")
        grid.addWidget(genes_listbox, 3, 3)

        rates_groupbox = QGroupBox()
        rates_groupbox_grid = QGridLayout()
        rates_groupbox.setLayout(rates_groupbox_grid)
        grid.addWidget(rates_groupbox, 3, 4)
        rates_groupbox_grid.addWidget(QLabel("Initiation rate: "), 0, 0)
        init_rate_spinbox = QDoubleSpinBox()
        init_rate_spinbox.setObjectName("init_rate_spinbox")
        init_rate_spinbox.setRange(0.01, 100.00)
        init_rate_spinbox.setSingleStep(0.01)
        rates_groupbox_grid.addWidget(init_rate_spinbox, 0, 1)

        rates_groupbox_grid.addWidget(QLabel("Termination rate: "), 1, 0)
        term_rate_spinbox = QDoubleSpinBox()
        term_rate_spinbox.setObjectName("term_rate_spinbox")
        term_rate_spinbox.setRange(0.01, 100.00)
        term_rate_spinbox.setSingleStep(0.01)
        rates_groupbox_grid.addWidget(term_rate_spinbox, 1, 1)

        rates_groupbox_grid.addWidget(QLabel("Transcript copy number: "), 2, 0)
        gene_copy_number_spinbox = QDoubleSpinBox()
        genes_listbox.setSelectionMode(2)
        gene_copy_number_spinbox.setObjectName("gene_copy_number_spinbox")
        gene_copy_number_spinbox.setRange(1, 1000)
        gene_copy_number_spinbox.setSingleStep(1)
        rates_groupbox_grid.addWidget(gene_copy_number_spinbox, 2, 1)

        add_gene_button = QPushButton("Add gene")
        add_gene_button.clicked.connect(self.add_simulation_entry)
        grid.addWidget(add_gene_button, 4, 1, 1, 4)

        grid.addWidget(QLabel("Added simulations: "), 5, 0)
        added_simulations_listbox = QTableWidget()
        added_simulations_listbox.setObjectName("added_simulations_listbox")
        added_simulations_listbox.setColumnCount(5)
        added_simulations_listbox.setShowGrid(False)
        added_simulations_listbox.setHorizontalHeaderLabels([
            'Fasta file', 'Gene', 'Initiation\nRate', 'Termination\nRate',
            'Transcript\nCopy Number'
        ])
        added_simulations_listbox.resizeColumnsToContents()
        added_simulations_listbox.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.Stretch)
        added_simulations_listbox.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)
        grid.addWidget(added_simulations_listbox, 6, 0, 6, 6)

        remove_entry_button = QPushButton("Remove entry")
        remove_entry_button.clicked.connect(self.remove_simulation_entry)
        grid.addWidget(remove_entry_button, 14, 5)

        termination_condition_groupbox = QGroupBox()
        termination_condition_groupbox.setTitle("Stop condition")
        termination_condition_groupbox_grid = QGridLayout()
        termination_condition_groupbox.setLayout(
            termination_condition_groupbox_grid)
        grid.addWidget(termination_condition_groupbox, 15, 0, 2, 2)

        iteration_limit_radiobutton = QRadioButton("Iteration limit:")

        steady_state_checkbox = QCheckBox("After steady state: ")
        steady_state_checkbox.setObjectName("steady_state_checkbox")
        termination_condition_groupbox_grid.addWidget(steady_state_checkbox, 0,
                                                      0)
        steady_state_checkbox.clicked.connect(
            self.changed_steady_state_checkbox)
        # termination_condition_groupbox_grid.addWidget(steady_state_checkbox, 0, 1)

        iteration_limit_radiobutton.setObjectName(
            "iteration_limit_radiobutton")
        termination_condition_groupbox_grid.addWidget(
            iteration_limit_radiobutton, 1, 0)
        iteration_limit_spinbox = QSpinBox()
        iteration_limit_spinbox.setObjectName("iteration_limit_spinbox")
        iteration_limit_spinbox.setRange(0, int(10e10))
        iteration_limit_spinbox.valueChanged.connect(
            self.changed_iteration_limit)
        termination_condition_groupbox_grid.addWidget(iteration_limit_spinbox,
                                                      1, 1)

        time_limit_radiobutton = QRadioButton("Time limit:")
        time_limit_radiobutton.setObjectName("time_limit_radiobutton")
        time_limit_radiobutton.setChecked(
            True)  # have a checked option for starters.
        termination_condition_groupbox_grid.addWidget(time_limit_radiobutton,
                                                      2, 0)
        time_limit_spinbox = QDoubleSpinBox()
        time_limit_spinbox.setObjectName("time_limit_spinbox")
        time_limit_spinbox.setRange(0, 10e10)
        time_limit_spinbox.setValue(60)  # set a default value
        self.stop_condition = ("time", float(time_limit_spinbox.value()))
        time_limit_spinbox.valueChanged.connect(self.changed_time_limit_entry)
        termination_condition_groupbox_grid.addWidget(time_limit_spinbox, 2, 1)

        finished_ribosomes_limit_radiobutton = QRadioButton(
            "Terminated Ribosomes:")
        finished_ribosomes_limit_radiobutton.setObjectName(
            "finished_ribosomes_limit_radiobutton")
        termination_condition_groupbox_grid.addWidget(
            finished_ribosomes_limit_radiobutton, 3, 0)
        finished_ribosomes_spinbox = QSpinBox()
        finished_ribosomes_spinbox.setObjectName("finished_ribosomes_spinbox")
        finished_ribosomes_spinbox.setRange(0, int(10e10))
        finished_ribosomes_spinbox.valueChanged.connect(
            self.changed_finished_ribosomes)
        termination_condition_groupbox_grid.addWidget(
            finished_ribosomes_spinbox, 3, 1)

        history_groupbox = QGroupBox()
        history_groupbox.setFlat(True)
        history_groupbox_grid = QGridLayout()
        history_groupbox.setLayout(history_groupbox_grid)
        grid.addWidget(history_groupbox, 15, 3, 2, 1)

        history_groupbox_grid.addWidget(QLabel("Number of history entries: "),
                                        0, 0)
        history_size_spinbox = QSpinBox()
        history_size_spinbox.setObjectName("history_size_spinbox")
        history_size_spinbox.setRange(1, int(10e15))
        history_size_spinbox.setValue(100000)
        history_groupbox_grid.addWidget(history_size_spinbox, 0, 1)

        generate_simulation_button = QPushButton("Generate Simulation file")
        generate_simulation_button.clicked.connect(
            self.generate_simulation_file)
        grid.addWidget(generate_simulation_button, 17, 1, 3, 4)
        self.show()
Example #43
0
    def __init__(self):
        super(FileGui, self).__init__()
        self.cl = QVBoxLayout()
        self.loggin = Logger('FileGui', self.logginn)

        tt = QHBoxLayout()
        self.local = QLabel('Local: ', self)
        self.pathbar = QLineEdit(self)
        folder = qta.icon('fa5s.folder-open',
                          color='orange',
                          color_active='red')
        self.pathbtn = QPushButton(folder, "", self)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbar)
        tt.addWidget(self.pathbtn)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.other = QLabel('Otro: ', self)
        self.pathbar2 = QLineEdit(self)
        folder = qta.icon('fa5s.folder-open',
                          color='orange',
                          color_active='red')
        self.pathbtn2 = QPushButton(folder, "", self)
        tt.addWidget(self.other)
        tt.addWidget(self.pathbar2)
        tt.addWidget(self.pathbtn2)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.local = QLabel('Folders: ')
        self.pathbarftp = QLineEdit(self)
        self.pathbarftp.setReadOnly(True)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbarftp)
        self.cl.addLayout(tt)

        self.li = QListWidget(self)
        self.cl.addWidget(self.li)
        self.li.itemDoubleClicked.connect(self.ftp_move_to)

        tt = QHBoxLayout()
        find = qta.icon('fa5s.search', color='orange', color_active='red')
        self.proc = QPushButton(find, "", self)
        tt.addWidget(self.proc)
        tt.addStretch()
        self.move = QButtonGroup()
        tt1 = QRadioButton("Todos")
        tt2 = QRadioButton("Último")
        tt2.setChecked(True)
        self.move.addButton(tt1, 2)
        self.move.addButton(tt2, 1)
        self.move.setExclusive(True)
        tt.addWidget(tt1)
        tt.addWidget(tt2)
        self.cl.addLayout(tt)

        tt = QVBoxLayout()
        tt3 = QHBoxLayout()
        self.namelabel = QLabel(self)
        tt3.addWidget(self.namelabel)
        tt2 = QHBoxLayout()
        self.progresslabel = QLabel(self)
        self.speedlabel = QLabel(self)
        tt2.addWidget(self.progresslabel)
        tt2.addWidget(self.speedlabel)
        self.progress = QProgressBar(self)
        self.progress.setMinimum(0)
        self.progress.setMaximum(100)
        tt.addLayout(tt3)
        tt.addLayout(tt2)
        tt.addWidget(self.progress)
        self.cl.addLayout(tt)

        self.setLayout(self.cl)
        self.pathbtn.clicked.connect(self.set_path)
        self.proc.clicked.connect(self.procces)
        self.pathbtn2.clicked.connect(self.set_path2)
        self.ftpm = None
        self.in_progress = False
Example #44
0
class MyUIExportLayers(object):
    def __init__(self):
        self.mainDialog = myexportlayersdialog.MyExportLayersDialog()
        self.mainLayout = QVBoxLayout(self.mainDialog)
        self.formLayout = QFormLayout()
        self.documentLayout = QVBoxLayout()
        self.directorySelectorLayout = QHBoxLayout()
        self.optionsLayout = QVBoxLayout()
        self.resolutionLayout = QHBoxLayout()

        self.refreshButton = QPushButton(i18n("Refresh"))
        self.widgetDocuments = QListWidget()
        self.directoryTextField = QLineEdit()
        self.directoryDialogButton = QPushButton(i18n("..."))
        self.exportFilterLayersCheckBox = QCheckBox(
            i18n("Export filter layers"))
        self.batchmodeCheckBox = QCheckBox(i18n("Export in batchmode"))
        self.ignoreInvisibleLayersCheckBox = QCheckBox(
            i18n("Ignore invisible layers"))
        self.xResSpinBox = QSpinBox()
        self.yResSpinBox = QSpinBox()
        self.formatsComboBox = QComboBox()

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        self.kritaInstance = krita.Krita.instance()
        self.documentsList = []

        self.directoryTextField.setReadOnly(True)
        self.batchmodeCheckBox.setChecked(True)
        self.directoryDialogButton.clicked.connect(self._selectDir)
        self.widgetDocuments.currentRowChanged.connect(self._setResolution)
        self.refreshButton.clicked.connect(self.refreshButtonClicked)
        self.buttonBox.accepted.connect(self.confirmButton)
        self.buttonBox.rejected.connect(self.mainDialog.close)

        self.mainDialog.setWindowModality(Qt.NonModal)
        self.widgetDocuments.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)

    def initialize(self):
        self.loadDocuments()

        self.xResSpinBox.setRange(1, 10000)
        self.yResSpinBox.setRange(1, 10000)

        self.formatsComboBox.addItem(i18n("JPEG"))
        self.formatsComboBox.addItem(i18n("PNG"))

        self.documentLayout.addWidget(self.widgetDocuments)
        self.documentLayout.addWidget(self.refreshButton)

        self.directorySelectorLayout.addWidget(self.directoryTextField)
        self.directorySelectorLayout.addWidget(self.directoryDialogButton)

        self.optionsLayout.addWidget(self.exportFilterLayersCheckBox)
        self.optionsLayout.addWidget(self.batchmodeCheckBox)
        #self.optionsLayout.addWidget(self.ignoreInvisibleLayersCheckBox)

        self.resolutionLayout.addWidget(self.xResSpinBox)
        self.resolutionLayout.addWidget(self.yResSpinBox)

        self.formLayout.addRow(i18n("Documents:"), self.documentLayout)
        self.formLayout.addRow(i18n("Initial directory:"),
                               self.directorySelectorLayout)
        self.formLayout.addRow(i18n("Export options:"), self.optionsLayout)
        self.formLayout.addRow(i18n("Resolution:"), self.resolutionLayout)
        self.formLayout.addRow(i18n("Images extensions:"),
                               self.formatsComboBox)

        self.line = QFrame()
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)

        self.mainLayout.addLayout(self.formLayout)
        self.mainLayout.addWidget(self.line)
        self.mainLayout.addWidget(self.buttonBox)

        self.mainDialog.resize(500, 300)
        self.mainDialog.setWindowTitle(i18n("Export Layers"))
        self.mainDialog.setSizeGripEnabled(True)
        self.mainDialog.show()
        self.mainDialog.activateWindow()

    def loadDocuments(self):
        self.widgetDocuments.clear()

        self.documentsList = [
            document for document in self.kritaInstance.documents()
            if document.fileName()
        ]

        for document in self.documentsList:
            self.widgetDocuments.addItem(document.fileName())

    def refreshButtonClicked(self):
        self.loadDocuments()

    def confirmButton(self):
        selectedPaths = [
            item.text() for item in self.widgetDocuments.selectedItems()
        ]
        selectedDocuments = [
            document for document in self.documentsList
            for path in selectedPaths if path == document.fileName()
        ]

        self.msgBox = QMessageBox(self.mainDialog)
        if not selectedDocuments:
            self.msgBox.setText(i18n("Select one document."))
        elif not self.directoryTextField.text():
            self.msgBox.setText(i18n("Select the initial directory."))
        else:
            self.export(selectedDocuments[0])
            self.msgBox.setText(i18n("All layers has been exported."))
        self.msgBox.exec_()

    def mkdir(self, directory):
        target_directory = self.directoryTextField.text() + directory
        if os.path.exists(target_directory) and os.path.isdir(
                target_directory):
            return

        try:
            os.makedirs(target_directory)
        except OSError as e:
            raise e

    def export(self, document):
        Application.setBatchmode(self.batchmodeCheckBox.isChecked())
        document.setBatchmode(self.batchmodeCheckBox.isChecked())

        documentName = document.fileName() if document.fileName(
        ) else 'Untitled'
        fileName, extension = os.path.splitext(os.path.basename(documentName))
        self.mkdir('/' + fileName)

        self._setVisible(document.rootNode())
        self._exportLayers(document.rootNode(),
                           self.formatsComboBox.currentText(), '/' + fileName,
                           document)
        Application.setBatchmode(True)

    def _setVisible(self, parentNode):
        for node in parentNode.childNodes():
            node.setVisible(False)
            if node.childNodes():
                self._setVisible(node)

    def _exportLayers(self, parentNode, fileFormat, parentDir, document):
        """ This method get all sub-nodes from the current node and export then in
            the defined format."""

        for node in parentNode.childNodes():
            newDir = ''
            if node.type() == 'grouplayer':
                newDir = os.path.join(parentDir, node.name())
                self.mkdir(newDir)
                node.setVisible(True)
            elif not self.exportFilterLayersCheckBox.isChecked(
            ) and 'filter' in node.type():
                continue
            elif self.ignoreInvisibleLayersCheckBox.isChecked(
            ) and not node.visible():
                continue
            else:
                nodeName = node.name()
                _fileFormat = self.formatsComboBox.currentText()
                if '[jpeg]' in nodeName:
                    _fileFormat = 'jpeg'
                elif '[png]' in nodeName:
                    _fileFormat = 'png'

                layerFileName = '{0}{1}/{2}.{3}'.format(
                    self.directoryTextField.text(), parentDir, node.name(),
                    _fileFormat)
                #node.save(layerFileName, self.xResSpinBox.value(), self.yResSpinBox.value())
                node.setVisible(True)
                document.refreshProjection()
                document.exportImage(layerFileName, krita.InfoObject())
                node.setVisible(False)

            if node.childNodes():
                self._exportLayers(node, fileFormat, newDir, document)

    def _selectDir(self):
        directory = QFileDialog.getExistingDirectory(self.mainDialog,
                                                     i18n("Select a Folder"),
                                                     os.path.expanduser("~"),
                                                     QFileDialog.ShowDirsOnly)
        self.directoryTextField.setText(directory)

    def _setResolution(self, index):
        document = self.documentsList[index]
        self.xResSpinBox.setValue(document.width())
        self.yResSpinBox.setValue(document.height())
Example #45
0
class GstPipeEdit(QWidget):
    def __init__(self, pipe, app_mode=False, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QGridLayout())
        self.layout().setAlignment(Qt.AlignTop)

        self._app_mode = app_mode

        # Input selection
        self.inputBox = QComboBox(self)
        self.layout().addWidget(self.inputBox, 0, 0, 1, 3)
        self.__init_inputs()

        # Current plugins list
        self.currentList = QListWidget(self)
        self.currentList.setDragEnabled(True)
        self.currentList.setDragDropMode(QAbstractItemView.InternalMove)
        self.layout().addWidget(self.currentList, 1, 0)

        # Available plugins list
        self.availableList = QListWidget(self)
        self.layout().addWidget(self.availableList, 1, 2)

        # Output selection
        self.outputBox = QComboBox(self)
        self.layout().addWidget(self.outputBox, 4, 0, 1, 3)
        self.__init_outputs()

        # Add/Remove plugins buttons
        self.buttonsLayout = QVBoxLayout()
        self.layout().addLayout(self.buttonsLayout, 1, 1)
        self.layout().setAlignment(self.buttonsLayout, Qt.AlignHCenter)

        self.addButton = QPushButton(self)
        self.addButton.setIcon(QIcon.fromTheme('go-previous'))
        self.addButton.clicked.connect(self.__add_plugin)
        self.buttonsLayout.addWidget(self.addButton)
        self.buttonsLayout.setAlignment(self.addButton, Qt.AlignHCenter)

        self.delButton = QPushButton(self)
        self.delButton.setIcon(QIcon.fromTheme('go-next'))
        self.delButton.clicked.connect(self.__remove_plugin)
        self.buttonsLayout.addWidget(self.delButton)
        self.buttonsLayout.setAlignment(self.delButton, Qt.AlignHCenter)

        # Load the pipeline
        self.set_pipe(pipe)

    def set_pipe(self, pipe):
        if pipe:
            if not self._app_mode:
                self.inputBox.setCurrentText(
                    translate('MediaElementName', elements.input_name(pipe[0])))

            self.outputBox.setCurrentText(
                translate('MediaElementName', elements.output_name(pipe[-1])))

        self.__init_current_plugins(pipe)
        self.__init_available_plugins(pipe)

    def get_pipe(self):
        pipe = [] if self._app_mode else [self.inputBox.currentData()]
        for n in range(self.currentList.count()):
            pipe.append(self.currentList.item(n).data(Qt.UserRole))
        pipe.append(self.outputBox.currentData())

        return tuple(pipe)

    def __init_inputs(self):
        if self._app_mode:
            self.inputBox.setEnabled(False)
        else:
            inputs_by_name = {}
            for key, input in elements.inputs().items():
                inputs_by_name[translate('MediaElementName', input.Name)] = key

            for name in sorted(inputs_by_name):
                self.inputBox.addItem(name, inputs_by_name[name])

            self.inputBox.setEnabled(self.inputBox.count() > 1)

    def __init_outputs(self):
        outputs_by_name = {}
        for key, output in elements.outputs().items():
            outputs_by_name[translate('MediaElementName', output.Name)] = key

        for name in sorted(outputs_by_name):
            self.outputBox.addItem(name, outputs_by_name[name])

        self.outputBox.setEnabled(self.outputBox.count() > 1)

    def __init_current_plugins(self, pipe):
        self.currentList.clear()

        # If not in app_mode, the first pipe element is the input
        # the last the output
        start = 0 if self._app_mode else 1
        for plugin in pipe[start:-1]:
            item = QListWidgetItem(
                translate('MediaElementName', elements.plugin_name(plugin)))
            item.setData(Qt.UserRole, plugin)
            self.currentList.addItem(item)

    def __init_available_plugins(self, pipe):
        self.availableList.clear()

        for plugin in elements.plugins():
            if plugin not in pipe:
                item = QListWidgetItem(
                    translate('MediaElementName', elements.plugin_name(plugin)))
                item.setData(Qt.UserRole, plugin)
                self.availableList.addItem(item)

    def __add_plugin(self):
        item = self.availableList.takeItem(self.availableList.currentRow())
        self.currentList.addItem(item)

    def __remove_plugin(self):
        item = self.currentList.takeItem(self.currentList.currentRow())
        self.availableList.addItem(item)
class EasyQListSuite(QWidget):
    """
    Provide a window that has a QListWidget with 'Add' and 'Remove' button.
    """
    def __init__(self, *__args):
        super(EasyQListSuite, self).__init__(*__args)

        self.__item_list = []

        self.__list_main = QListWidget(self)
        self.__button_add = QPushButton('Add')
        self.__button_remove = QPushButton('Remove')

        self.__init_ui()
        self.__config_ui()

    def update_item(self, items: [(str, any)]):
        """
        Specify a (key, value) tuple list.
            Key will be displayed as list item.
            Value can be retrieved by get_select_items()
        :param items: Specify a (key, value) tuple list.
        :return: None
        """
        self.__item_list.clear()
        for item in items:
            if isinstance(item, (list, tuple)):
                if len(item) == 0:
                    continue
                elif len(item) == 1:
                    self.__item_list.append((str(item[0]), item[0]))
                else:
                    self.__item_list.append((str(item[0]), item[1]))
            else:
                self.__item_list.append((str(item), item))
        self.__update_list()

    def get_select_items(self) -> [any]:
        """
        Get the value of the items that user selected.
        :return: The value of the items that user selected.
        """
        return [
            item.data(Qt.UserRole)
            for item in self.__list_main.selectedItems()
        ]

    def set_add_handler(self, handler):
        """
        Add a handler for 'Add' button clicking
        :param handler: The handler that connects to the button clicked signal
        :return:
        """
        self.__button_add.clicked.connect(handler)

    def set_remove_handler(self, handler):
        """
        Add a handler for 'Remove' button clicking
        :param handler: The handler that connects to the button clicked signal
        :return:
        """
        self.__button_remove.clicked.connect(handler)

    # ---------------------------------------- Private ----------------------------------------

    def __init_ui(self):
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)

        line_layout = QHBoxLayout()
        line_layout.addWidget(self.__button_add)
        line_layout.addWidget(self.__button_remove)

        main_layout.addWidget(self.__list_main)
        main_layout.addLayout(line_layout)

    def __config_ui(self):
        pass

    def __update_list(self):
        self.__list_main.clear()
        for text, obj in self.__item_list:
            item = QListWidgetItem()
            item.setText(text)
            item.setData(Qt.UserRole, obj)
            self.__list_main.addItem(item)
Example #47
0
class ScriptsMenu(QWidget):
    def interface_check(function):
        def wrapper(self):
            function(self)
            try:
                self.on_block()
            except:
                return wrapper

        return wrapper

    def __init__(self):
        super().__init__()
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        row_hight = 30
        margins = self.layout.contentsMargins()
        margins.setTop(row_hight)
        margins.setRight(20)
        self.layout.setContentsMargins(margins)

        # Initializing GUI elements
        self.settings_label = QLabel('Settings')
        self.platform_var_list = QComboBox()
        self.thread_var_list = QComboBox()

        self.intel64 = QCheckBox('Intel 64')
        self.IA32 = QCheckBox('IA32')
        self.TL = QCheckBox('Threading layer')
        self.omp = QRadioButton('OpenMP')
        self.tbb = QRadioButton('TBB')

        self.lib_name = QLineEdit()
        self.functions_list = QListWidget()
        self.save_build_script = QPushButton('Save build script')
        self.functions_names = []
        self.status_receiver = None

        self.lib_name.setPlaceholderText('Library name...')

        # Preparing elements by giving initial values and etc
        self.settings_label.setAlignment(Qt.AlignBottom)
        self.save_build_script.setDisabled(True)

        self.save_build_script.clicked.connect(self.on_save_build_script)
        self.IA32.clicked.connect(self.on_block)
        self.intel64.clicked.connect(self.on_block)
        self.TL.clicked.connect(self.set_tl)
        self.lib_name.textEdited.connect(self.on_block)
        self.platform_var_list.currentIndexChanged.connect(
            self.on_target_system_selection)

        # Setting all widgets in their places
        self.layout.addWidget(self.settings_label, 0, 0)

        self.layout.addWidget(self.TL, 1, 0)
        self.layout.addWidget(self.omp, 2, 0)
        self.layout.addWidget(self.tbb, 3, 0)

        self.layout.addWidget(self.intel64, 2, 1)
        self.layout.addWidget(self.IA32, 3, 1)
        self.layout.addWidget(self.platform_var_list, 2, 2, 1, 2)
        self.layout.addWidget(self.thread_var_list, 3, 2, 1, 2)

        self.layout.addWidget(self.lib_name, 4, 0, 1, 4)
        self.layout.addWidget(self.functions_list, 5, 0, 1, 4)
        self.layout.addWidget(self.save_build_script, 6, 0, 1, 4)

        self.settings_label.setFixedHeight(row_hight)
        self.TL.setFixedHeight(row_hight)
        self.platform_var_list.setFixedHeight(row_hight)
        self.thread_var_list.setFixedHeight(row_hight)

        self.__post_check()

    def set_configs(self, package):
        self.check_configs(package)

        self.TL.setChecked(settings.CONFIGS[package]['TL'])
        self.omp.setChecked(settings.CONFIGS[package]['OpenMP'])
        self.tbb.setChecked(settings.CONFIGS[package]['TBB'])
        self.set_tl()

        self.intel64.setChecked(settings.CONFIGS[package]['intel64'])
        self.IA32.setChecked(settings.CONFIGS[package]['IA32'])

        if self.intel64.isEnabled():
            if not self.intel64.isChecked() and not self.IA32.isChecked():
                self.intel64.setChecked(True)
        elif self.IA32.isEnabled():
            self.IA32.setChecked(True)

        self.thread_var_list.setCurrentText(utils.MULTI_THREADED) if settings.CONFIGS[package]['Multi-threaded'] \
            else self.thread_var_list.setCurrentText(utils.SINGLE_THREADED)

        self.functions_names = settings.CONFIGS[package]['functions_list']

    def check_configs(self, package):
        if self.parent.source.intel64_libs_path:
            self.intel64.setEnabled(True)
        else:
            settings.CONFIGS[package]['intel64'] = False
            self.intel64.setDisabled(True)

        if self.parent.source.ia32_libs_path:
            self.IA32.setEnabled(True)
        else:
            settings.CONFIGS[package]['IA32'] = False
            self.IA32.setDisabled(True)

        if self.check_dir('tl'):
            self.TL.setEnabled(True)
        else:
            settings.CONFIGS[package]['TL'] = False
            self.TL.setDisabled(True)

        self.thread_var_list.clear()
        if self.check_dir('threaded'):
            self.thread_var_list.addItems(
                [utils.SINGLE_THREADED, utils.MULTI_THREADED])
        else:
            self.thread_var_list.addItem(utils.SINGLE_THREADED)
            settings.CONFIGS[package]['Multi-threaded'] = False

    def check_dir(self, dir):
        return os.path.exists(os.path.join(self.parent.source.intel64_libs_path, dir)) or \
                os.path.exists(os.path.join(self.parent.source.ia32_libs_path, dir))

    def get_configs(self, package):
        if self.TL.isEnabled():
            settings.CONFIGS[package]['TL'] = self.TL.isChecked()

        if settings.CONFIGS[package]['TL']:
            settings.CONFIGS[package]['OpenMP'] = self.omp.isChecked()
            settings.CONFIGS[package]['TBB'] = self.tbb.isChecked()

        settings.CONFIGS[package]['intel64'] = self.intel64.isChecked()
        settings.CONFIGS[package]['IA32'] = self.IA32.isChecked()

        settings.CONFIGS[package]['Multi-threaded'] = (
            self.thread_var_list.currentText() == utils.MULTI_THREADED)

        settings.CONFIGS[package]['functions_list'] = self.functions_names

    def set_status_output(self, status_receiver):
        self.status_receiver = status_receiver

    def __get_interface_state(self):
        return {
            settings.PACKAGE:
            self.parent.source.ipp.isEnabled()
            or self.parent.source.ippcp.isEnabled(),
            settings.PLATFORM:
            self.IA32.isChecked() or self.intel64.isChecked(),
            settings.LIB_NAME:
            bool(self.lib_name.text()),
            settings.FUNCTIONS:
            bool(self.functions_names),
            settings.ANDK:
            not ((not bool(utils.ANDROID_NDK_PATH))
                 and self.platform_var_list.currentText() == utils.ANDROID)
        }

    def on_item_selected(self, item):
        self.functions_list.setCurrentItem(item)

    def on_block(self):
        autobuild_requrements = settings.AUTOBUILD_BUTTON_RULES
        script_requrements = settings.SCRIPT_BUTTON_GENERATOR_RULES
        interface_state = self.__get_interface_state()
        if autobuild_requrements == interface_state:
            self.parent.set_auto_build_disabled(False)
            self.status_receiver.showMessage("Ready to build custom library")
        else:
            self.parent.set_auto_build_disabled(True)
            differences = dict(autobuild_requrements.items() -
                               interface_state.items())
            self.status_receiver.showMessage("Set " +
                                             sorted(differences, key=len)[0])

        if script_requrements == {
                i: interface_state.get(i)
                for i in script_requrements.keys()
        }:
            self.save_build_script.setDisabled(False)
        else:
            self.save_build_script.setDisabled(True)

    def set_tl(self):
        if self.TL.isEnabled():
            self.set_threading_layer_enabled(self.TL.isChecked())
            self.parent.source.tl_selected = self.TL.isChecked()
        else:
            self.set_threading_layer_enabled(False)
            self.parent.source.tl_selected = False

        if self.parent.source.ipp.isChecked():
            self.parent.source.show_menu(utils.IPP)

        if not self.omp.isChecked() and not self.tbb.isChecked():
            if self.omp.isEnabled():
                self.omp.setChecked(True)
            elif self.tbb.isEnabled():
                self.tbb.setChecked(True)

    def set_threading_layer_enabled(self, bool):
        self.omp.setEnabled(bool) if self.check_dir(
            os.path.join('tl', 'openmp')) else self.omp.setDisabled(True)
        self.tbb.setEnabled(bool) if self.check_dir(os.path.join(
            'tl', 'tbb')) else self.tbb.setDisabled(True)

    def on_save_build_script(self):
        library_path = QFileDialog.getExistingDirectory(
            self, 'Select a folder')
        if library_path == '':
            return
        host_system = utils.HOST_SYSTEM
        target_system = self.platform_var_list.currentText()
        functions = self.functions_names
        library_name = self.lib_name.text()
        threading = self.thread_var_list.currentText() == 'Multi-threaded'
        threading_layer_type = self.parent.get_treading_layer_type()

        package = utils.IPP if self.parent.source.ipp.isChecked(
        ) else utils.IPPCP

        os.environ[package + 'ROOT'] = settings.CONFIGS[package]['Path']

        if self.IA32.isChecked():
            generate_script(
                package,
                host_system,
                target_system,
                functions,
                library_path,
                library_name,
                utils.IA32,
                threading,
                threading_layer_type,
            )
        if self.intel64.isChecked():
            generate_script(package, host_system, target_system, functions,
                            library_path, library_name, utils.INTEL64,
                            threading, threading_layer_type)
        QMessageBox.about(self, 'Success', 'Generation completed!')

    @interface_check
    def on_target_system_selection(self):
        system = self.platform_var_list.currentText()
        if utils.ONLY_THREADABLE[system]:
            self.thread_var_list.setCurrentIndex(1)
            self.thread_var_list.setDisabled(True)
        else:
            self.thread_var_list.setDisabled(False)

        if not utils.SUPPORTED_ARCHITECTURES[system][utils.IA32]:
            self.IA32.setCheckState(Qt.Unchecked)
            self.IA32.setDisabled(True)
        else:
            self.IA32.setDisabled(False)
        if not utils.SUPPORTED_ARCHITECTURES[system][utils.INTEL64]:
            self.intel64.setCheckState(Qt.Unchecked)
            self.intel64.setDisabled(True)
        else:
            self.intel64.setDisabled(False)

    def add_items(self, items):
        """
        Sorts and adds items to list view

        :param items: list of strings
        """
        self.functions_list.clear()

        if items:
            items.sort()
            self.functions_list.addItems(items)
            self.functions_list.setCurrentItem(self.functions_list.item(0))

        self.functions_list.repaint()

    def add_item(self, function):
        """
        Adds new function to required list

        :param domain: domain of function
        :param function: name if function
        """
        self.functions_names.append(function)
        self.add_items(self.functions_names)

    def remove_item(self):
        """
        Removes function from required list
        """
        if self.functions_list.currentItem() is None:
            return None
        lib = self.functions_list.currentItem().text()
        self.functions_names.remove(lib)
        self.add_items(self.functions_names)
        return lib

    def __post_check(self):
        """
        Fills platforms combo box according to host system
        """
        if utils.HOST_SYSTEM == utils.LINUX:
            self.platform_var_list.addItem(utils.LINUX)
        elif utils.HOST_SYSTEM == utils.MACOSX:
            self.platform_var_list.addItem(utils.MACOSX)
        elif utils.HOST_SYSTEM == utils.WINDOWS:
            self.platform_var_list.addItem(utils.WINDOWS)
Example #48
0
    def __init__(self):
        super(QWidget, self).__init__()

        globalFont = QFont("Times New Roman", 11)
        globalFont.setWeight(18)
        QApplication.setFont(globalFont)

        # Creating tabs and layouts
        self.layout = QVBoxLayout(self)
        self.Hlayout = QHBoxLayout(self)
        self.HDBlayout = QVBoxLayout(self)
        self.tabs = QTabWidget()
        self.MainTab = QWidget()
        self.DBTab = QWidget()
        self.tabs.addTab(self.MainTab, "Translate")
        self.tabs.addTab(self.DBTab, "Saved Words")

        self.MainTab.layout = QVBoxLayout(self)
        self.MainTab.layout.addLayout(self.Hlayout)
        self.DBTab.layout = QGridLayout()

        # Defining QLabels
        self.insertionBox = QLineEdit()
        self.romajiBox = QLabel()
        self.romajiBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.katakanaBox = QLabel()
        self.katakanaBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.hiraganaBox = QLabel()
        self.hiraganaBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.furiganaBox = QLabel()
        self.furiganaBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBox = QLabel()
        self.entriesBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBox.setWordWrap(True)
        self.charsBox = QLabel()
        self.charsBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.charsBox.setWordWrap(True)

        recordFont = QFont("Times New Roman", 15)
        recordFont.setWeight(18)
        self.romajiLabel = QLabel("Romaji")
        self.romajiLabel.setFont(recordFont)
        self.katakanaLabel = QLabel("Katakana")
        self.katakanaLabel.setFont(recordFont)
        self.hiraganaLabel = QLabel("Hiragana")
        self.hiraganaLabel.setFont(recordFont)
        self.furiganaLabel = QLabel("Furigana")
        self.furiganaLabel.setFont(recordFont)
        self.entriesLabel = QLabel("Entries")
        self.entriesLabel.setFont(recordFont)
        self.charsLabel = QLabel("Characters")
        self.charsLabel.setFont(recordFont)
        self.romajiLabelDB = QLabel("Romaji")
        self.romajiLabelDB.setFont(recordFont)
        self.katakanaLabelDB = QLabel("Katakana")
        self.katakanaLabelDB.setFont(recordFont)
        self.hiraganaLabelDB = QLabel("Hiragana")
        self.hiraganaLabelDB.setFont(recordFont)
        self.furiganaLabelDB = QLabel("Furigana")
        self.furiganaLabelDB.setFont(recordFont)
        self.entriesLabelDB = QLabel("Entries")
        self.entriesLabelDB.setFont(recordFont)
        self.charsLabelDB = QLabel("Characters")
        self.charsLabelDB.setFont(recordFont)

        self.romajiBoxDB = QLabel()
        self.romajiBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.katakanaBoxDB = QLabel()
        self.katakanaBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.hiraganaBoxDB = QLabel()
        self.hiraganaBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.furiganaBoxDB = QLabel()
        self.furiganaBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBoxDB = QLabel()
        self.entriesBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBoxDB.setWordWrap(True)
        self.charsBoxDB = QLabel()
        self.charsBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.charsBoxDB.setWordWrap(True)

        # Globally accessible text from insertionBox in MainTab
        global text
        text = self.insertionBox.text

        # For switching tables in DBTab
        self.tableDropDown = QComboBox()
        self.tableDropDown.setDuplicatesEnabled(False)
        for item in getTables(self.con):
            self.tableDropDown.addItem(repr(item).strip("('',)"))
        self.DBTab.layout.addWidget(self.tableDropDown)

        # List of saved words in selected table in DBTab
        self.listWords = QListWidget()
        self.listWords.setFixedWidth(145)
        self.listWords.itemSelectionChanged.connect(self.selectionView)
        self.DBTab.layout.addWidget(self.listWords)
        self.listWordsAdd()
        self.tableDropDown.currentTextChanged.connect(
            lambda: self.listWordsAdd())

        # Adding widgets to tab layouts
        self.MainTab.layout.addWidget(self.insertionBox)
        self.MainTab.layout.addWidget(self.romajiLabel)
        self.MainTab.layout.addWidget(self.romajiBox)
        self.MainTab.layout.addWidget(self.katakanaLabel)
        self.MainTab.layout.addWidget(self.katakanaBox)
        self.MainTab.layout.addWidget(self.hiraganaLabel)
        self.MainTab.layout.addWidget(self.hiraganaBox)
        self.MainTab.layout.addWidget(self.furiganaLabel)
        self.MainTab.layout.addWidget(self.furiganaBox)
        self.MainTab.layout.addWidget(self.entriesLabel)
        self.MainTab.layout.addWidget(self.entriesBox)
        self.MainTab.layout.addWidget(self.charsLabel)
        self.MainTab.layout.addWidget(self.charsBox)

        self.DBTab.layout.addWidget(self.entriesLabelDB, 0, 1)
        self.DBTab.layout.addWidget(self.entriesBoxDB, 1, 1)
        self.DBTab.layout.addWidget(self.katakanaLabelDB, 2, 1)
        self.DBTab.layout.addWidget(self.katakanaBoxDB, 3, 1)
        self.DBTab.layout.addWidget(self.hiraganaLabelDB, 4, 1)
        self.DBTab.layout.addWidget(self.hiraganaBoxDB, 5, 1)
        self.DBTab.layout.addWidget(self.furiganaLabelDB, 6, 1)
        self.DBTab.layout.addWidget(self.furiganaBoxDB, 7, 1)
        self.DBTab.layout.addWidget(self.romajiLabelDB, 8, 1)
        self.DBTab.layout.addWidget(self.romajiBoxDB, 9, 1)
        self.DBTab.layout.addWidget(self.charsLabelDB, 10, 1)
        self.DBTab.layout.addWidget(self.charsBoxDB, 11, 1)

        # Creating buttons, connecting them to functions
        newTableButton = QPushButton("New List", self)
        newTableButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(newTableButton)
        newTableButton.clicked.connect(self.newTableButtonClicked)

        deleteButton = QPushButton("Delete", self)
        deleteButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(deleteButton)
        deleteButton.clicked.connect(self.deleteItemClicked)

        deleteTableButton = QPushButton("Delete List", self)
        deleteTableButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(deleteTableButton)
        deleteTableButton.clicked.connect(self.deleteTableClicked)

        exportButton = QPushButton("Export to CSV", self)
        exportButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(exportButton)
        exportButton.clicked.connect(self.clickExportCSV)

        translationButton = QPushButton("Translate", self)
        translationButton.setFixedWidth(145)

        saveButton = QPushButton("Save Word", self)
        saveButton.setFixedWidth(145)

        self.Hlayout.addWidget(translationButton)
        self.Hlayout.addWidget(saveButton)
        translationButton.clicked.connect(self.translationButtonClicked)
        saveButton.clicked.connect(self.saveButtonClicked)

        # Window setup
        self.widget = QWidget()
        self.widget.setWindowTitle("Japanese Lookup Tool")

        self.MainTab.setLayout(self.MainTab.layout)
        self.DBTab.setLayout(self.DBTab.layout)
        self.layout.addWidget(self.tabs)
        self.widget.setLayout(self.layout)
        self.widget.setMinimumSize(400, 700)
        self.widget.show()
Example #49
0
class AudioAnalysis(QDialog):
    def __init__(self, mainwin, dir):
        super().__init__()
        self.main_Win = mainwin
        self.snd_record_ctr = 0 
        self.snd_play_ctr = 0
        self.snd_reset_ctr = 0
        self.is_snd_recording = None
        #
        self.audio = Audio(save_dir=dir)
        self.initAUD()
        self.initIF()
        self.initWaveList()

    def initIF(self):
        self.layout = QGridLayout(self)
        self.setLayout(self.layout)
        icon = QIcon()
        icon.addPixmap(QPixmap("./style/logo3.png"))
        self.setWindowIcon(icon)
        self.setWindowTitle("语音录制与分析")
        self.list_LW = QListWidget(self)
        self.list_LW.setMaximumWidth(160)
        class WaveSpectrum(QWidget):
            def __init__(self, parent=None, maindlg=None):
                super(WaveSpectrum, self).__init__(parent)
                self.main_Dlg = maindlg
                #self.pg_PL = pg.PlotWidget(enableMenu=False)
                self.audio = self.main_Dlg.audio
                self.layout = QGridLayout(self)
                self.setLayout(self.layout)
                self.pg_PL = pg.PlotWidget() #pg.plot(title="Three plot curves")
                self.pg_PL.hideButtons()
                self.layout.addWidget(self.pg_PL)               
                self.item = self.pg_PL.getPlotItem()
                self.item.hideButtons()
                self.item.setMouseEnabled(y=False)
                self.item.setYRange(0,20000)
                range = self.audio.rate/2
                self.item.setXRange(-range,range, padding=0)
                self.axis = self.item.getAxis("bottom")
                self.axis.setLabel("频率(赫兹)")
                
            def updatePlot(self):
               try:
                   data = np.fromstring(self.audio.block, 'int16')
                   #print(data)
                   T = 1.0/self.audio.rate
                   N = data.shape[0]
                   Fx = (1./N) * np.fft.fft(data) # 万一N==0
               except Exception as e:
                   print("??",e)
               else:
                   f = np.fft.fftfreq(N, T)
                   Fx = np.fft.fftshift(Fx)
                   f = np.fft.fftshift(f)
                   self.item.plot(x=f.tolist(), y=(np.absolute(Fx)).tolist(), clear=True)    
    
        self.wave_spectrum_PG = WaveSpectrum(maindlg=self)
        self.result_LB = QLabel(self)
        self.result_LB.setText("欢迎使用")
        self.running_SL = QSlider(Qt.Horizontal)
        self.running_SL.setMinimum(0)
        self.running_SL.setMaximum(100)
        self.running_SL.setStyleSheet("QSlider::handle:horizontal {background-color: #d91900;}")
        self.save_BT = QPushButton(self)
        self.save_BT.setText("保存与分析")
        self.save_BT.setMinimumSize(128,32)
        self.record_BT = QPushButton(self)
        self.record_BT.setText("开始录音")
        self.record_BT.setMinimumSize(144,32)
        self.play_BT = QPushButton(self)
        self.play_BT.setText("开始播放")
        self.play_BT.setMinimumSize(144,32)
        self.reset_BT = QPushButton(self)
        self.reset_BT.setText("停止")
        self.reset_BT.setMinimumSize(128,32)
               
        self.layout.addWidget(self.list_LW, 0,0,1,1)
        self.layout.addWidget(self.wave_spectrum_PG, 0,1, 1,3)
        self.layout.addWidget(self.result_LB, 1,0, 1,4)
        self.layout.addWidget(self.running_SL, 2,0, 1,4)
        self.layout.addWidget(self.save_BT, 3,0, 2,1)
        self.layout.addWidget(self.record_BT, 3,1, 2,1)
        self.layout.addWidget(self.play_BT, 3,2, 2,1)
        self.layout.addWidget(self.reset_BT, 3,3, 2,1)
        

        self.list_LW.itemClicked.connect(self.sel2Play)
        self.record_BT.clicked.connect(self.click2Record)
        self.running_SL.sliderReleased.connect(self.dragPosPlay) 
        # 注意这里得是用户主动的动作哟 另外如果需要点击位置定位的话还必须要重写mousePressEvent,这里就不弄了
        self.play_BT.clicked.connect(self.click2Play)
        self.reset_BT.clicked.connect(self.click2Reset)
        self.save_BT.clicked.connect(self.click2Save)
    
    def initWaveList(self):
        self.wave_dict = {"小黄":["catH1.wav",0],"小黄骚":["catH2.wav",0], "小黄又骚":["catH3.wav",0], "小黄又又骚":["catH4.wav",0]
                         ,"煤球":["catM1.wav",0],"煤球骚":["catM2.wav",0], "煤球又骚":["catM3.wav",0]
                         ,"老公":["laog.wav",0], "老婆":["laop.wav",0]}
        
        for k in self.wave_dict:
            item = QListWidgetItem()
            item.setText(k)
            item.setData(Qt.UserRole, self.wave_dict[k])
            self.list_LW.addItem(item)
            
    def initAUD(self):
        #
        info = QAudioDeviceInfo.defaultInputDevice()
        if (~info.isFormatSupported(self.audio.format)):
            # print("警告,设置的默认音频格式并不支持,将尝试采用最相近的支持格式")
            # 不知道这里面有什么神改动?
            self.audio.format  = info.nearestFormat(self.audio.format)
        #
        update_interval = 160
        self.audioRecorder = QAudioInput(self.audio.format)
        self.audioRecorder.setNotifyInterval(update_interval) #按毫秒ms 类似于QTimer的作用
        self.audioRecorder.notify.connect(self.processAudioData)
        self.audioRecorder_TD = QThread()
        self.audioRecorder.moveToThread(self.audioRecorder_TD)
        self.audioRecorder_TD.started.connect(self.startRecord)
        self.audioRecorder.stateChanged.connect(self.recordStopped)
        # 总结来说线程只是一个容器,里面执行的循环要是没法结束,强制退出也不好操作
        # 所以还是好好写好任务流然后发送信号比较合理
        self.audioPlayer = QAudioOutput(self.audio.format)
        self.audioPlayer.setNotifyInterval(update_interval)
        self.audioPlayer.notify.connect(self.processAudioData)
        self.audioPlayer_TD = QThread()
        self.audioPlayer.moveToThread(self.audioPlayer_TD)
        self.audioPlayer_TD.started.connect(self.startPlay)
        self.audioPlayer.stateChanged.connect(self.playStopped)
    
    #   
    def startRecord(self):
        self.audioRecorder.start(self.audio.record_buffer) # 独立出来主要就是为了传个参数进去
        
    def click2Record(self):
        if self.snd_play_ctr != 0:
            self.audioPlayer.suspend()
            self.audioPlayer.stop()
            self.audio.play_buffer.close()
            self.running_SL.setValue(0)
            self.audioPlayer_TD.quit()
            self.snd_play_ctr = 0
            self.play_BT.setText("开始播放")
        #
        self.is_snd_recording = True
        self.running_SL.setStyleSheet("QSlider::handle:horizontal {background-color: #d91900;}")
        self.running_SL.setValue(0)
        if self.snd_record_ctr == 0:
            self.audio.record_buffer.open(QIODevice.WriteOnly)
            self.audioRecorder_TD.start() #注意这里是分线程进行
            self.record_BT.setText("暂停录音")
            self.reset_BT.setText("停止录音")
        elif self.snd_record_ctr % 2 == 1:
            self.audioRecorder.suspend()
            self.result_LB.setText("录音暂停")
            self.record_BT.setText("继续录音")
        else: # self.snd_record_ctr % 2 == 0:
            self.audioRecorder.resume()
            self.record_BT.setText("暂停录音")
        self.snd_record_ctr += 1

    def recordStopped(self):
        if self.audioRecorder.state() == QAudio.StoppedState: #==2 #QAudio.IdleState: #==3;
            self.audioRecorder_TD.quit()

    def startPlay(self):
        self.audioPlayer.start(self.audio.play_buffer)

    def click2Play(self):
        if self.is_snd_recording == None:
            self.result_LB.setText("还没录音呢!!!")
        else:
            if self.snd_record_ctr % 2 == 1:
                self.audioRecorder.suspend()
                self.record_BT.setText("继续录音")
                self.snd_record_ctr += 1
            #
            self.is_snd_recording = False
            self.running_SL.setStyleSheet("QSlider::handle:horizontal {background-color: #007ad9;}")
            if self.snd_play_ctr == 0:
                data = self.audio.record_buffer.data()      
                self.audio.play_buffer.setData(data)
                self.audio.play_buffer.open(QIODevice.ReadOnly) # 要在关闭的情况下设置数据然后在以某种模式打开
                self.audioPlayer_TD.start()
                self.running_SL.setValue(0)
                self.start_time = 0
                # self.start_time = self.running_SL.value() / 100 * self.audio.duration
                # self.audioPlayer.setVolume(0.8)
                self.play_BT.setText("暂停播放")
                self.reset_BT.setText("停止播放")
            elif self.snd_play_ctr % 2 == 1:
                self.audioPlayer.suspend()
                self.result_LB.setText("播放暂停")
                self.play_BT.setText("继续播放")
            else:    
                self.audioPlayer.resume()
                self.play_BT.setText("暂停播放")
            self.snd_play_ctr += 1
    
    def playStopped(self):
        if self.audioPlayer.state() == QAudio.IdleState: #==3; #QAudio.StoppedState: #==2
            self.audioPlayer.stop()
            self.running_SL.setValue(0)
            self.audio.play_buffer.close()
            self.audioPlayer_TD.quit()
            self.snd_play_ctr = 0
            self.play_BT.setText("开始播放")
    
    def dragPosPlay(self):
        if self.is_snd_recording == None:
            self.running_SL.setValue(0)
        else:
            if self.is_snd_recording & (self.snd_record_ctr % 2 == 1):
                self.audioRecorder.suspend()
                self.record_BT.setText("继续录音")
                self.snd_record_ctr += 1
            if (not self.is_snd_recording) & (self.snd_play_ctr % 2 == 1):
                self.audioPlayer.suspend()
                self.play_BT.setText("继续播放")
                self.snd_play_ctr += 1
            self.is_snd_recording = False
            self.running_SL.setStyleSheet("QSlider::handle:horizontal {background-color: #007ad9;}")
            self.audioPlayer.stop()
            self.audio.play_buffer.close()
            self.audioPlayer_TD.quit()
            #
            data = self.audio.record_buffer.data()      
            self.audio.play_buffer.setData(data)
            self.audio.play_buffer.open(QIODevice.ReadOnly) # 要在关闭的情况下设置数据然后在以某种模式打开
            self.audioPlayer_TD.start()
            data_size = self.audio.record_buffer.data().size()
            sel_pcent = self.running_SL.value() / 100
            sel_size = int(sel_pcent * data_size)
            self.audio.pos = int(sel_pcent * (data_size / self.audio.chunksize)) # 重设第几个chunk开始播放
            self.start_time = int(sel_pcent * self.audio.duration) # 重设开始播放时间
            self.audio.play_buffer.seek(sel_size)
            self.snd_play_ctr = 1
            self.play_BT.setText("暂停播放")
    
    def sel2Play(self, item):
        c0 = (self.is_snd_recording == None)
        c1 = ((self.is_snd_recording == False) & (self.snd_play_ctr % 2 == 0))
        c2 = ((self.is_snd_recording == True) & (self.snd_record_ctr % 2 == 0))
        if (c0 | c1 | c2):
            self.cur_item = item
            sound_dir = "./sound/"
            #self.cur_wave = os.path.abspath(item.data(Qt.UserRole)[0])
            self.cur_wave = item.data(Qt.UserRole)[0]
            sound_path = os.path.join(sound_dir, self.cur_wave)
            with wave.open(sound_path, 'rb') as wf:
                data = wf.readframes(wf.getnframes())
                self.audio.play_buffer.setData(data)
                self.audio.play_buffer.open(QIODevice.ReadOnly)
                self.start_time = 0
                self.audio.duration = 10 # 随便给了个值,避免产生除0的问题其他没啥用
                self.audioPlayer_TD.start()           
    
    def click2Reset(self):
        if self.is_snd_recording == None:
            self.result_LB.setText("还没录音呢!!!")
        elif self.is_snd_recording:
            self.audioRecorder.stop()
            self.audio.record_buffer = QBuffer()
            self.snd_record_ctr = 0
            self.result_LB.setText("录音停止")
            self.record_BT.setText("开始录音")
        else: #not self.is_snd_recording:
            self.audioPlayer.stop()
            self.audio.pos = 0
            self.snd_play_ctr = 0
            self.result_LB.setText("播放停止")
            self.play_BT.setText("开始播放")
        self.running_SL.setValue(0)
        
    def click2Save(self):
        if self.is_snd_recording == None:
            self.result_LB.setText("还没录音呢!!!")
        elif self.is_snd_recording:
            self.audioRecorder.suspend()
        else:
            self.audioPlayer.suspend()
        #self.audio.save_path = QFileDialog().getSaveFileName(self.main_Dlg, "选个保存的地方吧", new_path)[0]
        # 注意末尾那个[0]别丢了,不然返回的是tuple类型
        self.audio.saveWave()
        self.snd_record_ctr = 0
        self.result_LB.setText("录音存于:{};刚刚应该是{}叫了:)".format(os.path.abspath(self.audio.save_path), self.getMinDist()))
        self.record_BT.setText("开始录音")
         
    def processAudioData(self):
        if self.is_snd_recording: #self.audioRecorder.state() == QAudio.ActiveState:
            self.audio.block = self.audio.record_buffer.data().right(self.audio.chunksize)
            self.audio.duration = self.audioRecorder.processedUSecs() # 注意这里是微秒!!!
            interval = 10
            self.running_SL.setValue((self.audio.duration / 1000000) % interval * (100 / interval))
            show_info = "已录制{:.1f}秒".format(self.audio.duration/1000000.0)
            self.result_LB.setText(show_info)
        else: # self.audioPlayer.state() == QAudio.ActiveState:
            # 试过chop 不过好像没有必要
            self.audio.block = self.audio.play_buffer.data().mid(self.audio.pos*self.audio.chunksize, self.audio.chunksize)
            self.audio.pos += 1
            self.running_SL.setValue((self.start_time + self.audioPlayer.processedUSecs())/self.audio.duration*100)
            show_info = "正在播放{:.1f}/{:.1f}秒".format((self.start_time + self.audioPlayer.processedUSecs())/1000000.0
                                                         ,self.audio.duration/1000000.0)
            self.result_LB.setText(show_info)
        self.wave_spectrum_PG.updatePlot()

    def getMFCC(self,path):
        (rate, sig) = scwav.read(path)
        mfcc_feature = mfcc(sig, rate)
        nmfcc = np.array(mfcc_feature)
        y, sr = librosa.load(path)
        return librosa.feature.mfcc(y, sr)
        
    def compareMFCC(self, demo_path):
        mfcc1 = self.getMFCC(self.audio.save_path)
        print(demo_path)
        mfcc2 = self.getMFCC(demo_path)
        norm = lambda x, y: nlnorm(x-y, ord=1)
        d, cost_matrix, acc_cost_matrix, path = dtw(mfcc1.T, mfcc2.T, dist=norm)
        return d
       
    def getMinDist(self):
        i = 1000000
        sound_dir = "./sound/"
        for k in self.wave_dict:
            self.wave_dict[k][1] = self.compareMFCC(os.path.join(sound_dir, self.wave_dict[k][0]))
            print("{}:{:.1f}".format(k, self.wave_dict[k][1]))
            i = min(i, self.wave_dict[k][1])
            if i == self.wave_dict[k][1]:
                min_k = k
        return min_k
Example #50
0
class Window(QMainWindow):
    sys.excepthook = new_excepthook

    con = connectDB()

    Rtext, Ktext, Htext, Ftext = [None for _ in range(4)]

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

        globalFont = QFont("Times New Roman", 11)
        globalFont.setWeight(18)
        QApplication.setFont(globalFont)

        # Creating tabs and layouts
        self.layout = QVBoxLayout(self)
        self.Hlayout = QHBoxLayout(self)
        self.HDBlayout = QVBoxLayout(self)
        self.tabs = QTabWidget()
        self.MainTab = QWidget()
        self.DBTab = QWidget()
        self.tabs.addTab(self.MainTab, "Translate")
        self.tabs.addTab(self.DBTab, "Saved Words")

        self.MainTab.layout = QVBoxLayout(self)
        self.MainTab.layout.addLayout(self.Hlayout)
        self.DBTab.layout = QGridLayout()

        # Defining QLabels
        self.insertionBox = QLineEdit()
        self.romajiBox = QLabel()
        self.romajiBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.katakanaBox = QLabel()
        self.katakanaBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.hiraganaBox = QLabel()
        self.hiraganaBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.furiganaBox = QLabel()
        self.furiganaBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBox = QLabel()
        self.entriesBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBox.setWordWrap(True)
        self.charsBox = QLabel()
        self.charsBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.charsBox.setWordWrap(True)

        recordFont = QFont("Times New Roman", 15)
        recordFont.setWeight(18)
        self.romajiLabel = QLabel("Romaji")
        self.romajiLabel.setFont(recordFont)
        self.katakanaLabel = QLabel("Katakana")
        self.katakanaLabel.setFont(recordFont)
        self.hiraganaLabel = QLabel("Hiragana")
        self.hiraganaLabel.setFont(recordFont)
        self.furiganaLabel = QLabel("Furigana")
        self.furiganaLabel.setFont(recordFont)
        self.entriesLabel = QLabel("Entries")
        self.entriesLabel.setFont(recordFont)
        self.charsLabel = QLabel("Characters")
        self.charsLabel.setFont(recordFont)
        self.romajiLabelDB = QLabel("Romaji")
        self.romajiLabelDB.setFont(recordFont)
        self.katakanaLabelDB = QLabel("Katakana")
        self.katakanaLabelDB.setFont(recordFont)
        self.hiraganaLabelDB = QLabel("Hiragana")
        self.hiraganaLabelDB.setFont(recordFont)
        self.furiganaLabelDB = QLabel("Furigana")
        self.furiganaLabelDB.setFont(recordFont)
        self.entriesLabelDB = QLabel("Entries")
        self.entriesLabelDB.setFont(recordFont)
        self.charsLabelDB = QLabel("Characters")
        self.charsLabelDB.setFont(recordFont)

        self.romajiBoxDB = QLabel()
        self.romajiBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.katakanaBoxDB = QLabel()
        self.katakanaBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.hiraganaBoxDB = QLabel()
        self.hiraganaBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.furiganaBoxDB = QLabel()
        self.furiganaBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBoxDB = QLabel()
        self.entriesBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.entriesBoxDB.setWordWrap(True)
        self.charsBoxDB = QLabel()
        self.charsBoxDB.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.charsBoxDB.setWordWrap(True)

        # Globally accessible text from insertionBox in MainTab
        global text
        text = self.insertionBox.text

        # For switching tables in DBTab
        self.tableDropDown = QComboBox()
        self.tableDropDown.setDuplicatesEnabled(False)
        for item in getTables(self.con):
            self.tableDropDown.addItem(repr(item).strip("('',)"))
        self.DBTab.layout.addWidget(self.tableDropDown)

        # List of saved words in selected table in DBTab
        self.listWords = QListWidget()
        self.listWords.setFixedWidth(145)
        self.listWords.itemSelectionChanged.connect(self.selectionView)
        self.DBTab.layout.addWidget(self.listWords)
        self.listWordsAdd()
        self.tableDropDown.currentTextChanged.connect(
            lambda: self.listWordsAdd())

        # Adding widgets to tab layouts
        self.MainTab.layout.addWidget(self.insertionBox)
        self.MainTab.layout.addWidget(self.romajiLabel)
        self.MainTab.layout.addWidget(self.romajiBox)
        self.MainTab.layout.addWidget(self.katakanaLabel)
        self.MainTab.layout.addWidget(self.katakanaBox)
        self.MainTab.layout.addWidget(self.hiraganaLabel)
        self.MainTab.layout.addWidget(self.hiraganaBox)
        self.MainTab.layout.addWidget(self.furiganaLabel)
        self.MainTab.layout.addWidget(self.furiganaBox)
        self.MainTab.layout.addWidget(self.entriesLabel)
        self.MainTab.layout.addWidget(self.entriesBox)
        self.MainTab.layout.addWidget(self.charsLabel)
        self.MainTab.layout.addWidget(self.charsBox)

        self.DBTab.layout.addWidget(self.entriesLabelDB, 0, 1)
        self.DBTab.layout.addWidget(self.entriesBoxDB, 1, 1)
        self.DBTab.layout.addWidget(self.katakanaLabelDB, 2, 1)
        self.DBTab.layout.addWidget(self.katakanaBoxDB, 3, 1)
        self.DBTab.layout.addWidget(self.hiraganaLabelDB, 4, 1)
        self.DBTab.layout.addWidget(self.hiraganaBoxDB, 5, 1)
        self.DBTab.layout.addWidget(self.furiganaLabelDB, 6, 1)
        self.DBTab.layout.addWidget(self.furiganaBoxDB, 7, 1)
        self.DBTab.layout.addWidget(self.romajiLabelDB, 8, 1)
        self.DBTab.layout.addWidget(self.romajiBoxDB, 9, 1)
        self.DBTab.layout.addWidget(self.charsLabelDB, 10, 1)
        self.DBTab.layout.addWidget(self.charsBoxDB, 11, 1)

        # Creating buttons, connecting them to functions
        newTableButton = QPushButton("New List", self)
        newTableButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(newTableButton)
        newTableButton.clicked.connect(self.newTableButtonClicked)

        deleteButton = QPushButton("Delete", self)
        deleteButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(deleteButton)
        deleteButton.clicked.connect(self.deleteItemClicked)

        deleteTableButton = QPushButton("Delete List", self)
        deleteTableButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(deleteTableButton)
        deleteTableButton.clicked.connect(self.deleteTableClicked)

        exportButton = QPushButton("Export to CSV", self)
        exportButton.setFixedWidth(145)
        self.DBTab.layout.addWidget(exportButton)
        exportButton.clicked.connect(self.clickExportCSV)

        translationButton = QPushButton("Translate", self)
        translationButton.setFixedWidth(145)

        saveButton = QPushButton("Save Word", self)
        saveButton.setFixedWidth(145)

        self.Hlayout.addWidget(translationButton)
        self.Hlayout.addWidget(saveButton)
        translationButton.clicked.connect(self.translationButtonClicked)
        saveButton.clicked.connect(self.saveButtonClicked)

        # Window setup
        self.widget = QWidget()
        self.widget.setWindowTitle("Japanese Lookup Tool")

        self.MainTab.setLayout(self.MainTab.layout)
        self.DBTab.setLayout(self.DBTab.layout)
        self.layout.addWidget(self.tabs)
        self.widget.setLayout(self.layout)
        self.widget.setMinimumSize(400, 700)
        self.widget.show()

    def translationButtonClicked(self, text):
        if self.insertionBox.text() == "":
            msg = QMessageBox()
            msg.setWindowTitle("Error")
            msg.setText("There is no word to translate!")
            msg.exec_()
        else:
            jmd = Jamdict()
            text = self.insertionBox.text()

            Window.Rtext = toRomaji(text)
            Window.Ktext = toKatakana(text)
            Window.Htext = toHiragana(text)
            result = jmd.lookup(text)

            text = toTokensDictionary(text)

            separater = ""
            Window.Ftext = toFurigana(text)
            Window.Ftext = separater.join(Window.Ftext)

            if result == None:
                result = jmd.lookup(Window.Ktext)
            if result == None:
                result = jmd.lookup(Window.Htext)

            Window.Etext = repr(result.entries).strip("[]")
            Window.Ctext = repr(result.chars).strip("[]")

            self.romajiBox.setText(Window.Rtext)
            self.katakanaBox.setText(Window.Ktext)
            self.hiraganaBox.setText(Window.Htext)
            self.furiganaBox.setText(Window.Ftext)
            self.entriesBox.setText(Window.Etext)
            self.charsBox.setText(Window.Ctext)

            return Window.Rtext, Window.Ktext, Window.Htext, Window.Ftext

    def saveButtonClicked(self):
        if len(getTables(self.con)) == 0:
            msg = QMessageBox()
            msg.setText("No lists to save to!")
            msg.exec_()
            return
        if Window.Rtext:
            tables = getTables(self.con)
            tables = [t[0] for t in tables]
            table, ok = QInputDialog.getItem(self, "List option",
                                             "Choose list to save to:", tables,
                                             0, False)
            if ok and table:
                msg = QMessageBox()
                insertWord(self.con, table, self.Rtext, self.Ktext, self.Htext,
                           self.Ftext, self.Etext, self.Ctext)
                msg.setText("Word saved to " + table)
                msg.exec_()
                if self.currentTable().strip("''") == table:
                    self.listWords.addItem(repr(self.Rtext).strip("''"))
        else:
            msg = QMessageBox()
            msg.setText("There is no translated word to save!")
            msg.exec_()

    def newTableButtonClicked(self):
        nameNewTable, ok = QInputDialog.getText(self, 'New list',
                                                'Enter new list name:')
        if self.tableDropDown.findText(nameNewTable) == -1:
            self.tableDropDown.addItem(nameNewTable)
            newTable(self.con, nameNewTable)
        else:
            msg = QMessageBox()
            msg.setWindowTitle("Error")
            msg.setText("Error creating list")
            msg.exec_()

    def deleteItemClicked(self):
        if self.listWords.selectedItems() != 0:
            for item in self.listWords.selectedItems():
                deleteWord(self.con,
                           self.listWords.currentItem().text(),
                           self.currentTable())
                self.listWords.takeItem(self.listWords.row(item))
        else:
            msg = QMessageBox()
            msg.setWindowTitle("Error")
            msg.setText("There is no word selected to delete!")
            msg.exec_()

    def deleteTableClicked(self):
        table = self.currentTable()
        confirm = QMessageBox.question(
            self, "Confirmation",
            "Are you sure you want to delete " + table + "?", QMessageBox.Yes,
            QMessageBox.Cancel)
        if confirm == QMessageBox.Yes:
            index = self.tableDropDown.findText(table.strip("''"))
            self.tableDropDown.removeItem(index)
            dropTable(self.con, table)

    def updateDBTabList(self, input):
        if type(input) is list:
            self.romajiBoxDB.setText(input[0])
            self.katakanaBoxDB.setText(input[1])
            self.hiraganaBoxDB.setText(input[2])
            self.furiganaBoxDB.setText(input[3])
            self.entriesBoxDB.setText(input[4])
            self.charsBoxDB.setText(input[5])
        else:
            self.romajiBoxDB.setText(input)
            self.katakanaBoxDB.setText(input)
            self.hiraganaBoxDB.setText(input)
            self.furiganaBoxDB.setText(input)
            self.entriesBoxDB.setText(input)
            self.charsBoxDB.setText(input)

    def selectionView(self):
        if self.listWords.selectedItems() != 0 and self.listWords.currentItem(
        ) is not None and self.currentTable() is not None:
            list = selectWord(self.con,
                              self.listWords.currentItem().text(),
                              self.currentTable())
            if list:
                self.updateDBTabList(list)

    def currentTable(self):
        if self.tableDropDown.currentText() is not None:
            return repr(self.tableDropDown.currentText())
        else:
            msg = QMessageBox()
            msg.setWindowTitle("Error")
            msg.setText("Create a list to be able to save words")
            msg.exec_()
            return None

    def listWordsAdd(self):
        self.updateDBTabList("")
        if len(getTables(self.con)) != 0 and self.currentTable() is not None:
            wordList = listTable(self.con, self.currentTable())
            self.listWords.clear()
            for word in wordList:
                self.listWords.addItem(repr(word).strip("'()',"))

    def clickExportCSV(self):
        exportCSV(self.con, self.currentTable())
        msg = QMessageBox()
        msg.setWindowTitle("Export successful")
        msg.setText("Exported as " + self.currentTable().strip("''") + ".csv")
        msg.exec_()
Example #51
0
class MainWidget(QWidget):
    def __init__(self):
        super(MainWidget, self).__init__()
        self.selected_images = []
        self.detector_checks = []
        self.detector_map = {}
        self.selected_detectors = []
        self.initUI()

    def initUI(self):
        grid_layout = QGridLayout()
        grid_layout.setObjectName("grid_layout")
        grid_layout.setContentsMargins(10, 10, 10, 10)

        grp_input = QGroupBox()
        grp_input.setObjectName("grp_input")
        grp_input.setTitle("Input images")

        self.lst_images = QListWidget(grp_input)
        self.lst_images.setObjectName("lst_images")
        self.lst_images.setSelectionMode(QAbstractItemView.NoSelection)

        self.btn_load = QPushButton()
        self.btn_load.setObjectName("btn_load")
        self.btn_load.setText("1. Load images")
        self.btn_load.clicked.connect(self.load_files)

        input_layout = QGridLayout()
        input_layout.setContentsMargins(0, 0, 0, 0)
        # Set the stretch
        input_layout.setColumnStretch(0, 0)  # row, stretch
        input_layout.setColumnStretch(3, 0)
        input_layout.setRowStretch(0, 0)
        input_layout.setRowStretch(3, 0)
        # Add widgets
        input_layout.addWidget(self.lst_images, 2, 2)
        input_layout.addWidget(self.btn_load, 3, 2)
        grp_input.setLayout(input_layout)

        grid_layout.addWidget(grp_input, 0, 0, 3, 1)

        grp_detectors = QGroupBox()
        grp_detectors.setObjectName("grp_detectors")
        grp_detectors_layout = QVBoxLayout()

        chk_thresh = QCheckBox(grp_detectors)
        chk_thresh.setObjectName("chk_thresh")
        chk_thresh.setText("ThresholdBlurDetector")
        chk_thresh.setChecked(True)
        self.detector_checks.append(chk_thresh)
        self.detector_map[chk_thresh] = ThresholdBlurDetector
        grp_detectors_layout.addWidget(chk_thresh)

        chk_canny = QCheckBox(grp_detectors)
        chk_canny.setObjectName("chk_canny")
        chk_canny.setText("CannyDetector")
        self.detector_checks.append(chk_canny)
        self.detector_map[chk_canny] = CannyDetector
        grp_detectors_layout.addWidget(chk_canny)

        chk_morphology = QCheckBox(grp_detectors)
        chk_morphology.setObjectName("chk_morphology")
        chk_morphology.setText("MorphologyTransformDetector")
        self.detector_checks.append(chk_morphology)
        self.detector_map[chk_morphology] = MorphologyTransformDetector
        grp_detectors_layout.addWidget(chk_morphology)

        grp_detectors.setLayout(grp_detectors_layout)
        grid_layout.addWidget(grp_detectors, 3, 0, 1, 1)

        self.btn_process = QPushButton()
        self.btn_process.setObjectName("btn_process")
        self.btn_process.setText("2. Process")
        self.btn_process.setEnabled(False)
        self.btn_process.clicked.connect(self.process_files)

        # addWidget(*Widget, row, column, rowspan, colspan)
        grid_layout.addWidget(self.btn_process, 4, 0, 1, 1)

        self.setLayout(grid_layout)
        self.setToolTip('This is a <b>QWidget</b> widget')
        self.setGeometry(300, 300, 400, 400)
        self.setWindowTitle('License Plate Number Recognition')
        self.center()
        self.show()

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

    def load_files(self):
        dialog_result = QFileDialog.getOpenFileNames(
            self, 'Open file', '.',
            "JPEG (*.jpg *.jpeg);;All files (*.*);;PNG (*.png)")
        if dialog_result[0]:
            self.selected_images = sorted(dialog_result[0])
            self.btn_process.setEnabled(True)
            for file_path in self.selected_images:
                item = QListWidgetItem(file_path)
                self.lst_images.addItem(item)

    def process_files(self):
        if len(self.selected_images) > 0:
            for check_box in self.detector_checks:
                if check_box.isChecked():
                    self.selected_detectors.append(
                        self.detector_map[check_box])
            if len(self.selected_detectors) > 0:
                self.hide()
                QCoreApplication.instance().quit()

                from main import main
                main(self.selected_images, self.selected_detectors)
        pass
Example #52
0
class StringListDlg(QDialog):
    def __init__(self, name, stringList=None, parent=None):
        super(StringListDlg, self).__init__(parent=parent)

        self.name = name
        self.listWidget = QListWidget()
        if stringList is not None:
            self.listWidget.addItems(stringList)
            self.listWidget.setCurrentRow(0)

        buttonlayout = QVBoxLayout()
        for text, slot in (("&Add...", self.add), ("&Edit...", self.edit),
                           ("&Remove.", self.remove), ("&Up....", self.up),
                           ("&Down...", self.down),
                           ("&Sort...", self.listWidget.sortItems),
                           ("&Close...", self.accept)):
            button = QPushButton(text)

            buttonlayout.addWidget(button)
            button.clicked.connect(slot)

        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonlayout)
        self.setLayout(layout)
        self.setWindowTitle("Edit %s List" % self.name)

    def add(self):
        row = self.listWidget.currentRow()
        title = "Add %s" % self.name
        string, ok = QInputDialog.getText(self, title, title)
        if ok and string:
            self.listWidget.insertItem(row, string)

    def edit(self):
        item = self.listWidget.currentItem()
        if item is not None:
            title = "Edit %s" % self.name
            string, ok = QInputDialog.getText(self, title, title,
                                              QLineEdit.Normal, item.text())

            if ok and string:
                item.setText(string)

    def remove(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.currentItem()
        if item is not None:
            reply = QMessageBox.question(
                self, "remove %s" % self.name,
                "remove {0} {1}".format(self.name, item.text()),
                QMessageBox.Ok | QMessageBox.No)
            if reply == QMessageBox.Ok:
                item = self.listWidget.takeItem(row)
                del item

    def up(self):
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row - 1, item)
            self.listWidget.setCurrentRow(row - 1)

    def down(self):
        row = self.listWidget.currentRow()
        if row <= self.listWidget.count():
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + 1, item)
            self.listWidget.setCurrentRow(row + 1)

    def accept(self):
        pass
Example #53
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        #        self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
        #        self.setAttribute(Qt.WA_TranslucentBackground)
        self.resize(900, 700)
        self.__search_mode = {
            'fuzzy': 'fuzzy_search',
            'precise': 'precise_search',
            'reg': 'reg_search'
        }
        # self.__pbn_switch_view = None

        # 创建窗口部件
        self.__widget_frame = QLabel()

        # window title
        self.__lab_title_fram = QLabel()
        self.__lab_title = QLabel('搜索辅助工具')
        self.__lab_title.setAlignment(Qt.AlignCenter)

        self.__lab_open_tool = QLabel('打开文件方式')
        self.__ln_open_tool = QLineEdit()
        self.__pbn_open_tool = QToolButton()
        self.__pbn_open_tool.setText('选择...')
        self.__ln_open_tool.setFixedHeight(20)
        self.__ln_open_tool.setFixedWidth(150)
        self.__pbn_open_tool.setFixedSize(48, 20)
        self.__lab_title_fram.setFixedHeight(50)

        # search mode
        self.__lab_mode_fram = QLabel()
        self.__rbn_fuzzy = QRadioButton('模糊搜索')
        self.__rbn_precise = QRadioButton('精确搜索')
        self.__rbn_reg = QRadioButton('正则表达式搜索')
        self.__rbn_fuzzy.setChecked(True)
        self.__lab_mode_fram.setFixedHeight(22)

        # search pattern
        self.__lab_pattern_fram = QLabel()
        self.__ln_file_name = QLineEdit()
        self.__ln_file_name.setPlaceholderText('请输入搜索条件或正则表达式......')
        self.__rbn_reg_Iyes = QRadioButton('区分大小写')
        self.__rbn_reg_Ino = QRadioButton('不区分大小写')
        self.__lab_pattern_fram.setFixedHeight(20)

        # search path
        self.__lab_path_fram = QLabel()
        self.__ln_file_path = QLineEdit()
        self.__ln_file_path.setPlaceholderText('请选择或输入路径......')
        self.__pbn_file_path = QToolButton()
        self.__pbn_file_path.setText('浏览...')
        self.__rbn_search_file = QRadioButton('检索文件名')
        self.__rbn_search_content = QRadioButton('检索文件内容')
        self.__pbn_file_path.setFixedSize(48, 20)
        self.__lab_path_fram.setFixedHeight(20)

        # search state
        self.__lab_state_fram = QLabel()
        self.__lab_state = QLabel('状态:暂无搜索结果!')
        self.__pbn_search = QPushButton('开始')
        self.__pbn_stop = QPushButton('停止')
        self.__pbn_search.setFixedWidth(89)
        self.__pbn_stop.setFixedWidth(89)
        self.__lab_state_fram.setFixedHeight(35)

        # search result
        self.__tabView = QTabWidget()
        self.__browser_result = QListWidget()
        self.__browser_error = QTextBrowser()
        self.__tabView.addTab(self.__browser_result, '匹配结果')
        self.__tabView.addTab(self.__browser_error, '错误结果')

        self.__btn_group_type = QButtonGroup()
        self.__btn_group_type.addButton(self.__rbn_search_file)
        self.__btn_group_type.addButton(self.__rbn_search_content)
        self.__rbn_search_file.setChecked(True)

        # radiobutton group
        self.__btn_group_re_I = QButtonGroup()
        self.__btn_group_re_I.addButton(self.__rbn_reg_Iyes)
        self.__btn_group_re_I.addButton(self.__rbn_reg_Ino)
        self.__rbn_reg_Iyes.setChecked(True)

        # lines
        '''
        self.__line_1 = QFrame()
        self.__line_1.setFrameStyle(QFrame.HLine | QFrame.Sunken)
        '''

        # 布局
        # open tool
        self.__layout_tool_choose = QHBoxLayout()
        self.__layout_tool_choose.addWidget(self.__ln_open_tool)
        self.__layout_tool_choose.addWidget(self.__pbn_open_tool)
        self.__layout_tool_choose.setSpacing(0)
        self.__layout_tool_choose.setContentsMargins(0, 0, 0, 0)

        self.__layout_open_tool = QHBoxLayout()
        self.__layout_open_tool.addWidget(self.__lab_open_tool)
        self.__layout_open_tool.addLayout(self.__layout_tool_choose)
        self.__layout_open_tool.setSpacing(2)

        # window title
        self.__layout_title = QHBoxLayout()
        self.__layout_title.addStretch(5)
        self.__layout_title.addWidget(self.__lab_title)
        self.__layout_title.addStretch(1)
        self.__layout_title.addLayout(self.__layout_open_tool)
        self.__layout_title.setContentsMargins(0, 0, 0, 20)
        self.__lab_title_fram.setLayout(self.__layout_title)

        # search mode
        self.__layout_search_mode = QHBoxLayout()
        self.__layout_search_mode.addWidget(self.__rbn_fuzzy)
        self.__layout_search_mode.addStretch()
        self.__layout_search_mode.addWidget(self.__rbn_precise)
        self.__layout_search_mode.addStretch()
        self.__layout_search_mode.addWidget(self.__rbn_reg)
        self.__layout_search_mode.setContentsMargins(60, 0, 60, 0)
        self.__lab_mode_fram.setLayout(self.__layout_search_mode)

        # search pattern
        self.__layout_search_reg_I = QHBoxLayout()
        self.__layout_search_reg_I.addWidget(self.__rbn_reg_Iyes)
        self.__layout_search_reg_I.addWidget(self.__rbn_reg_Ino)

        self.__layout_pattern = QHBoxLayout()
        self.__layout_pattern.addWidget(self.__ln_file_name)
        self.__layout_pattern.addLayout(self.__layout_search_reg_I)
        self.__layout_pattern.setContentsMargins(0, 0, 0, 0)
        self.__lab_pattern_fram.setLayout(self.__layout_pattern)

        # search path
        self.__layout_choose_path = QHBoxLayout()
        self.__layout_choose_path.addWidget(self.__ln_file_path)
        self.__layout_choose_path.addWidget(self.__pbn_file_path)
        self.__layout_choose_path.setSpacing(0)

        self.__layout_path = QHBoxLayout()
        self.__layout_path.addLayout(self.__layout_choose_path)
        self.__layout_path.addWidget(self.__rbn_search_file)
        self.__layout_path.addWidget(self.__rbn_search_content)
        self.__layout_path.setContentsMargins(0, 0, 0, 0)
        self.__lab_path_fram.setLayout(self.__layout_path)

        # search state
        self.__layout_state = QHBoxLayout()
        self.__layout_state.addWidget(self.__lab_state)
        self.__layout_state.addWidget(self.__pbn_search)
        self.__layout_state.addWidget(self.__pbn_stop)
        self.__layout_state.setContentsMargins(0, 0, 0, 10)
        self.__lab_state_fram.setLayout(self.__layout_state)

        # top layout
        self.__layout_top = QVBoxLayout()
        self.__layout_top.addWidget(self.__lab_title_fram)
        self.__layout_top.addWidget(self.__lab_mode_fram)
        self.__layout_top.addWidget(self.__lab_pattern_fram)
        self.__layout_top.addWidget(self.__lab_path_fram)
        self.__layout_top.addWidget(self.__lab_state_fram)
        self.__layout_top.addWidget(self.__tabView)
        self.__layout_top.setSpacing(10)
        self.__widget_frame.setLayout(self.__layout_top)

        self.__layout_fram = QGridLayout()
        self.__layout_fram.addWidget(self.__widget_frame, 0, 0, 1, 1)
        self.__layout_fram.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.__layout_fram)

        # set object name
        self.__widget_frame.setObjectName('fram')
        self.__lab_title.setObjectName('lab_title')
        self.__ln_open_tool.setObjectName('ln_open_tool')
        self.__lab_mode_fram.setObjectName('mode_fram')
        self.__ln_file_name.setObjectName('ln_pattern')
        self.__ln_file_path.setObjectName('ln_path')
        self.__lab_state.setObjectName('state')
        self.__tabView.setObjectName('tabView')
        self.__browser_result.setObjectName('browser_result')
        self.__browser_error.setObjectName('browser_error')

        self.setStyleSheet(
            '#fram{'
            'border-image: url(Images/bg);'
            '}'
            '#lab_title{'
            'color: white;'
            'font-size: 18pt;'
            '}'
            '#open_tool{'
            'color: black;'
            '}'
            '#mode_fram{'
            # 'border-top: 1px solid rgba(20, 20, 20, 100);'
            # 'border-bottom: 1px solid rgba(20, 20, 20, 100);'
            'background: rgba(0, 0, 0, 40);'
            '}'
            '#ln_open_tool, #ln_path{'
            'border-top-left-radius:    2px;'
            'border-bottom-left-radius: 2px;'
            '}'
            '#ln_pattern{'
            'border-radius: 2px;'
            '}'
            '#state{'
            'background: rgba(0, 0, 0, 40);'
            'border-radius: 2px;'
            'padding: 1px;'
            'color: rgb(240, 240, 240);'
            '}'
            'QTabBar::tab {'
            'border: 0;'
            'width:  90px;'
            'height: 20px;'
            'margin: 0 2px 0 0;'  # top right bottom left
            # 'border-top-left-radius: 5px;'
            # 'border-top-right-radius: 5px;'
            'color: rgb(200, 255, 255;);'
            '}'
            'QTabBar::tab:selected{'
            'background: rgba(25, 0, 0, 40);'
            'border-left: 1px solid rgba(255, 255, 255, 200);'
            'border-top: 1px solid rgba(255, 255, 255, 200);'
            'border-right: 1px solid rgba(255, 255, 255, 200);'
            '}'
            'QTabWidget:pane {'
            'border: 1px solid rgba(255, 255, 255, 200);'
            'background: rgba(0, 0, 0, 80);'
            '}'
            '#browser_result, #browser_error{'
            'background: rgba(0, 0, 0, 0);'
            'border: 0;'
            '}'
            'QLineEdit{'
            'background: rgba(0, 0, 0, 40);'
            'border: 1px solid rgba(220, 220, 220, 200);'
            'color: white;'
            'height: 20px;'
            '}'
            'QPushButton{'
            'background: rgba(0, 0, 0, 100);'
            'border-radius: 5px;'
            'height: 20px;'
            'color: white;'
            '}'
            'QPushButton::hover{'
            'background: rgba(0, 0, 0, 150);'
            '}'
            'QToolButton{'
            'background: rgba(0, 0, 0, 100);'
            'color: white;'
            'border-top-right-radius:    2px;'
            'border-bottom-right-radius: 2px;'
            '}'
            'QToolButton::hover{'
            'background: rgba(0, 0, 0, 150);'
            '}')

        self.__ln_file_name.setFocus()
        self.__pbn_search.setShortcut(Qt.Key_Return)

        # 关联 信号/槽
        self.__pbn_file_path.clicked.connect(self.choose_path)
        self.__pbn_search.clicked.connect(self.pbn_search_clicked)
        self.__pbn_stop.clicked.connect(self.pbn_stop)
        self.__pbn_open_tool.clicked.connect(self.choose_open_tool)
        self.__browser_result.doubleClicked.connect(self.listitem_clicked)

        # 线程间共享数据队列
        queue_size = 10000
        self.__queue_result = Queue(queue_size)
        self.__queue_error = Queue(queue_size)

        # 标记搜索状态
        self.__searching = False

        # 强制结束子线程
        self.__thread_killer = False
Example #54
0
class DataPanel(QTabWidget):

    def __init__(self, server: ServerConnector, message_func):
        super().__init__()

        self.server = server
        self.message_func = message_func

        self.free_breakages_widget = QListWidget()
        self.free_breakages_widget.itemDoubleClicked.connect(self.openBreakageWindow)

        self.my_breakages_widget = QListWidget()
        self.my_breakages_widget.itemDoubleClicked.connect(self.openBreakageWindow)

        self.breakages_in_work_widget = QListWidget()
        self.breakages_in_work_widget.itemDoubleClicked.connect(self.openBreakageWindow)

        self.update_data()

    def setEngineerMode(self):
        self.clear()
        self.addTab(self.free_breakages_widget, "Свободные поломки")
        self.addTab(self.my_breakages_widget, "Мои поломки")

    def setOperatorMode(self):
        self.clear()
        self.addTab(self.free_breakages_widget, "Свободные поломки")
        self.addTab(self.breakages_in_work_widget, "Поломки в работе")

    def setAdministratorMode(self):
        pass

    def update_data(self):
        self.free_breakages_widget.clear()
        self.my_breakages_widget.clear()
        self.breakages_in_work_widget.clear()
        for breakage in self.server.get_free_breakages():
            self.free_breakages_widget.addItem(BreakagesListItem(breakage))
        for breakage in self.server.get_taken_breakages():
            self.my_breakages_widget.addItem(BreakagesListItem(breakage))
        for breakage in self.server.get_breakages_in_work():
            self.breakages_in_work_widget.addItem(BreakagesListItem(breakage))

        if self.server.user_role == 'ADMIN':
            self.setAdministratorMode()
        elif self.server.user_role == 'ENGINEER':
            self.setEngineerMode()
        elif self.server.user_role == 'OPERATOR':
            self.setOperatorMode()

    def openBreakageWindow(self):
        window = BreakageWindow(self.sender().selectedItems()[0].data, self.server, self.message_func)
        window.exec()
 def __init__(self, dirpath, parent=None):
     QListWidget.__init__(self, parent)
     self.setDirpath(dirpath)
Example #56
0
 def __init__(self, *args, **kwargs):
     super(ListWidgetAction, self).__init__(*args, **kwargs)
     self._listWidget = QListWidget()
     self._listWidget.setAlternatingRowColors(True)
     self.setDefaultWidget(self._listWidget)
Example #57
0
class LoggingPanel(Panel):
    """A panel containing elements to log messages.

    Attributes
    ----------
    _log_handler: QLogHandler
        A widget to display log messages

    """
    _levels = {
        "Fatal": logging.FATAL,
        "Error": logging.ERROR,
        "Warning": logging.WARNING,
        "Info": logging.INFO,
        "Debug": logging.DEBUG
    }

    def __init__(self, toolbox: Toolbox=None, **kwargs):
        """Initialization of the LoggingPael.

        Parameters
        ----------
        parent  :   QWidget
                    The parent argument is sent to the QWidget constructor.
        """
        super().__init__(**kwargs)
        self._loggingRecorder = None
        self._toolbox = None
        self._initUI()
        self.setToolbox(toolbox)

    def _initUI(self):
        """Add the UI elements

            * The ``QLogHandler`` showing the log messages

        """
        #
        # Controls
        #
        self._log_handler = QLogHandler()
        self._log_handler._message_signal.connect(self._new_message)
        self._total = QLabel()
        self._updateLogViewButton = QPushButton("Update")
        self._updateLogViewButton.clicked.connect(self._onUpdateLogView)
        self._updateLogViewButton.setEnabled(self._loggingRecorder is not None)
        self._clearLogViewButton = QPushButton("Clear")
        self._clearLogViewButton.clicked.connect(self._onClearLogView)

        self._modules = QListWidget()

        self._checkProcess = QCheckBox("Process")
        self._checkProcess.clicked.connect(self._updateFormatter)
        self._checkThread = QCheckBox("Thread")
        self._checkThread.clicked.connect(self._updateFormatter)
        self._checkName = QCheckBox("Name")
        self._checkName.clicked.connect(self._updateFormatter)
        self._checkModule = QCheckBox("Module")
        self._checkModule.clicked.connect(self._updateFormatter)
        self._checkFile = QCheckBox("File")
        self._checkFile.clicked.connect(self._updateFormatter)
        self._checkLevel = QCheckBox("Level")
        self._checkLevel.clicked.connect(self._updateFormatter)

        self._radio = {}
        self._levelButtonGroup = QButtonGroup()
        for label in self._levels.keys():
            self._radio[label] = QRadioButton(label)
            self._radio[label].clicked.connect(self._onLoggerLevelClicked)
            self._levelButtonGroup.addButton(self._radio[label])
        self._checkLoggerEnabled = QCheckBox("enabled")
        self._checkLoggerEnabled.clicked.connect(self._onLoggerEnabledClicked)

        self._buttonLoggerClearLevel = QPushButton("Clear Level")
        self._buttonLoggerClearLevel.clicked.connect(self._onClearLevel)

        self._effectiveLevel = QLabel()


        self._loggerList = QListWidget()
        self._loggerList.setSortingEnabled(True)
        self._loggerList.currentItemChanged.connect(self._onCurrentLoggerChanged)

        self._loggerList_refresh = QPushButton("Refresh")
        self._loggerList_refresh.clicked.connect(self._updateLoggerList)

        self._rootLoggerLevel = QComboBox()
        for name, level in self._levels.items():
            self._rootLoggerLevel.addItem(name, level)
        self._rootLoggerLevel.currentIndexChanged.connect(self._onRootLevelChanged)

        self._exceptionPanel = QExceptionPanel()
        
        self._updateLoggerList()
        self._layoutComponents()

    def _layoutComponents(self):
        """Layout the UI elements.

            * The ``QLogHandler`` displaying the log messages

        """

        layout = QVBoxLayout()
        row = QHBoxLayout()
        row.addWidget(self._log_handler)
        row.addWidget(self._exceptionPanel)
        layout.addLayout(row)
        
        row = QHBoxLayout()
        text = QHBoxLayout()
        text.addWidget(QLabel("Messages: "))
        text.addWidget(self._total)
        row.addLayout(text)
        row.addWidget(self._updateLogViewButton)
        row.addWidget(self._clearLogViewButton)
        row.addWidget(self._checkProcess)
        row.addWidget(self._checkThread)
        row.addWidget(self._checkName)
        row.addWidget(self._checkModule)
        row.addWidget(self._checkFile)
        row.addWidget(self._checkLevel)
        row.addStretch()
        layout.addLayout(row)

        row = QHBoxLayout()
        column = QVBoxLayout()
        column.addWidget(self._loggerList)
        column.addWidget(self._loggerList_refresh)
        row.addLayout(column)
        
        column = QVBoxLayout()

        box = QGroupBox("Root Logger")
        boxLayout = QVBoxLayout()
        boxLayout.addWidget(self._rootLoggerLevel)
        box.setLayout(boxLayout)
        column.addWidget(box)

        box = QGroupBox("Logger Details")
        boxLayout = QVBoxLayout()
        boxLayout.addWidget(self._checkLoggerEnabled)
        line = QHBoxLayout()
        line.addWidget(QLabel("Effective Level: "))
        line.addWidget(self._effectiveLevel)
        boxLayout.addLayout(line)
        for button in self._radio.values():
            boxLayout.addWidget(button)
        boxLayout.addWidget(self._buttonLoggerClearLevel)
        box.setLayout(boxLayout)
        column.addWidget(box)

        column.addStretch()
        row.addLayout(column)

        row.addWidget(self._modules)

        layout.addLayout(row)
        
        self.setLayout(layout)

    def setToolbox(self, toolbox: Toolbox=None) -> None:
        self._exceptionPanel.setToolbox(toolbox)

    def addLogger(self, logger):
        """Add a logger to this :py:class:LoggingPanel.
        LogRecords emitted by that logger will be processed.
        """
        logger.addHandler(self._log_handler)
        if self._loggingRecorder is not None:
            logger.addHandler(self._loggingRecorder)

    def removeLogger(self, logger):
        """Remove a logger from this :py:class:LoggingPanel.
        LogRecords emitted by that logger will no longer be processed.
        """
        logger.removeHandler(self._log_handler)
        if self._loggingRecorder is not None:
            logger.removeHandler(self._loggingRecorder)

    def setLoggingRecorder(self, recorder: RecorderHandler) -> None:
        """Set a logging recorder for this :py:class:LoggingPanel.
        Having a logging recorder allows to replay the log messages
        recorded by that recorder.
        """
        self._loggingRecorder = recorder
        self._onUpdateLogView()
        self._updateLogViewButton.setEnabled(recorder is not None)

    def _new_message(self, message):
        total = str(len(self._log_handler))
        if self._loggingRecorder is not None:
            total += "/" + str(len(self._loggingRecorder))
        self._total.setText(total)

    def _updateFormatter(self):
        format = ""
        if self._checkProcess.isChecked():
            format += "[%(processName)s] "
        if self._checkThread.isChecked():
            format += "[%(threadName)s] "
        if self._checkName.isChecked():
            format += "(%(name)s) "
        if self._checkModule.isChecked():
            format += "%(module)s "
        if self._checkFile.isChecked():
            format += "%(filename)s:%(lineno)d: "
        if self._checkLevel.isChecked():
            format += "%(levelname)s: "
        format += "%(message)s"
        formatter = logging.Formatter(fmt=format, datefmt="%(asctime)s")
        self._log_handler.setFormatter(formatter)

    def _onClearLogView(self):
        """Update the log view.
        """
        self._log_handler.clear()

    def _onUpdateLogView(self):
        """Update the log view.
        """
        if self._loggingRecorder is not None:
            self._loggingRecorder.replay(self._log_handler)

    def _decorateLoggerItem(self, item: QListWidgetItem,
                            logger: logging.Logger) -> None:
        """Decorate an entry in the logger list reflecting the properties
        of the logger.
        """
        item.setForeground(self._colorForLogLevel(logger.getEffectiveLevel()))
        font = item.font()
        font.setBold(bool(logger.level))
        item.setFont(font)
        item.setBackground(Qt.lightGray if logger.disabled else Qt.white)

    def _updateLoggerList(self):
        self._loggerList.clear()
        self._updateLogger(None)
        # FIXME[bug]: this may raise a RuntimeError:
        #    dictionary changed size during iteration
        for name, logger in logging.Logger.manager.loggerDict.items():
            if not isinstance(logger, logging.Logger):
                continue
            level = logger.getEffectiveLevel()
            item = QListWidgetItem(name)
            self._decorateLoggerItem(item, logger)
            self._loggerList.addItem(item)

        index = self._rootLoggerLevel.findData(logging.Logger.root.level)
        self._rootLoggerLevel.setCurrentIndex(index)

    def _onCurrentLoggerChanged(self, item: QListWidgetItem,
                                previous: QListWidgetItem) -> None:
        """A logger was selected in the logger list.
        """
        logger = (None if item is None else
                  logging.Logger.manager.loggerDict[item.text()])
        self._updateLogger(logger)

    def _onRootLevelChanged(self, index: int) -> None:
        logging.Logger.root.setLevel(self._rootLoggerLevel.currentData())
        self._updateLoggerList()

    def _updateLogger(self, logger: logging.Logger):
        """Update the logger group to reflect the currently selected
        logger. If ther is no current logger (logger is None), then
        the logger group is cleared and disabled.
        """
        if logger is None or not logger.level:
            checked = self._levelButtonGroup.checkedButton()
            if checked is not None:
                self._levelButtonGroup.setExclusive(False)
                checked.setChecked(False)
                self._levelButtonGroup.setExclusive(True)

        self._checkLoggerEnabled.setCheckable(logger is not None)
        for button in self._levelButtonGroup.buttons():
            button.setCheckable(logger is not None)

        if logger is None:
            self._effectiveLevel.setText("")
        else:
            self._checkLoggerEnabled.setChecked(not logger.disabled)
            self._effectiveLevel.setText(str(logger.getEffectiveLevel()))
            if logger.level:
                button = self._buttonForForLogLevel(logger.level)
                if button is not None:
                    button.setChecked(True)

    def _onLoggerEnabledClicked(self, checked: bool) -> None:
        """A logger enable/disable button was pressed.
        """
        for item in self._loggerList.selectedItems():
            logger = logging.Logger.manager.loggerDict[item.text()]
            logger.disabled = not checked
            self._decorateLoggerItem(item, logger)

    def _onLoggerLevelClicked(self, checked: bool) -> None:
        """A logger level radio button was pressed.
        """
        checked = self._levelButtonGroup.checkedButton()
        level = 0 if checked is None else self._levels[checked.text()]
        for item in self._loggerList.selectedItems():
            logger = logging.Logger.manager.loggerDict[item.text()]
            logger.setLevel(level)
            self._decorateLoggerItem(item, logger)

    def _onClearLevel(self) -> None:
        """Clear the individual log level of the current logger.
        """
        logger = None
        for item in self._loggerList.selectedItems():
            logger = logging.Logger.manager.loggerDict[item.text()]
            logger.setLevel(0)
            self._decorateLoggerItem(item, logger)
        self._updateLogger(logger)

    def _buttonForForLogLevel(self, level):
        for label, _level in self._levels.items():
            if level == _level:
                return self._radio[label]
        return None       

    def _colorForLogLevel(self, level):
        if level <= logging.DEBUG: return Qt.blue
        if level <= logging.INFO: return Qt.green
        if level <= logging.WARNING: return Qt.darkYellow
        if level <= logging.ERROR: return Qt.red
        if level <= logging.FATAL: return Qt.magenta
        return Qt.black
Example #58
0
    def _initUI(self):
        """Add the UI elements

            * The ``QLogHandler`` showing the log messages

        """
        #
        # Controls
        #
        self._log_handler = QLogHandler()
        self._log_handler._message_signal.connect(self._new_message)
        self._total = QLabel()
        self._updateLogViewButton = QPushButton("Update")
        self._updateLogViewButton.clicked.connect(self._onUpdateLogView)
        self._updateLogViewButton.setEnabled(self._loggingRecorder is not None)
        self._clearLogViewButton = QPushButton("Clear")
        self._clearLogViewButton.clicked.connect(self._onClearLogView)

        self._modules = QListWidget()

        self._checkProcess = QCheckBox("Process")
        self._checkProcess.clicked.connect(self._updateFormatter)
        self._checkThread = QCheckBox("Thread")
        self._checkThread.clicked.connect(self._updateFormatter)
        self._checkName = QCheckBox("Name")
        self._checkName.clicked.connect(self._updateFormatter)
        self._checkModule = QCheckBox("Module")
        self._checkModule.clicked.connect(self._updateFormatter)
        self._checkFile = QCheckBox("File")
        self._checkFile.clicked.connect(self._updateFormatter)
        self._checkLevel = QCheckBox("Level")
        self._checkLevel.clicked.connect(self._updateFormatter)

        self._radio = {}
        self._levelButtonGroup = QButtonGroup()
        for label in self._levels.keys():
            self._radio[label] = QRadioButton(label)
            self._radio[label].clicked.connect(self._onLoggerLevelClicked)
            self._levelButtonGroup.addButton(self._radio[label])
        self._checkLoggerEnabled = QCheckBox("enabled")
        self._checkLoggerEnabled.clicked.connect(self._onLoggerEnabledClicked)

        self._buttonLoggerClearLevel = QPushButton("Clear Level")
        self._buttonLoggerClearLevel.clicked.connect(self._onClearLevel)

        self._effectiveLevel = QLabel()


        self._loggerList = QListWidget()
        self._loggerList.setSortingEnabled(True)
        self._loggerList.currentItemChanged.connect(self._onCurrentLoggerChanged)

        self._loggerList_refresh = QPushButton("Refresh")
        self._loggerList_refresh.clicked.connect(self._updateLoggerList)

        self._rootLoggerLevel = QComboBox()
        for name, level in self._levels.items():
            self._rootLoggerLevel.addItem(name, level)
        self._rootLoggerLevel.currentIndexChanged.connect(self._onRootLevelChanged)

        self._exceptionPanel = QExceptionPanel()
        
        self._updateLoggerList()
        self._layoutComponents()
Example #59
0
	def __init__(self):
		QListWidget.__init__(self)
Example #60
0
    def _make_gui(self) -> None:
        self.setWindowTitle("Confirm file transfer")

        # Widgets
        move_icon = QLabel()
        move_icon.setPixmap(QIcon.fromTheme("stock_folder-move").pixmap(48))
        move_icon.setAlignment(Qt.AlignTop | Qt.AlignHCenter)

        header = QLabel("<big>A file transfer was requested.</big>")
        header.setTextFormat(Qt.RichText)
        subheader = QLabel(
            "Do you want to transfer the following files to the given directory?"
        )

        source_files_widget = QGroupBox("Sources:")
        source_files_list = QListWidget()
        source_files_list.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)
        for source_file in self._source_files:
            source_files_list.addItem(source_file)

        box = QVBoxLayout()
        box.addWidget(source_files_list)
        source_files_widget.setLayout(box)

        arrow_label = QLabel()
        arrow_label.setPixmap(QIcon.fromTheme("down").pixmap(24))
        arrow_label.setAlignment(Qt.AlignCenter)

        target_directory_layout = self._make_file_info(self._target_directory)
        target_directory_widget = QGroupBox("Destination:")
        target_directory_widget.setLayout(target_directory_layout)

        # Widgets.ButtonBox
        button_box = QDialogButtonBox(self)
        button_box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        btn_cancel = button_box.addButton(QDialogButtonBox.Cancel)

        btn_copy = QPushButton(QIcon.fromTheme("stock_folder-copy"),
                               "Copy Files")
        btn_move = QPushButton(QIcon.fromTheme("stock_folder-move"),
                               "Move Files")
        btn_link = QPushButton(QIcon.fromTheme("stock_folder-move"),
                               "Link Files")
        button_box.addButton(btn_move, QDialogButtonBox.AcceptRole)
        button_box.addButton(btn_copy, QDialogButtonBox.AcceptRole)
        button_box.addButton(btn_link, QDialogButtonBox.AcceptRole)
        btn_move.setDefault(True)

        # Layout
        subvbox = QVBoxLayout()
        subvbox.addWidget(header)
        subvbox.addWidget(subheader)
        subvbox.addWidget(source_files_widget)
        subvbox.addWidget(arrow_label)
        subvbox.addWidget(target_directory_widget)

        hbox = QHBoxLayout()
        hbox.addWidget(move_icon)
        hbox.addLayout(subvbox)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addWidget(button_box)
        self.setLayout(vbox)

        # Signals
        btn_copy.clicked.connect(lambda: self.done(TransferRequestDialog.Copy))
        btn_move.clicked.connect(lambda: self.done(TransferRequestDialog.Move))
        btn_link.clicked.connect(lambda: self.done(TransferRequestDialog.Link))
        btn_cancel.clicked.connect(
            lambda: self.done(TransferRequestDialog.Cancel))