Exemplo n.º 1
0
class Application(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Конфигурация показа'
        self.top = 200
        self.left = 500
        self.width = 800
        self.height = 600
        self.listOfChilds = list()
        self.dictOfSignals = dict(
        )  # словарь с сигналами в которых мы потом производим поиск
        self.resultOfSearchList = list()
        self.numberOfSignals = 0  # считаем количество сигналов когда их выбираем после поиска

        self.initUI()

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Сообщение',
                                     "Вы точно хотите выйти?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def showSystemsTree(self, event):
        if (self.treeSystems.isHidden()):
            self.treeSystems.show()
            self.labelSelected.show()

            self.searchResultTree.hide()
            self.searchLine.hide()
            self.nuberOfSelectedLabel.hide()
            self.buttonSearch.hide()
            self.embeddedSignalsCheckBox.hide()
            self.discreteSignalsCheckBox.hide()
            self.ProjectProtocolsTree.hide()
            self.countingLabel.hide()
            self.savedProtocolsTree.hide()

    def showSearchTree(self, event):
        if (self.searchResultTree.isHidden()):
            self.searchResultTree.show()
            self.searchLine.show()
            self.nuberOfSelectedLabel.show()
            self.buttonSearch.show()
            self.embeddedSignalsCheckBox.show()
            self.discreteSignalsCheckBox.show()

            self.treeSystems.hide()
            self.labelSelected.hide()
            self.ProjectProtocolsTree.hide()
            self.countingLabel.hide()
            self.savedProtocolsTree.hide()

    def showProjectProtocolsTree(self, event):
        if (self.ProjectProtocolsTree.isHidden()):
            self.ProjectProtocolsTree.show()
            self.countingLabel.show()

            self.treeSystems.hide()
            self.labelSelected.hide()
            self.searchResultTree.hide()
            self.searchLine.hide()
            self.nuberOfSelectedLabel.hide()
            self.buttonSearch.hide()
            self.embeddedSignalsCheckBox.hide()
            self.discreteSignalsCheckBox.hide()
            self.savedProtocolsTree.hide()

    def showSavedProtocolsTree(self, event):
        if (self.savedProtocolsTree.isHidden()):
            self.savedProtocolsTree.show()

            self.ProjectProtocolsTree.hide()
            self.countingLabel.hide()
            self.treeSystems.hide()
            self.labelSelected.hide()
            self.searchResultTree.hide()
            self.searchLine.hide()
            self.nuberOfSelectedLabel.hide()
            self.buttonSearch.hide()
            self.embeddedSignalsCheckBox.hide()
            self.discreteSignalsCheckBox.hide()

    def searchSignals(self):
        # ищем в slef.dictOfSignals
        string = self.searchLine.text()
        self.resultOfSearchList = []
        self.searchResultTree.clear()
        if (type(string) == str):
            if self.embeddedSignalsCheckBox.checkState(
            ) == 2:  # 2 означает что на чекбокс тыкнули, 0 - нет
                for key in self.dictOfSignals.keys():
                    if string in key:
                        row = QTreeWidgetItem(self.searchResultTree, [key])
                        self.searchResultTree.addTopLevelItem(row)
                        for record in self.dictOfSignals[key]:
                            child = QTreeWidgetItem(row, [record])
                            row.addChild(child)
                            self.resultOfSearchList.append(record)
            if self.discreteSignalsCheckBox.checkState() == 2:
                for key in self.dictOfSignals.keys():
                    for record in self.dictOfSignals[key]:
                        if string in record:
                            self.resultOfSearchList.append(record)
                            row = QTreeWidgetItem(self.searchResultTree,
                                                  [record])
                            self.searchResultTree.addTopLevelItem(row)
            if (len(self.resultOfSearchList) == 0):
                self.nuberOfSelectedLabel.setText('Не найдено')
            else:
                self.nuberOfSelectedLabel.setText('{0} выбрано из {1}'.format(
                    len(self.resultOfSearchList), self.numberOfSignals))

    def moveSelectedSignals(self):
        if self.treeSystems.isHidden():
            currentTree = self.searchResultTree
        else:
            currentTree = self.treeSystems
        for sel in currentTree.selectedIndexes():
            item = currentTree.itemFromIndex(sel)  # убираем выделение
            item.setSelected(False)

            if (not sel.child(0, 0).isValid()):  # если нет дочерних элементов
                if (sel.data()
                        not in self.listOfChilds):  # если элемент уже добавлен
                    self.listOfChilds.append(sel.data())
                    self.listSelectedSignals.addItem(sel.data())
            else:
                index = 0
                while sel.child(index,
                                0).isValid():  # проходимся по всем дочерним
                    item = currentTree.itemFromIndex(sel.child(
                        index, 0))  # убираем выделение
                    item.setSelected(False)
                    selChild = sel.child(index, 0).data()
                    if (selChild not in self.listOfChilds
                        ):  # если элемент уже добавлен
                        self.listOfChilds.append(selChild)
                        self.listSelectedSignals.addItem(selChild)
                    index += 1
        self.labelHowMuchSelected.setText('Выбрано {0} из {1}'.format(
            len(self.listOfChilds), self.numberOfSignals))

    def moveAllSelectedSignals(self):
        if self.treeSystems.isHidden():
            currentTree = self.searchResultTree
        else:
            currentTree = self.treeSystems
        for index in range(currentTree.topLevelItemCount()):
            item = currentTree.topLevelItem(index)
            for childIndex in range(item.childCount()):
                childData = item.child(childIndex).data(
                    0, 0
                )  # 0,0 потому что элемент у нас туту всего один и дочерних не имеет
                if (childData not in self.listOfChilds):
                    self.listOfChilds.append(childData)
                    self.listSelectedSignals.addItem(childData)
        self.labelHowMuchSelected.setText('Выбрано {0} из {1}'.format(
            len(self.listOfChilds), self.numberOfSignals))

    def deleteSelectedSignals(self):
        for item in self.listSelectedSignals.selectedItems():
            deletedItem = self.listSelectedSignals.takeItem(
                self.listSelectedSignals.row(item))
            self.listOfChilds.remove(deletedItem.data(0))
        self.labelHowMuchSelected.setText('Выбрано {0} из {1}'.format(
            len(self.listOfChilds), self.numberOfSignals))

    def deleteAllSelectedSignals(self):
        self.listSelectedSignals.clear()
        self.listOfChilds = []
        self.labelHowMuchSelected.setText('Выбрано 0 из {}'.format(
            self.numberOfSignals))

    def fixSelection(self, modelSelectionOfSelectedItem):
        if self.treeSystems.isHidden():
            currentTree = self.searchResultTree
        else:
            currentTree = self.treeSystems
            model = modelSelectionOfSelectedItem
        if len(modelSelectionOfSelectedItem.indexes()) > 0:
            modelIndexOfSelectedItem = modelSelectionOfSelectedItem.indexes(
            )[0]
            item = currentTree.itemFromIndex(modelIndexOfSelectedItem)
            if (item.isSelected()):
                if (modelIndexOfSelectedItem.child(0, 0).isValid()):
                    childs = item.childCount()
                    for index in range(childs):
                        childItem = currentTree.itemFromIndex(
                            modelIndexOfSelectedItem.child(index, 0))
                        childItem.setSelected(True)
        else:
            for sel in currentTree.selectedIndexes():
                item = currentTree.itemFromIndex(sel)
                flag = False
                if (item.isSelected() and item.childCount() > 0):
                    for index in range(item.childCount()):
                        childItem = currentTree.itemFromIndex(
                            sel.child(index, 0))
                        if not childItem.isSelected():
                            flag = True
                if flag:
                    item.setSelected(False)

    def countGroupsAndSignals(self, value):
        self.fixSelection(value)
        group = 0
        childs = 0
        for sel in self.treeSystems.selectedIndexes():
            if (not sel.child(0, 0).isValid()):  # нет дочерних элементов
                childs += 1
            else:
                group += 1
        self.labelSelected.setText('Выбрано: {0} групп, {1} сигналов'.format(
            group, childs))

    def initUI(self):
        # selectedTreeElemStyleSheet = '''.QStandardItem {background-color: blue}'''
        centralButtonsSS = 'max-width: 20%; padding: 6px; margin: 10px; border-radius: 5px; border: 1px solid black'
        self.setStyleSheet(
            open(os.path.join(os.path.dirname(__file__), 'style.css')).read())

        self.setWindowIcon(QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        vboxList = QVBoxLayout()
        self.labelSignalSelection = QLabel('Выбор сигнала')
        self.labelSystems = QLabel('Системы')
        self.labelSystems.mousePressEvent = self.showSystemsTree

        '-------------------------ListWidget---------------------------'
        self.treeSystems = QTreeWidget()
        self.treeSystems.setAlternatingRowColors(1)
        self.treeSystems.setHeaderHidden(1)
        self.treeSystems.setColumnCount(1)
        self.treeSystems.setSelectionMode(QAbstractItemView.MultiSelection)
        self.treeSystems.selectionModel().selectionChanged.connect(
            self.countGroupsAndSignals
        )  # это для подсчёта выбранных групп и сигналов

        kks = db.MPK.select_column('Суффикс', False, False,
                                   False)  #проеверь чтобы postgres был запущен
        kks = set(kks)
        for record in kks:
            row = QTreeWidgetItem(self.treeSystems, [record])
            self.treeSystems.addTopLevelItem(row)
            self.dictOfSignals[record] = list()
            suffics = set(db.MPK.select_column('KKS', 'Суффикс', record,
                                               False))
            for elem in suffics:
                self.dictOfSignals[record].append(elem)
                child = QTreeWidgetItem(row, [elem])
                row.addChild(child)
                self.numberOfSignals += 1
        '----------------------------ListWidget--------------------------'

        self.labelSelected = QLabel('Выбрано: 0 групп, 0 сигналов')
        self.labelSearch = QLabel('Поиск')
        self.labelSearch.mousePressEvent = self.showSearchTree

        '--------------------------HiddenSearch--------------------------------'
        self.buttonSearch = QPushButton('Искать', self)
        self.buttonSearch.clicked.connect(self.searchSignals)
        self.buttonSearch.hide()

        self.searchLine = QLineEdit(self)
        self.searchLine.hide()

        hboxSearchLayout = QHBoxLayout()
        hboxSearchLayout.addWidget(self.buttonSearch)
        hboxSearchLayout.addWidget(self.searchLine)

        self.embeddedSignalsCheckBox = QCheckBox('Упакованные сигналы', self)
        self.embeddedSignalsCheckBox.hide()
        self.discreteSignalsCheckBox = QCheckBox('Дискретные сигналы', self)
        self.discreteSignalsCheckBox.hide()

        hboxSearchParametersLayout = QHBoxLayout()
        hboxSearchParametersLayout.addWidget(self.embeddedSignalsCheckBox)
        hboxSearchParametersLayout.addWidget(self.discreteSignalsCheckBox)

        self.searchResultTree = QTreeWidget()
        self.searchResultTree.setHeaderHidden(1)
        self.searchResultTree.setColumnCount(1)
        self.searchResultTree.hide()
        self.searchResultTree.setSelectionMode(
            QAbstractItemView.MultiSelection)
        self.searchResultTree.selectionModel().selectionChanged.connect(
            self.fixSelection)

        self.nuberOfSelectedLabel = QLabel('0 выбрано из {}'.format(
            self.numberOfSignals))
        self.nuberOfSelectedLabel.hide()
        '--------------------------HiddenSearch--------------------------------'

        '--------------------------ProjectProtocols----------------------------'
        self.ProjectProtocolsTree = QTreeWidget()
        self.ProjectProtocolsTree.setHeaderHidden(1)
        self.ProjectProtocolsTree.setColumnCount(1)
        self.ProjectProtocolsTree.hide()

        self.countingLabel = QLabel('Выбрано 0 групп, 0 сигналов')
        self.countingLabel.hide()
        '--------------------------ProjectProtocols----------------------------'

        '---------------------------SavedProtocols------------------------'
        self.savedProtocolsTree = QTreeWidget()
        self.savedProtocolsTree.setHeaderHidden(1)
        self.savedProtocolsTree.setColumnCount(1)
        self.savedProtocolsTree.hide()
        '---------------------------SavedProtocols------------------------'

        self.labelProjectProtocolSignals = QLabel(
            'Сигналы проектных протоколов')
        self.labelProjectProtocolSignals.mousePressEvent = self.showProjectProtocolsTree
        self.labelStoredProtocols = QLabel('Сохраненные протоколы')
        self.labelStoredProtocols.mousePressEvent = self.showSavedProtocolsTree
        widgets = (self.labelSignalSelection, self.labelSystems,
                   self.treeSystems, self.labelSelected, self.labelSearch,
                   self.searchResultTree, self.nuberOfSelectedLabel,
                   self.labelProjectProtocolSignals, self.ProjectProtocolsTree,
                   self.countingLabel, self.labelStoredProtocols,
                   self.savedProtocolsTree)
        for widget in widgets:
            vboxList.addWidget(widget)
            if widget == self.labelSearch:
                vboxList.addLayout(hboxSearchLayout)
                vboxList.addLayout(hboxSearchParametersLayout)

        vbox4Btn = QVBoxLayout()
        self.btnRigth = QPushButton('>', self)
        self.btnRigth.setStyleSheet(centralButtonsSS)
        self.btnRigth.clicked.connect(self.moveSelectedSignals)

        self.btnLeft = QPushButton('<', self)
        self.btnLeft.setStyleSheet(centralButtonsSS)
        self.btnLeft.clicked.connect(self.deleteSelectedSignals)

        self.btnRigthAll = QPushButton('>>', self)
        self.btnRigthAll.setStyleSheet(centralButtonsSS)
        self.btnRigthAll.clicked.connect(self.moveAllSelectedSignals)

        self.btnLeftAll = QPushButton('<<', self)
        self.btnLeftAll.setStyleSheet(centralButtonsSS)
        self.btnLeftAll.clicked.connect(self.deleteAllSelectedSignals)

        widgets = (self.btnRigth, self.btnLeft, self.btnRigthAll,
                   self.btnLeftAll)
        for widget in widgets:
            vbox4Btn.addWidget(widget)

        vboxSelectedList = QVBoxLayout()
        self.labelSelectedSignals = QLabel('Выбранные сигналы')

        self.listSelectedSignals = QListWidget()
        self.listSelectedSignals.setSelectionMode(
            QAbstractItemView.MultiSelection)

        self.labelHowMuchSelected = QLabel('Выбрано 0 из {}'.format(
            self.numberOfSignals))
        widgets = (self.labelSelectedSignals, self.listSelectedSignals,
                   self.labelHowMuchSelected)
        for widget in widgets:
            vboxSelectedList.addWidget(widget)

        hboxLists = QHBoxLayout()
        layouts = (vboxList, vbox4Btn, vboxSelectedList)
        for lay in layouts:
            hboxLists.addLayout(lay)

        hboxInputLine = QHBoxLayout()
        self.labelDescription = QLabel('Описание')
        self.inputLine = QLineEdit(self)
        widgets = (self.labelDescription, self.inputLine)
        for widget in widgets:
            hboxInputLine.addWidget(widget)

        hboxBottomButtons = QHBoxLayout()
        self.buttonOK = QPushButton('OK', self)
        self.buttonCancel = QPushButton('Отмена', self)
        hboxBottomButtons.addStretch(1)
        widgets = (self.buttonOK, self.buttonCancel)
        for widget in widgets:
            hboxBottomButtons.addWidget(widget)

        mainVBox = QVBoxLayout()
        layouts = (hboxLists, hboxInputLine, hboxBottomButtons)
        for lay in layouts:
            mainVBox.addLayout(lay)

        '-------------------------Tabs-------------------------'
        self.signalsTabWrapper = QWidget()
        self.signalsTabWrapper.setLayout(mainVBox)

        self.signalsTab = QTabWidget()
        self.signalsTab.addTab(self.signalsTabWrapper, 'Сигналы для показа')
        self.signalsTab.addTab(
            QWidget(),
            'Настройка показа')  # Вместо QWidget() вставить содержимое вкладки

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.signalsTab)
        '-------------------------Tabs-------------------------'

        self.setLayout(mainLayout)
        self.show()
Exemplo n.º 2
0
class VideoFinderAddLink(AddLinkWindow):
    running_thread = None
    threadPool = {}

    def __init__(self, parent, receiver_slot, settings, video_dict={}):
        super().__init__(parent, receiver_slot, settings, video_dict)
        self.setWindowTitle(
            QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video Finder'))
        self.size_label.hide()

        # empty lists for no_audio and no_video and video_audio files
        self.no_audio_list = []
        self.no_video_list = []
        self.video_audio_list = []

        self.media_title = ''

        # add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        # extension_label
        self.extension_label = QLabel(self.link_frame)
        self.change_name_horizontalLayout.addWidget(self.extension_label)

        # Fetch Button
        self.url_submit_pushButtontton = QPushButton(self.link_frame)
        self.link_horizontalLayout.addWidget(self.url_submit_pushButtontton)

        # Status Box
        self.status_box_textEdit = QTextEdit(self.link_frame)
        self.status_box_textEdit.setMaximumHeight(150)
        self.link_verticalLayout.addWidget(self.status_box_textEdit)

        # Select format horizontal layout
        select_format_horizontalLayout = QHBoxLayout()

        # Selection Label
        select_format_label = QLabel(self.link_frame)
        select_format_horizontalLayout.addWidget(select_format_label)

        # Selection combobox
        self.media_comboBox = QComboBox(self.link_frame)
        self.media_comboBox.setMinimumWidth(200)
        select_format_horizontalLayout.addWidget(self.media_comboBox)

        # Duration label
        self.duration_label = QLabel(self.link_frame)
        select_format_horizontalLayout.addWidget(self.duration_label)

        self.format_selection_frame = QFrame(self)
        self.format_selection_frame.setLayout(select_format_horizontalLayout)
        self.link_verticalLayout.addWidget(self.format_selection_frame)

        # advanced_format_selection_checkBox
        self.advanced_format_selection_checkBox = QCheckBox(self)
        self.link_verticalLayout.addWidget(
            self.advanced_format_selection_checkBox)

        # advanced_format_selection_frame
        self.advanced_format_selection_frame = QFrame(self)
        self.link_verticalLayout.addWidget(
            self.advanced_format_selection_frame)

        advanced_format_selection_horizontalLayout = QHBoxLayout(
            self.advanced_format_selection_frame)

        # video_format_selection
        self.video_format_selection_label = QLabel(
            self.advanced_format_selection_frame)
        self.video_format_selection_comboBox = QComboBox(
            self.advanced_format_selection_frame)

        # audio_format_selection
        self.audio_format_selection_label = QLabel(
            self.advanced_format_selection_frame)
        self.audio_format_selection_comboBox = QComboBox(
            self.advanced_format_selection_frame)

        for widget in [
                self.video_format_selection_label,
                self.video_format_selection_comboBox,
                self.audio_format_selection_label,
                self.audio_format_selection_comboBox
        ]:
            advanced_format_selection_horizontalLayout.addWidget(widget)

        # Set Texts
        self.url_submit_pushButtontton.setText(
            QCoreApplication.translate("ytaddlink_src_ui_tr",
                                       'Fetch Media List'))
        select_format_label.setText(
            QCoreApplication.translate("ytaddlink_src_ui_tr",
                                       'Select a format'))

        self.video_format_selection_label.setText(
            QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video format:'))
        self.audio_format_selection_label.setText(
            QCoreApplication.translate("ytaddlink_src_ui_tr", 'Audio format:'))

        self.advanced_format_selection_checkBox.setText(
            QCoreApplication.translate("ytaddlink_src_ui_tr",
                                       'Advanced options'))

        # Add Slot Connections
        self.url_submit_pushButtontton.setEnabled(False)
        self.change_name_lineEdit.setEnabled(False)
        self.ok_pushButton.setEnabled(False)
        self.download_later_pushButton.setEnabled(False)

        self.format_selection_frame.setEnabled(True)
        self.advanced_format_selection_frame.setEnabled(False)
        self.advanced_format_selection_checkBox.toggled.connect(
            self.advancedFormatFrame)

        self.url_submit_pushButtontton.clicked.connect(self.submitClicked)

        self.media_comboBox.activated.connect(
            partial(self.mediaSelectionChanged, 'video_audio'))

        self.video_format_selection_comboBox.activated.connect(
            partial(self.mediaSelectionChanged, 'video'))

        self.audio_format_selection_comboBox.activated.connect(
            partial(self.mediaSelectionChanged, 'audio'))

        self.link_lineEdit.textChanged.disconnect(
            super().linkLineChanged)  # Should be disconnected.
        self.link_lineEdit.textChanged.connect(self.linkLineChangedHere)

        self.setMinimumSize(650, 480)

        self.status_box_textEdit.hide()
        self.format_selection_frame.hide()
        self.advanced_format_selection_frame.hide()
        self.advanced_format_selection_checkBox.hide()

        if 'link' in video_dict.keys() and video_dict['link']:
            self.link_lineEdit.setText(video_dict['link'])
            self.url_submit_pushButtontton.setEnabled(True)
        else:
            # check clipboard
            clipboard = QApplication.clipboard()
            text = clipboard.text()
            if (("tp:/" in text[2:6]) or ("tps:/" in text[2:7])):
                self.link_lineEdit.setText(str(text))

            self.url_submit_pushButtontton.setEnabled(True)

    def advancedFormatFrame(self, button):
        if self.advanced_format_selection_checkBox.isChecked():

            self.advanced_format_selection_frame.setEnabled(True)
            self.format_selection_frame.setEnabled(False)
            self.mediaSelectionChanged(
                'video',
                int(self.video_format_selection_comboBox.currentIndex()))

        else:
            self.advanced_format_selection_frame.setEnabled(False)
            self.format_selection_frame.setEnabled(True)
            self.mediaSelectionChanged('video_audio',
                                       int(self.media_comboBox.currentIndex()))

    def getReadableSize(self, size):
        try:
            return '{:1.2f} MB'.format(int(size) / 1048576)
        except:
            return str(size)

    def getReadableDuration(self, seconds):
        try:
            seconds = int(seconds)
            hours = seconds // 3600
            seconds = seconds % 3600
            minutes = seconds // 60
            seconds = seconds % 60
            return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
        except:
            return str(seconds)

    # Define native slots

    def urlChanged(self, value):
        if ' ' in value or value == '':
            self.url_submit_pushButtontton.setEnabled(False)
            self.url_submit_pushButtontton.setToolTip(
                QCoreApplication.translate("ytaddlink_src_ui_tr",
                                           'Please enter a valid video link'))
        else:
            self.url_submit_pushButtontton.setEnabled(True)
            self.url_submit_pushButtontton.setToolTip('')

    def submitClicked(self, button=None):
        # Clear media list
        self.media_comboBox.clear()
        self.format_selection_frame.hide()
        self.advanced_format_selection_checkBox.hide()
        self.advanced_format_selection_frame.hide()
        self.video_format_selection_comboBox.clear()
        self.audio_format_selection_comboBox.clear()
        self.change_name_lineEdit.clear()
        self.threadPool.clear()
        self.change_name_checkBox.setChecked(False)
        self.video_audio_list.clear()
        self.no_video_list.clear()
        self.no_audio_list.clear()
        self.url_submit_pushButtontton.setEnabled(False)
        self.status_box_textEdit.setText(
            QCoreApplication.translate("ytaddlink_src_ui_tr",
                                       'Fetching Media Info...'))
        self.status_box_textEdit.show()
        self.ok_pushButton.setEnabled(False)
        self.download_later_pushButton.setEnabled(False)

        dictionary_to_send = deepcopy(self.plugin_add_link_dictionary)
        # More options
        more_options = self.collectMoreOptions()
        for k in more_options.keys():
            dictionary_to_send[k] = more_options[k]
        dictionary_to_send['link'] = self.link_lineEdit.text()

        fetcher_thread = MediaListFetcherThread(self.fetchedResult,
                                                dictionary_to_send, self)
        self.parent.threadPool.append(fetcher_thread)
        self.parent.threadPool[len(self.parent.threadPool) - 1].start()

    def fileNameChanged(self, value):
        if value.strip() == '':
            self.ok_pushButton.setEnabled(False)

    def mediaSelectionChanged(self, combobox, index):
        try:
            if combobox == 'video_audio':
                if self.media_comboBox.currentText() == 'Best quality':
                    self.change_name_lineEdit.setText(self.media_title)
                    self.extension_label.setText('.' +
                                                 self.no_audio_list[-1]['ext'])

                else:
                    self.change_name_lineEdit.setText(self.media_title)
                    self.extension_label.setText(
                        '.' + self.video_audio_list[index]['ext'])

                self.change_name_checkBox.setChecked(True)

            elif combobox == 'video':
                if self.video_format_selection_comboBox.currentText(
                ) != 'No video':
                    self.change_name_lineEdit.setText(self.media_title)
                    self.extension_label.setText('.' +
                                                 self.no_audio_list[index -
                                                                    1]['ext'])
                    self.change_name_checkBox.setChecked(True)

                else:

                    if self.audio_format_selection_comboBox.currentText(
                    ) != 'No audio':
                        self.change_name_lineEdit.setText(self.media_title)
                        self.extension_label.setText('.' + self.no_video_list[
                            int(self.audio_format_selection_comboBox.
                                currentIndex()) - 1]['ext'])

                        self.change_name_checkBox.setChecked(True)
                    else:
                        self.change_name_lineEdit.setChecked(False)

            elif combobox == 'audio':
                if self.audio_format_selection_comboBox.currentText(
                ) != 'No audio' and self.video_format_selection_comboBox.currentText(
                ) == 'No video':
                    self.change_name_lineEdit.setText(self.media_title)
                    self.extension_label.setText('.' +
                                                 self.no_video_list[index -
                                                                    1]['ext'])

                    self.change_name_checkBox.setChecked(True)

                elif (self.audio_format_selection_comboBox.currentText()
                      == 'No audio'
                      and self.video_format_selection_comboBox.currentText() !=
                      'No video') or (
                          self.audio_format_selection_comboBox.currentText() !=
                          'No audio' and
                          self.video_format_selection_comboBox.currentText() !=
                          'No video'):
                    self.change_name_lineEdit.setText(self.media_title)
                    self.extension_label.setText('.' + self.no_audio_list[
                        int(self.video_format_selection_comboBox.currentIndex(
                        )) - 1]['ext'])

                    self.change_name_checkBox.setChecked(True)

                elif self.audio_format_selection_comboBox.currentText(
                ) == 'No audio' and self.video_format_selection_comboBox.currentText(
                ) == 'No video':
                    self.change_name_checkBox.setChecked(False)

        except Exception as ex:
            logger.sendToLog(ex, "ERROR")

    def fetchedResult(self, media_dict):

        self.url_submit_pushButtontton.setEnabled(True)
        if 'error' in media_dict.keys():

            self.status_box_textEdit.setText('<font color="#f11">' +
                                             str(media_dict['error']) +
                                             '</font>')
            self.status_box_textEdit.show()
        else:  # Show the media list

            # add no audio and no video options to the comboboxes
            self.video_format_selection_comboBox.addItem('No video')
            self.audio_format_selection_comboBox.addItem('No audio')

            self.media_title = media_dict['title']
            if 'formats' not in media_dict.keys(
            ) and 'entries' in media_dict.keys():
                formats = media_dict['entries']
                formats = formats[0]
                media_dict['formats'] = formats['formats']
            elif 'formats' not in media_dict.keys(
            ) and 'format' in media_dict.keys():
                media_dict['formats'] = [media_dict.copy()]

            try:
                i = 0
                for f in media_dict['formats']:
                    no_audio = False
                    no_video = False
                    text = ''
                    if 'acodec' in f.keys():
                        # only video, no audio
                        if f['acodec'] == 'none':
                            no_audio = True

                        # resolution
                        if 'height' in f.keys():
                            text = text + ' ' + '{}p'.format(f['height'])

                    if 'vcodec' in f.keys():
                        #                         if f['vcodec'] == 'none' and f['acodec'] != 'none':
                        #                             continue

                        # No video, show audio bit rate
                        if f['vcodec'] == 'none':
                            text = text + '{}kbps'.format(f['abr'])
                            no_video = True

                    if 'ext' in f.keys():
                        text = text + ' ' + '.{}'.format(f['ext'])

                    if 'filesize' in f.keys() and f['filesize']:
                        # Youtube api does not supply file size for some formats, so check it.
                        text = text + ' ' + '{}'.format(
                            self.getReadableSize(f['filesize']))

                    else:  # Start spider to find file size
                        input_dict = deepcopy(self.plugin_add_link_dictionary)

                        input_dict['link'] = f['url']
                        more_options = self.collectMoreOptions()

                        for key in more_options.keys():
                            input_dict[key] = more_options[key]

                        size_fetcher = FileSizeFetcherThread(input_dict, i)
                        self.threadPool[str(i)] = {
                            'thread': size_fetcher,
                            'item_id': i
                        }
                        self.parent.threadPool.append(size_fetcher)
                        self.parent.threadPool[len(self.parent.threadPool) -
                                               1].start()
                        self.parent.threadPool[len(self.parent.threadPool) -
                                               1].FOUND.connect(
                                                   self.findFileSize)

                    # Add current format to the related comboboxes
                    if no_audio:
                        self.no_audio_list.append(f)
                        self.video_format_selection_comboBox.addItem(text)

                    elif no_video:
                        self.no_video_list.append(f)
                        self.audio_format_selection_comboBox.addItem(text)

                    else:
                        self.video_audio_list.append(f)
                        self.media_comboBox.addItem(text)

                    i = i + 1

                self.status_box_textEdit.hide()

                if 'duration' in media_dict.keys():
                    self.duration_label.setText(
                        'Duration ' +
                        self.getReadableDuration(media_dict['duration']))

                self.format_selection_frame.show()
                self.advanced_format_selection_checkBox.show()
                self.advanced_format_selection_frame.show()
                self.ok_pushButton.setEnabled(True)
                self.download_later_pushButton.setEnabled(True)

                # if we have no options for seperate audio and video, then hide advanced_format_selection...
                if len(self.no_audio_list) == 0 and len(
                        self.no_video_list) == 0:
                    self.advanced_format_selection_checkBox.hide()
                    self.advanced_format_selection_frame.hide()

                # set index of comboboxes on best available quality.
                if len(self.no_audio_list) != 0 and len(
                        self.no_video_list) != 0:
                    self.media_comboBox.addItem('Best quality')
                    self.media_comboBox.setCurrentIndex(
                        len(self.video_audio_list))
                elif len(self.video_audio_list) != 0:
                    self.media_comboBox.setCurrentIndex(
                        len(self.video_audio_list) - 1)

                if len(self.no_audio_list) != 0:
                    self.video_format_selection_comboBox.setCurrentIndex(
                        len(self.no_audio_list))

                if len(self.no_video_list) != 0:
                    self.audio_format_selection_comboBox.setCurrentIndex(
                        len(self.no_video_list))

                self.mediaSelectionChanged(
                    'video_audio', int(self.media_comboBox.currentIndex()))

            except Exception as ex:
                logger.sendToLog(ex, "ERROR")

    def findFileSize(self, result):
        try:
            item_id = self.threadPool[str(result['thread_key'])]['item_id']
            if result['file_size'] and result['file_size'] != '0':
                text = self.media_comboBox.itemText(item_id)
                self.media_comboBox.setItemText(
                    item_id, '{} - {}'.format(text, result['file_size']))
        except Exception as ex:
            logger.sendToLog(ex, "ERROR")

    def linkLineChangedHere(self, lineEdit):
        if str(lineEdit) == '':
            self.url_submit_pushButtontton.setEnabled(False)
        else:
            self.url_submit_pushButtontton.setEnabled(True)

    # This method collects additional information like proxy ip, user, password etc.
    def collectMoreOptions(self):
        options = {
            'ip': None,
            'port': None,
            'proxy_user': None,
            'proxy_passwd': None,
            'download_user': None,
            'download_passwd': None
        }
        if self.proxy_checkBox.isChecked():
            options['ip'] = self.ip_lineEdit.text()
            options['port'] = self.port_spinBox.value()
            options['proxy_user'] = self.proxy_user_lineEdit.text()
            options['proxy_passwd'] = self.proxy_pass_lineEdit.text()
        if self.download_checkBox.isChecked():
            options['download_user'] = self.download_user_lineEdit.text()
            options['download_passwd'] = self.download_pass_lineEdit.text()

        # These info (keys) are required for spider to find file size, because spider() does not check if key exists.
        additional_info = [
            'header', 'load_cookies', 'user_agent', 'referer', 'out'
        ]
        for i in additional_info:
            if i not in self.plugin_add_link_dictionary.keys():
                options[i] = None
        return options

    # user commited information by pressing ok_pushButton, so get information
    # from VideoFinderAddLink window and return them to the mainwindow with callback!
    def okButtonPressed(self, button, download_later):

        link_list = []
        # seperate audio format and video format is selected.
        if self.advanced_format_selection_checkBox.isChecked():

            if self.video_format_selection_comboBox.currentText(
            ) == 'No video' and self.audio_format_selection_comboBox.currentText(
            ) != 'No audio':

                # only audio link must be added to the link_list
                audio_link = self.no_video_list[
                    self.audio_format_selection_comboBox.currentIndex() -
                    1]['url']
                link_list.append(audio_link)

            elif self.video_format_selection_comboBox.currentText(
            ) != 'No video' and self.audio_format_selection_comboBox.currentText(
            ) == 'No audio':

                # only video link must be added to the link_list
                video_link = self.no_audio_list[
                    self.video_format_selection_comboBox.currentIndex() -
                    1]['url']
                link_list.append(video_link)

            elif self.video_format_selection_comboBox.currentText(
            ) != 'No video' and self.audio_format_selection_comboBox.currentText(
            ) != 'No audio':

                # video and audio links must be added to the link_list
                audio_link = self.no_video_list[
                    self.audio_format_selection_comboBox.currentIndex() -
                    1]['url']
                video_link = self.no_audio_list[
                    self.video_format_selection_comboBox.currentIndex() -
                    1]['url']
                link_list = [video_link, audio_link]

            elif self.video_format_selection_comboBox.currentText(
            ) == 'No video' and self.audio_format_selection_comboBox.currentText(
            ) == 'No audio':

                # no video and no video selected! REALY?!. user is DRUNK! close the window! :))
                self.close()
        else:
            if self.media_comboBox.currentText() == 'Best quality':

                # the last item in no_video_list and no_audio_list are the best.
                audio_link = self.no_video_list[-1]['url']
                video_link = self.no_audio_list[-1]['url']
                link_list = [video_link, audio_link]
            else:
                audio_and_video_link = self.video_audio_list[
                    self.media_comboBox.currentIndex()]['url']
                link_list.append(audio_and_video_link)

        # write user's new inputs in persepolis_setting for next time :)
        self.persepolis_setting.setValue('add_link_initialization/ip',
                                         self.ip_lineEdit.text())
        self.persepolis_setting.setValue('add_link_initialization/port',
                                         self.port_spinBox.value())
        self.persepolis_setting.setValue('add_link_initialization/proxy_user',
                                         self.proxy_user_lineEdit.text())
        self.persepolis_setting.setValue(
            'add_link_initialization/download_user',
            self.download_user_lineEdit.text())

        # get proxy information
        if not (self.proxy_checkBox.isChecked()):
            ip = None
            port = None
            proxy_user = None
            proxy_passwd = None
        else:
            ip = self.ip_lineEdit.text()
            if not (ip):
                ip = None
            port = self.port_spinBox.value()
            if not (port):
                port = None
            proxy_user = self.proxy_user_lineEdit.text()
            if not (proxy_user):
                proxy_user = None
            proxy_passwd = self.proxy_pass_lineEdit.text()
            if not (proxy_passwd):
                proxy_passwd = None

        # get download username and password information
        if not (self.download_checkBox.isChecked()):
            download_user = None
            download_passwd = None
        else:
            download_user = self.download_user_lineEdit.text()
            if not (download_user):
                download_user = None
            download_passwd = self.download_pass_lineEdit.text()
            if not (download_passwd):
                download_passwd = None

        # check that if user limits download speed.
        if not (self.limit_checkBox.isChecked()):
            limit = 0
        else:
            if self.limit_comboBox.currentText() == "KiB/s":
                limit = str(self.limit_spinBox.value()) + str("K")
            else:
                limit = str(self.limit_spinBox.value()) + str("M")

        # get start time for download if user set that.
        if not (self.start_checkBox.isChecked()):
            start_time = None
        else:
            start_time = self.start_time_qDataTimeEdit.text()

        # get end time for download if user set that.
        if not (self.end_checkBox.isChecked()):
            end_time = None
        else:
            end_time = self.end_time_qDateTimeEdit.text()

        # set name for file(s)
        if self.change_name_checkBox.isChecked():
            name = str(self.change_name_lineEdit.text())
            if name == '':
                name = 'video_finder_file'
        else:
            name = 'video_finder_file'

        # video finder always finds extension
        # but if it can't find file extension
        # use mp4 for extension.
        if str(self.extension_label.text()) == '':
            extension = '.mp4'
        else:
            extension = str(self.extension_label.text())

        # did user select seperate audio and video?
        if len(link_list) == 2:
            video_name = name + extension
            audio_name = name + '.' + \
                str(self.no_video_list[self.audio_format_selection_comboBox.currentIndex() - 1]['ext'])

            name_list = [video_name, audio_name]
        else:
            name_list = [name + extension]

        # get number of connections
        connections = self.connections_spinBox.value()

        # get download_path
        download_path = self.download_folder_lineEdit.text()

        # referer
        if self.referer_lineEdit.text() != '':
            referer = self.referer_lineEdit.text()
        else:
            referer = None

        # header
        if self.header_lineEdit.text() != '':
            header = self.header_lineEdit.text()
        else:
            header = None

        # user_agent
        if self.user_agent_lineEdit.text() != '':
            user_agent = self.user_agent_lineEdit.text()
        else:
            user_agent = None

        # load_cookies
        if self.load_cookies_lineEdit.text() != '':
            load_cookies = self.load_cookies_lineEdit.text()
        else:
            load_cookies = None

        add_link_dictionary_list = []
        if len(link_list) == 1:
            # save information in a dictionary(add_link_dictionary).
            add_link_dictionary = {
                'referer': referer,
                'header': header,
                'user_agent': user_agent,
                'load_cookies': load_cookies,
                'out': name_list[0],
                'start_time': start_time,
                'end_time': end_time,
                'link': link_list[0],
                'ip': ip,
                'port': port,
                'proxy_user': proxy_user,
                'proxy_passwd': proxy_passwd,
                'download_user': download_user,
                'download_passwd': download_passwd,
                'connections': connections,
                'limit_value': limit,
                'download_path': download_path
            }

            add_link_dictionary_list.append(add_link_dictionary)

        else:
            video_add_link_dictionary = {
                'referer': referer,
                'header': header,
                'user_agent': user_agent,
                'load_cookies': load_cookies,
                'out': name_list[0],
                'start_time': start_time,
                'end_time': end_time,
                'link': link_list[0],
                'ip': ip,
                'port': port,
                'proxy_user': proxy_user,
                'proxy_passwd': proxy_passwd,
                'download_user': download_user,
                'download_passwd': download_passwd,
                'connections': connections,
                'limit_value': limit,
                'download_path': download_path
            }

            audio_add_link_dictionary = {
                'referer': referer,
                'header': header,
                'user_agent': user_agent,
                'load_cookies': load_cookies,
                'out': name_list[1],
                'start_time': None,
                'end_time': end_time,
                'link': link_list[1],
                'ip': ip,
                'port': port,
                'proxy_user': proxy_user,
                'proxy_passwd': proxy_passwd,
                'download_user': download_user,
                'download_passwd': download_passwd,
                'connections': connections,
                'limit_value': limit,
                'download_path': download_path
            }

            add_link_dictionary_list = [
                video_add_link_dictionary, audio_add_link_dictionary
            ]

        # get category of download
        category = str(self.add_queue_comboBox.currentText())

        del self.plugin_add_link_dictionary

        # return information to mainwindow
        self.callback(add_link_dictionary_list, download_later, category)

        # close window
        self.close()
Exemplo n.º 3
0
class Dialog(QDialog):
    MESSAGE = "<p>Message boxes have a caption, a text, and up to three " \
            "buttons, each with standard or custom texts.</p>" \
            "<p>Click a button to close the message box. Pressing the Esc " \
            "button will activate the detected escape button (if any).</p>"

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.openFilesPath = ''

        self.errorMessageDialog = QErrorMessage(self)

        frameStyle = QFrame.Sunken | QFrame.Panel

        self.issueLabel = QLabel()
        self.issueLabel.setFrameStyle(frameStyle)
        self.issueLabel = QLabel("Insert Issue id", self)

        self.issueText = QLineEdit()

        self.issueText = QLineEdit(self)

        self.openFileNameLabel = QLabel()
        self.openFileNameLabel.setFrameStyle(frameStyle)
        self.openFileNameButton = QPushButton("Browse File")

        self.newReqLabel = QLabel()
        self.newReqLabel.setFrameStyle(frameStyle)
        self.newReqLabel = QLabel("Insert Requirement", self)

        self.newReqText = QPlainTextEdit()
        self.newReqText.setFrameStyle(frameStyle)
        self.newReqText = QPlainTextEdit(self)

        self.addTable = QVBoxLayout()

        self.resultViewButton = QPushButton("View Result")

        self.vizViewButton = QPushButton("View Visualizer")

        self.web = QWebEngineView()

        self.openFileNameButton.clicked.connect(self.setOpenFileName)

        self.resultViewButton.clicked.connect(self.setLabelResult)

        self.vizViewButton.clicked.connect(self.open_webbrowser)

        self.headline = QFont("Arial", 14, QFont.Bold)

        self.Issueidlabel = QLabel()
        self.Issueidlabel.setFrameStyle(frameStyle)
        self.Issueidlabel = QLabel("IssueID", self)
        self.Issueidlabel.setFont(self.headline)

        self.similaritylabel = QLabel()
        self.similaritylabel.setFrameStyle(frameStyle)
        self.similaritylabel = QLabel("Similarity", self)
        self.similaritylabel.setFont(self.headline)

        self.Requirementlabel = QLabel()
        self.Requirementlabel.setFrameStyle(frameStyle)
        self.Requirementlabel = QLabel("Requirement", self)
        self.Requirementlabel.setFont(self.headline)

        self.label1 = QLabel()
        self.label1.setFrameStyle(frameStyle)
        self.label1 = QLabel("", self)

        self.label2 = QLabel()
        self.label2.setFrameStyle(frameStyle)
        self.label2 = QLabel("", self)

        self.label3 = QLabel()
        self.label3.setFrameStyle(frameStyle)
        self.label3 = QLabel("", self)

        self.label4 = QLabel()
        self.label4.setFrameStyle(frameStyle)
        self.label4 = QLabel("", self)

        self.label5 = QLabel()
        self.label5.setFrameStyle(frameStyle)
        self.label5 = QLabel("", self)

        self.label6 = QLabel()
        self.label6.setFrameStyle(frameStyle)
        self.label6 = QLabel("", self)

        self.label7 = QLabel()
        self.label7.setFrameStyle(frameStyle)
        self.label7 = QLabel("", self)

        self.label8 = QLabel()
        self.label8.setFrameStyle(frameStyle)
        self.label8 = QLabel("", self)

        self.label9 = QLabel()
        self.label9.setFrameStyle(frameStyle)
        self.label9 = QLabel("", self)

        self.label10 = QLabel()
        self.label10.setFrameStyle(frameStyle)
        self.label10 = QLabel("", self)

        self.label11 = QLabel()
        self.label11.setFrameStyle(frameStyle)
        self.label11 = QLabel("", self)

        self.label12 = QLabel()
        self.label12.setFrameStyle(frameStyle)
        self.label12 = QLabel("", self)

        self.label13 = QLabel()
        self.label13.setFrameStyle(frameStyle)
        self.label13 = QLabel("", self)

        self.label14 = QLabel()
        self.label14.setFrameStyle(frameStyle)
        self.label14 = QLabel("", self)

        self.label15 = QLabel()
        self.label15.setFrameStyle(frameStyle)
        self.label15 = QLabel("", self)

        self.native = QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)

        layout.addWidget(self.openFileNameButton, 6, 0)
        layout.addWidget(self.openFileNameLabel, 6, 1)

        layout.addWidget(self.issueLabel, 7, 0)
        layout.addWidget(self.issueText, 7, 1)

        layout.addWidget(self.web, 8, 1)
        layout.addWidget(self.newReqLabel, 9, 0)

        layout.addWidget(self.newReqText, 9, 1)

        layout.addWidget(self.resultViewButton, 11, 0)

        layout.addWidget(self.Issueidlabel, 15, 0)
        layout.addWidget(self.similaritylabel, 15, 1)
        layout.addWidget(self.Requirementlabel, 15, 2)

        layout.addWidget(self.label1, 16, 0)
        layout.addWidget(self.label2, 16, 1)
        layout.addWidget(self.label3, 16, 2)

        layout.addWidget(self.label4, 17, 0)
        layout.addWidget(self.label5, 17, 1)
        layout.addWidget(self.label6, 17, 2)

        layout.addWidget(self.label7, 18, 0)
        layout.addWidget(self.label8, 18, 1)
        layout.addWidget(self.label9, 18, 2)

        layout.addWidget(self.label10, 19, 0)
        layout.addWidget(self.label11, 19, 1)
        layout.addWidget(self.label12, 19, 2)

        layout.addWidget(self.label13, 20, 0)
        layout.addWidget(self.label14, 20, 1)
        layout.addWidget(self.label15, 20, 2)

        layout.addWidget(self.vizViewButton, 25, 0)

        width = 1000

        # setting  the fixed width of window
        self.setFixedWidth(width)

        self.setLayout(layout)

        self.setWindowTitle("Change Impact Analysis")

    def initUI(self):

        self.createTable()

        # Add box layout, add table to box layout and add box layout to widget
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.tableWidget)
        self.setLayout(self.layout)

        # Show widget
        self.show()

    def setExistingDirectory(self):
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        directory = QFileDialog.getExistingDirectory(
            self,
            "QFileDialog.getExistingDirectory()",
            self.directoryLabel.text(),
            options=options)
        if directory:
            self.directoryLabel.setText(directory)

    def setOpenFileName(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            self.openFileNameLabel.text(),
            "All Files (*);;Text Files (*.txt)",
            options=options)
        if fileName:
            self.openFileNameLabel.setText(fileName)

    def setLabelResult(self):
        issueid = self.issueText.text()

        reqtext = self.newReqText.toPlainText()

        filename = self.openFileNameLabel.text()

        pr.append(issueid, reqtext, filename)

        if not os.path.exists('docx'):
            os.makedirs('docx')

        if not os.path.exists('txt'):
            os.makedirs('txt')

        if not os.path.exists('candidates'):
            os.makedirs('candidates')

        path = "docx/"
        pr.csvToDocx(filename)
        pr.convertDocxToText(path)
        filenames = os.listdir('./txt')
        pr.docToVec(filenames)
        cia_model = "sl_doc2vec.model"
        pr.vecToCsv(cia_model)
        result1 = pr.similarDocs(cia_model)

        # model_test = "clustering_model2.pkl"
        # vecs = "vecs.csv"

        # txt_folder = "txt/"
        # candidates_fld = 'candidates/'

        # result2 = pr.cluster(model_test, filename, vecs, txt_folder, candidates_fld)

        tableValues1 = []
        tableValues2 = []

        for i in result1[0]:
            tableValues1.append(result1[1][i[0]])
            tableValues2.append(str(i[1]))
        print("successfully finished!")

        df = pd.read_csv("new_input.csv")

        content = []

        for f in df['Issue_key'].values:
            for i in tableValues1:
                if i in df['Issue_key'].values:
                    content.append(df.loc[df['Issue_key'] == i, 'Requirement'])

        from string import digits

        res = ''.join(filter(lambda x: not x.isdigit(), content[0]))
        self.label3.setText(res)

        self.label3.adjustSize()
        self.label3.setWordWrap(True)

        res2 = ''.join(filter(lambda x: not x.isdigit(), content[1]))
        self.label6.setText(res2)
        self.label6.adjustSize()
        self.label6.setWordWrap(True)

        res3 = ''.join(filter(lambda x: not x.isdigit(), content[2]))
        self.label9.setText(res3)
        self.label9.setWordWrap(True)
        res4 = ''.join(filter(lambda x: not x.isdigit(), content[3]))
        self.label12.setText(res4)
        self.label12.setWordWrap(True)

        res5 = ''.join(filter(lambda x: not x.isdigit(), content[4]))
        self.label15.setText(res5)
        self.label15.setWordWrap(True)

        self.label1.setText(tableValues1[0])
        self.label2.setText(tableValues2[0])

        self.label4.setText(tableValues1[1])
        self.label5.setText(tableValues2[1])

        self.label7.setText(tableValues1[2])
        self.label8.setText(tableValues2[2])

        self.label10.setText(tableValues1[3])
        self.label11.setText(tableValues2[3])

        self.label13.setText(tableValues1[4])
        self.label14.setText(tableValues2[4])

        fig = go.Figure(data=[
            go.Table(columnorder=[1, 2, 3],
                     columnwidth=[80, 80, 400],
                     header=dict(values=[['<b>IssueId</b><br>'],
                                         ['<b>Similarity</b>'],
                                         ['<b>Requirement</b>']],
                                 line_color='darkslategray',
                                 fill_color='royalblue',
                                 align=['left', 'center'],
                                 font=dict(color='white', size=12),
                                 height=40))
        ])

    def createTable(self):
        # Create table
        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setItem(0, 0, QTableWidgetItem("Cell (1,1)"))
        self.tableWidget.setItem(0, 1, QTableWidgetItem("Cell (1,2)"))
        self.tableWidget.setItem(1, 0, QTableWidgetItem("Cell (2,1)"))
        self.tableWidget.setItem(1, 1, QTableWidgetItem("Cell (2,2)"))
        self.tableWidget.setItem(2, 0, QTableWidgetItem("Cell (3,1)"))
        self.tableWidget.setItem(2, 1, QTableWidgetItem("Cell (3,2)"))
        self.tableWidget.setItem(3, 0, QTableWidgetItem("Cell (4,1)"))
        self.tableWidget.setItem(3, 1, QTableWidgetItem("Cell (4,2)"))
        self.tableWidget.move(55, 70)

        # table selection change
        self.tableWidget.doubleClicked.connect(self.on_click)

    def open_webbrowser(self):
        webbrowser.open(
            'http://projector.tensorflow.org/?config=https://raw.githubusercontent.com/Bitseat/embeddings_projector/master/req_plot_config.json'
        )


#btn.clicked.connect(open_webbrowser)

    @pyqtSlot()
    def on_click(self):
        print("\n")
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            print(currentQTableWidgetItem.row(),
                  currentQTableWidgetItem.column(),
                  currentQTableWidgetItem.text())
Exemplo n.º 4
0
class Application(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Конфигурация показа'
        self.top = 200
        self.left = 500
        self.width = 800
        self.height = 600
        self.listOfChilds = list()
        self.dictOfSignals = dict() # словарь с сигналами в которых мы потом производим поиск
        self.resultOfSearchList = list()
        self.numberOfSignals = 0 # считаем количество сигналов когда их выбираем после поиска

        self.initUI()

    def showSystemsTree(self, event):
        if (self.treeSystems.isHidden()):
            self.treeSystems.show()
            self.labelSelected.show()

            self.searchResultTree.hide()
            self.searchLine.hide()
            self.nuberOfSelectedLabel.hide()
            self.buttonSearch.hide()
            self.embeddedSignalsCheckBox.hide()
            self.discreteSignalsCheckBox.hide()
            self.ProjectProtocolsTree.hide()
            self.countingLabel.hide()
            self.savedProtocolsTree.hide()

    def showSearchTree(self, event):
        if (self.searchResultTree.isHidden()):
            self.searchResultTree.show()
            self.searchLine.show()
            self.nuberOfSelectedLabel.show()
            self.buttonSearch.show()
            self.embeddedSignalsCheckBox.show()
            self.discreteSignalsCheckBox.show()

            self.treeSystems.hide()
            self.labelSelected.hide()
            self.ProjectProtocolsTree.hide()
            self.countingLabel.hide()
            self.savedProtocolsTree.hide()

    def showProjectProtocolsTree(self, event):
        if (self.ProjectProtocolsTree.isHidden()):
            self.ProjectProtocolsTree.show()
            self.countingLabel.show()

            self.treeSystems.hide()
            self.labelSelected.hide()
            self.searchResultTree.hide()
            self.searchLine.hide()
            self.nuberOfSelectedLabel.hide()
            self.buttonSearch.hide()
            self.embeddedSignalsCheckBox.hide()
            self.discreteSignalsCheckBox.hide()
            self.savedProtocolsTree.hide()

    def showSavedProtocolsTree(self,event):
        if (self.savedProtocolsTree.isHidden()):
            self.savedProtocolsTree.show()

            self.ProjectProtocolsTree.hide()
            self.countingLabel.hide()
            self.treeSystems.hide()
            self.labelSelected.hide()
            self.searchResultTree.hide()
            self.searchLine.hide()
            self.nuberOfSelectedLabel.hide()
            self.buttonSearch.hide()
            self.embeddedSignalsCheckBox.hide()
            self.discreteSignalsCheckBox.hide()

    def searchSignals(self):
        # ищем в slef.dictOfSignals
        string = self.searchLine.text()
        self.resultOfSearchList = []
        self.searchResultTree.clear()
        if (type(string) == str):
            if self.embeddedSignalsCheckBox.checkState() == 2: # 2 означает что на чекбокс тыкнули, 0 - нет
                for key in self.dictOfSignals.keys():
                    if string in key:
                        row = QTreeWidgetItem(self.searchResultTree, [key])
                        self.searchResultTree.addTopLevelItem(row)
                        for record in self.dictOfSignals[key]:
                            child = QTreeWidgetItem(row, [record])
                            row.addChild(child)
                            self.resultOfSearchList.append(record)   
            if self.discreteSignalsCheckBox.checkState() == 2:
                for key in self.dictOfSignals.keys():
                    for record in self.dictOfSignals[key]:
                        if string in record:
                            self.resultOfSearchList.append(record)
                            row = QTreeWidgetItem(self.searchResultTree, [record])
                            self.searchResultTree.addTopLevelItem(row)
            if (len(self.resultOfSearchList) == 0):
                self.nuberOfSelectedLabel.setText('Не найдено')
            else:
                self.nuberOfSelectedLabel.setText('{0} выбрано из {1}'.format(len(self.resultOfSearchList), self.numberOfSignals))

    def moveSelectedSignals(self):
        if self.treeSystems.isHidden():
            currentTree = self.searchResultTree
        else:
            currentTree = self.treeSystems
        for sel in currentTree.selectedIndexes():
            item = currentTree.itemFromIndex(sel) # убираем выделение
            item.setSelected(False)

            if (not sel.child(0,0).isValid()): # если нет дочерних элементов
                if (sel.data() not in self.listOfChilds): # если элемент уже добавлен
                    self.listOfChilds.append(sel.data())
                    self.listSelectedSignals.addItem(sel.data())
            else:
                index = 0
                while sel.child(index,0).isValid(): # проходимся по всем дочерним
                    item = currentTree.itemFromIndex(sel.child(index,0)) # убираем выделение
                    item.setSelected(False)
                    selChild = sel.child(index,0).data()
                    if (selChild not in self.listOfChilds): # если элемент уже добавлен
                        self.listOfChilds.append(selChild)
                        self.listSelectedSignals.addItem(selChild)
                    index += 1
        self.labelHowMuchSelected.setText('Выбрано {0} из {1}'.format(len(self.listOfChilds), self.numberOfSignals))

    def moveAllSelectedSignals(self):
        if self.treeSystems.isHidden():
            currentTree = self.searchResultTree
        else: 
            currentTree = self.treeSystems
        for index in range(currentTree.topLevelItemCount()):
            item = currentTree.topLevelItem(index)
            for childIndex in range(item.childCount()):
                childData = item.child(childIndex).data(0,0) # 0,0 потому что элемент у нас туту всего один и дочерних не имеет
                if (childData not in self.listOfChilds):
                    self.listOfChilds.append(childData) 
                    self.listSelectedSignals.addItem(childData)
        self.labelHowMuchSelected.setText('Выбрано {0} из {1}'.format(len(self.listOfChilds), self.numberOfSignals))

    def deleteSelectedSignals(self):
        for item in self.listSelectedSignals.selectedItems():
            deletedItem = self.listSelectedSignals.takeItem(self.listSelectedSignals.row(item))
            self.listOfChilds.remove(deletedItem.data(0))
        self.labelHowMuchSelected.setText('Выбрано {0} из {1}'.format(len(self.listOfChilds), self.numberOfSignals))

    def deleteAllSelectedSignals(self):
        self.listSelectedSignals.clear()
        self.listOfChilds = []
        self.labelHowMuchSelected.setText('Выбрано 0 из {}'.format(self.numberOfSignals))

    def fixSelection(self, modelSelectionOfSelectedItem):
        if self.treeSystems.isHidden():
            currentTree = self.searchResultTree
        else:
            currentTree = self.treeSystems
            model = modelSelectionOfSelectedItem
        if len(modelSelectionOfSelectedItem.indexes()) > 0:
            modelIndexOfSelectedItem = modelSelectionOfSelectedItem.indexes()[0]
            item = currentTree.itemFromIndex(modelIndexOfSelectedItem)
            if (item.isSelected()):
                if (modelIndexOfSelectedItem.child(0,0).isValid()):
                    childs = item.childCount()
                    for index in range(childs):
                        childItem = currentTree.itemFromIndex(modelIndexOfSelectedItem.child(index, 0))
                        childItem.setSelected(True) 
        else:
            for sel in currentTree.selectedIndexes():
                item = currentTree.itemFromIndex(sel)
                flag = False
                if (item.isSelected() and item.childCount() > 0):
                    for index in range(item.childCount()):
                        childItem = currentTree.itemFromIndex(sel.child(index, 0))
                        if not childItem.isSelected():
                            flag = True
                if flag:
                    item.setSelected(False)

    def countGroupsAndSignals(self, value):
        self.fixSelection(value)
        group = 0
        childs = 0
        for sel in self.treeSystems.selectedIndexes():
            if (not sel.child(0,0).isValid()): # нет дочерних элементов
                childs += 1
            else:
                group += 1
        self.labelSelected.setText('Выбрано: {0} групп, {1} сигналов'.format(group, childs))

    def initUI(self):
        centralButtonsSS = 'max-width: 20%; padding: 6px; margin: 10px; border-radius: 5px; border: 1px solid black'
        self.setStyleSheet(open(os.path.join(os.path.dirname(__file__), 'style.css')).read())

        self.setWindowIcon(QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        vboxList = QVBoxLayout()
        self.labelSignalSelection = QLabel('Выбор сигнала')
        self.labelSystems = QLabel('Системы')
        self.labelSystems.mousePressEvent = self.showSystemsTree

        '-------------------------ListWidget---------------------------'
        self.treeSystems = QTreeWidget()
        self.treeSystems.setAlternatingRowColors(1)
        self.treeSystems.setHeaderHidden(1)
        self.treeSystems.setColumnCount(1)
        self.treeSystems.setSelectionMode(QAbstractItemView.MultiSelection)
        self.treeSystems.selectionModel().selectionChanged.connect(self.countGroupsAndSignals) # это для подсчёта выбранных групп и сигналов

        # kks = db.MPK.select_column('Суффикс', False, False, False) #проеверь чтобы postgres был запущен
        # kks = set(kks)
        # for record in kks:
        #     row = QTreeWidgetItem(self.treeSystems, [record])
        #     self.treeSystems.addTopLevelItem(row)
        #     self.dictOfSignals[record] = list()
        #     suffics = set(db.MPK.select_column('KKS', 'Суффикс', record, False))
        #     for elem in suffics:
        #         self.dictOfSignals[record].append(elem)
        #         child = QTreeWidgetItem(row, [elem])
        #         row.addChild(child)   
        #         self.numberOfSignals += 1
        '----------------------------ListWidget--------------------------'

        self.labelSelected = QLabel('Выбрано: 0 групп, 0 сигналов')
        self.labelSearch = QLabel('Поиск')
        self.labelSearch.mousePressEvent = self.showSearchTree

        '--------------------------HiddenSearch--------------------------------'
        self.buttonSearch = QPushButton('Искать', self)
        self.buttonSearch.clicked.connect(self.searchSignals)
        self.buttonSearch.hide()

        self.searchLine = QLineEdit(self)
        self.searchLine.hide()

        hboxSearchLayout = QHBoxLayout()
        hboxSearchLayout.addWidget(self.buttonSearch)
        hboxSearchLayout.addWidget(self.searchLine)

        self.embeddedSignalsCheckBox = QCheckBox('Упакованные сигналы', self)
        self.embeddedSignalsCheckBox.hide()
        self.discreteSignalsCheckBox = QCheckBox('Дискретные сигналы', self)
        self.discreteSignalsCheckBox.hide()

        hboxSearchParametersLayout = QHBoxLayout()
        hboxSearchParametersLayout.addWidget(self.embeddedSignalsCheckBox)
        hboxSearchParametersLayout.addWidget(self.discreteSignalsCheckBox)

        self.searchResultTree = QTreeWidget()
        self.searchResultTree.setHeaderHidden(1)
        self.searchResultTree.setColumnCount(1)
        self.searchResultTree.hide()
        self.searchResultTree.setSelectionMode(QAbstractItemView.MultiSelection)
        self.searchResultTree.selectionModel().selectionChanged.connect(self.fixSelection)

        self.nuberOfSelectedLabel = QLabel('0 выбрано из {}'.format(self.numberOfSignals))
        self.nuberOfSelectedLabel.hide()
        '--------------------------HiddenSearch--------------------------------'

        '--------------------------ProjectProtocols----------------------------'
        self.ProjectProtocolsTree = QTreeWidget()
        self.ProjectProtocolsTree.setHeaderHidden(1)
        self.ProjectProtocolsTree.setColumnCount(1)
        self.ProjectProtocolsTree.hide()

        self.countingLabel = QLabel('Выбрано 0 групп, 0 сигналов')
        self.countingLabel.hide()
        '--------------------------ProjectProtocols----------------------------'

        '---------------------------SavedProtocols------------------------'
        self.savedProtocolsTree = QTreeWidget()
        self.savedProtocolsTree.setHeaderHidden(1)
        self.savedProtocolsTree.setColumnCount(1)
        self.savedProtocolsTree.hide()
        '---------------------------SavedProtocols------------------------'

        self.labelProjectProtocolSignals = QLabel('Сигналы проектных протоколов')
        self.labelProjectProtocolSignals.mousePressEvent = self.showProjectProtocolsTree
        self.labelStoredProtocols = QLabel('Сохраненные протоколы')
        self.labelStoredProtocols.mousePressEvent = self.showSavedProtocolsTree
        widgets = (self.labelSignalSelection, 
                   self.labelSystems, 
                   self.treeSystems, 
                   self.labelSelected, 
                   self.labelSearch, 
                   self.searchResultTree, 
                   self.nuberOfSelectedLabel, 
                   self.labelProjectProtocolSignals,
                   self.ProjectProtocolsTree,
                   self.countingLabel, 
                   self.labelStoredProtocols,
                   self.savedProtocolsTree)
        for widget in widgets:
            vboxList.addWidget(widget)
            if widget == self.labelSearch:
                vboxList.addLayout(hboxSearchLayout)
                vboxList.addLayout(hboxSearchParametersLayout)

        vbox4Btn = QVBoxLayout()
        self.btnRigth = QPushButton('>', self)
        self.btnRigth.setStyleSheet(centralButtonsSS)
        self.btnRigth.clicked.connect(self.moveSelectedSignals)
        
        self.btnLeft = QPushButton('<', self)
        self.btnLeft.setStyleSheet(centralButtonsSS)
        self.btnLeft.clicked.connect(self.deleteSelectedSignals)

        self.btnRigthAll = QPushButton('>>', self)
        self.btnRigthAll.setStyleSheet(centralButtonsSS)
        self.btnRigthAll.clicked.connect(self.moveAllSelectedSignals)
        
        self.btnLeftAll = QPushButton('<<', self)
        self.btnLeftAll.setStyleSheet(centralButtonsSS)
        self.btnLeftAll.clicked.connect(self.deleteAllSelectedSignals)

        widgets = (self.btnRigth, 
                   self.btnLeft, 
                   self.btnRigthAll, 
                   self.btnLeftAll)
        for widget in widgets:
            vbox4Btn.addWidget(widget)

        vboxSelectedList = QVBoxLayout()
        self.labelSelectedSignals = QLabel('Выбранные сигналы')

        self.listSelectedSignals = QListWidget()
        self.listSelectedSignals.setSelectionMode(QAbstractItemView.MultiSelection)

        self.labelHowMuchSelected = QLabel('Выбрано 0 из {}'.format(self.numberOfSignals))
        widgets = (self.labelSelectedSignals, 
                   self.listSelectedSignals, 
                   self.labelHowMuchSelected)
        for widget in widgets:
            vboxSelectedList.addWidget(widget)
        
        hboxLists = QHBoxLayout()
        layouts = (vboxList, vbox4Btn, vboxSelectedList)
        for lay in layouts:
            hboxLists.addLayout(lay)

        hboxInputLine = QHBoxLayout()
        self.labelDescription = QLabel('Описание')
        self.inputLine = QLineEdit(self)
        widgets = (self.labelDescription, 
                   self.inputLine)
        for widget in widgets:
            hboxInputLine.addWidget(widget)

        hboxBottomButtons = QHBoxLayout()
        self.buttonOK = QPushButton('OK', self)
        self.buttonCancel = QPushButton('Отмена', self)
        hboxBottomButtons.addStretch(1)
        widgets = (self.buttonOK, 
                   self.buttonCancel)
        for widget in widgets:
            hboxBottomButtons.addWidget(widget)

        mainVBox = QVBoxLayout()
        layouts = (hboxLists, hboxInputLine, hboxBottomButtons)
        for lay in layouts:
            mainVBox.addLayout(lay)

        '---------------------View settings type---------------'
        vs_main = QWidget()
        vs_mainLayout = QVBoxLayout()

        vs_type = QWidget()
        vs_typeLayout = QVBoxLayout()
        vs_typeLayout.addWidget(QLabel('Представление:\n'))
        

        vs_type_bar = QWidget()
        vs_type_barLayout = QHBoxLayout()
       

        self.vs_type_trend = QRadioButton('Тренд')									#display type radio buttons
        self.vs_type_trend.setChecked(True)
        self.vs_type_gist = QRadioButton('Гистограмма')
        self.vs_type_prot = QRadioButton('Протокол')
        self.vs_type_cut = QRadioButton('Срез')
        self.vs_type_comp = QRadioButton('Сравнение')

        vs_type_barLayout.addWidget(self.vs_type_trend)
        vs_type_barLayout.addWidget(self.vs_type_gist)
        vs_type_barLayout.addWidget(self.vs_type_prot)
        #vs_type_barLayout.addWidget(self.vs_type_cut)
        vs_type_barLayout.addWidget(self.vs_type_comp)

        vs_type_barLayout.addStretch(1)
        vs_type_bar.setLayout(vs_type_barLayout)

        vs_typeLayout.addWidget(vs_type_bar)
        vs_type.setLayout(vs_typeLayout)
        vs_typeLayout.addStretch(1)


        vs_mainLayout.addWidget(vs_type)
        vs_main.setLayout(vs_mainLayout)
        '---------------------View settings type---------------'

        '---------------------View settings data---------------'
        vs_data = QWidget()
        vs_dataLayout = QVBoxLayout()
        vs_data.setLayout(vs_dataLayout)

        vs_dataLayout.addWidget(QLabel("Выбор данных:\n"))
        self.vs_data_current = QRadioButton('Текущие данные')							#current radio button
        self.vs_data_current.setChecked(True)
        vs_dataLayout.addWidget(self.vs_data_current)
        
        vs_data_cur_settings = QWidget()
        vs_data_cur_settingsLayout = QHBoxLayout()
        vs_data_cur_settings.setLayout(vs_data_cur_settingsLayout)

        vs_data_cur_settingsLayout.addWidget(QLabel("Интервал:"))
        self.vs_data_interval = QLineEdit('5')											#interval value
        vs_data_cur_settingsLayout.addWidget(self.vs_data_interval)
        self.vs_data_interval_combo = QComboBox()										#interval scale
        self.vs_data_interval_combo.addItems(["Минут","Часов","Секунд"])
        vs_data_cur_settingsLayout.addWidget(self.vs_data_interval_combo)
        vs_data_cur_settingsLayout.addStretch(1)

        vs_dataLayout.addWidget(vs_data_cur_settings)

        vs_dataLayout.addWidget(QLabel("\n\n"))
        self.vs_data_arch_btn = QRadioButton('Архив:')												# archive radio btn
        vs_dataLayout.addWidget(self.vs_data_arch_btn)
        vs_data_arch = QWidget()
        vs_data_archLayout = QHBoxLayout()
        vs_data_arch.setLayout(vs_data_archLayout) 
        vs_data_archLayout.addWidget(QLabel("Введите интервал для отбора по времени:"))       
        self.vs_data_arch_time = QLineEdit("от 2020-11-11-21:37:51 до 2020-11-11-21:37:58") 			#archive interval choose

        self.vs_data_arch_time.setMinimumSize(QSize(250,0))											#намутить функцию для формирования корректных занчений по умолчанию
        vs_data_archLayout.addWidget(self.vs_data_arch_time)
        vs_data_archLayout.addStretch(1)


        vs_dataLayout.addWidget(vs_data_arch)
        vs_mainLayout.addWidget(vs_data)


        vs_mainLayout.addStretch(1)
        '---------------------View settings data---------------'
        hboxBottomButtons = QHBoxLayout()
        self.buttonOK2 = QPushButton('OK', self)
        self.buttonCancel2 = QPushButton('Отмена', self)
        hboxBottomButtons.addStretch(1)
        self.errorLabel = QLabel('')
        hboxBottomButtons.addWidget(self.errorLabel)
        widgets = (self.buttonOK2, 
                   self.buttonCancel2)
        for widget in widgets:
            hboxBottomButtons.addWidget(widget)

        vs_mainLayout.addLayout(hboxBottomButtons)




        '-------------------------Tabs-------------------------'
        self.signalsTabWrapper = QWidget()
        self.signalsTabWrapper.setLayout(mainVBox)

        self.signalsTab = QTabWidget()
        self.signalsTab.addTab(self.signalsTabWrapper, 'Сигналы для показа')
        self.signalsTab.addTab(vs_main, 'Настройка показа') 

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.signalsTab)
        '-------------------------Tabs-------------------------'

        self.setLayout(mainLayout)
        self.show()





        '---------------------Method links----------------------'
        self.buttonOK2.clicked.connect(self.display)
        #self.buttonOK.clicked.connect(self.display)

    def display(self):
        'отображает сигналы в новом окне изходя из требований'
    
        display_type = ['trend','gist','prot','cut','comp'][[[self.vs_type_trend,self.vs_type_gist,self.vs_type_prot,self.vs_type_cut,self.vs_type_comp].index(btn) for btn in [self.vs_type_trend,self.vs_type_gist,self.vs_type_prot,self.vs_type_cut,self.vs_type_comp] if btn.isChecked()][0]]
        display_time = ['current','archive'][[[self.vs_data_current,self.vs_data_arch_btn].index(btn) for btn in [self.vs_data_current,self.vs_data_arch_btn] if btn.isChecked()][0]]
        display_interval,display_interval_borders = None,None
        try:
            if display_time =='current':
                display_interval = int(self.vs_data_interval.text()) * [60,3600,1][self.vs_data_interval_combo.currentIndex()]
            else:
                display_interval_borders = self.str_to_mkt2(self.vs_data_arch_time.text())
                if display_interval_borders ==0:
                	raise Exception()
        except Exception: 
        	self.errorLabel.setText("Неверный формат ввода, повторите!")
        else:
        	self.errorLabel.setText("")


        	global windows
        	windows.append(self.win(display_type)(display_time,display_interval,display_interval_borders,self.form_sygnals()))
        	windows[-1].show()
    
    
    
    def form_sygnals(self,example = True):
        'возвращает массив объектов класса сигнал (случайных при труъ экзампл). А вообще из бд должно'

        sygnals = []
        if example:
            for i in range (3):
                example_data = [[(time.mktime(time.localtime())-i+3600*3) for i in range(7)][::-1],[randint(1800,2200) for i in range(7)]]
                sygnal = Sygnal('00MOT01CS001','example description','обороты в минуту',0,3500,example_data)  #аргументы: id_kks, name, description, единицы измерения, мин, макс, [массив икс значений(моментов времени в секундах с начала эпохи), массив игрек значений]
                sygnals.append(sygnal)
        else:
            sygnals = None #выбранные сигналы из бд



        return sygnals




        
    
        '---------------------Utility--------------------------'

    def str_to_mkt2(self,s):																#returns 0 in case of format error
        'converts string(от 2020-11-11-21:37:51 до 2020-11-11-21:37:58) into 2 values in seconds from epoch start'

        try:
            time_start,time_fin = s.split(' ')[1],s.split(' ')[3]
            time_start,time_fin = self.str_to_mkt([time_start,time_fin])

            time_start,time_fin = time_start+3600*3,time_fin+3600*3

        except Exception:
            return 0 

        else:
            return (time_start,time_fin)

    def str_to_mkt(self,values):
        res = []
        for s in values:    
            struct = time.strptime(s,"%Y-%m-%d-%H:%M:%S")
            mkt = time.mktime(struct)
            res.append(mkt)
        return res

    def win(self,display_type):
    	return {"trend":trend,"gist":gist,"prot":prot,"comp":comp}[display_type]
Exemplo n.º 5
0
class TorWarnDialog(WindowModalDialog):
    def __init__(self, app, w_path):
        super(TorWarnDialog, self).__init__(None)
        self.app = app
        self.network = app.daemon.network
        self.config = app.config
        self.tor_detected = False
        self.setMinimumSize(600, 350)

        app_name = 'Axe Electrum'
        if constants.net.TESTNET:
            app_name += ' Testnet'
        app_name += f' {ELECTRUM_VERSION}'
        w_basename = os.path.basename(w_path)
        self.setWindowTitle(f'{app_name}  -  {w_basename}')

        vbox = QVBoxLayout(self)
        vbox.setSpacing(10)
        hbox = QHBoxLayout()
        vbox.addLayout(hbox)

        w_icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning)
        self.w_icn_lbl = QLabel()
        self.w_icn_lbl.setPixmap(w_icon.pixmap(36))
        self.w_lbl = QLabel(self.network.TOR_WARN_MSG_QT)
        self.w_lbl.setOpenExternalLinks(True)
        hbox.addWidget(self.w_icn_lbl)
        hbox.addWidget(self.w_lbl)
        hbox.setSpacing(10)
        hbox.addStretch(1)
        vbox.addStretch(1)

        self.tor_auto_on_cb = QCheckBox(self.network.TOR_AUTO_ON_MSG)
        self.tor_auto_on_cb.setChecked(self.config.get('tor_auto_on', True))
        vbox.addWidget(self.tor_auto_on_cb)

        def use_tor_auto_on(b):
            self.config.set_key('tor_auto_on', b, True)
            if not b:
                self.config.set_key('proxy', None, True)

        self.tor_auto_on_cb.clicked.connect(use_tor_auto_on)

        self.no_tor_btn = QPushButton(_('Continue without Tor'))
        self.no_tor_btn.clicked.connect(self.continue_without_tor)
        vbox.addWidget(self.no_tor_btn)

        self.detect_btn = QPushButton(_('Detect Tor again'))
        self.detect_btn.clicked.connect(self.detect_tor_again)
        vbox.addWidget(self.detect_btn)

        self.close_w_btn = QPushButton(_('Close wallet'))
        self.close_w_btn.clicked.connect(self.close_wallet)
        vbox.addWidget(self.close_w_btn)

        self.ok_btn = QPushButton(_('OK'))
        self.ok_btn.hide()
        self.ok_btn.clicked.connect(self.on_ok)
        vbox.addWidget(self.ok_btn)

    def keyPressEvent(self, event):
        if self.tor_detected:
            super(TorWarnDialog, self).keyPressEvent(event)
            return

        if event.key() == Qt.Key_Escape:
            event.ignore()
        else:
            super(TorWarnDialog, self).keyPressEvent(event)

    def closeEvent(self, event):
        if self.tor_detected:
            super(TorWarnDialog, self).closeEvent(event)
            return

        if self.question('Continue without Tor?'):
            self.continue_without_tor()
        else:
            self.done(-1)
        event.ignore()

    def continue_without_tor(self):
        net = self.network
        net_params = net.get_parameters()
        if net_params.proxy:
            host = net_params.proxy['host']
            port = net_params.proxy['port']
            if host == '127.0.0.1' and port in ['9050', '9150']:
                net_params = net_params._replace(proxy=None)
                coro = net.set_parameters(net_params)
                net.run_from_another_thread(coro)
        self.done(0)

    def detect_tor_again(self):
        net = self.network
        proxy_modifiable = self.config.is_modifiable('proxy')
        if not proxy_modifiable:
            return

        self.tor_detected = net.detect_tor_proxy()
        if not self.tor_detected:
            return

        net_params = net.get_parameters()
        proxy = deserialize_proxy(self.tor_detected)
        net_params = net_params._replace(proxy=proxy)
        coro = net.set_parameters(net_params)
        net.run_from_another_thread(coro)

        i_style = QStyle.SP_MessageBoxInformation
        i_icon = QApplication.style().standardIcon(i_style)
        self.w_icn_lbl.setPixmap(i_icon.pixmap(36))
        self.setWindowTitle(_('Information'))
        self.w_lbl.setText(_('Tor proxy detected'))
        self.no_tor_btn.hide()
        self.detect_btn.hide()
        self.close_w_btn.hide()
        self.ok_btn.show()
        self.tor_auto_on_cb.hide()
        self.setMinimumSize(self.minimumSizeHint())

    def close_wallet(self):
        self.done(-1)

    def on_ok(self):
        self.done(0)
Exemplo n.º 6
0
class Dialog(QDialog):

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.openFilesPath = ''

        self.errorMessageDialog = QErrorMessage(self)

        frameStyle = QFrame.Sunken | QFrame.Panel

        self.DescriptionLabel = QLabel()
        self.DescriptionLabel.setFrameStyle(frameStyle)
        self.DescriptionLabel.setText('This utility will convert IMGT FASTA files to NCBI FASTA files')


        self.openFileNameLabel = QLabel()
        self.openFileNameLabel.setFrameStyle(frameStyle)
        self.openFileNameButton = QPushButton("Open (IMGT FASTA filename):")

        self.saveFileNameLabel = QLabel()
        self.saveFileNameLabel.setFrameStyle(frameStyle)
        self.saveFileNameButton = QPushButton("Save as (NCBI FASTA filename):")

        self.initiateButton = QPushButton("Initiate conversion")

        self.openFileNameButton.clicked.connect(self.setOpenFileName)
        self.saveFileNameButton.clicked.connect(self.setSaveFileName)
        self.initiateButton.clicked.connect(self.setInitiateConversion)

        self.native = QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)

        layout.addWidget(self.DescriptionLabel, 0, 0)
        layout.addWidget(self.openFileNameButton, 1, 0)
        layout.addWidget(self.openFileNameLabel, 1, 1)
        layout.addWidget(self.saveFileNameButton, 2, 0)
        layout.addWidget(self.saveFileNameLabel, 2, 1)
        layout.addWidget(self.initiateButton, 3, 0)

        layout.addWidget(self.native, 4, 0)
        self.setLayout(layout)

        self.setWindowTitle("IMGT to NCBI FASTA converter")



    def setOpenFileName(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,
                "QFileDialog.getOpenFileName()", self.openFileNameLabel.text(),
                "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            self.openFileNameLabel.setText(fileName)


    def setSaveFileName(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(self,
                "QFileDialog.getSaveFileName()",
                self.saveFileNameLabel.text(),
                "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            self.saveFileNameLabel.setText(fileName)

    def setInitiateConversion(self):
        print('converted')

        Ofilenamed = self.openFileNameLabel.text()
        SfileNamed = self.saveFileNameLabel.text()

        # (dirname, filename) = os.path.split(SfileNamed)
        # print(dirname)
        # print(filename)

        IMGTFile  = open(Ofilenamed, 'r')
        NCBIfile = open(SfileNamed, 'w')

        NCBILine = ''
        StartLine = True
        for IMGTlines in IMGTFile:

            if IMGTlines[0] == '>':
                if StartLine == False:
                    NCBIfile.write('\n')

                SIMGTLines = IMGTlines.split('|')
                NCBILine = SIMGTLines[0] + '-' + SIMGTLines[1] + '\n'
                NCBILine = NCBILine.replace('/', '-')
                print(NCBILine)
                NCBIfile.write(NCBILine)
                StartLine = False


            else:
                NCBILine = IMGTlines
                NCBILine2 = ''
                NCBILine3 = ''
                SIMGTLines = NCBILine.split('.')  #  top get rid of .
                for seqparts in SIMGTLines:
                    NCBILine2 += seqparts
                NCBILine3 = NCBILine2.replace('\n', '')

                NCBIfile.write(NCBILine3)
                print(NCBILine3)

        NCBIfile.write('\n')



        IMGTFile.close()
        NCBIfile.close()
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.directoryValue =''
        self.effectValue = 0.00
        self.fileValue = ''
        self.openFilesPath = ''
        self.saveFileName = ''

        self.setFixedSize(800,600)
        frameStyle = QFrame.Sunken | QFrame.Panel

        self.directoryLabel = QLabel()
        self.directoryLabel.setFrameStyle(frameStyle)
        self.directoryButton = QPushButton("指定文件夹路径:")

        #self.directoryLabelReset = QLabel()
        #self.directoryLabelReset.setFrameStyle(frameStyle)
        self.directoryButtonReset = QPushButton("Reset")

        self.openFileNamesLabel = QLabel()
        self.openFileNamesLabel.setFrameStyle(frameStyle)
        self.openFileNamesButton = QPushButton("指定文件路径:")
        self.openFileNamesButtonReset = QPushButton("Reset")

        self.doubleLabel = QLabel()
        self.doubleLabel.setFrameStyle(frameStyle)
        self.doubleButton = QPushButton("有效交易值:")
        self.doubleLabel.setText("$3333")

        self.saveFileNameLabel = QLabel()
        self.saveFileNameLabel.setFrameStyle(frameStyle)
        self.saveFileNameButton = QPushButton("生成excel路径")
        self.saveFileNameButtonReset = QPushButton("Reset")

        buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel)

        #self.okdirectoryLabel = QLabel()
        #self.okdirectoryLabel.setFrameStyle(frameStyle)
        self.okdirectoryButton = QPushButton("OK:")

        #buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        self.doubleButton.clicked.connect(self.setDouble)
        self.openFileNamesButton.clicked.connect(self.setOpenFileNames)
        self.openFileNamesButtonReset.clicked.connect(self.setOpenFileNamesReset)
        self.saveFileNameButton.clicked.connect(self.setSaveFileName)
        self.saveFileNameButtonReset.clicked.connect(self.setSaveFileNameReset)
        self.directoryButton.clicked.connect(self.setExistingDirectory)
        self.directoryButtonReset.clicked.connect(self.setExistingDirectoryReset)
        self.okdirectoryButton.clicked.connect(self.okButton)

        self.native = QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)

        layout.addWidget(self.directoryButton, 0, 0)
        layout.addWidget(self.directoryButtonReset, 0, 2)
        layout.addWidget(self.directoryLabel, 0, 1)
        #layout.addWidget(self.directoryLabelReset, 0, 2)

        layout.addWidget(self.openFileNamesButton, 1, 0)
        layout.addWidget(self.openFileNamesButtonReset, 1, 2)
        layout.addWidget(self.openFileNamesLabel, 1, 1)

        layout.addWidget(self.doubleButton, 2, 0)
        layout.addWidget(self.doubleLabel, 2, 1)

        layout.addWidget(self.saveFileNameButton, 3, 0)
        layout.addWidget(self.saveFileNameButtonReset, 3, 2)
        layout.addWidget(self.saveFileNameLabel, 3, 1)

        layout.addWidget(self.okdirectoryButton, 4, 0)
        #layout.addWidget(self.okdirectoryLabel, 4, 1)

        layout.addWidget(self.native, 15, 0)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

    def checkResourceFile(self, fileName):
            parse = [ ]
            self.checkFileType = 0
            try:
                with open(fileName, 'r') as file:
                    for line in file:
                        line = line.strip('\n').strip();
                        if line != '':
                            parse.append(line)
                    #print((parse[1].split('         ')[0].split(':'))[0].strip().split('      ')[1]);
                    self.checkFileType = ((parse[1].split('         ')[0].split(':'))[0].strip().split('      ')[1]);
                    #print(self.checkFileType)
            finally:
                file.close();
            return self.checkFileType
        
    def okButton(self):      
        fileList=[]
        
        if not self.effectValue:
            self.effectValue = 3333;
            
        if len(self.fileValue):
            for i in self.fileValue:
                fileList.append(i)

        if len(self.directoryValue):
            for file in os.listdir(self.directoryValue):                
                file = self.directoryValue+"\\"+file;
                if file.find('.') == -1:
                    #print(self.checkResourceFile(file))
                    if  os.path.isfile(file) and int(self.checkResourceFile(file)) > 0:
                        print(file)
                        fileList.append(file)
        if not self.saveFileName:
                self.saveFileName = 'C:\\自动生成对账单.xls'

        if len(fileList):
            for file in fileList:
                parsefile = writeExcelData(self.saveFileName, file, self.effectValue)
                parsefile.wirteExcelData()

        
        #print('self.fileValue =%s\n' %self.fileValue)
        #print('self.effectValue=%s\n' %self.effectValue)
        MESSAGE = "<p>Excel 已经生成!</p>"
        if os.path.isfile(self.saveFileName):
            reply = QMessageBox.information(self,
                "生成Excel状态提示", MESSAGE)

    def setSaveFileNameReset(self):    
        self.saveFileNameLabel.setText('')

    def setSaveFileName(self):    
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(self,
                "QFileDialog.getSaveFileName()",
                self.saveFileNameLabel.text(),
                "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            if platform.system() == 'Windows':
                fileName = fileName.replace('/','\\');
            if fileName.find('.xls') <= 0:
               fileName = fileName.split('.')[0]+'.xls'
            self.saveFileNameLabel.setText(fileName)
            self.saveFileName = fileName
            
    def setDouble(self):    
        d, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()",
                "Amount:", 3333.00, -10000, 1000000, 1)
        if ok:
            self.doubleLabel.setText("$%g" % d)
            self.effectValue = d

    def setOpenFileNamesReset(self):    
        self.openFileNamesLabel.setText('');

    def setOpenFileNames(self):    
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(self,
                "QFileDialog.getOpenFileNames()", self.openFilesPath,
                "All Files (*);;Text Files (*.txt)", options=options)
        if files:             
            self.openFilesPath = files[0]
            if platform.system() == 'Windows':
                self.openFileNamesLabel.setText(str(files).replace('/','\\'))
            else:
                self.openFileNamesLabel.setText("[%s]" % ', '.join(files))
            self.fileValue = files 

    def setExistingDirectoryReset(self):    
        self.directoryLabel.setText('')

    def setExistingDirectory(self):    
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        directory = QFileDialog.getExistingDirectory(self,
                "QFileDialog.getExistingDirectory()",
                self.directoryLabel.text(), options=options)
        if directory:
            if platform.system() == 'Windows':
                directory = directory.replace('/','\\')
            self.directoryValue = directory
            self.directoryLabel.setText(directory)
Exemplo n.º 8
0
class Prueba(QMainWindow):
    def __init__(self):
        super().__init__()

        self.title = "Proyecto Biologia Computacional"
        self.top = 0
        self.left = 0
        self.width = 1200
        self.height = 700
        button1 = QPushButton("ALINEAR!", self)
        button1.move(100, 450)
        button1.setToolTip("<h4>Comprobar sintaxis</h4>")
        button1.clicked.connect(self.onClick1)

        button2 = QPushButton("MOSTRAR!", self)
        button2.move(100, 400)
        button2.setToolTip("<h4>Agregar secuencias</h4>")
        button2.clicked.connect(self.onClick2)

        button3 = QPushButton("LIMPIAR!", self)
        button3.move(100, 500)
        button3.setToolTip("<h4>Limpiar Texto</h4>")
        button3.clicked.connect(self.onClick3)

        button4 = QPushButton("BLAST!", self)
        button4.move(100, 550)
        button4.setToolTip("<h4>Alinea con BLAST</h4>")
        button4.clicked.connect(self.onClick4)

        button5 = QPushButton("ARBOL FILOGENETICO!", self)
        button5.setGeometry(50, 600, 150, 30)
        button5.setToolTip("<h4>Muestra el arbol creado</h4>")
        button5.clicked.connect(self.onClick5)

        button6 = QPushButton("EPIPEDOBATES!", self)
        button6.setGeometry(250, 10, 100, 30)
        button6.setToolTip("<h4>Escoger specie</h4>")
        button6.clicked.connect(self.onClick6)

        button7 = QPushButton("COLOSTETHUS!", self)
        button7.setGeometry(450, 10, 100, 30)
        button7.setToolTip("<h4>Escoger especie</h4>")
        button7.clicked.connect(self.onClick7)

        button8 = QPushButton("AMEEREGA!", self)
        button8.setGeometry(650, 10, 100, 30)
        button8.setToolTip("<h4>Escoger especie</h4>")
        button8.clicked.connect(self.onClick8)

        button9 = QPushButton("PROTEINAS!", self)
        button9.setGeometry(850, 10, 100, 30)
        button9.setToolTip("<h4>Escoger proteinas</h4>")
        button9.clicked.connect(self.onClick9)

        self.InitWindow()

    def InitWindow(self):
        self.contador = 0

        self.label2 = QLabel(self)
        self.label2.setPixmap(QPixmap('images/epipedobates_anthonyi.jpg'))
        self.label2.setGeometry(50, 30, 200, 250)
        self.label2.hide()
        self.checkbox1 = QCheckBox("Epipedobates\nAnthonyi", self)
        self.checkbox1.setGeometry(50, 240, 150, 50)
        self.checkbox1.hide()

        self.label3 = QLabel(self)
        self.label3.setPixmap(QPixmap('images/epipedobates_boulengeri.jpg'))
        self.label3.setGeometry(250, 30, 450, 250)
        self.label3.hide()
        self.checkbox2 = QCheckBox("Epipedobates\nBoulengeri", self)
        self.checkbox2.setGeometry(250, 220, 150, 50)
        self.checkbox2.hide()

        self.label4 = QLabel(self)
        self.label4.setPixmap(
            QPixmap('images/epipedobates_darwinwallacei.jpg'))
        self.label4.setGeometry(450, 30, 650, 250)
        self.label4.hide()
        self.checkbox3 = QCheckBox("Epipedobates\nDarwinwallacei", self)
        self.checkbox3.setGeometry(450, 210, 150, 50)
        self.checkbox3.hide()

        self.label5 = QLabel(self)
        self.label5.setPixmap(QPixmap('images/epipedobates_espinosai.jpg'))
        self.label5.setGeometry(650, 30, 800, 250)
        self.label5.hide()
        self.checkbox4 = QCheckBox("Epipedobates\nEspinosai", self)
        self.checkbox4.setGeometry(650, 210, 150, 50)
        self.checkbox4.hide()

        self.label6 = QLabel(self)
        self.label6.setPixmap(QPixmap('images/epipedobates_machalilla.jpg'))
        self.label6.setGeometry(850, 30, 950, 250)
        self.label6.hide()
        self.checkbox5 = QCheckBox("Epipedobates\nMachalilla", self)
        self.checkbox5.setGeometry(850, 210, 150, 50)
        self.checkbox5.hide()

        self.label7 = QLabel(self)
        self.label7.setPixmap(QPixmap('images/epipedobates_tricolor.jpg'))
        self.label7.setGeometry(1050, 30, 1150, 250)
        self.label7.hide()
        self.checkbox6 = QCheckBox("Epipedobates\nTricolor", self)
        self.checkbox6.setGeometry(1050, 210, 150, 50)
        self.checkbox6.hide()

        self.label8 = QLabel(self)
        self.label8.setPixmap(QPixmap('images/colostethus_fraterdanieli.jpg'))
        self.label8.setGeometry(50, 30, 200, 250)
        self.label8.hide()
        self.checkbox7 = QCheckBox("Colostethus\nFraterdanie", self)
        self.checkbox7.setGeometry(50, 220, 150, 50)
        self.checkbox7.hide()

        self.label9 = QLabel(self)
        self.label9.setPixmap(QPixmap('images/colostethus_inguinalis.jpg'))
        self.label9.setGeometry(310, 30, 400, 250)
        self.label9.hide()
        self.checkbox8 = QCheckBox("Colostethus\nInguinalis", self)
        self.checkbox8.setGeometry(310, 210, 150, 50)
        self.checkbox8.hide()

        self.label10 = QLabel(self)
        self.label10.setPixmap(QPixmap('images/colostethus_agilis.jpg'))
        self.label10.setGeometry(550, 30, 200, 250)
        self.label10.hide()
        self.checkbox9 = QCheckBox("Colostethus\nAgilis", self)
        self.checkbox9.setGeometry(550, 210, 150, 50)
        self.checkbox9.hide()

        self.label11 = QLabel(self)
        self.label11.setPixmap(QPixmap('images/colostethus_panamansis.jpg'))
        self.label11.setGeometry(800, 30, 200, 250)
        self.label11.hide()
        self.checkbox10 = QCheckBox("Colostethus\nPanamansis", self)
        self.checkbox10.setGeometry(800, 210, 150, 50)
        self.checkbox10.hide()

        self.label12 = QLabel(self)
        self.label12.setPixmap(QPixmap('images/colostethus_pratti.jpg'))
        self.label12.setGeometry(1050, 30, 200, 250)
        self.label12.hide()
        self.checkbox11 = QCheckBox("Colostethus\nPratti", self)
        self.checkbox11.setGeometry(1050, 210, 150, 50)
        self.checkbox11.hide()

        self.label13 = QLabel(self)
        self.label13.setPixmap(QPixmap('images/ameerega_bassleri.jpg'))
        self.label13.setGeometry(50, 30, 200, 250)
        self.label13.hide()
        self.checkbox12 = QCheckBox("Ameerega\nBassleri", self)
        self.checkbox12.setGeometry(50, 210, 150, 50)
        self.checkbox12.hide()

        self.label14 = QLabel(self)
        self.label14.setPixmap(QPixmap('images/ameerega_bilinguis.jpg'))
        self.label14.setGeometry(260, 30, 200, 250)
        self.label14.hide()
        self.checkbox13 = QCheckBox("Ameerega\nBilinguis", self)
        self.checkbox13.setGeometry(260, 210, 150, 50)
        self.checkbox13.hide()

        self.label15 = QLabel(self)
        self.label15.setPixmap(QPixmap('images/ameerega_flavopicta.jpg'))
        self.label15.setGeometry(480, 30, 200, 250)
        self.label15.hide()
        self.checkbox14 = QCheckBox("Ameerega\nFlavopicta", self)
        self.checkbox14.setGeometry(480, 210, 150, 50)
        self.checkbox14.hide()

        self.label16 = QLabel(self)
        self.label16.setPixmap(QPixmap('images/ameerega_hahneli.jpg'))
        self.label16.setGeometry(700, 55, 150, 150)
        self.label16.hide()
        self.checkbox15 = QCheckBox("Ameerega\nHahneli", self)
        self.checkbox15.setGeometry(700, 210, 150, 50)
        self.checkbox15.hide()

        self.label17 = QLabel(self)
        self.label17.setPixmap(QPixmap('images/ameerega_macero.jpg'))
        self.label17.setGeometry(880, 30, 250, 250)
        self.label17.hide()
        self.checkbox16 = QCheckBox("Ameerega\nMacero", self)
        self.checkbox16.setGeometry(880, 210, 150, 50)
        self.checkbox16.hide()

        self.label18 = QLabel(self)
        self.label18.setPixmap(QPixmap('images/ameerega_shihuemoy.jpg'))
        self.label18.setGeometry(1100, 30, 200, 250)
        self.label18.hide()
        self.checkbox17 = QCheckBox("Ameerega\nShihuemoy", self)
        self.checkbox17.setGeometry(1100, 210, 150, 50)
        self.checkbox17.hide()

        self.cajadetexto = QTextEdit(self)
        self.cajadetexto.setGeometry(200, 270, 1050, 430)

        self.setWindowTitle(self.title)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.blue)
        self.setPalette(p)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.show()

    def CloseApp(self):
        reply = QMessageBox.question(self, "Mensaje!", "¿Seguro de cerrar?",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.close()

    def contextMenuEvent(self, event):
        contextMenu = QMenu(self)
        newAct = contextMenu.addAction("Nuevo")
        openAct = contextMenu.addAction("Abrir")
        quitAct = contextMenu.addAction("Cerrar")

        action = contextMenu.exec_(self.mapToGlobal(event.pos()))

        if action == quitAct:
            self.CloseApp()

    def onClick1(self):
        self.alineamiento_multiple()

    def onClick2(self):
        handle_output = open("Conjunto_fasta.fasta", "w+")
        if self.checkbox1.isChecked():
            self.f1 = open("secuencias/epipedobates-anthonyi-parcial.fasta",
                           "r")
            texto1 = self.f1.read().strip()
            handle_output.write(texto1 + "\n\n")
        if self.checkbox2.isChecked():
            self.f2 = open("secuencias/epipedobates-boulengei-parcial.fasta",
                           "r")
            texto2 = self.f2.read().strip()
            handle_output.write(texto2 + "\n\n")
        if self.checkbox3.isChecked():
            self.f3 = open(
                "secuencias/epipedobates-darwinwallacei-parcial.fasta", "r")
            texto3 = self.f3.read().strip()
            handle_output.write(texto3 + "\n\n")
        if self.checkbox4.isChecked():
            self.f4 = open("secuencias/epipedobates-espinosai-parcial.fasta",
                           "r")
            texto4 = self.f4.read().strip()
            handle_output.write(texto4 + "\n\n")
        if self.checkbox5.isChecked():
            self.f5 = open("secuencias/epipedobates-machalilla-parcial.fasta",
                           "r")
            texto5 = self.f5.read().strip()
            handle_output.write(texto5 + "\n\n")
        if self.checkbox6.isChecked():
            self.f6 = open("secuencias/epipedobates-tricolor-parcial.fasta",
                           "r")
            texto6 = self.f6.read().strip()
            handle_output.write(texto6 + "\n\n")
        handle_output.close()
        ftotal = open("Conjunto_fasta.fasta", "r")
        texto_total = ftotal.read().strip()
        self.cajadetexto.setText(texto_total)

    def alineamiento_multiple(self):
        subprocess.call(
            ['/home/cristian/BC-and-Topicos1/Proyect-BC/procesa_clustal.sh'])
        ft = open("Conjunto_fasta.aln", "r")
        input = ft.read().strip()
        self.cajadetexto.setText(input)

    def onClick3(self):
        self.cajadetexto.clear()

    def onClick4(self):
        print("BLAST en proceso")

    def onClick5(self):
        with open("Conjunto_fasta.aln", "r") as aln:
            #usar AlignIO tpara leer el archivo de alineamiento en formato 'clustal' format
            alignment = align.read(aln, "clustal")
        #calcular la  matriz de distancias
        calculator = DistanceCalculator('identity')
        # añade la matriz de  distancias al objeto calculator y lo retorna
        dm = calculator.get_distance(alignment)

        #Construir el arbol filogenetico aprtir de las distancias
        constructor = DistanceTreeConstructor(calculator)

        upgma_tree = constructor.upgma(dm)

        Phylo.draw_ascii(upgma_tree)
        Phylo.draw(upgma_tree)

    def onClick6(self):
        self.label2.show()
        self.checkbox1.show()
        self.label3.show()
        self.checkbox2.show()
        self.label4.show()
        self.checkbox3.show()
        self.label5.show()
        self.checkbox4.show()
        self.label6.show()
        self.checkbox5.show()
        self.label7.show()
        self.checkbox6.show()
        self.label8.hide()
        self.checkbox7.hide()
        self.label9.hide()
        self.checkbox8.hide()
        self.label10.hide()
        self.checkbox9.hide()
        self.label11.hide()
        self.checkbox10.hide()
        self.label12.hide()
        self.checkbox11.hide()
        self.label13.hide()
        self.checkbox12.hide()
        self.label14.hide()
        self.checkbox13.hide()
        self.label15.hide()
        self.checkbox14.hide()
        self.label16.hide()
        self.checkbox15.hide()
        self.label17.hide()
        self.checkbox16.hide()
        self.label18.hide()
        self.checkbox17.hide()

    def onClick7(self):
        self.label2.hide()
        self.checkbox1.hide()
        self.label3.hide()
        self.checkbox2.hide()
        self.label4.hide()
        self.checkbox3.hide()
        self.label5.hide()
        self.checkbox4.hide()
        self.label6.hide()
        self.checkbox5.hide()
        self.label7.hide()
        self.checkbox6.hide()
        self.label8.show()
        self.checkbox7.show()
        self.label9.show()
        self.checkbox8.show()
        self.label10.show()
        self.checkbox9.show()
        self.label11.show()
        self.checkbox10.show()
        self.label12.show()
        self.checkbox11.show()
        self.label13.hide()
        self.checkbox12.hide()
        self.label14.hide()
        self.checkbox13.hide()
        self.label15.hide()
        self.checkbox14.hide()
        self.label16.hide()
        self.checkbox15.hide()
        self.label17.hide()
        self.checkbox16.hide()
        self.label18.hide()
        self.checkbox17.hide()

    def onClick8(self):
        self.label2.hide()
        self.checkbox1.hide()
        self.label3.hide()
        self.checkbox2.hide()
        self.label4.hide()
        self.checkbox3.hide()
        self.label5.hide()
        self.checkbox4.hide()
        self.label6.hide()
        self.checkbox5.hide()
        self.label7.hide()
        self.checkbox6.hide()
        self.label8.hide()
        self.checkbox7.hide()
        self.label9.hide()
        self.checkbox8.hide()
        self.label10.hide()
        self.checkbox9.hide()
        self.label11.hide()
        self.checkbox10.hide()
        self.label12.hide()
        self.checkbox11.hide()
        self.label13.show()
        self.checkbox12.show()
        self.label14.show()
        self.checkbox13.show()
        self.label15.show()
        self.checkbox14.show()
        self.label16.show()
        self.checkbox15.show()
        self.label17.show()
        self.checkbox16.show()
        self.label18.show()
        self.checkbox17.show()

    def onClick9(self):
        print("Proteinas")
class ShuffleWidget(QWidget):
    def __init__(self, window):
        QWidget.__init__(self)
        self.window = window
        self.timer = QtCore.QTimer()
        self.update_inputs_timer = QtCore.QTimer()
        self.waiting_timeout = 180
        self.timer.timeout.connect(self.tick)
        self.update_inputs_timer.timeout.connect(self.update_inputs)
        self.update_inputs_timer.start(15000)
        self.coinshuffle_fee_constant = 1000
        self.bot_thread = None
        self.bot_limit_value = 1
        self.bot_maximum_value = 3
        self.bot_period_value = 1
        self.bot_stopper = False
        # This is for debug
        # self.coinshuffle_fee_constant = 10
        #
        # self.coinshuffle_amounts = [1e7, 1e6]
        # Use this in test mode
        self.coinshuffle_amounts = [1e5, 1e6, 1e7]
        self.shuffle_grid = QGridLayout()
        self.shuffle_grid.setSpacing(8)
        self.shuffle_grid.setColumnStretch(3, 1)

        self.coinshuffle_servers = ServersList()
        self.coinshuffle_enable_bot = QCheckBox(_('Use bot'))
        self.coinshuffle_inputs_label = QLabel(_('Shuffle input address '))
        self.coinshuffle_inputs_total_label = QLabel(
            _('Total amount in selected coins'))
        self.coinshuffle_inputs_total_output = QLabel()
        self.coinshuffle_changes = ChangeAdressWidget()
        self.coinshuffle_changes_label = QLabel(_('Shuffle change address'))
        self.coinshuffle_fresh_changes = QCheckBox(
            _('Show only fresh change addresses'))
        self.coinshuffle_use_external_output = QCheckBox(
            _('Use external output address'))
        self.coinshuffle_outputs = OutputAdressWidget()
        self.coinshuffle_outputs_label = QLabel(_('Shuffle output address'))
        self.coinshuffle_external_output = ExternalOutput(
            testnet=self.window.config.get("testnet", False))
        self.coinshuffle_amount_radio = AmountSelect(self.coinshuffle_amounts,
                                                     window=self.window)
        self.coinshuffle_fee = QLabel(
            _(
                self.window.format_amount_and_units(
                    self.coinshuffle_fee_constant)))
        self.coinshuffle_amount_label = QLabel(_('Amount'))
        self.coinshuffle_text_output = ConsoleOutput()
        self.coinshuffle_timer_output = QLabel()

        self.coinshuffle_inputs_list = InputAddressesWidget(
            decimal_point=self.window.get_decimal_point, parent=self.window)

        self.coinshuffle_bot_limit = QLineEdit()
        self.coinshuffle_bot_limit.setValidator(QIntValidator(1, 100))
        self.coinshuffle_bot_limit.setText(str(self.bot_limit_value))
        self.coinshuffle_bot_limit_label = QLabel(
            _('Minimal number of players in pool'))
        self.coinshuffle_bot_maximum = QLineEdit()
        self.coinshuffle_bot_maximum.setValidator(QIntValidator(1, 100))
        self.coinshuffle_bot_maximum.setText(str(self.bot_maximum_value))
        self.coinshuffle_bot_maximum_label = QLabel(
            _('Maximum players to support pool'))
        self.coinshuffle_bot_period = QLineEdit()
        self.coinshuffle_bot_period.setValidator(QIntValidator(1, 1000))
        self.coinshuffle_bot_period.setText(str(self.bot_period_value))
        self.coinshuffle_bot_period_label = QLabel(
            _('Lookup period in minutes'))

        self.coinshuffle_bot_start_button = EnterButton(
            _("Run bot"), lambda: self.start_bot())
        self.coinshuffle_bot_stop_button = EnterButton(
            _("Stop bot"), lambda: self.cancel_bot())
        self.coinshuffle_bot_start_button.setEnabled(True)
        self.coinshuffle_bot_stop_button.setEnabled(False)

        self.coinshuffle_bot_limit.hide()
        self.coinshuffle_bot_maximum.hide()
        self.coinshuffle_bot_period.hide()
        self.coinshuffle_bot_limit_label.hide()
        self.coinshuffle_bot_maximum_label.hide()
        self.coinshuffle_bot_period_label.hide()
        self.coinshuffle_bot_start_button.hide()
        self.coinshuffle_bot_stop_button.hide()

        self.coinshuffle_inputs_list.clicked.connect(
            self.check_sufficient_ammount)
        self.coinshuffle_amount_radio.button_group.buttonClicked.connect(
            self.check_sufficient_ammount)
        self.coinshuffle_fresh_changes.stateChanged.connect(
            lambda: self.coinshuffle_changes.update(
                self.window.wallet,
                fresh_only=self.coinshuffle_fresh_changes.isChecked()))
        self.coinshuffle_use_external_output.stateChanged.connect(
            lambda: self.coinshuffle_change_outputs(
                self.coinshuffle_use_external_output.isChecked()))
        self.coinshuffle_external_output.textChanged.connect(
            self.check_sufficient_ammount)
        self.coinshuffle_enable_bot.stateChanged.connect(self.switch_bot)

        self.coinshuffle_start_button = EnterButton(
            _("Shuffle"), lambda: self.start_coinshuffle_protocol())
        self.coinshuffle_cancel_button = EnterButton(
            _("Cancel"), lambda: self.cancel_coinshuffle_protocol())
        self.coinshuffle_start_button.setEnabled(False)
        self.coinshuffle_cancel_button.setEnabled(False)

        self.shuffle_grid.addWidget(QLabel(_('Shuffle server')), 1, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_inputs_label, 2, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_inputs_total_label, 3, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_inputs_total_output, 3, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_changes_label, 4, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_outputs_label, 6, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_amount_label, 9, 0)
        self.shuffle_grid.addWidget(QLabel(_('Fee')), 10, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_servers, 1, 1, 1, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_enable_bot, 1, 2, 1, -1)
        self.shuffle_grid.addWidget(self.coinshuffle_fresh_changes, 5, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_use_external_output, 7, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_external_output, 8, 1, 1,
                                    -1)
        self.shuffle_grid.addWidget(self.coinshuffle_inputs_list, 2, 1, 1, -1)
        self.shuffle_grid.addWidget(self.coinshuffle_changes, 4, 1, 1, -1)
        self.shuffle_grid.addWidget(self.coinshuffle_outputs, 6, 1, 1, -1)
        self.shuffle_grid.addWidget(self.coinshuffle_amount_radio, 9, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_fee, 10, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_start_button, 11, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_cancel_button, 11, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_timer_output, 11, 2)
        self.shuffle_grid.addWidget(self.coinshuffle_text_output, 12, 0, 1, -1)

        self.shuffle_grid.addWidget(self.coinshuffle_bot_limit, 2, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_bot_maximum, 4, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_bot_period, 5, 1)
        self.shuffle_grid.addWidget(self.coinshuffle_bot_limit_label, 2, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_bot_maximum_label, 4, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_bot_period_label, 5, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_bot_start_button, 6, 0)
        self.shuffle_grid.addWidget(self.coinshuffle_bot_stop_button, 6, 1)

        self.shuffle_grid.addWidget(self.coinshuffle_inputs_list, 13, 1, 1, -1)

        self.window.cashaddr_toggled_signal.connect(
            lambda: self.update_inputs(force_update=True))

        self.check_sufficient_ammount()

        vbox0 = QVBoxLayout()
        vbox0.addLayout(self.shuffle_grid)
        hbox = QHBoxLayout()
        hbox.addLayout(vbox0)
        vbox = QVBoxLayout(self)
        vbox.addLayout(hbox)
        vbox.addStretch(1)

    def disable_bot_settings(self):
        self.coinshuffle_servers.setEnabled(False)
        self.coinshuffle_enable_bot.setEnabled(False)
        self.coinshuffle_bot_limit.setEnabled(False)
        self.coinshuffle_bot_maximum.setEnabled(False)
        self.coinshuffle_bot_period.setEnabled(False)

    def enable_bot_settings(self):
        self.coinshuffle_servers.setEnabled(True)
        self.coinshuffle_enable_bot.setEnabled(True)
        self.coinshuffle_bot_limit.setEnabled(True)
        self.coinshuffle_bot_maximum.setEnabled(True)
        self.coinshuffle_bot_period.setEnabled(True)

    def start_bot(self):
        server_params = self.coinshuffle_servers.get_current_server()
        server = server_params['server']
        port = server_params['port']
        info = server_params['info']
        ssl = server_params.get('ssl', False)
        stat_endpoint = "http{}://{}:{}/stats".format("s" if ssl else "",
                                                      server, info)
        limit_value = self.coinshuffle_bot_limit.text()
        limit = int(
            limit_value) if not limit_value == "" else self.bot_limit_value
        maximum_value = self.coinshuffle_bot_maximum.text()
        maximum = int(maximum_value
                      ) if not maximum_value == "" else self.bot_maximum_value
        period_value = self.coinshuffle_bot_period.text()
        period = int(
            period_value) if not period_value == "" else self.bot_period_value
        basic_logger = SimpleLogger(logchan=self.coinshuffle_text_output)
        coin = Coin(self.window.network)
        fee = self.coinshuffle_fee_constant
        password = None
        parent = self.window.top_level_window()
        while self.window.wallet.has_password():
            password = self.window.password_dialog(parent=parent)
            if password is None:
                # User cancelled password input
                return
            try:
                self.window.wallet.check_password(password)
                break
            except Exception as e:
                self.window.show_error(str(e), parent=parent)
                continue
        bot_logger = ConsoleLogger()
        bot_logger.logUpdater.connect(
            lambda x: self.coinshuffle_text_output.append(x))
        self.bot_thread = BotThread(stat_endpoint, server, port,
                                    self.window.network, ssl, limit, maximum,
                                    SimpleLogger, self.window.wallet, password,
                                    fee, bot_logger, True, period)
        self.bot_thread.start()
        self.disable_bot_settings()
        self.coinshuffle_bot_start_button.setEnabled(False)
        self.coinshuffle_bot_stop_button.setEnabled(True)

    def cancel_bot(self):
        self.coinshuffle_bot_stop_button.setEnabled(False)
        if self.bot_thread:
            self.bot_thread.join()
        self.coinshuffle_bot_start_button.setEnabled(True)
        self.enable_bot_settings()

    def switch_bot(self, checked):
        if checked:
            self.coinshuffle_inputs_list.hide()
            self.coinshuffle_inputs_label.hide()
            self.coinshuffle_inputs_total_label.hide()
            self.coinshuffle_inputs_total_output.hide()
            self.coinshuffle_changes.hide()
            self.coinshuffle_changes_label.hide()
            self.coinshuffle_fresh_changes.hide()
            self.coinshuffle_outputs_label.hide()
            self.coinshuffle_outputs.hide()
            self.coinshuffle_use_external_output.hide()
            self.coinshuffle_external_output.hide()
            self.coinshuffle_amount_label.hide()
            self.coinshuffle_amount_radio.hide()
            self.coinshuffle_start_button.hide()
            self.coinshuffle_cancel_button.hide()
            self.coinshuffle_timer_output.hide()

            self.coinshuffle_bot_limit.show()
            self.coinshuffle_bot_maximum.show()
            self.coinshuffle_bot_period.show()
            self.coinshuffle_bot_limit_label.show()
            self.coinshuffle_bot_maximum_label.show()
            self.coinshuffle_bot_period_label.show()
            self.coinshuffle_bot_start_button.show()
            self.coinshuffle_bot_stop_button.show()

        else:
            self.coinshuffle_bot_limit.hide()
            self.coinshuffle_bot_maximum.hide()
            self.coinshuffle_bot_period.hide()
            self.coinshuffle_bot_limit_label.hide()
            self.coinshuffle_bot_maximum_label.hide()
            self.coinshuffle_bot_period_label.hide()
            self.coinshuffle_bot_start_button.hide()
            self.coinshuffle_bot_stop_button.hide()

            self.coinshuffle_inputs_list.show()
            self.coinshuffle_inputs_label.show()
            self.coinshuffle_inputs_total_label.show()
            self.coinshuffle_inputs_total_output.show()
            self.coinshuffle_changes.show()
            self.coinshuffle_changes_label.show()
            self.coinshuffle_fresh_changes.show()
            self.coinshuffle_outputs_label.show()
            self.coinshuffle_outputs.show()
            self.coinshuffle_use_external_output.show()
            self.coinshuffle_external_output.show()
            self.coinshuffle_amount_label.show()
            self.coinshuffle_amount_radio.show()
            self.coinshuffle_start_button.show()
            self.coinshuffle_cancel_button.show()
            self.coinshuffle_timer_output.show()

    def coinshuffle_change_outputs(self, checked):
        if checked:
            self.coinshuffle_external_output.setEnabled(True)
            self.coinshuffle_outputs.setEnabled(False)
        else:
            self.coinshuffle_external_output.setEnabled(False)
            self.coinshuffle_outputs.setEnabled(True)
        self.check_sufficient_ammount()

    def update_inputs(self, force_update=False):
        if not self.coinshuffle_cancel_button.isEnabled():
            self.coinshuffle_inputs_list.update(self.window.wallet,
                                                force_update=force_update)
            self.coinshuffle_outputs.update(self.window.wallet)
            self.coinshuffle_changes.update(
                self.window.wallet,
                fresh_only=self.coinshuffle_fresh_changes.isChecked())

    def tick(self):
        self.waiting_timeout -= 1
        if self.waiting_timeout > 0:
            self.coinshuffle_timer_output.setText("{} s to break".format(
                self.waiting_timeout))
        else:
            self.logger.send("Error: timeout waiting for another players")

    def set_coinshuffle_addrs(self):
        self.coinshuffle_servers.setItems()
        self.coinshufle_input_addrs = map(lambda x: x.get('address'),
                                          self.window.wallet.get_utxos())
        self.coinshuffle_outputs_addrs = map(lambda x: x.get('address'),
                                             self.window.wallet.get_utxos())
        self.coinshuffle_inputs_list.setItems(self.window.wallet)
        self.coinshuffle_changes.setItems(
            self.window.wallet,
            fresh_only=self.coinshuffle_fresh_changes.isChecked())
        self.coinshuffle_outputs.setItems(self.window.wallet)

    def get_sufficient_amount(self):
        return self.coinshuffle_amount_radio.get_amount(
        ) + self.coinshuffle_fee_constant

    def check_sufficient_ammount(self):
        coin_amount = self.coinshuffle_inputs_list.get_selected_amount()
        self.coinshuffle_inputs_total_output.setText(
            self.window.format_amount_and_units(coin_amount))
        shuffle_amount = self.coinshuffle_amount_radio.get_amount()
        fee = self.coinshuffle_fee_constant
        if shuffle_amount and fee:
            if coin_amount > (fee + shuffle_amount):
                self.coinshuffle_start_button.setEnabled(True)
                if self.coinshuffle_use_external_output.isChecked():
                    if not Address.is_valid(
                            self.coinshuffle_external_output.text()):
                        self.coinshuffle_start_button.setEnabled(False)
            else:
                self.coinshuffle_start_button.setEnabled(False)
        else:
            self.coinshuffle_start_button.setEnabled(False)

    def enable_coinshuffle_settings(self):
        # self.check_sufficient_ammount()
        self.coinshuffle_servers.setEnabled(True)
        self.coinshuffle_start_button.setEnabled(True)
        self.coinshuffle_inputs_list.setEnabled(True)
        self.coinshuffle_changes.setEnabled(True)
        self.coinshuffle_outputs.setEnabled(True)
        self.coinshuffle_amount_radio.setEnabled(True)
        self.waiting_timeout = 180
        self.coinshuffle_timer_output.setText("")
        self.coinshuffle_use_external_output.setEnabled(True)
        self.coinshuffle_external_output.setEnabled(True)
        self.coinshuffle_fresh_changes.setEnabled(True)
        self.coinshuffle_enable_bot.setEnabled(True)

    def disable_coinshuffle_settings(self):
        self.coinshuffle_servers.setEnabled(False)
        self.coinshuffle_start_button.setEnabled(False)
        self.coinshuffle_inputs_list.setEnabled(False)
        self.coinshuffle_changes.setEnabled(False)
        self.coinshuffle_outputs.setEnabled(False)
        self.coinshuffle_amount_radio.setEnabled(False)
        self.coinshuffle_use_external_output.setEnabled(False)
        self.coinshuffle_external_output.setEnabled(False)
        self.coinshuffle_fresh_changes.setEnabled(False)
        self.coinshuffle_enable_bot.setEnabled(False)

    def process_protocol_messages(self, message):
        if message.startswith("Error"):
            self.pThread.join()
            self.coinshuffle_text_output.setTextColor(QColor('red'))
            self.coinshuffle_text_output.append(message)
            self.enable_coinshuffle_settings()
            self.coinshuffle_cancel_button.setEnabled(False)
            self.coinshuffle_inputs_list.update(self.window.wallet)
            self.coinshuffle_outputs.update(self.window.wallet)
            self.timer.stop()
        elif message[-17:] == "complete protocol":
            self.coinshuffle_text_output.append(message)
            self.pThread.done.set()
            tx = self.pThread.protocol.tx
            if tx:
                self.pThread.join()
            else:
                print("No tx: " + str(tx.raw))
            self.enable_coinshuffle_settings()
            self.coinshuffle_cancel_button.setEnabled(False)
            self.coinshuffle_inputs_list.update(self.window.wallet)
            self.coinshuffle_outputs.update(self.window.wallet)
        elif "begins" in message:
            self.timer.stop()
            self.coinshuffle_timer_output.setText("")
            self.waiting_timeout = 180
        else:
            header = message[:6]
            if header == 'Player':
                self.coinshuffle_text_output.setTextColor(QColor('green'))
            if header[:5] == 'Blame':
                self.coinshuffle_text_output.setTextColor(QColor('red'))
                if "insufficient" in message:
                    pass
                elif "wrong hash" in message:
                    pass
                else:
                    self.pThread.join()
                    self.enable_coinshuffle_settings()
                    self.coinshuffle_text_output.append(
                        str(self.pThread.isAlive()))
            self.coinshuffle_text_output.append(message)
            self.coinshuffle_text_output.setTextColor(QColor('black'))

    def start_coinshuffle_protocol(self):
        from .client import ProtocolThread
        from electroncash.bitcoin import (regenerate_key, deserialize_privkey)
        from .shuffle import ConsoleLogger
        parent = self.window.top_level_window()
        password = None
        while self.window.wallet.has_password():
            password = self.window.password_dialog(parent=parent)
            if password is None:
                # User cancelled password input
                return
            try:
                self.window.wallet.check_password(password)
                break
            except Exception as e:
                self.window.show_error(str(e), parent=parent)
                continue
        try:
            server_params = self.coinshuffle_servers.get_current_server()
            server = server_params['server']
            port = server_params['port']
            ssl = server_params.get('ssl', False)
        except:
            self.coinshuffle_text_output.setText(
                'Wrong server connection string')
            return

        inputs_utxos = self.coinshuffle_inputs_list.get_checked_utxos()
        possible_change_address = self.coinshuffle_changes.get_change_address()
        if possible_change_address:
            change_address = possible_change_address
        else:
            change_address = inputs_utxos[0]['address'].to_string(
                Address.FMT_LEGACY)
        if self.coinshuffle_use_external_output.isChecked():
            output_address = self.coinshuffle_external_output.text()
        else:
            output_address = self.coinshuffle_outputs.get_output_address()
        #disable inputs
        self.disable_coinshuffle_settings()
        self.coinshuffle_cancel_button.setEnabled(True)
        #
        amount = self.coinshuffle_amount_radio.get_amount()
        fee = self.coinshuffle_fee_constant
        self.logger = ConsoleLogger()
        self.logger.logUpdater.connect(
            lambda x: self.process_protocol_messages(x))
        sks = {}
        inputs = {}
        for utxo in inputs_utxos:
            public_key = self.window.wallet.get_public_key(utxo['address'])
            priv_key = self.window.wallet.export_private_key(
                utxo['address'], password)
            sks[public_key] = regenerate_key(deserialize_privkey(priv_key)[1])
            if not public_key in inputs:
                inputs[public_key] = []
            inputs[public_key].append(utxo['prevout_hash'] + ":" +
                                      str(utxo['prevout_n']))
        pub_key = list(inputs.keys())[0]
        sk = sks[pub_key]
        self.pThread = ProtocolThread(server,
                                      port,
                                      self.window.network,
                                      amount,
                                      fee,
                                      sk,
                                      sks,
                                      inputs,
                                      pub_key,
                                      output_address,
                                      change_address,
                                      logger=self.logger,
                                      ssl=ssl)
        self.pThread.start()
        self.timer.start(1000)

    def cancel_coinshuffle_protocol(self):
        if self.pThread.is_alive():
            self.pThread.join()
            while self.pThread.is_alive():
                time.sleep(0.1)
            self.coinshuffle_cancel_button.setEnabled(False)
            self.timer.stop()
            self.enable_coinshuffle_settings()
Exemplo n.º 10
0
class Dialog(QDialog):
    """Class to generate an user-defined input box

    Example

    >>> dialog = Dialog(varnames)
    >>> dialog.exec_()
    >>> return dialog.returnValues()

    Attributes:
        closeButton (QPushButton): Push butto to close the dialog box
        errorMessageDialog (TYPE): Description
        native (QCheckBox): Description
        varnames (list): Name of the variable we want to  input
    """
    def __init__(self,
                 varnames,
                 vartypes='float',
                 window_name='Enter Values',
                 parent=None):
        super(Dialog, self).__init__(parent)

        frameStyle = QFrame.Sunken | QFrame.Panel

        self.varnames = varnames
        self.vartypes = vartypes
        if not isinstance(self.vartypes, list):
            self.vartypes = [vartypes] * len(self.varnames)

        self.Label, self.Button, self.values = {}, {}, {}

        for name in varnames:
            self.Label[name] = QLabel()
            self.Label[name].setFrameStyle(frameStyle)
            self.Button[name] = QPushButton(name)

        self.closeButton = QPushButton("OK")

        for name, vtype in zip(self.varnames, self.vartypes):
            self.Button[name].clicked.connect(
                partial(self.setValue, name, vtype))
        self.closeButton.clicked.connect(self.close)

        self.native = QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)

        for i, name in enumerate(varnames):
            layout.addWidget(self.Button[name], i, 0)
            layout.addWidget(self.Label[name], i, 1)

        layout.addWidget(self.closeButton, len(varnames), 1)
        self.setLayout(layout)
        self.setWindowTitle(window_name)

    def setValue(self, name, vtype):
        """Set the value of the variable

        Args:
            name (str): variable name
            type (str): variable type
        """
        if vtype == 'float':
            d, ok = QInputDialog.getDouble(self, "Get Double", "Value:", 37.56,
                                           -10000, 10000, 2)
            if ok:
                self.Label[name].setText("$%g" % d)
                self.values[name] = d

        elif vtype == 'str':
            text, ok = QInputDialog.getText(self, "Get String", "Value:",
                                            QLineEdit.Normal, '')
            if ok and text != '':
                self.Label[name].setText(text)
                self.values[name] = text

        elif vtype == 'int':
            i, ok = QInputDialog.getInt(self, "Get Integer", "Value:", 25, 0,
                                        100, 1)
            if ok:
                self.Label[name].setText("%d%%" % i)
                self.values[name] = i

    def returnValues(self):
        """Return the values of all the variables

        Returns:
            list: The values of the variables
        """
        return [self.values[name] for name in self.varnames]
Exemplo n.º 11
0
class MainWindow(QWidget):
    """ This class contain the GUI and the functions for the Main window \n
    and uses all the other classes."""
    
    def __init__(self):
        super(MainWindow, self).__init__()
        """Overall layout of the main window."""
        self.setWindowTitle('Plot segmentation')
        self.resize(self.sizeHint())
        
        ## initialization
        self.field_image = None
        self.displaySize = 400
        self.threshold = 0.20
        self.noise = 200
        self.pix4D = None
        self.rawImgFold = None

        ## definition
        self.text_intro = QLabel('LOAD FIELD IMAGE')
        self.text_intro.setAlignment(Qt.AlignCenter)
        self.text_screenSize = QLabel('Select your screen resolution:')
        self.text_screenSize2 = QLabel('(If the size is not in the list, please choose a smaller size.)')
        self.comboBox_screenSize = QComboBox()
        self.comboBox_screenSize.addItem('1024 x 640 pixels')
        self.comboBox_screenSize.addItem('1280 x 800 pixels')
        self.comboBox_screenSize.addItem('1440 x 900 pixels')
        self.comboBox_screenSize.addItem('1680 x 1050 pixels')        
        self.comboBox_screenSize.addItem('2048 x 1152 pixels')
        self.comboBox_screenSize.addItem('2560 x 1140 pixels')
        self.comboBox_screenSize.addItem('3200 x 1800 pixels')
        self.text_fieldImage = QLabel('Choose the field image: ')
        self.button_fieldImage = QPushButton('Choose')
        self.text_image = QLabel('Image chosen:')
        self.text_imagePath = QLabel(str(self.field_image))
        self.button_drawField = QPushButton('Draw field shape')
        self.button_getBinary = QPushButton('Convert to binary')
        self.check_binary = QCheckBox('Check this if the chosen image is already a binary')
        self.text_threshold = QLabel('ExG threshold to create binary:')
        self.text_threshold2 = QLabel('0.20 usually works. Set to 1.00 for automatic.')
        self.spinbox_threshold = QDoubleSpinBox()
        self.spinbox_threshold.setRange(0.00, 1.00)
        self.spinbox_threshold.setSingleStep(0.05)
        self.spinbox_threshold.setValue(0.20)
        self.text_noise = QLabel('Minimum feature size for noise removal (px):')
        self.spinbox_noise = QSpinBox()
        self.spinbox_noise.setRange(1, 10000)
        self.spinbox_noise.setValue(200)
        
        self.text_plot = QLabel('PLOT PARAMETERS')
        self.text_plot.setAlignment(Qt.AlignCenter)
        self.text_nbOfRowPerPlot = QLabel('Number of plant rows per plot:')
        self.spinbox_nbOfRowPerPlot = QSpinBox()
        self.spinbox_nbOfRowPerPlot.setRange(1, 100)
        self.spinbox_nbOfRowPerPlot.setSingleStep(1)
        self.spinbox_nbOfRowPerPlot.setValue(1)
        self.text_nbOfColumnPerPlot = QLabel('Number of ranges per plot:')
        self.spinbox_nbOfColumnPerPlot = QSpinBox()
        self.spinbox_nbOfColumnPerPlot.setRange(1, 100)
        self.spinbox_nbOfColumnPerPlot.setSingleStep(1)
        self.spinbox_nbOfColumnPerPlot.setValue(1)
        self.text_plotArrangment = QLabel('Global orientation of the ranges:')
        self.radio_horizontal = QRadioButton('Horizontal\t\t\t')
        self.radio_horizontal.setChecked(True)
        self.radio_vertical = QRadioButton('Vertical')
        self.radio_vertical.setChecked(False)
        self.button_apply = QPushButton('Identify plots')

        self.text_intro_revCal = QLabel('CALCULATE PLOT COORDINATES IN RAW IMAGES')
        self.text_intro_revCal.setAlignment(Qt.AlignCenter)
        self.text_pix4D = QLabel('Pix4D project folder:')
        self.button_pix4D = QPushButton('Choose')
        self.text_rawImgFold = QLabel('Raw images folder:')
        self.button_rawImgFold = QPushButton('Choose')
        self.button_apply_revCal = QPushButton('Apply')
        
        ## connections
        self.button_fieldImage.clicked.connect(self.fieldImage_clicked)
        self.button_drawField.clicked.connect(self.drawField_clicked)
        self.comboBox_screenSize.activated.connect(self.ScreenSizeFunction)
        self.button_getBinary.clicked.connect(self.getBinary_clicked)
        self.button_apply.clicked.connect(self.application)
        self.button_pix4D.clicked.connect(self.button_pix4D_clicked)
        self.button_rawImgFold.clicked.connect(self.button_rawImgFold_clicked)
        self.button_apply_revCal.clicked.connect(self.button_apply_revCal_clicked)
        
        ## options
        self.text_screenSize.hide()
        self.text_screenSize2.hide()
        self.comboBox_screenSize.hide()
        self.check_binary.hide()
        self.text_threshold.hide()
        self.text_threshold2.hide()
        self.spinbox_threshold.hide()
        self.text_noise.hide()
        self.spinbox_noise.hide()
        self.button_drawField.hide()
        self.text_imagePath.hide()
        self.text_image.hide()
        self.text_plot.hide()
        self.button_getBinary.hide()
        self.text_nbOfColumnPerPlot.hide()
        self.spinbox_nbOfColumnPerPlot.hide()
        self.text_nbOfRowPerPlot.hide()
        self.spinbox_nbOfRowPerPlot.hide()
        self.button_apply.hide()
        self.text_plotArrangment.hide()
        self.radio_horizontal.hide()
        self.radio_vertical.hide()
        self.text_intro_revCal.hide()
        self.text_pix4D.hide()
        self.button_pix4D.hide()
        self.text_rawImgFold.hide()
        self.button_rawImgFold.hide()
        self.button_apply_revCal.hide()
        
        ## layout
        self.layout = QGridLayout()
        self.layout.addWidget(self.text_intro, 1, 0, 1, -1)
        self.layout.addWidget(self.text_fieldImage, 2, 0)
        self.layout.addWidget(self.button_fieldImage, 2, 1, 1, -1)
        self.layout.addWidget(self.text_image, 3, 0)
        self.layout.addWidget(self.text_imagePath, 3, 1, 1, -1)
        self.layout.addWidget(self.check_binary, 4, 1, 1, -1)
        self.layout.addWidget(self.text_noise, 5, 0)
        self.layout.addWidget(self.spinbox_noise, 5, 1)
        self.layout.addWidget(self.text_screenSize, 6, 0)
        self.layout.addWidget(self.comboBox_screenSize, 6, 1)
        self.layout.addWidget(self.text_screenSize2, 6, 2, 1, 3)
        self.layout.addWidget(self.button_drawField, 7, 0, 1, -1)
        
        self.layout.addWidget(self.text_threshold, 8, 0)
        self.layout.addWidget(self.spinbox_threshold, 8, 1)
        self.layout.addWidget(self.text_threshold2, 8, 2, 1, -1)
        self.layout.addWidget(self.button_getBinary, 9, 0, 1, -1)
        
        self.layout.addWidget(self.text_plot,10, 0, 1, -1)
        self.layout.addWidget(self.text_nbOfRowPerPlot, 11, 0)
        self.layout.addWidget(self.spinbox_nbOfRowPerPlot, 11, 1, 1, -1)
        self.layout.addWidget(self.text_nbOfColumnPerPlot, 12, 0)
        self.layout.addWidget(self.spinbox_nbOfColumnPerPlot, 12, 1, 1, -1)
        self.layout.addWidget(self.text_plotArrangment, 13, 0)
        self.layout.addWidget(self.radio_horizontal, 13, 1)
        self.layout.addWidget(self.radio_vertical, 13, 2)
        self.layout.addWidget(self.button_apply, 14, 0, 1, -1)
        
        self.layout.addWidget(self.text_intro_revCal, 15, 0, 1, -1)
        self.layout.addWidget(self.text_pix4D, 16, 0)
        self.layout.addWidget(self.button_pix4D, 16, 1, 1, -1)
        self.layout.addWidget(self.text_rawImgFold, 17, 0)
        self.layout.addWidget(self.button_rawImgFold, 17, 1, 1, -1)
        self.layout.addWidget(self.button_apply_revCal, 18, 0, 1, -1)
        self.setLayout(self.layout)  
        
        self.show()


    def ScreenSizeFunction(self):
        """ This function is part of the class 'MainWindow'. \n
        It is linked to the change of the combo box self.comboBox_screenSize \n
        It decides the maximum size for the display of pictures depending on the
        inputted size of the screen """
        if self.comboBox_screenSize.currentText() == '1024 x 640 pixels':
            self.displaySize = 600
        if self.comboBox_screenSize.currentText() == '1280 x 800 pixels':
            self.displaySize = 800
        if self.comboBox_screenSize.currentText() == '1440 x 900 pixels':
            self.displaySize = 900
        if self.comboBox_screenSize.currentText() == '1680 x 1050 pixels':
            self.displaySize = 1000
        if self.comboBox_screenSize.currentText() == '2048 x 1152 pixels':
            self.displaySize = 1100
        if self.comboBox_screenSize.currentText() == '2560 x 1140 pixels':
            self.displaySize = 1100
        if self.comboBox_screenSize.currentText() == '3200 x 1800 pixels':
            self.displaySize = 1700

    def fieldImage_clicked(self):
        """ This function is part of the class 'MainWindow' \n
        It is connected to the button button_fieldImage and allows the user to
        chose the image of the whole field on which all the program is based"""
        self.field_image, _ = QFileDialog.getOpenFileName(self, "Select the field image", "",".tif or .tiff or .jpg or .jpeg or .png (*.tif *.tiff *.TIF *.TIFF *.jpg *.jpeg *.JPG *.JPEG *.PNG *.png)", options=QFileDialog.DontUseNativeDialog)
        self.field_image = Path(self.field_image)
        self.text_imagePath.setText(str(self.field_image))
        if self.field_image.is_file():
            self.check_binary.show()
            self.text_noise.show()
            self.spinbox_noise.show()
            self.text_imagePath.show()
            self.text_image.show()
            self.text_screenSize.show()
            self.text_screenSize2.show()
            self.comboBox_screenSize.show()
            self.button_drawField.show()
        else:
            self.check_binary.hide()
            self.text_noise.hide()
            self.spinbox_noise.hide()
            self.text_imagePath.hide()
            self.text_image.hide()
            self.text_screenSize.hide()
            self.text_screenSize2.hide()
            self.comboBox_screenSize.hide()
            self.button_drawField.hide()
        self.coord = []
        self.text_threshold.hide()
        self.text_threshold2.hide()
        self.spinbox_threshold.hide()
        self.button_getBinary.hide()
        self.text_plot.hide()
        self.text_nbOfRowPerPlot.hide()
        self.spinbox_nbOfRowPerPlot.hide()
        self.text_nbOfColumnPerPlot.hide()
        self.spinbox_nbOfColumnPerPlot.hide()
        self.button_apply.hide()
        self.text_plotArrangment.hide()
        self.radio_horizontal.hide()
        self.radio_vertical.hide()
        self.text_intro_revCal.hide()
        self.text_pix4D.hide()
        self.button_pix4D.hide()
        self.text_rawImgFold.hide()
        self.button_rawImgFold.hide()
        self.button_apply_revCal.hide()

    def drawField_clicked(self):
        """This function is part of the class 'MainWindow' \n
        It is connected to the button button_drawField and opens the beforehand
        chosen image of fieldImage_clicked into a new window so the user can
        select the field points as they wish. The image is then binarized using
        ExGreen calculation and cropped to avoid useless data storage"""
        
        # instructions
        QMessageBox.about(self, 'Information', "A drawing window will appear. \nTo (Q)uit without saving, press Q.\nTo (R)estart, press R. \nWhen you are (D)one, press D. \n\nPlease mark the corners of the field. \nNo need to close the polygon.")
        
        # initialization
        self.coord = []
        self.YN_binary = self.check_binary.isChecked()
        self.img = cv2.imread(str(self.field_image))
        img_name = self.field_image.stem
        WindowsName = 'Mark the corners of the field. (Q)uit  (R)estart  (D)one'
 
        # make a repository
        self.main_folder = self.field_image.parent / str('Micro_plots_' + img_name)
        if self.main_folder.is_dir():
            rmtree(self.main_folder, ignore_errors = True)
        try:
            self.main_folder.mkdir()   
        except PermissionError:
            QMessageBox.about(self, 'Information', "Previous results for this image already existed and have been erased.")
            self.main_folder.mkdir()   
        except FileExistsError:
            QMessageBox.about(self, 'Information', "Results for this image already exist. Please delete or rename it and try again.")
            return
        
        # resize the image according to the screen size 
        if len(self.img[:, 0]) >= len(self.img[0,:]) : #if the picture's height is bigger than its width 
            self.H = self.displaySize
            coeff = self.H/len(self.img[:, 0])
            self.W = int(coeff*len(self.img[0, :]))
        else: # if width is bigger than height
            self.W = self.displaySize
            coeff = self.W/len(self.img[0, :])
            self.H = int(coeff*len(self.img[:, 0]))
        self.img = cv2.resize(self.img, (self.W, self.H)) 
        
        # if binary is [0,1], map 1's to 255
        if np.amax(self.img) == 1 :
            self.img [self.img == 1] = 255

        # display the picture in a new window
        cv2.namedWindow(WindowsName) 
        cv2.setMouseCallback(WindowsName, self.draw_point, param = None)
        
        # events while drawing (infinite loop)
        while (1):
            # show the image window
            cv2.imshow(WindowsName, self.img)
            key = cv2.waitKey(20) & 0xFF
            
            # to restart the drawing
            if key == ord('r') or key == ord('R'): 
                # reload the original image (without any points on it)
                self.img = cv2.imread(str(self.field_image))
                self.img = cv2.resize(self.img, (self.W, self.H)) 
                cv2.namedWindow(WindowsName, cv2.WINDOW_NORMAL) # define the name of the window again
                cv2.setMouseCallback(WindowsName, self.draw_point, param = None) # call the function 
                self.coord = [] # do not save any coordinates

            # to exit and stop the drawing mode
            if key == ord('q') or key == ord('Q'):
                self.coord = [] # no pixels are saved
                QMessageBox.about(self, 'Information', "No corners were selected.")
                # close the window
                cv2.destroyAllWindows()
                cv2.waitKey(1)
                self.text_threshold.hide()
                self.text_threshold2.hide()
                self.spinbox_threshold.hide()
                self.button_getBinary.hide()
                self.text_plot.hide()
                self.text_nbOfRowPerPlot.hide()
                self.spinbox_nbOfRowPerPlot.hide()
                self.text_nbOfColumnPerPlot.hide()
                self.spinbox_nbOfColumnPerPlot.hide()
                self.button_apply.hide()
                self.text_plotArrangment.hide()
                self.radio_horizontal.hide()
                self.radio_vertical.hide()
                self.text_intro_revCal.hide()
                self.text_pix4D.hide()
                self.button_pix4D.hide()
                self.text_rawImgFold.hide()
                self.button_rawImgFold.hide()
                self.button_apply_revCal.hide()
                return
            
            # to finish the drawing and save the points drawn
            if key == ord('d') or key == ord('D'): 
                # field must be at least rectangular
                if len(self.coord) < 3:
                    QMessageBox.about(self, 'Information', "Please select at least 3 points. \nIf you want to escape, press 'e' key.")
                else: 
                    ## when done, saving the images and producing exG + binary images
                    # close the drawing with the last magenta line
                    cv2.line(self.img, self.coord[-1], self.coord[0], (255, 0, 255), 1)
                    cv2.imshow(WindowsName, self.img)
                    QMessageBox.about(self, 'Information', "Selected points are: \n" + str(self.coord) + '\n\nThe image will be processed. \nPress OK and wait a few seconds.')
                    # save the coordinate image
                    cv2.imwrite(str(self.main_folder / 'Field_points.jpg'), self.img)
                    cv2.destroyWindow(WindowsName)
                    self.img = get_drawn_image(self.field_image, self.coord, coeff)
                    
                    if self.YN_binary:
                        # get rid of the useless black pixels
                        coords = np.argwhere(self.img)
                        y0, x0 = coords.min(axis = 0)
                        y1, x1 = coords.max(axis = 0) + 1
                        self.img = self.img[y0:y1, x0:x1]
                        # apply the noise removal
                        B = (self.img != 0)
                        self.img_binary = morphology.remove_small_objects(B, min_size = int(self.noise))*255
                        # save binary image
                        cv2.imwrite(str(self.main_folder / 'Binary_image.tiff'), self.img_binary)
                        # save the value of cutted black parts for the end of the program (shp files)
                        self.y_offset, self.x_offset = y0, x0
        
                        self.text_plot.show()
                        self.text_nbOfRowPerPlot.show()
                        self.spinbox_nbOfRowPerPlot.show()
                        self.text_nbOfColumnPerPlot.show()
                        self.spinbox_nbOfColumnPerPlot.show()
                        self.button_apply.show()
                        self.text_plotArrangment.show()
                        self.radio_horizontal.show()
                        self.radio_vertical.show()
                        self.text_threshold.hide()
                        self.text_threshold2.hide()
                        self.spinbox_threshold.hide()
                        self.button_getBinary.hide()
                    else:
                        self.text_threshold.show()
                        self.text_threshold2.show()
                        self.spinbox_threshold.show()
                        self.button_getBinary.show()
                    self.text_intro_revCal.hide()
                    self.text_pix4D.hide()
                    self.button_pix4D.hide()
                    self.text_rawImgFold.hide()
                    self.button_rawImgFold.hide()
                    self.button_apply_revCal.hide()
                    return
                    
    def getBinary_clicked(self):
        """This function is part of the class 'MainWindow' \n
        It is connected to the button button_getBinary and opens the beforehand
        chosen image of fieldImage_clicked into a new window so the user can
        select the field points as they wish. The image is then binarized using
        ExGreen calculation and cropped to avoid useless data storage"""
        
        self.threshold = self.spinbox_threshold.value()
        self.noise = self.spinbox_noise.value()
        # get coordinates of the first non-black pixels
        coords = np.argwhere(self.img)
        try:
            y0, x0, z = coords.min(axis = 0)
            y1, x1, z = coords.max(axis = 0) + 1
            # generate a binary image
            self.img_exG, self.img_binary = get_binary(self.img, self.noise, self.threshold)
           # cut all images according to avoid useless black pixels
            self.img = self.img[y0:y1, x0:x1]
            self.img_exG = self.img_exG[y0:y1, x0:x1]
            self.img_binary = self.img_binary[y0:y1, x0:x1]
            # save outputs
            cv2.imwrite(str(self.main_folder / 'ExcessGreen.tiff'), self.img_exG)
            cv2.imwrite(str(self.main_folder / 'Field_area.tiff'), self.img)
             # show binary and ask to accept/reject
            QMessageBox.about(self, 'Information', "The binary will be displayed. \nTo (A)ccept it, press A.\nTo (R)etry with a different threshold, press R.")
            while (1):
                # show the image window
                self.img_binary_show = cv2.resize(self.img_binary, (self.W, self.H)) 
                cv2.imshow('Binary. (A)ccept  (R)etry', self.img_binary_show)
                key = cv2.waitKey(20) & 0xFF
                # to retry with different values
                if key == ord('r') or key == ord('R'): 
                    cv2.destroyAllWindows()
                    self.text_plot.hide()
                    self.text_nbOfRowPerPlot.hide()
                    self.spinbox_nbOfRowPerPlot.hide()
                    self.text_nbOfColumnPerPlot.hide()
                    self.spinbox_nbOfColumnPerPlot.hide()
                    self.button_apply.hide()
                    self.text_plotArrangment.hide()
                    self.radio_horizontal.hide()
                    self.radio_vertical.hide()
                    self.text_intro_revCal.hide()
                    self.text_pix4D.hide()
                    self.button_pix4D.hide()
                    self.text_rawImgFold.hide()
                    self.button_rawImgFold.hide()
                    self.button_apply_revCal.hide()
                    return
                if key == ord('a') or key == ord('A'): 
                    cv2.destroyAllWindows()
                    break
        except ValueError:
            QMessageBox.about(self, 'Information', "It seems that your image is already a binary. It will be treated as a binary for the rest of the program.")
            self.YN_binary == True
            y0, x0 = coords.min(axis = 0)
            y1, x1 = coords.max(axis = 0) + 1
            self.img = self.img[y0:y1, x0:x1]
            # apply the noise removal
            B = (self.img != 0)
            self.img_binary = morphology.remove_small_objects(B, min_size = int(self.noise))*255
        
        # save the value of cutted black parts for the end of the program (shp files)
        self.y_offset, self.x_offset = y0, x0
        
        # displays buttons useful for next steps
        self.text_plot.show()
        self.text_nbOfRowPerPlot.show()
        self.spinbox_nbOfRowPerPlot.show()
        self.text_nbOfColumnPerPlot.show()
        self.spinbox_nbOfColumnPerPlot.show()
        self.button_apply.show()
        self.text_plotArrangment.show()
        self.radio_horizontal.show()
        self.radio_vertical.show()
        self.text_intro_revCal.hide()
        self.text_pix4D.hide()
        self.button_pix4D.hide()
        self.text_rawImgFold.hide()
        self.button_rawImgFold.hide()
        self.button_apply_revCal.hide()
            
    def draw_point (self, event, x, y, flags, param):
        """ This function is part of the class 'MainWindow' and is used in the
        function 'drawField_clicked'. 
        It draws a red circle everytime the right
        button of the mouse is clicked down. If there is more than one point, a 
        magenta line will link the two latest points clicked.
        
        Inputs : 5
            event : mouth clicked down
            x : position on the x-axis
            y : position on the y-axis (going down)
            flags : 
            param : None [could pass a specific color if needed]
            """
        if event == cv2.EVENT_LBUTTONDOWN: 
            #when the button is pushed, the first pixel is recorded and a circle is drawn on the picture
            self.coord.append((int(x), int(y)))
            cv2.circle(self.img, (x,y), 6, (0, 0, 255), -1) #draw the circle
            if len(self.coord) > 1:
                cv2.line(self.img, self.coord[-2], self.coord[-1], (255, 0, 255), 1)
                
    def application(self):
        """ This function is part of the class 'MainWindow'.
        It is linked to the button 'button_apply' and starts the image 
        processing (i.e. clustering, cropping, *.shp files, reverse calculation) 
        """
        if self.radio_horizontal.isChecked() == False and self.radio_vertical.isChecked() == False:
            QMessageBox.about(self, 'Information', "Please indicate if the ranges are more vertically or horizontally oriented. \nIf no particular orientation stands out, choose any.")
        else:
            img_raster = rasterio.open(self.field_image)
            aff = img_raster.transform
            self.crs = img_raster.crs
            if type(self.crs) == type(None):
                aff = 0
            img_raster.close()
            nbRow = self.spinbox_nbOfRowPerPlot.value()
            nbColumn = self.spinbox_nbOfColumnPerPlot.value()
            if self.radio_horizontal.isChecked() == True:
                orientation = 'H'
            elif self.radio_vertical.isChecked() == True:
                orientation = 'V'
            # inform the user the program is finished

            output = MPE(self.img_binary, self.main_folder, self.img, self.YN_binary,
                nbRow, nbColumn, orientation, self.noise,
                self.field_image, aff, self.y_offset, self.x_offset)
        
            if output == '1':
                QMessageBox.about(self, 'Information', 'Sorry, no range has been detected. Please change the input parameters and retry.')
                self.text_intro_revCal.hide()
                self.text_pix4D.hide()
                self.button_pix4D.hide()
                self.text_rawImgFold.hide()
                self.button_rawImgFold.hide()
                self.button_apply_revCal.hide()
            if output == '2':
                QMessageBox.about(self, 'Information', 'Sorry, no row has been detected. Please change the input parameters and retry.')
                self.text_intro_revCal.hide()
                self.text_pix4D.hide()
                self.button_pix4D.hide()
                self.text_rawImgFold.hide()
                self.button_rawImgFold.hide()
                self.button_apply_revCal.hide()
            elif output == 'OK' :
                QMessageBox.about(self, 'Information', '''Micro-plot extraction finished!''')
                # if the original image is georeferenced
                if type(self.crs) != type(None):
                    # unlock inputs for reverse calculation
                    self.text_intro_revCal.show()
                    self.text_pix4D.show()
                    self.button_pix4D.show()
                    self.text_rawImgFold.show()
                    self.button_rawImgFold.show()
                    self.button_apply_revCal.show()
                else :
                    QMessageBox.about(self, 'Information', 'The original image is not georeferenced. Thus, reverse calculation cannot be performed.')
                # make sure everything is unchecked/back to the original value
                self.spinbox_nbOfRowPerPlot.setValue(1)
                self.spinbox_nbOfColumnPerPlot.setValue(1)
                self.radio_horizontal.setChecked(True)
                self.radio_vertical.setChecked(False)

    def button_pix4D_clicked(self):
        self.pix4D = QFileDialog.getExistingDirectory(self, "Select the pix4D project folder")
        self.pix4D = Path(self.pix4D)
        
    def button_rawImgFold_clicked(self):
        self.rawImgFold = QFileDialog.getExistingDirectory(self, "Select the raw images folder")
        self.rawImgFold = Path(self.rawImgFold)

    def button_apply_revCal_clicked(self):
        if self.pix4D is None or self.rawImgFold is None:
            QMessageBox.about(self, 'Error', 'There are missing parameters. Please make sure you provided all the inputs.')
        else :

            revCal_csv = ReverseCalculation(self.main_folder, self.pix4D, self.rawImgFold)
                        
            QMessageBox.about(self, 'Information', 'Reverse calculation finished! Output: ' + 
                              str(revCal_csv))
            self.pix4D = None
            self.rawImgFold = None
Exemplo n.º 12
0
class Dialog(QDialog):

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.openFilesPath = ''

        self.errorMessageDialog = QErrorMessage(self)

        frameStyle = QFrame.Sunken | QFrame.Panel

        self.openFileNameLabel = QLabel()
        self.openFileNameLabel.setFrameStyle(frameStyle)
        self.openFileNameButton = QPushButton("Open()")

        self.saveFileNameLabel = QLabel()
        self.saveFileNameLabel.setFrameStyle(frameStyle)
        self.saveFileNameButton = QPushButton("Save()")


        self.openFileNameButton.clicked.connect(self.setOpenFileName)
        self.saveFileNameButton.clicked.connect(self.setSaveFileName)

        self.native = QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)

        # layout.addWidget(self.directoryLabel, 0, 0)
        layout.addWidget(self.openFileNameButton, 1, 0)
        layout.addWidget(self.openFileNameLabel, 1, 1)
        layout.addWidget(self.saveFileNameButton, 2, 0)
        layout.addWidget(self.saveFileNameLabel, 2, 1)

        layout.addWidget(self.native, 15, 0)
        self.setLayout(layout)

        self.setWindowTitle("Open Save File")



    def setOpenFileName(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,
                "QFileDialog.getOpenFileName()", self.openFileNameLabel.text(),
                "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            self.openFileNameLabel.setText(fileName)


    def setSaveFileName(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(self,
                "QFileDialog.getSaveFileName()",
                self.saveFileNameLabel.text(),
                "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            self.saveFileNameLabel.setText(fileName)
Exemplo n.º 13
0
class FilterWidget(CardView):

    attributesByComparison = {
        TagComparison.AT_LEAST: {
            "multipleKeys": False,
            "comparisonMessage": "is at least",
            "multipleValues": False,
            "exactValue": False,
            "negate": True,
            "numeric": True
        },
        TagComparison.AT_MOST: {
            "multipleKeys": False,
            "comparisonMessage": "is at most",
            "multipleValues": False,
            "exactValue": False,
            "negate": True,
            "numeric": True
        },
        TagComparison.CONTAIN_ALL: {
            "multipleKeys": False,
            "comparisonMessage": "contain the words",
            "multipleValues": True,
            "exactValue": True,
            "negate": True,
            "numeric": False
        },
        TagComparison.EQUAL: {
            "multipleKeys": False,
            "comparisonMessage": "is equal to",
            "multipleValues": False,
            "exactValue": True,
            "negate": True,
            "numeric": False
        },
        TagComparison.HAS_KEY: {
            "multipleKeys": False,
            "comparisonMessage": "exists",
            "multipleValues": None,
            "exactValue": True,
            "negate": False,
            "numeric": False
        },
        TagComparison.HAS_NOT_KEY: {
            "multipleKeys": False,
            "comparisonMessage": "does not exists",
            "multipleValues": None,
            "exactValue": False,
            "negate": False,
            "numeric": False
        },
        TagComparison.HAS_ONE_KEY: {
            "multipleKeys": True,
            "comparisonMessage": "at least one exists",
            "multipleValues": None,
            "exactValue": True,
            "negate": False,
            "numeric": False
        },
        TagComparison.IS_ONE_OF: {
            "multipleKeys": False,
            "comparisonMessage": "is one of",
            "multipleValues": True,
            "exactValue": True,
            "negate": True,
            "numeric": False
        }
    }

    def __init__(self, parent, comparison, keyList=None):
        super().__init__(parent)
        self.comparison = comparison
        if keyList is None:
            keyList = []
        self.keyList = keyList

        self.layout = self.__generateLayout__()
        self.setLayout(self.layout)
        if FilterWidget.attributesByComparison[comparison]["multipleKeys"]:
            self.__generateMultiKeyWidget__()
        else:
            topWidget, self.keyInput = self.__generateKeyWidget__()
            self.layout.addRow("Keys:", topWidget)
            self.layout.addRow(
                "",
                self.__generateComparisonLabel__(
                    FilterWidget.attributesByComparison[comparison]
                    ["comparisonMessage"]))
        if FilterWidget.attributesByComparison[comparison]["multipleValues"]:
            self.__generateMultiValueWidget__()
        elif FilterWidget.attributesByComparison[comparison][
                "multipleValues"] == False:
            self.__generateValueWidget__(
                FilterWidget.attributesByComparison[comparison]["numeric"])
        if FilterWidget.attributesByComparison[comparison]["exactValue"]:
            self.__generateFlagsWidget__()
            self.__addExactFlag__()
            if FilterWidget.attributesByComparison[comparison]["negate"]:
                self.__addNegateFlag__()
        elif FilterWidget.attributesByComparison[comparison]["negate"]:
            self.__generateFlagsWidget__()
            self.__addNegateFlag__()

    # UI COMPONENTS

    def __generateLayout__(self):
        layout = QFormLayout()
        layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        layout.setContentsMargins(10, 5, 10, 5)
        layout.setVerticalSpacing(5)
        layout.setLabelAlignment(Qt.AlignLeft)
        layout.setFormAlignment(Qt.AlignLeft | Qt.AlignTop)
        return layout

    def __generateKeyWidget__(self):
        topWidget = QWidget()
        topLayout = QHBoxLayout()
        topLayout.setSpacing(0)
        topLayout.setContentsMargins(0, 0, 0, 0)
        topWidget.setLayout(topLayout)

        keyInput = QComboBox()
        keyInput.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
        keyInput.setEditable(True)
        keyInput.lineEdit().setPlaceholderText("'highway', 'name'...")
        keyInput.addItems(self.keyList)
        topLayout.addWidget(keyInput)

        filterOptionsButton = IconButton(
            QIcon(os.path.join(picturesDir, "options.png")),
            topWidget.windowHandle(), keyInput.height())
        filterOptionsButton.setStyleSheet(
            """QPushButton::menu-indicator{image: none;}""")

        filterOptionsMenu = QMenu()

        removeAct = QAction('Remove filter', self)
        removeAct.triggered.connect(self.deleteLater)
        filterOptionsMenu.addAction(removeAct)

        helpAct = QAction('Help', self)
        helpAct.triggered.connect(self.getInfo)
        filterOptionsMenu.addAction(helpAct)

        filterOptionsButton.setMenu(filterOptionsMenu)
        filterOptionsButton.setFlat(True)
        topLayout.addWidget(filterOptionsButton)

        return topWidget, keyInput

    def __generateMultiKeyWidget__(self):
        topWidget = QWidget()
        topWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        topLayout = QHBoxLayout()
        topLayout.setSpacing(0)
        topLayout.setAlignment(Qt.AlignRight)
        topLayout.setContentsMargins(0, 0, 0, 0)
        topWidget.setLayout(topLayout)

        filterOptionsButton = IconButton(
            QIcon(os.path.join(picturesDir, "options.png")),
            topWidget.windowHandle(), topWidget.height())
        filterOptionsButton.setStyleSheet(
            """QPushButton::menu-indicator{image: none;}""")

        filterOptionsMenu = QMenu()

        removeAct = QAction('Remove filter', self)
        removeAct.triggered.connect(self.deleteLater)
        filterOptionsMenu.addAction(removeAct)

        helpAct = QAction('Help', self)
        helpAct.triggered.connect(self.getInfo)
        filterOptionsMenu.addAction(helpAct)

        filterOptionsButton.setMenu(filterOptionsMenu)
        filterOptionsButton.setFlat(True)
        topLayout.addWidget(filterOptionsButton)

        self.layout.addRow("Keys:", topWidget)

        keysArea = QScrollArea()
        keysArea.setWidgetResizable(True)
        self.keysWidget = QWidget()
        keysArea.setWidget(self.keysWidget)
        keysWidgetLayout = QVBoxLayout()
        keysWidgetLayout.setSpacing(0)
        keysWidgetLayout.setContentsMargins(0, 0, 0, 0)
        self.keysWidget.setLayout(keysWidgetLayout)

        self.layout.addWidget(keysArea)

        keysButtons = WidgetFactory.buildIconButtonGroup([
            {
                "image": "add.png",
                "tooltip": "Add key",
                "checkable": False,
                "action": self.addKey
            },
        ])

        self.layout.addWidget(keysButtons)

    def __generateComparisonLabel__(self, comparisonMessage):
        self.comparisonLabel = QLabel(comparisonMessage)
        return self.comparisonLabel

    def __generateValueWidget__(self, numeric=False):
        self.valueInput = QComboBox()
        self.valueInput.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Preferred)
        self.valueInput.setEditable(True)
        self.valueInput.lineEdit().setPlaceholderText(
            "'service', 'motorway'...")
        if numeric:
            self.valueInput.setValidator(
                QRegularExpressionValidator(QRegularExpression("^[0-9]+$")))
        self.keyInput.currentTextChanged.connect(self.valueInput.clear)

        self.layout.addRow("Value:", self.valueInput)

    def __generateMultiValueWidget__(self):
        self.valuesWidget = VariableInputList(placeHolder="Value")
        self.layout.addRow("Values:", self.valuesWidget)

    def __generateFlagsWidget__(self):
        flagsWidget = QWidget()
        flagsWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.flagsWidgetLayout = QHBoxLayout()
        self.flagsWidgetLayout.setContentsMargins(0, 0, 0, 0)
        flagsWidget.setLayout(self.flagsWidgetLayout)

        self.layout.addRow("Flags:", flagsWidget)

    def __addNegateFlag__(self):
        self.checkboxNegate = QCheckBox()
        self.checkboxNegate.setText("Negate")
        self.flagsWidgetLayout.addWidget(self.checkboxNegate)

    def __addExactFlag__(self):
        self.checkboxAccuracy = QCheckBox()
        self.checkboxAccuracy.setText("Exact")
        self.flagsWidgetLayout.addWidget(self.checkboxAccuracy)

    # TAG GETTERS

    def getFilter(self):
        key = self.getMultipleKeys() if FilterWidget.attributesByComparison[
            self.comparison]["multipleKeys"] else self.getKey()
        if type(key) is str and key == "":
            raise BadFilterAttributes("The key is empty.")
        elif type(key) is list:
            if len(key) == 0:
                raise BadFilterAttributes("There is no keys.")
            elif not all([len(each) > 0 for each in key]):
                raise BadFilterAttributes("One of the keys is empty.")
        comparison = self.getComparison()
        value = self.getMultipleValues(
        ) if FilterWidget.attributesByComparison[
            self.comparison]["multipleValues"] else self.getValue()
        if type(value) is str and value == "":
            raise BadFilterAttributes("The value is empty.")
        elif type(value) is list:
            if len(value) == 0:
                raise BadFilterAttributes("There is no values.")
            elif not all([len(each) > 0 for each in value]):
                raise BadFilterAttributes("One of the values is empty.")
        negated = self.isNegateSelected()
        exactValue = self.isExactValueSelected()

        return OverpassFilter(key, comparison, value, negated, exactValue)

    def getKey(self):
        try:
            return self.keyInput.currentText()
        except AttributeError:
            return None

    def getMultipleKeys(self):
        return [
            lineEdit.text()
            for lineEdit in self.keysWidget.findChildren(QLineEdit)
        ]

    def getComparison(self):
        return self.comparison

    def getValue(self):
        try:
            return self.valueInput.currentText()
        except AttributeError:
            return None

    def getMultipleValues(self):
        return [
            lineEdit.text()
            for lineEdit in self.valuesWidget.findChildren(QLineEdit)
        ]

    def isExactValueSelected(self):
        try:
            return self.checkboxAccuracy.isChecked()
        except AttributeError:
            return None

    def isNegateSelected(self):
        try:
            return self.checkboxNegate.isChecked()
        except AttributeError:
            return None

    # TAG SETTERS

    def setFilter(self, newFilter):
        if FilterWidget.attributesByComparison[
                self.comparison]["multipleKeys"]:
            self.setMultipleKeys(newFilter.key)
        else:
            self.setKey(newFilter.key)
        if FilterWidget.attributesByComparison[
                self.comparison]["multipleValues"]:
            self.setMultipleValues(newFilter.value)
        elif FilterWidget.attributesByComparison[
                self.comparison]["multipleValues"] == False:
            self.setValue(newFilter.value)
        if FilterWidget.attributesByComparison[self.comparison]["exactValue"]:
            self.setExactValue(newFilter.isExactValue)
        if FilterWidget.attributesByComparison[self.comparison]["negate"]:
            self.setNegate(newFilter.isNegated)

    def setKey(self, key):
        try:
            self.keyInput.setEditText(key)
        except AttributeError:
            pass

    def setMultipleKeys(self, keys=None):
        if keys is None:
            keys = []
        for lineEdit in self.keysWidget.findChildren(QLineEdit):
            lineEdit.deleteLater()
        for newKey in keys:
            self.addKey(newKey)

    def addKey(self, newKey=0):
        keyWidget = QWidget()
        keyWidgetLayout = QHBoxLayout()
        keyWidgetLayout.setContentsMargins(0, 0, 0, 0)
        keyWidget.setLayout(keyWidgetLayout)
        keyInput = QLineEdit()
        if newKey != 0:
            keyInput.setText(str(newKey))
        keyInput.setPlaceholderText("Key")
        keyInput.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
        keyWidgetLayout.addWidget(keyInput)
        removeIdButton = IconButton(
            QIcon(os.path.join(picturesDir, "remove.png")),
            keyWidget.windowHandle(), keyWidget.height())
        removeIdButton.setToolTip("Show table")
        removeIdButton.setFlat(True)
        removeIdButton.clicked.connect(keyWidget.deleteLater)

        keyWidgetLayout.addWidget(removeIdButton)

        self.keysWidget.layout().addWidget(keyWidget)

    def setValue(self, value):
        try:
            self.valueInput.setEditText(value)
        except AttributeError:
            pass

    def setMultipleValues(self, values=None):
        self.valuesWidget.setItems(values)

    def addValue(self, newValue=""):
        self.valuesWidget.addItem(newValue)

    def setExactValue(self, checked):
        try:
            self.checkboxAccuracy.setChecked(checked)
        except AttributeError:
            pass

    def setNegate(self, checked):
        try:
            self.checkboxNegate.setChecked(checked)
        except AttributeError:
            pass

    # SIGNALS

    def __onComparisonSelected__(self, i):
        if i > 4:
            self.valueInput.setEnabled(False)
            self.valueInput.lineEdit().setPlaceholderText("Not required")
            self.checkboxNegate.hide()
        else:
            self.valueInput.setEnabled(True)
            self.valueInput.lineEdit().setPlaceholderText(
                "'service', 'motorway'...")
            self.checkboxNegate.show()

        if 2 < i <= 5:
            self.checkboxAccuracy.hide()
        else:
            self.checkboxAccuracy.show()

    def getInfo(self):
        keyList = self.getMultipleKeys(
        ) if FilterWidget.attributesByComparison[
            self.comparison]["multipleKeys"] else [self.getKey()]
        try:
            for keyName in keyList:
                descriptions = getKeyDescription(keyName)
                if len(descriptions) == 0:
                    logging.warning(
                        "'{}' is an unofficial or unused key. No available description."
                        .format(keyName))
                else:
                    englishDescription = next(
                        (d["description"] for d in descriptions
                         if d["language_en"] == "English"),
                        "English description not available.")
                    logging.info(keyName + ": " + englishDescription)
        except RequestException:
            logging.error(
                "There was a problem with the internet connection. Can't get the key description."
            )
            return

        try:
            if self.getValue() is not None:
                self.valueInput.clear()
                if not FilterWidget.attributesByComparison[
                        self.comparison]["multipleKeys"]:
                    self.valueInput.addItems(getValuesByKey(keyList[0]))
        except requests.exceptions.Timeout:
            logging.warning("Too many available values for the given key.")
        except RequestException:
            logging.error(
                "There was a problem with the internet connection. Can't get the possible values for the "
                "given key.")
Exemplo n.º 14
0
class GalleryDialog(QWidget):
    """
    A window for adding/modifying gallery.
    Pass a list of QModelIndexes to edit their data
    or pass a path to preset path
    """
    def __init__(self, parent, arg=None):
        super().__init__(parent, Qt.Dialog)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAutoFillBackground(True)
        self.parent_widget = parent
        m_l = QVBoxLayout()
        self.main_layout = QVBoxLayout()
        dummy = QWidget(self)
        scroll_area = QScrollArea(self)
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameStyle(scroll_area.StyledPanel)
        dummy.setLayout(self.main_layout)
        scroll_area.setWidget(dummy)
        m_l.addWidget(scroll_area, 3)

        final_buttons = QHBoxLayout()
        final_buttons.setAlignment(Qt.AlignRight)
        m_l.addLayout(final_buttons)
        self.done = QPushButton("Done")
        self.done.setDefault(True)
        cancel = QPushButton("Cancel")
        final_buttons.addWidget(cancel)
        final_buttons.addWidget(self.done)
        self._multiple_galleries = False
        self._edit_galleries = []

        def new_gallery():
            self.setWindowTitle('Add a new gallery')
            self.newUI()
            self.commonUI()
            self.done.clicked.connect(self.accept)
            cancel.clicked.connect(self.reject)

        if arg:
            if isinstance(arg, (list, gallerydb.Gallery)):
                if isinstance(arg, gallerydb.Gallery):
                    self.setWindowTitle('Edit gallery')
                    self._edit_galleries.append(arg)
                else:
                    self.setWindowTitle('Edit {} galleries'.format(len(arg)))
                    self._multiple_galleries = True
                    self._edit_galleries.extend(arg)
                self.commonUI()
                self.setGallery(arg)
                self.done.clicked.connect(self.accept_edit)
                cancel.clicked.connect(self.reject_edit)
            elif isinstance(arg, str):
                new_gallery()
                self.choose_dir(arg)
        else:
            new_gallery()

        log_d('GalleryDialog: Create UI: successful')
        self.setLayout(m_l)
        if self._multiple_galleries:
            self.resize(500, 480)
        else:
            self.resize(500, 600)
        frect = self.frameGeometry()
        frect.moveCenter(QDesktopWidget().availableGeometry().center())
        self.move(frect.topLeft())
        self._fetch_inst = fetch.Fetch()
        self._fetch_thread = QThread(self)
        self._fetch_thread.setObjectName("GalleryDialog metadata thread")
        self._fetch_inst.moveToThread(self._fetch_thread)
        self._fetch_thread.started.connect(self._fetch_inst.auto_web_metadata)

    def commonUI(self):
        if not self._multiple_galleries:
            f_web = QGroupBox("Metadata from the Web")
            f_web.setCheckable(False)
            self.main_layout.addWidget(f_web)
            web_main_layout = QVBoxLayout()
            web_info = misc.ClickedLabel(
                "Which gallery URLs are supported? (hover)", parent=self)
            web_info.setToolTip(app_constants.SUPPORTED_METADATA_URLS)
            web_info.setToolTipDuration(999999999)
            web_main_layout.addWidget(web_info)
            web_layout = QHBoxLayout()
            web_main_layout.addLayout(web_layout)
            f_web.setLayout(web_main_layout)

            def basic_web(name):
                return QLabel(name), QLineEdit(), QPushButton(
                    "Get metadata"), QProgressBar()

            url_lbl, self.url_edit, url_btn, url_prog = basic_web("URL:")
            url_btn.clicked.connect(lambda: self.web_metadata(
                self.url_edit.text(), url_btn, url_prog))
            url_prog.setTextVisible(False)
            url_prog.setMinimum(0)
            url_prog.setMaximum(0)
            web_layout.addWidget(url_lbl, 0, Qt.AlignLeft)
            web_layout.addWidget(self.url_edit, 0)
            web_layout.addWidget(url_btn, 0, Qt.AlignRight)
            web_layout.addWidget(url_prog, 0, Qt.AlignRight)
            self.url_edit.setPlaceholderText(
                "Insert supported gallery URLs or just press the button!")
            url_prog.hide()

        f_gallery = QGroupBox("Gallery Info")
        f_gallery.setCheckable(False)
        self.main_layout.addWidget(f_gallery)
        gallery_layout = QFormLayout()
        f_gallery.setLayout(gallery_layout)

        def checkbox_layout(widget):
            if self._multiple_galleries:
                l = QHBoxLayout()
                l.addWidget(widget.g_check)
                widget.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Preferred)
                l.addWidget(widget)
                return l
            else:
                widget.g_check.setChecked(True)
                widget.g_check.hide()
                return widget

        def add_check(widget):
            widget.g_check = QCheckBox(self)
            return widget

        self.title_edit = add_check(QLineEdit())
        self.author_edit = add_check(QLineEdit())
        author_completer = misc.GCompleter(self, False, True, False)
        author_completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.author_edit.setCompleter(author_completer)
        self.descr_edit = add_check(QTextEdit())
        self.descr_edit.setAcceptRichText(True)
        self.lang_box = add_check(QComboBox())
        self.lang_box.addItems(app_constants.G_LANGUAGES)
        self.lang_box.addItems(app_constants.G_CUSTOM_LANGUAGES)
        self.rating_box = add_check(QSpinBox())
        self.rating_box.setMaximum(5)
        self.rating_box.setMinimum(0)
        self._find_combobox_match(self.lang_box, app_constants.G_DEF_LANGUAGE,
                                  0)
        tags_l = QVBoxLayout()
        tag_info = misc.ClickedLabel(
            "How do i write namespace & tags? (hover)", parent=self)
        tag_info.setToolTip(
            "Ways to write tags:\n\nNormal tags:\ntag1, tag2, tag3\n\n" +
            "Namespaced tags:\nns1:tag1, ns1:tag2\n\nNamespaced tags with one or more"
            +
            " tags under same namespace:\nns1:[tag1, tag2, tag3], ns2:[tag1, tag2]\n\n"
            +
            "Those three ways of writing namespace & tags can be combined freely.\n"
            +
            "Tags are seperated by a comma, NOT whitespace.\nNamespaces will be capitalized while tags"
            + " will be lowercased.")
        tag_info.setToolTipDuration(99999999)
        tags_l.addWidget(tag_info)
        self.tags_edit = add_check(misc.CompleterTextEdit())
        self.tags_edit.setCompleter(misc.GCompleter(self, False, False))
        self.tags_append = QCheckBox("Append tags", self)
        self.tags_append.setChecked(False)
        if not self._multiple_galleries:
            self.tags_append.hide()
        if self._multiple_galleries:
            self.tags_append.setChecked(app_constants.APPEND_TAGS_GALLERIES)
            tags_ml = QVBoxLayout()
            tags_ml.addWidget(self.tags_append)
            tags_ml.addLayout(checkbox_layout(self.tags_edit), 5)
            tags_l.addLayout(tags_ml, 3)
        else:
            tags_l.addWidget(checkbox_layout(self.tags_edit), 5)
        self.tags_edit.setPlaceholderText(
            "Press Tab to autocomplete (Ctrl + E to show popup)")
        self.type_box = add_check(QComboBox())
        self.type_box.addItems(app_constants.G_TYPES)
        self._find_combobox_match(self.type_box, app_constants.G_DEF_TYPE, 0)
        #self.type_box.currentIndexChanged[int].connect(self.doujin_show)
        #self.doujin_parent = QLineEdit()
        #self.doujin_parent.setVisible(False)
        self.status_box = add_check(QComboBox())
        self.status_box.addItems(app_constants.G_STATUS)
        self._find_combobox_match(self.status_box, app_constants.G_DEF_STATUS,
                                  0)
        self.pub_edit = add_check(QDateEdit())
        self.pub_edit.setCalendarPopup(True)
        self.pub_edit.setDate(QDate.currentDate())
        self.path_lbl = misc.ClickedLabel("")
        self.path_lbl.setWordWrap(True)
        self.path_lbl.clicked.connect(lambda a: utils.open_path(a, a)
                                      if a else None)

        link_layout = QHBoxLayout()
        self.link_lbl = add_check(QLabel(""))
        self.link_lbl.setWordWrap(True)
        self.link_edit = QLineEdit()
        link_layout.addWidget(self.link_edit)
        if self._multiple_galleries:
            link_layout.addLayout(checkbox_layout(self.link_lbl))
        else:
            link_layout.addWidget(checkbox_layout(self.link_lbl))
        self.link_edit.hide()
        self.link_btn = QPushButton("Modify")
        self.link_btn.setFixedWidth(50)
        self.link_btn2 = QPushButton("Set")
        self.link_btn2.setFixedWidth(40)
        self.link_btn.clicked.connect(self.link_modify)
        self.link_btn2.clicked.connect(self.link_set)
        link_layout.addWidget(self.link_btn)
        link_layout.addWidget(self.link_btn2)
        self.link_btn2.hide()

        rating_ = checkbox_layout(self.rating_box)
        lang_ = checkbox_layout(self.lang_box)
        if self._multiple_galleries:
            rating_.insertWidget(0, QLabel("Rating:"))
            lang_.addLayout(rating_)
            lang_l = lang_
        else:
            lang_l = QHBoxLayout()
            lang_l.addWidget(lang_)
            lang_l.addWidget(QLabel("Rating:"), 0, Qt.AlignRight)
            lang_l.addWidget(rating_)

        gallery_layout.addRow("Title:", checkbox_layout(self.title_edit))
        gallery_layout.addRow("Author:", checkbox_layout(self.author_edit))
        gallery_layout.addRow("Description:", checkbox_layout(self.descr_edit))
        gallery_layout.addRow("Language:", lang_l)
        gallery_layout.addRow("Tags:", tags_l)
        gallery_layout.addRow("Type:", checkbox_layout(self.type_box))
        gallery_layout.addRow("Status:", checkbox_layout(self.status_box))
        gallery_layout.addRow("Publication Date:",
                              checkbox_layout(self.pub_edit))
        gallery_layout.addRow("Path:", self.path_lbl)
        gallery_layout.addRow("URL:", link_layout)

        self.title_edit.setFocus()

    def resizeEvent(self, event):
        self.tags_edit.setFixedHeight(event.size().height() // 8)
        self.descr_edit.setFixedHeight(event.size().height() // 12.5)
        return super().resizeEvent(event)

    def _find_combobox_match(self, combobox, key, default):
        f_index = combobox.findText(key, Qt.MatchFixedString)
        if f_index != -1:
            combobox.setCurrentIndex(f_index)
            return True
        else:
            combobox.setCurrentIndex(default)
            return False

    def setGallery(self, gallery):
        "To be used for when editing a gallery"
        if isinstance(gallery, gallerydb.Gallery):
            self.gallery = gallery

            if not self._multiple_galleries:
                self.url_edit.setText(gallery.link)

            self.title_edit.setText(gallery.title)
            self.author_edit.setText(gallery.artist)
            self.descr_edit.setText(gallery.info)
            self.rating_box.setValue(gallery.rating)

            self.tags_edit.setText(utils.tag_to_string(gallery.tags))

            if not self._find_combobox_match(self.lang_box, gallery.language,
                                             1):
                self._find_combobox_match(self.lang_box,
                                          app_constants.G_DEF_LANGUAGE, 1)
            if not self._find_combobox_match(self.type_box, gallery.type, 0):
                self._find_combobox_match(self.type_box,
                                          app_constants.G_DEF_TYPE, 0)
            if not self._find_combobox_match(self.status_box, gallery.status,
                                             0):
                self._find_combobox_match(self.status_box,
                                          app_constants.G_DEF_STATUS, 0)

            gallery_pub_date = "{}".format(gallery.pub_date).split(' ')
            try:
                self.gallery_time = datetime.strptime(gallery_pub_date[1],
                                                      '%H:%M:%S').time()
            except IndexError:
                pass
            qdate_pub_date = QDate.fromString(gallery_pub_date[0],
                                              "yyyy-MM-dd")
            self.pub_edit.setDate(qdate_pub_date)

            self.link_lbl.setText(gallery.link)
            self.path_lbl.setText(gallery.path)

        elif isinstance(gallery, list):
            g = gallery[0]
            if all(map(lambda x: x.title == g.title, gallery)):
                self.title_edit.setText(g.title)
                self.title_edit.g_check.setChecked(True)
            if all(map(lambda x: x.artist == g.artist, gallery)):
                self.author_edit.setText(g.artist)
                self.author_edit.g_check.setChecked(True)
            if all(map(lambda x: x.info == g.info, gallery)):
                self.descr_edit.setText(g.info)
                self.descr_edit.g_check.setChecked(True)
            if all(map(lambda x: x.tags == g.tags, gallery)):
                self.tags_edit.setText(utils.tag_to_string(g.tags))
                self.tags_edit.g_check.setChecked(True)
            if all(map(lambda x: x.language == g.language, gallery)):
                if not self._find_combobox_match(self.lang_box, g.language, 1):
                    self._find_combobox_match(self.lang_box,
                                              app_constants.G_DEF_LANGUAGE, 1)
                self.lang_box.g_check.setChecked(True)
            if all(map(lambda x: x.rating == g.rating, gallery)):
                self.rating_box.setValue(g.rating)
                self.rating_box.g_check.setChecked(True)
            if all(map(lambda x: x.type == g.type, gallery)):
                if not self._find_combobox_match(self.type_box, g.type, 0):
                    self._find_combobox_match(self.type_box,
                                              app_constants.G_DEF_TYPE, 0)
                self.type_box.g_check.setChecked(True)
            if all(map(lambda x: x.status == g.status, gallery)):
                if not self._find_combobox_match(self.status_box, g.status, 0):
                    self._find_combobox_match(self.status_box,
                                              app_constants.G_DEF_STATUS, 0)
                self.status_box.g_check.setChecked(True)
            if all(map(lambda x: x.pub_date == g.pub_date, gallery)):
                gallery_pub_date = "{}".format(g.pub_date).split(' ')
                try:
                    self.gallery_time = datetime.strptime(
                        gallery_pub_date[1], '%H:%M:%S').time()
                except IndexError:
                    pass
                qdate_pub_date = QDate.fromString(gallery_pub_date[0],
                                                  "yyyy-MM-dd")
                self.pub_edit.setDate(qdate_pub_date)
                self.pub_edit.g_check.setChecked(True)
            if all(map(lambda x: x.link == g.link, gallery)):
                self.link_lbl.setText(g.link)
                self.link_lbl.g_check.setChecked(True)

    def newUI(self):

        f_local = QGroupBox("Directory/Archive")
        f_local.setCheckable(False)
        self.main_layout.addWidget(f_local)
        local_layout = QHBoxLayout()
        f_local.setLayout(local_layout)

        choose_folder = QPushButton("From Directory")
        choose_folder.clicked.connect(lambda: self.choose_dir('f'))
        local_layout.addWidget(choose_folder)

        choose_archive = QPushButton("From Archive")
        choose_archive.clicked.connect(lambda: self.choose_dir('a'))
        local_layout.addWidget(choose_archive)

        self.file_exists_lbl = QLabel()
        local_layout.addWidget(self.file_exists_lbl)
        self.file_exists_lbl.hide()

    def choose_dir(self, mode):
        """
        Pass which mode to open the folder explorer in:
        'f': directory
        'a': files
        Or pass a predefined path
        """
        self.done.show()
        self.file_exists_lbl.hide()
        if mode == 'a':
            name = QFileDialog.getOpenFileName(self,
                                               'Choose archive',
                                               filter=utils.FILE_FILTER)
            name = name[0]
        elif mode == 'f':
            name = QFileDialog.getExistingDirectory(self, 'Choose folder')
        elif mode:
            if os.path.exists(mode):
                name = mode
            else:
                return None
        if not name:
            return
        head, tail = os.path.split(name)
        name = os.path.join(head, tail)
        parsed = utils.title_parser(tail)
        self.title_edit.setText(parsed['title'])
        self.author_edit.setText(parsed['artist'])
        self.path_lbl.setText(name)
        if not parsed['language']:
            parsed['language'] = app_constants.G_DEF_LANGUAGE
        l_i = self.lang_box.findText(parsed['language'])
        if l_i != -1:
            self.lang_box.setCurrentIndex(l_i)
        if gallerydb.GalleryDB.check_exists(name):
            self.file_exists_lbl.setText(
                '<font color="red">Gallery already exists.</font>')
            self.file_exists_lbl.show()
        # check galleries
        gs = 1
        if name.endswith(utils.ARCHIVE_FILES):
            gs = len(utils.check_archive(name))
        elif os.path.isdir(name):
            g_dirs, g_archs = utils.recursive_gallery_check(name)
            gs = len(g_dirs) + len(g_archs)
        if gs == 0:
            self.file_exists_lbl.setText(
                '<font color="red">Invalid gallery source.</font>')
            self.file_exists_lbl.show()
            self.done.hide()
        if app_constants.SUBFOLDER_AS_GALLERY:
            if gs > 1:
                self.file_exists_lbl.setText(
                    '<font color="red">More than one galleries detected in source! Use other methods to add.</font>'
                )
                self.file_exists_lbl.show()
                self.done.hide()

    def check(self):
        if not self._multiple_galleries:
            if len(self.title_edit.text()) == 0:
                self.title_edit.setFocus()
                self.title_edit.setStyleSheet(
                    "border-style:outset;border-width:2px;border-color:red;")
                return False
            elif len(self.author_edit.text()) == 0:
                self.author_edit.setText("Unknown")

            if len(self.path_lbl.text()) == 0 or self.path_lbl.text(
            ) == 'No path specified':
                self.path_lbl.setStyleSheet("color:red")
                self.path_lbl.setText('No path specified')
                return False

        return True

    def reject(self):
        if self.check():
            msgbox = QMessageBox()
            msgbox.setText(
                "<font color='red'><b>Noo oniichan! You were about to add a new gallery.</b></font>"
            )
            msgbox.setInformativeText("Do you really want to discard?")
            msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            msgbox.setDefaultButton(QMessageBox.No)
            if msgbox.exec() == QMessageBox.Yes:
                self.close()
        else:
            self.close()

    def web_metadata(self, url, btn_widget, pgr_widget):
        if not self.path_lbl.text():
            return
        self.link_lbl.setText(url)
        btn_widget.hide()
        pgr_widget.show()

        def status(stat):
            def do_hide():
                try:
                    pgr_widget.hide()
                    btn_widget.show()
                except RuntimeError:
                    pass

            if stat:
                do_hide()
            else:
                danger = """QProgressBar::chunk {
                    background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,stop: 0 #FF0350,stop: 0.4999 #FF0020,stop: 0.5 #FF0019,stop: 1 #FF0000 );
                    border-bottom-right-radius: 5px;
                    border-bottom-left-radius: 5px;
                    border: .px solid black;}"""
                pgr_widget.setStyleSheet(danger)
                QTimer.singleShot(3000, do_hide)

        def gallery_picker(gallery, title_url_list, q):
            self.parent_widget._web_metadata_picker(gallery, title_url_list, q,
                                                    self)

        try:
            dummy_gallery = self.make_gallery(self.gallery, False)
        except AttributeError:
            dummy_gallery = self.make_gallery(gallerydb.Gallery(), False, True)
        if not dummy_gallery:
            status(False)
            return None

        dummy_gallery._g_dialog_url = url
        self._fetch_inst.galleries = [dummy_gallery]
        self._disconnect()
        self._fetch_inst.GALLERY_PICKER.connect(gallery_picker)
        self._fetch_inst.GALLERY_EMITTER.connect(self.set_web_metadata)
        self._fetch_inst.FINISHED.connect(status)
        self._fetch_thread.start()

    def set_web_metadata(self, metadata):
        assert isinstance(metadata, gallerydb.Gallery)
        self.link_lbl.setText(metadata.link)
        self.title_edit.setText(metadata.title)
        self.author_edit.setText(metadata.artist)
        tags = ""
        lang = ['English', 'Japanese']
        self._find_combobox_match(self.lang_box, metadata.language, 2)
        self.tags_edit.setText(utils.tag_to_string(metadata.tags))
        pub_string = "{}".format(metadata.pub_date)
        pub_date = QDate.fromString(pub_string.split()[0], "yyyy-MM-dd")
        self.pub_edit.setDate(pub_date)
        self._find_combobox_match(self.type_box, metadata.type, 0)

    def make_gallery(self, new_gallery, add_to_model=True, new=False):
        def is_checked(widget):
            return widget.g_check.isChecked()

        if self.check():
            if is_checked(self.title_edit):
                new_gallery.title = self.title_edit.text()
                log_d('Adding gallery title')
            if is_checked(self.author_edit):
                new_gallery.artist = self.author_edit.text()
                log_d('Adding gallery artist')
            if not self._multiple_galleries:
                new_gallery.path = self.path_lbl.text()
                log_d('Adding gallery path')
            if is_checked(self.descr_edit):
                new_gallery.info = self.descr_edit.toPlainText()
                log_d('Adding gallery descr')
            if is_checked(self.type_box):
                new_gallery.type = self.type_box.currentText()
                log_d('Adding gallery type')
            if is_checked(self.lang_box):
                new_gallery.language = self.lang_box.currentText()
                log_d('Adding gallery lang')
            if is_checked(self.rating_box):
                new_gallery.rating = self.rating_box.value()
                log_d('Adding gallery rating')
            if is_checked(self.status_box):
                new_gallery.status = self.status_box.currentText()
                log_d('Adding gallery status')
            if is_checked(self.tags_edit):
                if self.tags_append.isChecked():
                    new_gallery.tags = utils.tag_to_dict(
                        utils.tag_to_string(new_gallery.tags) + "," +
                        self.tags_edit.toPlainText())
                else:
                    new_gallery.tags = utils.tag_to_dict(
                        self.tags_edit.toPlainText())
                log_d('Adding gallery: tagging to dict')
            if is_checked(self.pub_edit):
                qpub_d = self.pub_edit.date().toString("ddMMyyyy")
                dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date()
                try:
                    d_t = self.gallery_time
                except AttributeError:
                    d_t = datetime.now().time().replace(microsecond=0)
                dpub_d = datetime.combine(dpub_d, d_t)
                new_gallery.pub_date = dpub_d
                log_d('Adding gallery pub date')
            if is_checked(self.link_lbl):
                new_gallery.link = self.link_lbl.text()
                log_d('Adding gallery link')

            if new:
                if not new_gallery.chapters:
                    log_d('Starting chapters')
                    thread = threading.Thread(target=utils.make_chapters,
                                              args=(new_gallery, ))
                    thread.start()
                    thread.join()
                    log_d('Finished chapters')
                    if new and app_constants.MOVE_IMPORTED_GALLERIES:
                        app_constants.OVERRIDE_MONITOR = True
                        new_gallery.move_gallery()
                if add_to_model:
                    self.parent_widget.default_manga_view.add_gallery(
                        new_gallery, True)
                    log_i('Sent gallery to model')
            else:
                if add_to_model:
                    self.parent_widget.default_manga_view.replace_gallery(
                        [new_gallery], False)
            return new_gallery

    def link_set(self):
        t = self.link_edit.text()
        self.link_edit.hide()
        self.link_lbl.show()
        self.link_lbl.setText(t)
        self.link_btn2.hide()
        self.link_btn.show()

    def link_modify(self):
        t = self.link_lbl.text()
        self.link_lbl.hide()
        self.link_edit.show()
        self.link_edit.setText(t)
        self.link_btn.hide()
        self.link_btn2.show()

    def _disconnect(self):
        try:
            self._fetch_inst.GALLERY_PICKER.disconnect()
            self._fetch_inst.GALLERY_EMITTER.disconnect()
            self._fetch_inst.FINISHED.disconnect()
        except TypeError:
            pass

    def delayed_close(self):
        if self._fetch_thread.isRunning():
            self._fetch_thread.finished.connect(self.close)
            self.hide()
        else:
            self.close()

    def accept(self):
        self.make_gallery(gallerydb.Gallery(), new=True)
        self.delayed_close()

    def accept_edit(self):
        gallerydb.execute(database.db.DBBase.begin, True)
        app_constants.APPEND_TAGS_GALLERIES = self.tags_append.isChecked()
        settings.set(app_constants.APPEND_TAGS_GALLERIES, 'Application',
                     'append tags to gallery')
        for g in self._edit_galleries:
            self.make_gallery(g)
        self.delayed_close()
        gallerydb.execute(database.db.DBBase.end, True)

    def reject_edit(self):
        self.delayed_close()
Exemplo n.º 15
0
class Tag(QWidget):
    """ allow to move and resize by user"""
    menu = None
    mode = Mode.NONE
    position = None
    inFocus = pyqtSignal(bool)
    outFocus = pyqtSignal(bool)
    newGeometry = pyqtSignal(QRect)

    def __init__(self,
                 parent,
                 detection_id,
                 label,
                 bbox,
                 editable=False,
                 color=None):
        super().__init__(parent=parent)
        #combo.setEnabled(not finalized)
        self.menu = QMenu(parent=self, title='menu')
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        self.move(QPoint(0, 0))

        self.m_infocus = True
        self.m_showMenu = False
        self.m_isEditing = editable
        self.installEventFilter(parent)
        self.bbox = bbox
        self.detection_id = detection_id

        x = round(bbox[1] * self.parentWidget().pixmap().width())
        y = round(bbox[0] * self.parentWidget().pixmap().height())
        w = round(bbox[3] * self.parentWidget().pixmap().width() - x)
        h = round(bbox[2] * self.parentWidget().pixmap().height() - y)
        self.setGeometry(x, y, w, h)
        self.tik = QCheckBox(self)
        self.tik.move(0, 0)
        self.title = QLabel(self)
        self.title.move(15, 0)
        self.title.setStyleSheet(
            "QLabel {  color : white; font-weight: bold; }")
        if not editable:
            self.tik.hide()
            self.title.move(0, 0)
        self.updateLabel(label)
        self.pen = QPen()
        self.pen.setStyle(Qt.SolidLine)
        self.pen.setWidth(3)
        self.pen.setBrush(self.color)

        #print(self.bbox)
        self.setVisible(True)
        self.setAutoFillBackground(False)
        self.setMouseTracking(True)
        self.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.setFocus()

    """def resizeEvent(self, event):
        print("resize invalidate",event.oldSize())
        self.valid= False

    def moveEvent(self, event):
        print("move invalidate", event.oldPos())
        self.valid= False"""

    def updateLabel(self, label):
        self.label = label
        self.title.setText(self.label.name)
        if self.width() < 40:
            self.title.setText(self.label.name[0:2])
            if self.m_isEditing:
                self.title.move(0, 15)
        if self.label.id == -1:
            self.color = Qt.red
        else:
            self.color = Qt.green
        if hasattr(self, 'pen'):
            self.pen.setBrush(self.color)
        self.tik.setCheckState(False)
        #self.addWidget(self.child)
        self.update()

    def getFinal(self):
        y = self.x() / self.parentWidget().pixmap().width()
        x = self.y() / self.parentWidget().pixmap().height()
        h = (self.x() + self.width()) / self.parentWidget().pixmap().width()
        w = (self.y() + self.height()) / self.parentWidget().pixmap().height()
        if abs(x -
               self.bbox[0]) < 0.01 and abs(x - self.bbox[0]) < 0.01 and abs(
                   x - self.bbox[0]) < 0.01 and abs(x - self.bbox[0]) < 0.01:
            return self.detection_id, (self.bbox[0], self.bbox[1],
                                       self.bbox[2], self.bbox[3])
        else:
            return self.detection_id, (x, y, w, h)

    def speciesChanged(self, text):
        if text == 'Add New':
            self.parentWidget().parentWidget().parentWidget().parentWidget(
            ).setCurrentIndex(2)
        else:
            self.label = text

    """def setChildWidget(self, cWidget):
        if cWidget:
            self.childWidget = cWidget
            self.childWidget.setParent(self)
            self.childWidget.setMinimumSize(70,20)
            self.childWidget.move(0,0)"""

    def popupShow(self, pt: QPoint):
        if self.menu.isEmpty:
            return
        global_ = self.mapToGlobal(pt)
        self.m_showMenu = True
        self.menu.exec(global_)
        self.m_showMenu = False

    def contextMenuEvent(self, event):

        menu = QMenu(self)
        quitAction = menu.addAction("Delete Tag")
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == quitAction:
            self.parentWidget().tags.remove(self)
            self.setParent(None)

    def focusInEvent(self, a0: QtGui.QFocusEvent):
        self.m_infocus = True
        p = self.parentWidget()
        p.installEventFilter(self)
        p.repaint()
        self.inFocus.emit(True)

    def focusOutEvent(self, a0: QtGui.QFocusEvent):
        if not self.m_isEditing:
            return
        if self.m_showMenu:
            return
        self.mode = Mode.NONE
        self.outFocus.emit(False)
        self.m_infocus = False

    def paintEvent(self, e: QtGui.QPaintEvent):
        painter = QtGui.QPainter(self)
        rect = e.rect()
        rect.adjust(0, 0, -1, -1)
        painter.setPen(self.pen)
        painter.drawRect(rect)

    def mousePressEvent(self, e: QtGui.QMouseEvent):
        self.position = QPoint(e.globalX() - self.geometry().x(),
                               e.globalY() - self.geometry().y())
        if not self.m_isEditing:
            return
        if not self.m_infocus:
            return
        if not e.buttons() and QtCore.Qt.LeftButton:
            self.setCursorShape(e.pos())
            return
        if e.button() == QtCore.Qt.RightButton:
            self.popupShow(e.pos())
            e.accept()

    def keyPressEvent(self, e: QtGui.QKeyEvent):
        if not self.m_isEditing: return
        if e.key() == QtCore.Qt.Key_Delete:
            self.deleteLater()
        # Moving container with arrows
        if QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:
            newPos = QPoint(self.x(), self.y())
            if e.key() == QtCore.Qt.Key_Up:
                newPos.setY(newPos.y() - 1)
            if e.key() == QtCore.Qt.Key_Down:
                newPos.setY(newPos.y() + 1)
            if e.key() == QtCore.Qt.Key_Left:
                newPos.setX(newPos.x() - 1)
            if e.key() == QtCore.Qt.Key_Right:
                newPos.setX(newPos.x() + 1)
            self.move(newPos)

        if QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:
            if e.key() == QtCore.Qt.Key_Up:
                self.resize(self.width(), self.height() - 1)
            if e.key() == QtCore.Qt.Key_Down:
                self.resize(self.width(), self.height() + 1)
            if e.key() == QtCore.Qt.Key_Left:
                self.resize(self.width() - 1, self.height())
            if e.key() == QtCore.Qt.Key_Right:
                self.resize(self.width() + 1, self.height())
        self.newGeometry.emit(self.geometry())

    def setCursorShape(self, e_pos: QPoint):
        diff = 3
        # Left - Bottom

        if (((e_pos.y() > self.y() + self.height() - diff) and  # Bottom
             (e_pos.x() < self.x() + diff)) or  # Left
                # Right-Bottom
            ((e_pos.y() > self.y() + self.height() - diff) and  # Bottom
             (e_pos.x() > self.x() + self.width() - diff)) or  # Right
                # Left-Top
            ((e_pos.y() < self.y() + diff) and  # Top
             (e_pos.x() < self.x() + diff)) or  # Left
                # Right-Top
            (e_pos.y() < self.y() + diff) and  # Top
            (e_pos.x() > self.x() + self.width() - diff)):  # Right
            # Left - Bottom
            if ((e_pos.y() > self.y() + self.height() - diff) and  # Bottom
                (e_pos.x() < self.x() + diff)):  # Left
                self.mode = Mode.RESIZEBL
                self.setCursor(QCursor(QtCore.Qt.SizeBDiagCursor))
                # Right - Bottom
            if ((e_pos.y() > self.y() + self.height() - diff) and  # Bottom
                (e_pos.x() > self.x() + self.width() - diff)):  # Right
                self.mode = Mode.RESIZEBR
                self.setCursor(QCursor(QtCore.Qt.SizeFDiagCursor))
            # Left - Top
            if ((e_pos.y() < self.y() + diff) and  # Top
                (e_pos.x() < self.x() + diff)):  # Left
                self.mode = Mode.RESIZETL
                self.setCursor(QCursor(QtCore.Qt.SizeFDiagCursor))
            # Right - Top
            if ((e_pos.y() < self.y() + diff) and  # Top
                (e_pos.x() > self.x() + self.width() - diff)):  # Right
                self.mode = Mode.RESIZETR
                self.setCursor(QCursor(QtCore.Qt.SizeBDiagCursor))
        # check cursor horizontal position
        elif ((e_pos.x() < self.x() + diff) or  # Left
              (e_pos.x() > self.x() + self.width() - diff)):  # Right
            if e_pos.x() < self.x() + diff:  # Left
                self.setCursor(QCursor(QtCore.Qt.SizeHorCursor))
                self.mode = Mode.RESIZEL
            else:  # Right
                self.setCursor(QCursor(QtCore.Qt.SizeHorCursor))
                self.mode = Mode.RESIZER
        # check cursor vertical position
        elif ((e_pos.y() > self.y() + self.height() - diff) or  # Bottom
              (e_pos.y() < self.y() + diff)):  # Top
            if e_pos.y() < self.y() + diff:  # Top
                self.setCursor(QCursor(QtCore.Qt.SizeVerCursor))
                self.mode = Mode.RESIZET
            else:  # Bottom
                self.setCursor(QCursor(QtCore.Qt.SizeVerCursor))
                self.mode = Mode.RESIZEB
        else:
            self.setCursor(QCursor(QtCore.Qt.ArrowCursor))
            self.mode = Mode.MOVE

    def mouseReleaseEvent(self, e: QtGui.QMouseEvent):
        QWidget.mouseReleaseEvent(self, e)

    def mouseMoveEvent(self, e: QtGui.QMouseEvent):
        QWidget.mouseMoveEvent(self, e)
        if not self.m_isEditing:
            return
        if not self.m_infocus:
            return
        if not e.buttons() and QtCore.Qt.LeftButton:
            p = QPoint(e.x() + self.geometry().x(),
                       e.y() + self.geometry().y())
            self.setCursorShape(p)
            return

        if (self.mode == Mode.MOVE or self.mode
                == Mode.NONE) and e.buttons() and QtCore.Qt.LeftButton:
            toMove = e.globalPos() - self.position
            if toMove.x() < 0: return
            if toMove.y() < 0: return
            if toMove.x() > self.parentWidget().width() - self.width(): return
            self.move(toMove)
            self.newGeometry.emit(self.geometry())
            self.parentWidget().repaint()
            return
        if (self.mode != Mode.MOVE) and e.buttons() and QtCore.Qt.LeftButton:
            if self.mode == Mode.RESIZETL:  # Left - Top
                newwidth = e.globalX() - self.position.x() - self.geometry().x(
                )
                newheight = e.globalY() - self.position.y() - self.geometry(
                ).y()
                toMove = e.globalPos() - self.position
                self.resize(self.geometry().width() - newwidth,
                            self.geometry().height() - newheight)
                self.move(toMove.x(), toMove.y())
            elif self.mode == Mode.RESIZETR:  # Right - Top
                newheight = e.globalY() - self.position.y() - self.geometry(
                ).y()
                toMove = e.globalPos() - self.position
                self.resize(e.x(), self.geometry().height() - newheight)
                self.move(self.x(), toMove.y())
            elif self.mode == Mode.RESIZEBL:  # Left - Bottom
                newwidth = e.globalX() - self.position.x() - self.geometry().x(
                )
                toMove = e.globalPos() - self.position
                self.resize(self.geometry().width() - newwidth, e.y())
                self.move(toMove.x(), self.y())
            elif self.mode == Mode.RESIZEB:  # Bottom
                self.resize(self.width(), e.y())
            elif self.mode == Mode.RESIZEL:  # Left
                newwidth = e.globalX() - self.position.x() - self.geometry().x(
                )
                toMove = e.globalPos() - self.position
                self.resize(self.geometry().width() - newwidth, self.height())
                self.move(toMove.x(), self.y())
            elif self.mode == Mode.RESIZET:  # Top
                newheight = e.globalY() - self.position.y() - self.geometry(
                ).y()
                toMove = e.globalPos() - self.position
                self.resize(self.width(), self.geometry().height() - newheight)
                self.move(self.x(), toMove.y())
            elif self.mode == Mode.RESIZER:  # Right
                self.resize(e.x(), self.height())
            elif self.mode == Mode.RESIZEBR:  # Right - Bottom
                self.resize(e.x(), e.y())
            self.parentWidget().repaint()
        self.newGeometry.emit(self.geometry())
Exemplo n.º 16
0
class NetworkChoiceLayout(object):
    def __init__(self, network, config, wizard=False):
        self.network = network
        self.config = config
        self.protocol = None
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        server_tab = QWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(server_tab, _('Server'))
        tabs.addTab(proxy_tab, _('Proxy'))

        if wizard:
            tabs.setCurrentIndex(1)

        # server tab
        grid = QGridLayout(server_tab)
        grid.setSpacing(8)

        self.server_host = QLineEdit()
        self.server_host.setFixedWidth(200)
        self.server_port = QLineEdit()
        self.server_port.setFixedWidth(60)
        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))

        self.server_host.editingFinished.connect(self.set_server)
        self.server_port.editingFinished.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)

        msg = ' '.join([
            _("If auto-connect is enabled, ElectrumSV will always use a server that "
              "is on the longest blockchain."),
            _("If it is disabled, you have to choose a server you want to use. "
              "ElectrumSV will warn you if your server is lagging.")
        ])
        grid.addWidget(self.autoconnect_cb, 0, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_host, 1, 1, 1, 2)
        grid.addWidget(self.server_port, 1, 3)

        label = _('Server peers') if network.is_connected() else _(
            'Default Servers')
        grid.addWidget(QLabel(label), 2, 0, 1, 5)
        self.servers_list = ServerListWidget(self)
        grid.addWidget(self.servers_list, 3, 0, 1, 5)

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(['SOCKS4', 'SOCKS5', 'HTTP'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(200)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(100)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_user.setFixedWidth(self.proxy_host.width())
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_user.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(
            self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_user.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('Proxy settings apply to all connections: both '
                  'ElectrumSV servers and third-party services.')), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_user, 5, 2, Qt.AlignTop)
        grid.addWidget(self.proxy_password, 5, 3, Qt.AlignTop)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg = ' '.join([
            _("ElectrumSV connects to several nodes in order to download block headers "
              "and find out the longest blockchain."),
            _("This blockchain is used to verify the transactions sent by your "
              "transaction server.")
        ])
        self.status_label = QLabel('')
        grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
        grid.addWidget(self.status_label, 0, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        self.server_label = QLabel('')
        msg = _(
            "ElectrumSV sends your wallet addresses to a single server, in order to "
            "receive your transaction history.")
        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_label, 1, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.height_label = QLabel('')
        msg = _('This is the height of your local copy of the blockchain.')
        grid.addWidget(QLabel(_('Blockchain') + ':'), 2, 0)
        grid.addWidget(self.height_label, 2, 1)
        grid.addWidget(HelpButton(msg), 2, 4)

        self.split_label = QLabel('')
        grid.addWidget(self.split_label, 3, 0, 1, 3)

        self.nodes_list_widget = NodesListWidget(self)
        grid.addWidget(self.nodes_list_widget, 5, 0, 1, 5)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.fill_in_proxy_settings()
        self.update()

    def check_disable_proxy(self, b):
        if not self.config.is_modifiable('proxy'):
            b = False
        for w in [
                self.proxy_mode, self.proxy_host, self.proxy_port,
                self.proxy_user, self.proxy_password
        ]:
            w.setEnabled(b)

    def enable_set_server(self):
        if self.config.is_modifiable('server'):
            enabled = not self.autoconnect_cb.isChecked()
            self.server_host.setEnabled(enabled)
            self.server_port.setEnabled(enabled)
            self.servers_list.setEnabled(enabled)
        else:
            for w in [
                    self.autoconnect_cb, self.server_host, self.server_port,
                    self.servers_list
            ]:
                w.setEnabled(False)

    def update(self):
        host, port, protocol, proxy_config, auto_connect = self.network.get_parameters(
        )
        self.server_host.setText(host)
        self.server_port.setText(port)
        self.autoconnect_cb.setChecked(auto_connect)

        host = self.network.interface.host if self.network.interface else _(
            'None')
        self.server_label.setText(host)

        self.set_protocol(protocol)
        self.servers = self.network.get_servers()
        self.servers_list.update(self.servers, self.protocol,
                                 self.tor_cb.isChecked())
        self.enable_set_server()

        height_str = "%d " % (self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.get_interfaces())
        status = _("Connected to %d nodes.") % n if n else _("Not connected")
        self.status_label.setText(status)
        if self.network.blockchain_count() > 1:
            chain = self.network.blockchain()
            heights = set()
            for blockchain in self.network.interfaces_by_blockchain():
                if blockchain != chain:
                    heights.add(chain.common_height(blockchain) + 1)
            msg = _('Chain split detected at height(s) {}\n').format(','.join(
                f'{height:,d}' for height in sorted(heights)))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(self.network)

    def fill_in_proxy_settings(self):
        host, port, protocol, proxy_config, auto_connect = self.network.get_parameters(
        )
        if not proxy_config:
            proxy_config = {
                "mode": "none",
                "host": "localhost",
                "port": "9050"
            }

        b = proxy_config.get('mode') != "none"
        self.check_disable_proxy(b)
        if b:
            self.proxy_cb.setChecked(True)
            self.proxy_mode.setCurrentIndex(
                self.proxy_mode.findText(str(
                    proxy_config.get("mode").upper())))

        self.proxy_host.setText(proxy_config.get("host"))
        self.proxy_port.setText(proxy_config.get("port"))
        self.proxy_user.setText(proxy_config.get("user", ""))
        self.proxy_password.setText(proxy_config.get("password", ""))

    def layout(self):
        return self.layout_

    def set_protocol(self, protocol):
        if protocol != self.protocol:
            self.protocol = protocol

    def change_protocol(self, use_ssl):
        p = 's' if use_ssl else 't'
        host = self.server_host.text()
        pp = self.servers.get(host, Net.DEFAULT_PORTS)
        if p not in pp.keys():
            p = list(pp.keys())[0]
        port = pp[p]
        self.server_host.setText(host)
        self.server_port.setText(port)
        self.set_protocol(p)
        self.set_server()

    def follow_server(self, server):
        self.network.switch_to_interface(server)
        host, port, protocol, proxy, auto_connect = self.network.get_parameters(
        )
        host, port, protocol = deserialize_server(server)
        self.network.set_parameters(host, port, protocol, proxy, auto_connect)
        self.update()

    def server_changed(self, x):
        if x:
            self.change_server(str(x.text(0)), self.protocol)

    def change_server(self, host, protocol):
        pp = self.servers.get(host, Net.DEFAULT_PORTS)
        if protocol and protocol not in protocol_letters:
            protocol = None
        if protocol:
            port = pp.get(protocol)
            if port is None:
                protocol = None
        if not protocol:
            if 's' in pp.keys():
                protocol = 's'
                port = pp.get(protocol)
            else:
                protocol = list(pp.keys())[0]
                port = pp.get(protocol)
        self.server_host.setText(host)
        self.server_port.setText(port)

    def accept(self):
        pass

    def set_server(self):
        host, port, protocol, proxy, auto_connect = self.network.get_parameters(
        )
        host = str(self.server_host.text())
        port = str(self.server_port.text())
        auto_connect = self.autoconnect_cb.isChecked()
        self.network.set_parameters(host, port, protocol, proxy, auto_connect)

    def set_proxy(self):
        host, port, protocol, proxy, auto_connect = self.network.get_parameters(
        )
        if self.proxy_cb.isChecked():
            proxy = {
                'mode': str(self.proxy_mode.currentText()).lower(),
                'host': str(self.proxy_host.text()),
                'port': str(self.proxy_port.text()),
                'user': str(self.proxy_user.text()),
                'password': str(self.proxy_password.text())
            }
        else:
            proxy = None
            self.tor_cb.setChecked(False)
        self.network.set_parameters(host, port, protocol, proxy, auto_connect)

    def suggest_proxy(self, found_proxy):
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if (self.proxy_mode.currentIndex()
                == self.proxy_mode.findText('SOCKS5')
                and self.proxy_host.text() == "127.0.0.1"
                and self.proxy_port.text() == str(found_proxy[1])):
            self.tor_cb.setChecked(True)
        self.tor_cb.show()

    def use_tor_proxy(self, use_it):
        if not use_it:
            self.proxy_cb.setChecked(False)
        else:
            socks5_mode_index = self.proxy_mode.findText('SOCKS5')
            if socks5_mode_index == -1:
                logger.error("can't find proxy_mode 'SOCKS5'")
                return
            self.proxy_mode.setCurrentIndex(socks5_mode_index)
            self.proxy_host.setText("127.0.0.1")
            self.proxy_port.setText(str(self.tor_proxy[1]))
            self.proxy_user.setText("")
            self.proxy_password.setText("")
            self.tor_cb.setChecked(True)
            self.proxy_cb.setChecked(True)
        self.check_disable_proxy(use_it)
        self.set_proxy()

    def proxy_settings_changed(self):
        self.tor_cb.setChecked(False)
Exemplo n.º 17
0
class NetworkChoiceLayout(object):
    def __init__(self, network: Network, config: 'SimpleConfig', wizard=False):
        self.network = network
        self.config = config
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(proxy_tab, _('Proxy'))

        fixed_width_hostname = 24 * char_width_in_lineedit()
        fixed_width_port = 6 * char_width_in_lineedit()

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)
        self.proxy_cb.setEnabled(self.config.is_modifiable('proxy'))

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(['SOCKS4', 'SOCKS5'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(fixed_width_hostname)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(fixed_width_port)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))
        self.proxy_password.setFixedWidth(fixed_width_port)

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_user.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(
            self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_user.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        self.tor_auto_on_cb = QCheckBox(self.network.TOR_AUTO_ON_MSG)
        self.tor_auto_on_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_auto_on_cb.setChecked(self.config.get('tor_auto_on', True))
        self.tor_auto_on_cb.clicked.connect(self.use_tor_auto_on)

        self.fiat_bypass_tor_cb = QCheckBox(self.network.FIAT_BYPASS_TOR_MSG)
        fiat_bypass_tor = self.config.get('fiat_bypass_tor', False)
        self.fiat_bypass_tor_cb.setChecked(fiat_bypass_tor)
        self.fiat_bypass_tor_cb.clicked.connect(self.fiat_bypass_tor)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('Proxy settings apply to all connections: with Zcash Electrum servers, but also with third-party services.'
                  )), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_user, 5, 2)
        grid.addWidget(self.proxy_password, 5, 3)
        grid.addWidget(self.tor_auto_on_cb, 6, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('During wallet startup try to detect and use Tor Proxy.')),
            6, 4)
        grid.addWidget(self.fiat_bypass_tor_cb, 7, 0, 1, 3)
        grid.setRowStretch(8, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg = ' '.join([
            _("Zcash Electrum connects to several nodes in order to download block headers and find out the longest blockchain."
              ),
            _("This blockchain is used to verify the transactions sent by your transaction server."
              )
        ])
        self.status_label = QLabel('')
        grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
        grid.addWidget(self.status_label, 0, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)
        msg = ' '.join([
            _("If auto-connect is enabled, Zcash Electrum will always use a server that is on the longest blockchain."
              ),
            _("If it is disabled, you have to choose a server you want to use. Zcash Electrum will warn you if your server is lagging."
              )
        ])
        grid.addWidget(self.autoconnect_cb, 1, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.server_e = QLineEdit()
        self.server_e.setFixedWidth(fixed_width_hostname + fixed_width_port)
        self.server_e.editingFinished.connect(self.set_server)
        msg = _(
            "Zcash Electrum sends your wallet addresses to a single server, in order to receive your transaction history."
        )
        grid.addWidget(QLabel(_('Server') + ':'), 2, 0)
        grid.addWidget(self.server_e, 2, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 2, 4)

        self.height_label = QLabel('')
        msg = _('This is the height of your local copy of the blockchain.')
        grid.addWidget(QLabel(_('Blockchain') + ':'), 3, 0)
        grid.addWidget(self.height_label, 3, 1)
        grid.addWidget(HelpButton(msg), 3, 4)

        self.split_label = QLabel('')
        grid.addWidget(self.split_label, 4, 0, 1, 3)

        self.nodes_list_widget = NodesListWidget(self)
        grid.addWidget(self.nodes_list_widget, 6, 0, 1, 5)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.fill_in_proxy_settings()
        self.update()

    def clean_up(self):
        if self.td:
            self.td.found_proxy.disconnect()
            self.td.stop()
            self.td = None

    def check_disable_proxy(self, b):
        if not self.config.is_modifiable('proxy'):
            b = False
        for w in [
                self.proxy_mode, self.proxy_host, self.proxy_port,
                self.proxy_user, self.proxy_password
        ]:
            w.setEnabled(b)

    def enable_set_server(self):
        if self.config.is_modifiable('server'):
            enabled = not self.autoconnect_cb.isChecked()
            self.server_e.setEnabled(enabled)
        else:
            for w in [
                    self.autoconnect_cb, self.server_e, self.nodes_list_widget
            ]:
                w.setEnabled(False)

    def update(self):
        net_params = self.network.get_parameters()
        server = net_params.server
        auto_connect = net_params.auto_connect
        if not self.server_e.hasFocus():
            self.server_e.setText(server.to_friendly_name())
        self.autoconnect_cb.setChecked(auto_connect)

        height_str = "%d " % (self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.get_interfaces())
        status = _("Connected to {0} nodes.").format(n) if n > 1 else _(
            "Connected to {0} node.").format(n) if n == 1 else _(
                "Not connected")
        self.status_label.setText(status)
        chains = self.network.get_blockchains()
        if len(chains) > 1:
            chain = self.network.blockchain()
            forkpoint = chain.get_max_forkpoint()
            name = chain.get_name()
            msg = _('Chain split detected at block {0}').format(
                forkpoint) + '\n'
            msg += (_('You are following branch') if auto_connect else
                    _('Your server is on branch')) + ' ' + name
            msg += ' (%d %s)' % (chain.get_branch_size(), _('blocks'))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(network=self.network,
                                      servers=self.network.get_servers(),
                                      use_tor=self.tor_cb.isChecked())
        self.enable_set_server()

    def fill_in_proxy_settings(self):
        proxy_config = self.network.get_parameters().proxy
        if not proxy_config:
            proxy_config = {
                "mode": "none",
                "host": "localhost",
                "port": "9050"
            }

        b = proxy_config.get('mode') != "none"
        self.check_disable_proxy(b)
        if b:
            self.proxy_cb.setChecked(True)
            self.proxy_mode.setCurrentIndex(
                self.proxy_mode.findText(str(
                    proxy_config.get("mode").upper())))

        self.proxy_host.setText(proxy_config.get("host"))
        self.proxy_port.setText(proxy_config.get("port"))
        self.proxy_user.setText(proxy_config.get("user", ""))
        self.proxy_password.setText(proxy_config.get("password", ""))

    def layout(self):
        return self.layout_

    def follow_branch(self, chain_id):
        self.network.run_from_another_thread(
            self.network.follow_chain_given_id(chain_id))
        self.update()

    def follow_server(self, server: ServerAddr):
        self.network.run_from_another_thread(
            self.network.follow_chain_given_server(server))
        self.update()

    def accept(self):
        pass

    def set_server(self):
        net_params = self.network.get_parameters()
        try:
            server = ServerAddr.from_str_with_inference(
                str(self.server_e.text()))
            if not server: raise Exception("failed to parse")
        except Exception:
            return
        net_params = net_params._replace(
            server=server, auto_connect=self.autoconnect_cb.isChecked())
        self.network.run_from_another_thread(
            self.network.set_parameters(net_params))

    def set_proxy(self):
        net_params = self.network.get_parameters()
        if self.proxy_cb.isChecked():
            proxy = {
                'mode': str(self.proxy_mode.currentText()).lower(),
                'host': str(self.proxy_host.text()),
                'port': str(self.proxy_port.text()),
                'user': str(self.proxy_user.text()),
                'password': str(self.proxy_password.text())
            }
        else:
            proxy = None
            self.tor_cb.setChecked(False)
        net_params = net_params._replace(proxy=proxy)
        self.network.run_from_another_thread(
            self.network.set_parameters(net_params))

    def suggest_proxy(self, found_proxy):
        if found_proxy is None:
            self.tor_cb.hide()
            return
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if (self.proxy_cb.isChecked() and self.proxy_mode.currentIndex()
                == self.proxy_mode.findText('SOCKS5')
                and self.proxy_host.text() == "127.0.0.1"
                and self.proxy_port.text() == str(found_proxy[1])):
            self.tor_cb.setChecked(True)
        self.tor_cb.show()

    def use_tor_proxy(self, use_it):
        if not use_it:
            self.proxy_cb.setChecked(False)
        else:
            socks5_mode_index = self.proxy_mode.findText('SOCKS5')
            if socks5_mode_index == -1:
                _logger.info("can't find proxy_mode 'SOCKS5'")
                return
            self.proxy_mode.setCurrentIndex(socks5_mode_index)
            self.proxy_host.setText("127.0.0.1")
            self.proxy_port.setText(str(self.tor_proxy[1]))
            self.proxy_user.setText("")
            self.proxy_password.setText("")
            self.tor_cb.setChecked(True)
            self.proxy_cb.setChecked(True)
        self.check_disable_proxy(use_it)
        self.set_proxy()

    def fiat_bypass_tor(self, bypass):
        self.config.set_key('fiat_bypass_tor', bypass, False)
        coro = self.network.restart()
        self.network.run_from_another_thread(coro)

    def proxy_settings_changed(self):
        self.tor_cb.setChecked(False)

    def use_tor_auto_on(self, use_it):
        self.config.set_key('tor_auto_on', use_it, True)
Exemplo n.º 18
0
class BaseApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(50, 50, 560,
                         500)  #Setting up window geometry. The width is fixed.
        self.setMaximumWidth(560)
        self.setWindowTitle('Just a simple app in PyQt5')
        self.initUI()

    def initUI(
        self
    ):  #This function holds all declarations of widgets used in the application.
        #First, the radio buttons connected to function doCaseOrRepo, which shows widgest depending on the option selected
        self.case = QRadioButton("Case")
        self.repo = QRadioButton("Raport")
        self.case.toggled.connect(self.doCaseOrRepo)
        self.repo.toggled.connect(self.doCaseOrRepo)

        #All of the widgets below is hiden at start. To show them you mast slect case or report
        self.urgent = QCheckBox("Pilne")
        self.urgent.setEnabled(False)
        self.urgent.hide()
        self.note = QCheckBox("notatka")

        self.reason = QLineEdit("powód")
        self.reason.setEnabled(False)
        self.reason.hide()
        self.urgent.stateChanged.connect(self.doCheckReason)

        self.note_txt = QLineEdit("notatka")
        self.note_txt.setEnabled(False)
        self.note.stateChanged.connect(self.doCheckNote)
        self.note.hide()
        self.note_txt.hide()

        self.sub_label = QLabel("dodaj podmiot:")
        self.sub1 = QCheckBox("podmiot1")
        self.sub2 = QCheckBox("podmiot2")
        self.sub3 = QCheckBox("podmiot3")
        self.sub4 = QCheckBox("podmiot4")
        self.sub_label.hide()
        self.sub1.hide()
        self.sub2.hide()
        self.sub3.hide()
        self.sub4.hide()

        self.country = QComboBox(self)
        self.country.addItem("Wybierz kraj")
        for i in range(25):
            self.country.addItem("Kraj %i" % i)
        self.pos1 = QComboBox(self)

        # Defining criteriums. It could be a function that produces these criteriums but in real life each of them
        # contains different items, and it should be defined separately
        self.pos1.addItem("Kryterium1")
        for i in range(4):
            self.pos1.addItem("opcja %i" % i)
        self.pos2 = QComboBox(self)
        self.pos2.addItem("Kryterium2")
        for i in range(4):
            self.pos2.addItem("opcja %i" % i)
        self.pos3 = QComboBox(self)
        self.pos3.addItem("Kryterium3")
        for i in range(4):
            self.pos3.addItem("opcja %i" % i)
        self.pos4 = QComboBox(self)
        self.pos4.addItem("Kryterium4")
        for i in range(4):
            self.pos4.addItem("opcja %i" % i)
        self.country.hide()
        self.pos1.hide()
        self.pos2.hide()
        self.pos3.hide()
        self.pos4.hide()

        #Definition of critrtium table
        self.tab_crit = QTableWidget(1, 5)
        self.tab_crit.columnWidth(60)
        #disable editing of cells
        self.tab_crit.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tab_crit.hide()

        #Here are buttons used to create and change criteriums.
        self.dodaj = QPushButton("Dodaj wiersz")
        self.dodaj.clicked.connect(self.addCrit)
        self.dodaj.hide()

        self.usun_kom = QPushButton("Usuń komórkę")
        self.usun_kom.clicked.connect(self.removeCell)
        self.usun_kom.hide()

        self.usun_wi = QPushButton("Usuń wiersz")
        self.usun_wi.clicked.connect(self.removeRow)
        self.usun_wi.hide()

        #someone has tu accept this criteriums
        self.accept_label = QLabel("Akceptacja:")
        self.minion = QCheckBox("minion")
        self.master = QCheckBox("master")
        self.superior = QCheckBox("superior")
        self.accept_label.hide()
        self.minion.hide()
        self.master.hide()
        self.superior.hide()

        #here is where the date format is used
        self.rapo_date_sent = QCheckBox("Raport wysłano: " + str(date.today()))
        self.case_date_sent = QCheckBox("Zapytanie wysłano: " +
                                        str(date.today()))
        self.rapo_date_sent.hide()
        #function connected to date checkbox activares generate_xml button
        self.rapo_date_sent.stateChanged.connect(self.activateXML)
        self.case_date_sent.hide()
        self.case_date_sent.stateChanged.connect(self.activateXML)

        self.generate_xml = QPushButton("Generuj XML")
        self.generate_xml.setEnabled(False)
        self.generate_xml.hide()
        self.generate_xml.clicked.connect(self.genXML)

        #after generating XML it shows new textbox with report
        self.XML_code = QPlainTextEdit()
        self.XML_code.hide()

        #Here is where the layout is defined. I used grid layout because its easier to plan the whole GUI and it's quite
        #resistant to resolution changes
        self.createLayout()
        win_layout = QVBoxLayout()
        win_layout.addWidget(self.horizontalGroupBox)
        self.setLayout(win_layout)
        self.show()

    def createLayout(self):
        #name of groupbox
        self.horizontalGroupBox = QGroupBox("Wprowadź dane.")
        layout = QGridLayout()

        layout.setColumnMinimumWidth(0, 80)
        layout.setColumnMinimumWidth(1, 80)
        layout.setColumnMinimumWidth(2, 80)
        layout.setColumnMinimumWidth(3, 80)
        layout.setColumnMinimumWidth(4, 80)

        #all the widgets pland in their places. Args in addWigdet are: widget, row, col, rowspan, colspan
        layout.addWidget(QLabel("Co chcesz zrobić: "), 0, 0)
        layout.addWidget(self.case, 0, 1)
        layout.addWidget(self.repo, 0, 2)
        layout.addWidget(self.urgent, 1, 0)
        layout.addWidget(self.reason, 1, 1, 1, 3)
        layout.addWidget(self.note, 2, 0)
        layout.addWidget(self.note_txt, 2, 1, 1, 3)

        layout.addWidget(
            self.sub_label,
            3,
            0,
        )
        layout.addWidget(self.sub1, 4, 0)
        layout.addWidget(self.sub2, 5, 0)
        layout.addWidget(self.sub3, 6, 0)
        layout.addWidget(self.sub4, 7, 0)

        layout.addWidget(self.country, 8, 0)
        layout.addWidget(self.pos1, 8, 1)
        layout.addWidget(self.pos2, 8, 2)
        layout.addWidget(self.pos3, 8, 3)
        layout.addWidget(self.pos4, 8, 4)

        layout.addWidget(self.dodaj, 9, 0)
        layout.addWidget(self.usun_kom, 9, 1)
        layout.addWidget(self.usun_wi, 9, 2)

        layout.addWidget(self.tab_crit, 10, 0, 4, 5)
        layout.addWidget(self.accept_label, 14, 0)
        layout.addWidget(self.minion, 14, 1)
        layout.addWidget(self.master, 14, 2)
        layout.addWidget(self.superior, 14, 3)
        layout.addWidget(self.case_date_sent, 15, 0)
        layout.addWidget(self.rapo_date_sent, 15, 0)
        layout.addWidget(self.generate_xml, 15, 4)
        layout.addWidget(self.XML_code, 16, 0, 10, 5)

        self.horizontalGroupBox.setLayout(layout)

    #addCrit function is used to add criteriums to the table. If user doesn't select the country it will return an
    #error message.Also, there is no criterium selected it will return an error message. If some of the criteriums
    #are on primary positions it will skip them and leave the cell blank
    def addCrit(self):
        #this list holds all of the current values from country and criterium comboboxes
        list = [
            self.country.currentText(),
            self.pos1.currentText(),
            self.pos2.currentText(),
            self.pos3.currentText(),
            self.pos4.currentText()
        ]
        x = self.tab_crit.rowCount()
        for i in range(
                1, 6
        ):  #I heave no idea why it didn't work, when i set range from 0 to 5. Seriously.
            #what if the user wont select the country
            if list[i - 1] == self.country.itemText(0):
                error_message_country = QMessageBox.information(
                    self, "Błąd kraju", "Wybierz kraj!", QMessageBox.Ok)
                if error_message_country == QMessageBox.Ok:
                    print("Always look on the bright side of life!")
                    break
            #what if the user wont select any of the criteriums
            elif self.pos1.currentText() == self.pos1.itemText(0) \
                    and self.pos2.currentText() == self.pos2.itemText(0) \
                    and self.pos3.currentText() == self.pos3.itemText(0) \
                    and self.pos4.currentText() == self.pos4.itemText(0):
                error_message_crit = QMessageBox.information(
                    self, "Błędne kryteria",
                    "Wybierz przynajmniej jedno kryterium!", QMessageBox.Ok)
                if error_message_crit == QMessageBox.Ok:
                    break
            #what if some of criteriums are in primary position
            elif list[i - 1] == self.pos1.itemText(0) or list[i - 1] == self.pos2.itemText(0) \
                    or list[i - 1] == self.pos3.itemText(0) or list[i - 1] == self.pos4.itemText(0):
                self.tab_crit.setItem(x - 1, i - 1, QTableWidgetItem(""))
            else:
                self.tab_crit.setItem(x - 1, i - 1,
                                      QTableWidgetItem(list[i - 1]))
        if list[i - 1] == self.country.itemText(0) or self.pos1.currentText() == self.pos1.itemText(0) \
                and self.pos2.currentText() == self.pos2.itemText(0) \
                and self.pos3.currentText() == self.pos3.itemText(0) \
                and self.pos4.currentText() == self.pos4.itemText(0):
            pass
        else:
            #you need to add a new row at the end of any successful adding
            self.tab_crit.setRowCount(x + 1)

    def removeCell(self):
        #if you remove country cell it will remove the whole row
        if self.tab_crit.currentColumn(
        ) == 0 and self.tab_crit.currentRow() != self.tab_crit.rowCount() - 1:
            self.tab_crit.removeRow(self.tab_crit.currentRow())
        else:
            self.tab_crit.setItem(self.tab_crit.currentRow(),
                                  self.tab_crit.currentColumn(),
                                  QTableWidgetItem(""))
            #if you remove all of the criteriums in row it will remowve the whole row
            if self.tab_crit.item(self.tab_crit.currentRow(), 1)== "" \
                    and self.tab_crit.item(self.tab_crit.currentRow(), 2) == "" \
                    and self.tab_crit.item(self.tab_crit.currentRow(), 3) == "" \
                    and self.tab_crit.item(self.tab_crit.currentRow(), 4) == "":
                self.tab_crit.removeRow(self.tab_crit.currentRow())
            else:
                pass

    def removeRow(self):
        #This "if" prevents from removing last, empty row:
        if self.tab_crit.currentRow() == self.tab_crit.rowCount() - 1:
            pass
        else:
            self.tab_crit.removeRow(self.tab_crit.currentRow())

    def doCheckReason(
            self):  #this function enables reason field if user check urgent
        if self.urgent.isChecked():
            self.reason.setEnabled(True)
        else:
            self.reason.setEnabled(False)

    def doCheckNote(
            self):  #this function enables noet field if user check note
        if self.note.isChecked():
            self.note_txt.setEnabled(True)
        else:
            self.note_txt.setEnabled(False)

    def genXML(self):
        # This function generates the output of this program. It should be XML code, but right now it just prints all of the
        # received pieces of information. it throws error messages when some of the necessary pieces of information are
        # incorrect or blank
        txt = "data " + str(date.today()) + "\n"
        if self.case.isChecked():
            #if user select Case
            # it will throw error message if user check urgent and dosen't change text, or leave it blank
            if self.urgent.isChecked():
                if self.reason.text() == "" or self.reason.text() == "powód":
                    error_message_reason = QMessageBox.information(
                        self, "Brak powodu", "Podaj Powód", QMessageBox.Ok)
                    if error_message_reason == QMessageBox.Ok:
                        print("Nobody expects the Spanish Inquisition!")
                else:
                    txt = txt + "powód: " + self.reason.text() + "\n"
            else:
                pass
            if self.note.isChecked():
                #it will throw error message if user check note and dosen't change text, or leave it blank
                if self.note_txt.text() == "" or self.note_txt.text(
                ) == "notatka":
                    error_message_note = QMessageBox.information(
                        self, "Brak notatki", "Zapisz notatkę!",
                        QMessageBox.Ok)
                    if error_message_note == QMessageBox.Ok:
                        print(
                            "I am an enchanter. There are some who call me...Tim."
                        )
                else:
                    txt = txt + "notatka: " + self.note_txt.text() + "\n"
            else:
                pass
            if self.sub1.isChecked() == False and self.sub2.isChecked() == False and self.sub3.isChecked() == False \
                and self.sub4.isChecked() == False:
                # it will throw error message if user leave all of subs checkboxes unchecked
                error_message_subject = QMessageBox.information(
                    self, "Brak powodu", "Podaj Powód", QMessageBox.Ok)
                if error_message_subject == QMessageBox.Ok:
                    print("This is but a scratch!")
            else:
                txt = txt + "Podmioty: "
                if self.sub1.isChecked():
                    txt = txt + "podmiot1, "
                if self.sub2.isChecked():
                    txt = txt + "podmiot2, "
                if self.sub3.isChecked():
                    txt = txt + "podmiot3, "
                if self.sub4.isChecked():
                    txt = txt + "podmiot4, "
                txt = txt + "\n"
            if self.minion.isChecked() == False and self.master.isChecked(
            ) == False and self.superior.isChecked() == False:
                # it will throw error message if user leave all of accept checkboxes unchecked
                error_message_accept = QMessageBox.information(
                    self, "Bład akceptacji", "Nikt nie zaakceptował",
                    QMessageBox.Ok)
                if error_message_accept == QMessageBox.Ok:
                    print("We use only the finest baby frogs…")
            else:
                txt = txt + "Zaakceptowano: "
                if self.sub1.isChecked():
                    txt = txt + "minion, "
                if self.sub2.isChecked():
                    txt = txt + "master, "
                if self.sub3.isChecked():
                    txt = txt + "superior, "
                txt = txt + "\n"
        else:
            #if user select report
            # it will throw error message if user check note and dosen't change text, or leave it blank
            if self.note.isChecked():
                if self.note_txt.text() == "" or self.note_txt.text(
                ) == "notatka":
                    error_message_note = QMessageBox.information(
                        self, "Brak notatki", "Zapisz notatkę!",
                        QMessageBox.Ok)
                    if error_message_note == QMessageBox.Ok:
                        print(
                            "I am an enchanter. There are some who call me...Tim."
                        )
                else:
                    txt = txt + "notatka: " + self.note_txt.text() + "\n"
            else:
                pass
            if self.sub1.isChecked() == False and self.sub2.isChecked() == False and self.sub3.isChecked() == False \
                and self.sub4.isChecked() == False:
                # it will throw error message if user leave all of subs checkboxes unchecked
                error_message_subject = QMessageBox.information(
                    self, "Brak powodu", "Podaj Powód", QMessageBox.Ok)
                if error_message_subject == QMessageBox.Ok:
                    print("This is but a scratch!")
            else:
                txt = txt + "Podmioty: "
                if self.sub1.isChecked():
                    txt = txt + "podmiot1, "
                if self.sub2.isChecked():
                    txt = txt + "podmiot2, "
                if self.sub3.isChecked():
                    txt = txt + "podmiot3, "
                if self.sub4.isChecked():
                    txt = txt + "podmiot4, "
                txt = txt + "\n"
            if self.tab_crit.rowCount() == 1:
                # it will throw error message if there are no criteriums defined
                error_message_rows = QMessageBox.information(
                    self, "Brak kryteriów", "dodaj kryteria", QMessageBox.Ok)
                if error_message_rows == QMessageBox.Ok:
                    print("Are you suggesting that coconuts migrate?")
            else:
                for i in range(self.tab_crit.rowCount() - 1):
                    for j in range(4):
                        #this loop reads cells from tab_crit and add them to report
                        txt = txt + self.tab_crit.item(i, j).text() + ", "
                    txt = txt + "\n"
            if self.minion.isChecked() == False and self.master.isChecked(
            ) == False and self.superior.isChecked() == False:
                error_message_accept = QMessageBox.information(
                    self, "Bład akceptacji", "Nikt nie zaakceptował",
                    QMessageBox.Ok)
                if error_message_accept == QMessageBox.Ok:
                    print("We use only the finest baby frogs")
            else:
                txt = txt + "Zaakceptowano: "
                if self.sub1.isChecked():
                    txt = txt + "minion, "
                if self.sub2.isChecked():
                    txt = txt + "master, "
                if self.sub3.isChecked():
                    txt = txt + "superior, "
                txt = txt + "\n"
        #all of the gathered information is shown on new texfield
        self.XML_code.show()
        self.XML_code.setPlainText(txt)

    def doCaseOrRepo(
        self
    ):  #depending on chosen option (case, report) it will show or hide widgets
        if self.case.isChecked():
            self.urgent.show()
            self.urgent.setEnabled(True)
            self.reason.show()
            self.note.show()
            self.note_txt.show()
            self.tab_crit.hide()
            self.sub_label.show()
            self.sub1.show()
            self.sub2.show()
            self.sub3.show()
            self.sub4.show()
            self.country.hide()
            self.pos1.hide()
            self.pos2.hide()
            self.pos3.hide()
            self.pos4.hide()
            self.dodaj.hide()
            self.usun_kom.hide()
            self.usun_wi.hide()
            self.accept_label.show()
            self.minion.show()
            self.master.show()
            self.superior.show()
            self.rapo_date_sent.hide()
            self.case_date_sent.show()
            self.generate_xml.show()
            #it also clears note textbox and disables generat_XML button
            self.generate_xml.setEnabled(False)
            self.XML_code.hide()
            self.note_txt.setText("notatka")
        else:
            self.urgent.hide()
            self.urgent.setEnabled(True)
            self.reason.hide()
            self.note.show()
            self.note_txt.show()
            self.tab_crit.show()
            self.country.show()
            self.sub_label.show()
            self.sub1.show()
            self.sub2.show()
            self.sub3.show()
            self.sub4.show()
            self.pos1.show()
            self.pos2.show()
            self.pos3.show()
            self.pos4.show()
            self.dodaj.show()
            self.usun_kom.show()
            self.usun_wi.show()
            self.accept_label.show()
            self.minion.show()
            self.master.show()
            self.superior.show()
            self.rapo_date_sent.show()
            self.case_date_sent.hide()
            self.generate_xml.show()
            # it also clears note textbox and disables generat_XML button
            self.generate_xml.setEnabled(False)
            self.XML_code.hide()
            self.note_txt.setText("notatka")

    def activateXML(
        self
    ):  #this function activates generate_XML button if user confirms date
        if self.rapo_date_sent.isChecked() and self.repo.isChecked():
            self.generate_xml.setEnabled(True)
        elif self.case_date_sent.isChecked() and self.case.isChecked():
            self.generate_xml.setEnabled(True)
        else:
            self.generate_xml.setEnabled(False)
Exemplo n.º 19
0
class NetworkChoiceLayout(object):

    def __init__(self, network: Network, config, wizard=False):
        self.network = network
        self.config = config
        self.protocol = None
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        server_tab = QWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(server_tab, _('Server'))
        tabs.addTab(proxy_tab, _('Proxy'))

        # server tab
        grid = QGridLayout(server_tab)
        grid.setSpacing(8)

        self.server_host = QLineEdit()
        self.server_host.setFixedWidth(200)
        self.server_port = QLineEdit()
        self.server_port.setFixedWidth(60)
        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(self.config.is_modifiable('auto_connect'))

        self.server_host.editingFinished.connect(self.set_server)
        self.server_port.editingFinished.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)

        msg = ' '.join([
            _("If auto-connect is enabled, Electrum will always use a server that is on the longest blockchain."),
            _("If it is disabled, you have to choose a server you want to use. Electrum will warn you if your server is lagging.")
        ])
        grid.addWidget(self.autoconnect_cb, 0, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_host, 1, 1, 1, 2)
        grid.addWidget(self.server_port, 1, 3)

        label = _('Server peers') if network.is_connected() else _('Default Servers')
        grid.addWidget(QLabel(label), 2, 0, 1, 5)
        self.servers_list = ServerListWidget(self)
        grid.addWidget(self.servers_list, 3, 0, 1, 5)

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(['SOCKS4', 'SOCKS5'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(200)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(60)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_password = QLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))
        self.proxy_password.setEchoMode(QLineEdit.Password)
        self.proxy_password.setFixedWidth(60)

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_user.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_user.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(HelpButton(_('Proxy settings apply to all connections: with Electrum servers, but also with third-party services.')), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_user, 5, 2)
        grid.addWidget(self.proxy_password, 5, 3)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg =  ' '.join([
            _("Electrum connects to several nodes in order to download block headers and find out the longest blockchain."),
            _("This blockchain is used to verify the transactions sent by your transaction server.")
        ])
        self.status_label = QLabel('')
        grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
        grid.addWidget(self.status_label, 0, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        self.server_label = QLabel('')
        msg = _("Electrum sends your wallet addresses to a single server, in order to receive your transaction history.")
        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_label, 1, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.height_label = QLabel('')
        msg = _('This is the height of your local copy of the blockchain.')
        grid.addWidget(QLabel(_('Blockchain') + ':'), 2, 0)
        grid.addWidget(self.height_label, 2, 1)
        grid.addWidget(HelpButton(msg), 2, 4)

        self.split_label = QLabel('')
        grid.addWidget(self.split_label, 3, 0, 1, 3)

        self.nodes_list_widget = NodesListWidget(self)
        grid.addWidget(self.nodes_list_widget, 5, 0, 1, 5)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.fill_in_proxy_settings()
        self.update()

    def check_disable_proxy(self, b):
        if not self.config.is_modifiable('proxy'):
            b = False
        for w in [self.proxy_mode, self.proxy_host, self.proxy_port, self.proxy_user, self.proxy_password]:
            w.setEnabled(b)

    def enable_set_server(self):
        if self.config.is_modifiable('server'):
            enabled = not self.autoconnect_cb.isChecked()
            self.server_host.setEnabled(enabled)
            self.server_port.setEnabled(enabled)
            self.servers_list.setEnabled(enabled)
        else:
            for w in [self.autoconnect_cb, self.server_host, self.server_port, self.servers_list]:
                w.setEnabled(False)

    def update(self):
        net_params = self.network.get_parameters()
        host, port, protocol = net_params.host, net_params.port, net_params.protocol
        proxy_config, auto_connect = net_params.proxy, net_params.auto_connect
        self.server_host.setText(host)
        self.server_port.setText(str(port))
        self.autoconnect_cb.setChecked(auto_connect)

        interface = self.network.interface
        host = interface.host if interface else _('None')
        self.server_label.setText(host)

        self.set_protocol(protocol)
        self.servers = self.network.get_servers()
        self.servers_list.update(self.servers, self.protocol, self.tor_cb.isChecked())
        self.enable_set_server()

        height_str = "%d "%(self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.get_interfaces())
        status = _("Connected to {0} nodes.").format(n) if n else _("Not connected")
        self.status_label.setText(status)
        chains = self.network.get_blockchains()
        if len(chains) > 1:
            chain = self.network.blockchain()
            forkpoint = chain.get_max_forkpoint()
            name = chain.get_name()
            msg = _('Chain split detected at block {0}').format(forkpoint) + '\n'
            msg += (_('You are following branch') if auto_connect else _('Your server is on branch'))+ ' ' + name
            msg += ' (%d %s)' % (chain.get_branch_size(), _('blocks'))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(self.network)

    def fill_in_proxy_settings(self):
        proxy_config = self.network.get_parameters().proxy
        if not proxy_config:
            proxy_config = {"mode": "none", "host": "localhost", "port": "9050"}

        b = proxy_config.get('mode') != "none"
        self.check_disable_proxy(b)
        if b:
            self.proxy_cb.setChecked(True)
            self.proxy_mode.setCurrentIndex(
                self.proxy_mode.findText(str(proxy_config.get("mode").upper())))

        self.proxy_host.setText(proxy_config.get("host"))
        self.proxy_port.setText(proxy_config.get("port"))
        self.proxy_user.setText(proxy_config.get("user", ""))
        self.proxy_password.setText(proxy_config.get("password", ""))

    def layout(self):
        return self.layout_

    def set_protocol(self, protocol):
        if protocol != self.protocol:
            self.protocol = protocol

    def change_protocol(self, use_ssl):
        p = 's' if use_ssl else 't'
        host = self.server_host.text()
        pp = self.servers.get(host, constants.net.DEFAULT_PORTS)
        if p not in pp.keys():
            p = list(pp.keys())[0]
        port = pp[p]
        self.server_host.setText(host)
        self.server_port.setText(port)
        self.set_protocol(p)
        self.set_server()

    def follow_branch(self, chain_id):
        self.network.run_from_another_thread(self.network.follow_chain_given_id(chain_id))
        self.update()

    def follow_server(self, server):
        self.network.run_from_another_thread(self.network.follow_chain_given_server(server))
        self.update()

    def server_changed(self, x):
        if x:
            self.change_server(str(x.text(0)), self.protocol)

    def change_server(self, host, protocol):
        pp = self.servers.get(host, constants.net.DEFAULT_PORTS)
        if protocol and protocol not in protocol_letters:
            protocol = None
        if protocol:
            port = pp.get(protocol)
            if port is None:
                protocol = None
        if not protocol:
            if 's' in pp.keys():
                protocol = 's'
                port = pp.get(protocol)
            else:
                protocol = list(pp.keys())[0]
                port = pp.get(protocol)
        self.server_host.setText(host)
        self.server_port.setText(port)

    def accept(self):
        pass

    def set_server(self):
        net_params = self.network.get_parameters()
        net_params = net_params._replace(host=str(self.server_host.text()),
                                         port=str(self.server_port.text()),
                                         auto_connect=self.autoconnect_cb.isChecked())
        self.network.run_from_another_thread(self.network.set_parameters(net_params))

    def set_proxy(self):
        net_params = self.network.get_parameters()
        if self.proxy_cb.isChecked():
            proxy = { 'mode':str(self.proxy_mode.currentText()).lower(),
                      'host':str(self.proxy_host.text()),
                      'port':str(self.proxy_port.text()),
                      'user':str(self.proxy_user.text()),
                      'password':str(self.proxy_password.text())}
        else:
            proxy = None
            self.tor_cb.setChecked(False)
        net_params = net_params._replace(proxy=proxy)
        self.network.run_from_another_thread(self.network.set_parameters(net_params))

    def suggest_proxy(self, found_proxy):
        if found_proxy is None:
            self.tor_cb.hide()
            return
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if (self.proxy_cb.isChecked()
                and self.proxy_mode.currentIndex() == self.proxy_mode.findText('SOCKS5')
                and self.proxy_host.text() == "127.0.0.1"
                and self.proxy_port.text() == str(found_proxy[1])):
            self.tor_cb.setChecked(True)
        self.tor_cb.show()

    def use_tor_proxy(self, use_it):
        if not use_it:
            self.proxy_cb.setChecked(False)
        else:
            socks5_mode_index = self.proxy_mode.findText('SOCKS5')
            if socks5_mode_index == -1:
                _logger.info("can't find proxy_mode 'SOCKS5'")
                return
            self.proxy_mode.setCurrentIndex(socks5_mode_index)
            self.proxy_host.setText("127.0.0.1")
            self.proxy_port.setText(str(self.tor_proxy[1]))
            self.proxy_user.setText("")
            self.proxy_password.setText("")
            self.tor_cb.setChecked(True)
            self.proxy_cb.setChecked(True)
        self.check_disable_proxy(use_it)
        self.set_proxy()

    def proxy_settings_changed(self):
        self.tor_cb.setChecked(False)
Exemplo n.º 20
0
class LaserRangeFinder(PluginBase):
    def __init__(self, *args):
        super().__init__(BrickletLaserRangeFinder, *args)

        self.lrf = self.device

        # the firmware version of a EEPROM Bricklet can (under common circumstances)
        # not change during the lifetime of an EEPROM Bricklet plugin. therefore,
        # it's okay to make final decisions based on it here
        self.has_sensor_hardware_version_api = self.firmware_version >= (2, 0, 3)
        self.has_configuration_api = self.firmware_version >= (2, 0, 3)

        self.cbe_distance = CallbackEmulator(self.lrf.get_distance,
                                             None,
                                             self.cb_distance,
                                             self.increase_error_count)
        self.cbe_velocity = CallbackEmulator(self.lrf.get_velocity,
                                             None,
                                             self.cb_velocity,
                                             self.increase_error_count)

        self.current_distance = CurveValueWrapper() # int, cm
        self.current_velocity = CurveValueWrapper() # float, m/s

        plots_distance = [('Distance', Qt.red, self.current_distance, format_distance)]
        plots_velocity = [('Velocity', Qt.red, self.current_velocity, '{:.2f} m/s'.format)]
        self.plot_widget_distance = PlotWidget('Distance [cm]', plots_distance, y_resolution=1.0)
        self.plot_widget_velocity = PlotWidget('Velocity [m/s]', plots_velocity, y_resolution=0.01)

        self.mode_label = QLabel('Mode:')
        self.mode_combo = QComboBox()
        self.mode_combo.addItem("Distance: 1cm resolution, 40m max")
        self.mode_combo.addItem("Velocity: 0.10 m/s resolution, 12.70m/s max")
        self.mode_combo.addItem("Velocity: 0.25 m/s resolution, 31.75m/s max")
        self.mode_combo.addItem("Velocity: 0.50 m/s resolution, 63.50m/s max")
        self.mode_combo.addItem("Velocity: 1.00 m/s resolution, 127.00m/s max")
        self.mode_combo.currentIndexChanged.connect(self.mode_changed)
        self.mode_combo.hide()

        self.label_average_distance = QLabel('Moving Average for Distance:')

        self.spin_average_distance = QSpinBox()
        self.spin_average_distance.setMinimum(0)
        self.spin_average_distance.setMaximum(50)
        self.spin_average_distance.setSingleStep(1)
        self.spin_average_distance.setValue(10)
        self.spin_average_distance.editingFinished.connect(self.spin_average_finished)

        self.label_average_velocity = QLabel('Moving Average for Velocity:')

        self.spin_average_velocity = QSpinBox()
        self.spin_average_velocity.setMinimum(0)
        self.spin_average_velocity.setMaximum(50)
        self.spin_average_velocity.setSingleStep(1)
        self.spin_average_velocity.setValue(10)
        self.spin_average_velocity.editingFinished.connect(self.spin_average_finished)

        self.enable_laser = QCheckBox("Enable Laser")
        self.enable_laser.stateChanged.connect(self.enable_laser_changed)

        self.label_acquisition_count = QLabel('Acquisition Count:')
        self.spin_acquisition_count = QSpinBox()
        self.spin_acquisition_count.setMinimum(1)
        self.spin_acquisition_count.setMaximum(255)
        self.spin_acquisition_count.setSingleStep(1)
        self.spin_acquisition_count.setValue(128)

        self.enable_qick_termination = QCheckBox("Quick Termination")

        self.label_threshold = QLabel('Threshold:')
        self.threshold = QCheckBox("Automatic Threshold")

        self.spin_threshold = QSpinBox()
        self.spin_threshold.setMinimum(1)
        self.spin_threshold.setMaximum(255)
        self.spin_threshold.setSingleStep(1)
        self.spin_threshold.setValue(1)

        self.label_frequency = QLabel('Frequency [Hz]:')
        self.frequency = QCheckBox("Automatic Frequency (Disable for Velocity)")

        self.spin_frequency = QSpinBox()
        self.spin_frequency.setMinimum(10)
        self.spin_frequency.setMaximum(500)
        self.spin_frequency.setSingleStep(1)
        self.spin_frequency.setValue(10)

        self.spin_acquisition_count.editingFinished.connect(self.configuration_changed)
        self.enable_qick_termination.stateChanged.connect(self.configuration_changed)
        self.spin_threshold.editingFinished.connect(self.configuration_changed)
        self.threshold.stateChanged.connect(self.configuration_changed)
        self.spin_frequency.editingFinished.connect(self.configuration_changed)
        self.frequency.stateChanged.connect(self.configuration_changed)

        layout_h1 = QHBoxLayout()
        layout_h1.addWidget(self.plot_widget_distance)
        layout_h1.addWidget(self.plot_widget_velocity)

        layout_h2 = QHBoxLayout()
        layout_h2.addWidget(self.mode_label)
        layout_h2.addWidget(self.mode_combo)
        layout_h2.addWidget(self.label_average_distance)
        layout_h2.addWidget(self.spin_average_distance)
        layout_h2.addWidget(self.label_average_velocity)
        layout_h2.addWidget(self.spin_average_velocity)
        layout_h2.addStretch()
        layout_h2.addWidget(self.enable_laser)

        layout_h3 = QHBoxLayout()
        layout_h3.addWidget(self.label_frequency)
        layout_h3.addWidget(self.spin_frequency)
        layout_h3.addWidget(self.frequency)
        layout_h3.addStretch()
        layout_h3.addWidget(self.enable_qick_termination)

        layout_h4 = QHBoxLayout()
        layout_h4.addWidget(self.label_threshold)
        layout_h4.addWidget(self.spin_threshold)
        layout_h4.addWidget(self.threshold)
        layout_h4.addStretch()
        layout_h4.addWidget(self.label_acquisition_count)
        layout_h4.addWidget(self.spin_acquisition_count)

        self.widgets_distance = [self.plot_widget_distance, self.spin_average_distance, self.label_average_distance]
        self.widgets_velocity = [self.plot_widget_velocity, self.spin_average_velocity, self.label_average_velocity]

        for w in self.widgets_distance:
            w.hide()

        for w in self.widgets_velocity:
            w.hide()

        line = QFrame()
        line.setObjectName("line")
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h1)
        layout.addWidget(line)
        layout.addLayout(layout_h2)
        layout.addLayout(layout_h3)
        layout.addLayout(layout_h4)

    def start(self):
        if self.has_sensor_hardware_version_api:
            async_call(self.lrf.get_sensor_hardware_version, None, self.get_sensor_hardware_version_async, self.increase_error_count)
        else:
            self.get_sensor_hardware_version_async(1)

        if self.has_configuration_api:
            async_call(self.lrf.get_configuration, None, self.get_configuration_async, self.increase_error_count)

        async_call(self.lrf.get_mode, None, self.get_mode_async, self.increase_error_count)
        async_call(self.lrf.is_laser_enabled, None, self.enable_laser.setChecked, self.increase_error_count)
        async_call(self.lrf.get_moving_average, None, self.get_moving_average_async, self.increase_error_count)

        self.cbe_distance.set_period(25)
        self.cbe_velocity.set_period(25)

        self.plot_widget_distance.stop = False
        self.plot_widget_velocity.stop = False

    def stop(self):
        self.cbe_distance.set_period(0)
        self.cbe_velocity.set_period(0)

        self.plot_widget_distance.stop = True
        self.plot_widget_velocity.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletLaserRangeFinder.DEVICE_IDENTIFIER

    def enable_laser_changed(self, state):
        if state == Qt.Checked:
            self.lrf.enable_laser()
        else:
            self.lrf.disable_laser()

    def mode_changed(self, value):
        if value < 0 or value > 4:
            return

        self.lrf.set_mode(value)
        if value == 0:
            for w in self.widgets_velocity:
                w.hide()
            for w in self.widgets_distance:
                w.show()
        else:
            for w in self.widgets_distance:
                w.hide()
            for w in self.widgets_velocity:
                w.show()

    def cb_distance(self, distance):
        self.current_distance.value = distance

    def cb_velocity(self, velocity):
        self.current_velocity.value = velocity / 100.0

    def configuration_changed(self):
        acquisition_count = self.spin_acquisition_count.value()
        enable_quick_termination = self.enable_qick_termination.isChecked()

        if self.threshold.isChecked():
            threshold = 0
        else:
            threshold = self.spin_threshold.value()

        if self.frequency.isChecked():
            frequency = 0
            for w in self.widgets_velocity:
                w.hide()
        else:
            frequency = self.spin_frequency.value()
            for w in self.widgets_velocity:
                w.show()

        self.spin_threshold.setDisabled(threshold == 0)
        self.spin_frequency.setDisabled(frequency == 0)

        self.lrf.set_configuration(acquisition_count, enable_quick_termination, threshold, frequency)

    def get_configuration_async(self, conf):
        self.spin_acquisition_count.blockSignals(True)
        self.spin_acquisition_count.setValue(conf.acquisition_count)
        self.spin_acquisition_count.blockSignals(False)

        self.enable_qick_termination.blockSignals(True)
        self.enable_qick_termination.setChecked(conf.enable_quick_termination)
        self.enable_qick_termination.blockSignals(False)

        self.spin_threshold.blockSignals(True)
        self.spin_threshold.setValue(conf.threshold_value)
        self.spin_threshold.setDisabled(conf.threshold_value == 0)
        self.spin_threshold.blockSignals(False)

        self.spin_frequency.blockSignals(True)
        self.spin_frequency.setValue(conf.measurement_frequency)
        self.spin_frequency.setDisabled(conf.measurement_frequency == 0)
        self.spin_frequency.blockSignals(False)

        self.threshold.blockSignals(True)
        self.threshold.setChecked(conf.threshold_value == 0)
        self.threshold.blockSignals(False)

        self.frequency.blockSignals(True)
        self.frequency.setChecked(conf.measurement_frequency == 0)
        self.frequency.blockSignals(False)

        self.configuration_changed()

    def get_sensor_hardware_version_async(self, value):
        if value == 1:
            self.mode_combo.show()
            self.mode_label.show()
            self.label_acquisition_count.hide()
            self.spin_acquisition_count.hide()
            self.enable_qick_termination.hide()
            self.label_threshold.hide()
            self.spin_threshold.hide()
            self.threshold.hide()
            self.label_frequency.hide()
            self.spin_frequency.hide()
            self.frequency.hide()
        else:
            self.mode_combo.hide()
            self.mode_label.hide()
            self.label_acquisition_count.show()
            self.spin_acquisition_count.show()
            self.enable_qick_termination.show()
            self.label_threshold.show()
            self.spin_threshold.show()
            self.threshold.show()
            self.label_frequency.show()
            self.spin_frequency.show()
            self.frequency.show()

            for w in self.widgets_distance:
                w.show()
            for w in self.widgets_velocity:
                w.show()

    def get_mode_async(self, value):
        self.mode_combo.setCurrentIndex(value)
        self.mode_changed(value)

    def get_moving_average_async(self, avg):
        self.spin_average_distance.setValue(avg.distance_average_length)
        self.spin_average_velocity.setValue(avg.velocity_average_length)

    def spin_average_finished(self):
        self.lrf.set_moving_average(self.spin_average_distance.value(), self.spin_average_velocity.value())
Exemplo n.º 21
0
class RotamerDialog(ToolInstance):

    help = "help:user/tools/rotamers.html"
    SESSION_SAVE = True
    registerer = "swap_res RotamerDialog"

    def __init__(self, session, tool_name, *args):
        ToolInstance.__init__(self, session, tool_name)
        if args:
            # being called directly rather than during session restore
            self.finalize_init(*args)

    def finalize_init(self, mgr, res_type, rot_lib, *, table_info=None):
        self.mgr = mgr
        self.res_type = res_type
        self.rot_lib = rot_lib

        self.subdialogs = {}
        from collections import OrderedDict
        self.opt_columns = OrderedDict()
        self.handlers = [
            self.mgr.triggers.add_handler('fewer rotamers',
                                          self._fewer_rots_cb),
            self.mgr.triggers.add_handler('self destroyed',
                                          self._mgr_destroyed_cb),
        ]
        from chimerax.ui.widgets import ItemTable
        global _settings
        if _settings is None:
            from chimerax.core.settings import Settings

            class _RotamerSettings(Settings):
                EXPLICIT_SAVE = {ItemTable.DEFAULT_SETTINGS_ATTR: {}}

            _settings = _RotamerSettings(self.session, "Rotamers")
        from chimerax.ui import MainToolWindow
        self.tool_window = tw = MainToolWindow(self)
        parent = tw.ui_area
        from PyQt5.QtWidgets import QVBoxLayout, QLabel, QCheckBox, QGroupBox, QWidget, QHBoxLayout, \
            QPushButton, QRadioButton, QButtonGroup, QGridLayout
        from PyQt5.QtCore import Qt
        self.layout = layout = QVBoxLayout()
        parent.setLayout(layout)
        lib_display_name = self.session.rotamers.library(rot_lib).display_name
        layout.addWidget(
            QLabel("%s %s rotamers" % (lib_display_name, res_type)))
        column_disp_widget = QWidget()

        class RotamerTable(ItemTable):
            def sizeHint(self):
                from PyQt5.QtCore import QSize
                return QSize(350, 450)

        self.table = RotamerTable(column_control_info=(column_disp_widget,
                                                       _settings, {}, True,
                                                       None, None, False),
                                  auto_multiline_headers=False)
        for i in range(len(self.mgr.rotamers[0].chis)):
            self.table.add_column("Chi %d" % (i + 1),
                                  lambda r, i=i: r.chis[i],
                                  format="%6.1f")
        self.table.add_column("Probability", "rotamer_prob", format="%.6f ")

        if table_info:
            table_state, additional_col_info = table_info
            for col_type, title, data_fetch, display_format in additional_col_info:
                AtomicStructure.register_attr(
                    self.session,
                    data_fetch,
                    self.registerer,
                    attr_type=(int if data_fetch.startswith("num") else float))
                self.opt_columns[col_type] = self.table.add_column(
                    title, data_fetch, format=display_format)
        else:
            table_state = None
        self.table.data = self.mgr.rotamers
        self.table.launch(session_info=table_state)
        if not table_info:
            self.table.sortByColumn(len(self.mgr.rotamers[0].chis),
                                    Qt.DescendingOrder)
        self.table.selection_changed.connect(self._selection_change)
        layout.addWidget(self.table)
        if mgr.base_residue.name == res_type:
            self.retain_side_chain = QCheckBox("Retain original side chain")
            self.retain_side_chain.setChecked(False)
            layout.addWidget(self.retain_side_chain)
        else:
            self.retain_side_chain = None

        column_group = QGroupBox("Column display")
        layout.addWidget(column_group)
        cg_layout = QVBoxLayout()
        cg_layout.setContentsMargins(0, 0, 0, 0)
        cg_layout.setSpacing(0)
        column_group.setLayout(cg_layout)
        cg_layout.addWidget(column_disp_widget)

        add_col_layout = QGridLayout()
        add_col_layout.setContentsMargins(0, 0, 0, 0)
        add_col_layout.setSpacing(0)
        cg_layout.addLayout(add_col_layout)
        self.add_col_button = QPushButton("Calculate")
        add_col_layout.addWidget(self.add_col_button,
                                 0,
                                 0,
                                 alignment=Qt.AlignRight)
        radio_layout = QVBoxLayout()
        radio_layout.setContentsMargins(0, 0, 0, 0)
        add_col_layout.addLayout(radio_layout, 0, 1, alignment=Qt.AlignLeft)
        self.button_group = QButtonGroup()
        self.add_col_button.clicked.connect(
            lambda checked, *, bg=self.button_group: self._show_subdialog(
                bg.checkedButton().text()))
        for add_type in ["H-Bonds", "Clashes", "Density"]:
            rb = QRadioButton(add_type)
            rb.clicked.connect(self._update_button_text)
            radio_layout.addWidget(rb)
            if not self.button_group.buttons():
                rb.setChecked(True)
            self.button_group.addButton(rb)
        self.ignore_solvent_button = QCheckBox("Ignore solvent")
        self.ignore_solvent_button.setChecked(True)
        add_col_layout.addWidget(self.ignore_solvent_button,
                                 1,
                                 0,
                                 1,
                                 2,
                                 alignment=Qt.AlignCenter)

        from PyQt5.QtWidgets import QDialogButtonBox as qbbox
        bbox = qbbox(qbbox.Ok | qbbox.Cancel | qbbox.Help)
        bbox.accepted.connect(self._apply_rotamer)
        bbox.rejected.connect(self.tool_window.destroy)
        from chimerax.core.commands import run
        bbox.helpRequested.connect(
            lambda run=run, ses=self.session: run(ses, "help " + self.help))
        layout.addWidget(bbox)
        self.tool_window.manage(placement=None)

    def delete(self, from_mgr=False):
        for handler in self.handlers:
            handler.remove()
        self.subdialogs.clear()
        self.opt_columns.clear()
        if not from_mgr:
            self.mgr.destroy()
        super().delete()

    @classmethod
    def restore_snapshot(cls, session, data):
        inst = super().restore_snapshot(session, data['ToolInstance'])
        lib_display_name = data['lib_display_name']
        for lib_name in session.rotamers.library_names(installed_only=True):
            lib = session.rotamers.library(lib_name)
            if lib.display_name == lib_display_name:
                break
        else:
            raise RuntimeError(
                "Cannot restore Rotamers tool because %s rotamer library is not installed"
                % lib_display_name)
        inst.finalize_init(data['mgr'],
                           data['res_type'],
                           lib_name,
                           table_info=data['table info'])
        return inst

    def take_snapshot(self, session, flags):
        import sys
        data = {
            'ToolInstance':
            ToolInstance.take_snapshot(self, session, flags),
            'mgr':
            self.mgr,
            'res_type':
            self.res_type,
            'lib_display_name':
            session.rotamers.library(self.rot_lib).display_name,
            'table info': (self.table.session_info(),
                           [(col_type, c.title, c.data_fetch, c.display_format)
                            for col_type, c in self.opt_columns.items()])
        }
        return data

    def _apply_rotamer(self):
        rots = self.table.selected
        if not rots:
            if self.button_group.checkedButton().text() in self.opt_columns:
                raise UserError("No rotamers selected")
            else:
                raise UserError(
                    "No rotamers selected.  Click the 'Calculate' button (not 'OK') to"
                    " add a column to the table.")
        rot_nums = [r.id[-1] for r in rots]
        from chimerax.core.commands import run
        cmd = "swapaa %s %s criteria %s rotLib %s" % (
            self.mgr.base_residue.string(style="command"),
            self.res_type,
            ",".join(["%d" % rn for rn in rot_nums]),
            self.rot_lib,
        )
        if self.retain_side_chain:
            cmd += " retain %s" % str(
                self.retain_side_chain.isChecked()).lower()
        run(self.session, cmd)
        self.delete()

    def _eval_vol(self, vol):
        AtomicStructure.register_attr(self.session,
                                      "sum_density",
                                      self.registerer,
                                      attr_type=float)
        for rot in self.mgr.rotamers:
            values = vol.interpolated_values(rot.atoms.coords,
                                             point_xform=rot.scene_position)
            total = 0
            for a, val in zip(rot.atoms, values):
                # 'is_side_chain' only works for actual polymers
                if a.name not in a.residue.aa_max_backbone_names:
                    total += val
            rot.sum_density = total
        sd_type = "Density"
        if sd_type in self.opt_columns:
            self.table.update_column(self.opt_columns[sd_type], data=True)
        else:
            self.opt_columns[sd_type] = self.table.add_column(sd_type,
                                                              "sum_density",
                                                              format="%g")

    def _fewer_rots_cb(self, trig_name, mgr):
        self.rot_table.set_data(self.mgr.rotamers)

    def _mgr_destroyed_cb(self, trig_name, mgr):
        self.delete(from_mgr=True)

    def _selection_change(self, selected, deselected):
        if self.table.selected:
            display = set(self.table.selected)
        else:
            display = set(self.mgr.rotamers)
        for rot in self.mgr.rotamers:
            rot.display = rot in display

    def _process_subdialog(self, sd_type):
        sd = self.subdialogs[sd_type]
        from chimerax.core.commands import run
        if sd_type == "H-Bonds":
            cmd_name, spec, args = sd.hbonds_gui.get_command()
            res = self.mgr.base_residue
            base_spec = "#!%s & ~%s" % (res.structure.id_string,
                                        res.string(style="command"))
            if self.ignore_solvent_button.isChecked():
                base_spec += " & ~solvent"
            hbs = run(
                self.session, "%s %s %s restrict #%s & ~@c,ca,n" %
                (cmd_name, base_spec, args, self.mgr.group.id_string))
            AtomicStructure.register_attr(self.session,
                                          "num_hbonds",
                                          self.registerer,
                                          attr_type=int)
            for rotamer in self.mgr.rotamers:
                rotamer.num_hbonds = 0
            for d, a in hbs:
                if d.structure == res.structure:
                    a.structure.num_hbonds += 1
                else:
                    d.structure.num_hbonds += 1
            if sd_type in self.opt_columns:
                self.table.update_column(self.opt_columns[sd_type], data=True)
            else:
                self.opt_columns[sd_type] = self.table.add_column(sd_type,
                                                                  "num_hbonds",
                                                                  format="%d")
        elif sd_type == "Clashes":
            cmd_name, spec, args = sd.clashes_gui.get_command()
            res = self.mgr.base_residue
            base_spec = "#!%s & ~%s" % (res.structure.id_string,
                                        res.string(style="command"))
            if self.ignore_solvent_button.isChecked():
                base_spec += " & ~solvent"
            clashes = run(
                self.session, "%s %s %s restrict #%s & ~@c,ca,n" %
                (cmd_name, base_spec, args, self.mgr.group.id_string))
            AtomicStructure.register_attr(self.session,
                                          "num_clashes",
                                          self.registerer,
                                          attr_type=int)
            for rotamer in self.mgr.rotamers:
                rotamer.num_clashes = 0
            for a, clashing in clashes.items():
                if a.structure != res.structure:
                    a.structure.num_clashes += len(clashing)
            if sd_type in self.opt_columns:
                self.table.update_column(self.opt_columns[sd_type], data=True)
            else:
                self.opt_columns[sd_type] = self.table.add_column(
                    sd_type, "num_clashes", format="%d")
        else:  # Density
            vol = sd.vol_list.value
            if not vol:
                return
            self._eval_vol(vol)
        self._update_button_text()

    def _show_subdialog(self, sd_type):
        if sd_type == "Density":
            from chimerax.map import Volume
            volumes = [m for m in self.session.models if isinstance(m, Volume)]
            if not volumes:
                raise UserError("Must open a volume/map file first!")
            if len(volumes) == 1:
                self._eval_vol(volumes[0])
                return
        if sd_type not in self.subdialogs:
            self.subdialogs[
                sd_type] = sd = self.tool_window.create_child_window(
                    "Add %s Column" % sd_type)
            from PyQt5.QtWidgets import QVBoxLayout, QDialogButtonBox as qbbox
            layout = QVBoxLayout()
            sd.ui_area.setLayout(layout)
            if sd_type == "H-Bonds":
                from chimerax.hbonds.gui import HBondsGUI
                sd.hbonds_gui = HBondsGUI(self.session,
                                          settings_name="rotamers",
                                          reveal=True,
                                          show_inter_model=False,
                                          show_intra_model=False,
                                          show_intra_mol=False,
                                          show_intra_res=False,
                                          show_model_restrict=False,
                                          show_bond_restrict=False,
                                          show_save_file=False)
                layout.addWidget(sd.hbonds_gui)
            elif sd_type == "Clashes":
                from chimerax.clashes.gui import ClashesGUI
                sd.clashes_gui = ClashesGUI(self.session,
                                            False,
                                            settings_name="rotamers",
                                            radius=0.075,
                                            show_restrict=False,
                                            show_bond_separation=False,
                                            show_res_separation=False,
                                            show_inter_model=False,
                                            show_intra_model=False,
                                            show_intra_res=False,
                                            show_intra_mol=False,
                                            show_attr_name=False,
                                            show_set_attrs=False,
                                            show_checking_frequency=False,
                                            restrict="cross",
                                            bond_separation=0,
                                            reveal=True,
                                            show_save_file=False)
                layout.addWidget(sd.clashes_gui)
            else:  # Density
                from chimerax.ui.widgets import ModelListWidget
                from PyQt5.QtWidgets import QFormLayout
                density_layout = QFormLayout()
                layout.addLayout(density_layout)
                sd.vol_list = ModelListWidget(self.session,
                                              selection_mode='single',
                                              class_filter=Volume)
                density_layout.addRow("Select density:", sd.vol_list)
            bbox = qbbox(qbbox.Ok | qbbox.Close | qbbox.Help)
            bbox.accepted.connect(
                lambda sdt=sd_type: self._process_subdialog(sdt))
            bbox.accepted.connect(lambda sd=sd: setattr(sd, 'shown', False))
            bbox.rejected.connect(lambda sd=sd: setattr(sd, 'shown', False))
            layout.addWidget(bbox)
            sd.manage(placement=None)
        else:
            self.subdialogs[sd_type].title = "Update %s Column" % sd_type
        self.subdialogs[sd_type].shown = True

    def _update_button_text(self):
        cur_choice = self.button_group.checkedButton().text()
        if cur_choice.startswith("Density"):
            self.ignore_solvent_button.hide()
        else:
            self.ignore_solvent_button.show()
Exemplo n.º 22
0
class GpsConfigDlg(QDialog):
    def __init__(self, parent, gps_config_data, model, version):
        super().__init__(parent)
        self.gps_config_data = GpsConfigData(gps_config_data)
        self.model = model
        self.version = version
        # Layout form
        dlg_layout = QVBoxLayout(self)
        form_layout = QFormLayout()
        caption_constellation = QLabel(self)
        caption_constellation.setText(
            "Constellations Tracked:\n\n  (Not all combos supported)")
        gnss_layout = QVBoxLayout()
        self.gps_checkbox = QCheckBox(self)
        self.gps_checkbox.setText("GPS")
        self.glonass_checkbox = QCheckBox(self)
        self.glonass_checkbox.setText("GLONASS")
        self.beidou_checkbox = QCheckBox(self)
        self.beidou_checkbox.setText("BEIDOU")
        self.galileo_checkbox = QCheckBox(self)
        self.galileo_checkbox.setText("GALILEO")
        gnss_layout.addWidget(self.gps_checkbox)
        gnss_layout.addWidget(self.glonass_checkbox)
        gnss_layout.addWidget(self.beidou_checkbox)
        gnss_layout.addWidget(self.galileo_checkbox)
        if self.is_old_fs740():
            caption_constellation.hide()
            self.gps_checkbox.hide()
            self.glonass_checkbox.hide()
            self.beidou_checkbox.hide()
            self.galileo_checkbox.hide()
        form_layout.setWidget(0, QFormLayout.LabelRole, caption_constellation)
        form_layout.setLayout(0, QFormLayout.FieldRole, gnss_layout)
        caption_alignment = QLabel(self)
        caption_alignment.setText("Timing Alignment:")
        self.align_combobox = QComboBox(self)
        self.align_combobox.addItem("Align to UTC")
        self.align_combobox.addItem("Align to GPS")
        if not self.is_old_fs740():
            self.align_combobox.addItem("Align to GLONASS")
            self.align_combobox.addItem("Align to BEIDOU")
            self.align_combobox.addItem("Align to GALILEO")
        form_layout.setWidget(1, QFormLayout.LabelRole, caption_alignment)
        form_layout.setWidget(1, QFormLayout.FieldRole, self.align_combobox)
        caption_quality = QLabel(self)
        caption_quality.setText("Timing Quality:")
        self.quality_combobox = QComboBox(self)
        self.quality_combobox.addItem("Require only 1 satellite")
        self.quality_combobox.addItem("Require 3 satellites")
        form_layout.setWidget(2, QFormLayout.LabelRole, caption_quality)
        form_layout.setWidget(2, QFormLayout.FieldRole, self.quality_combobox)
        caption_min_snr = QLabel(self)
        caption_min_snr.setText("Minimum SNR:")
        self.min_snr_spinbox = QSpinBox(self)
        self.min_snr_spinbox.setMinimum(0)
        self.min_snr_spinbox.setMaximum(55)
        form_layout.setWidget(3, QFormLayout.LabelRole, caption_min_snr)
        form_layout.setWidget(3, QFormLayout.FieldRole, self.min_snr_spinbox)
        caption_min_elevation = QLabel(self)
        caption_min_elevation.setText("Minimum Sat. Elevation (Deg):")
        self.min_elevation_spinbox = QSpinBox(self)
        self.min_elevation_spinbox.setMinimum(0)
        self.min_elevation_spinbox.setMaximum(90)
        form_layout.setWidget(4, QFormLayout.LabelRole, caption_min_elevation)
        form_layout.setWidget(4, QFormLayout.FieldRole,
                              self.min_elevation_spinbox)
        caption_survey_mode = QLabel(self)
        caption_survey_mode.setText("Position Survey:")
        self.survey_combobox = QComboBox(self)
        self.survey_combobox.addItem("Disabled")
        self.survey_combobox.addItem("Redo survey at power on")
        self.survey_combobox.addItem("Remember survey results")
        form_layout.setWidget(5, QFormLayout.LabelRole, caption_survey_mode)
        form_layout.setWidget(5, QFormLayout.FieldRole, self.survey_combobox)
        caption_survey_fixes = QLabel(self)
        caption_survey_fixes.setText("Position Fixes in Survey:")
        self.fixes_spinbox = QSpinBox(self)
        self.fixes_spinbox.setMinimum(1)
        self.fixes_spinbox.setMaximum(2**31 - 1)
        form_layout.setWidget(6, QFormLayout.LabelRole, caption_survey_fixes)
        form_layout.setWidget(6, QFormLayout.FieldRole, self.fixes_spinbox)
        caption_antenna_delay = QLabel(self)
        caption_antenna_delay.setText("Antenna Delay Correction (ns):")
        self.antenna_delay_spinbox = QSpinBox(self)
        self.antenna_delay_spinbox.setMinimum(-32768)
        self.antenna_delay_spinbox.setMaximum(32767)
        form_layout.setWidget(7, QFormLayout.LabelRole, caption_antenna_delay)
        form_layout.setWidget(7, QFormLayout.FieldRole,
                              self.antenna_delay_spinbox)
        caption_local_time_offset = QLabel(self)
        caption_local_time_offset.setText("Local Time Offset (hr):")
        self.local_offset_spinbox = QDoubleSpinBox(self)
        self.local_offset_spinbox.setDecimals(1)
        self.local_offset_spinbox.setMinimum(-24.0)
        self.local_offset_spinbox.setMaximum(+24.0)
        form_layout.setWidget(8, QFormLayout.LabelRole,
                              caption_local_time_offset)
        form_layout.setWidget(8, QFormLayout.FieldRole,
                              self.local_offset_spinbox)
        dlg_layout.addLayout(form_layout)
        # Layout dialog buttons
        dialog_btns = QDialogButtonBox(self)
        dialog_btns.setStandardButtons(QDialogButtonBox.Ok
                                       | QDialogButtonBox.Cancel)
        dlg_layout.addWidget(dialog_btns)
        # Initialize widgets
        if not self.is_old_fs740():
            self.gps_checkbox.setChecked(True if (gps_config_data.constellation
                                                  & 1) else False)
            self.glonass_checkbox.setChecked(True if (
                gps_config_data.constellation & 2) else False)
            self.beidou_checkbox.setChecked(True if (
                gps_config_data.constellation & 4) else False)
            self.galileo_checkbox.setChecked(True if (
                gps_config_data.constellation & 8) else False)
        if self.is_old_fs740():
            if "GPS" == gps_config_data.time_alignment:
                index = 1
            else:
                index = 0
        else:
            if "GPS" == gps_config_data.time_alignment:
                index = 1
            elif "GLON" == gps_config_data.time_alignment:
                index = 2
            elif "BEID" == gps_config_data.time_alignment:
                index = 3
            elif "GAL" == gps_config_data.time_alignment:
                index = 4
            else:
                index = 0
        self.align_combobox.setCurrentIndex(index)
        self.quality_combobox.setCurrentIndex(
            0 if "1SAT" == gps_config_data.time_quality else 1)
        if "DIS" == gps_config_data.survey_mode:
            index = 0
        elif "REM" == gps_config_data.survey_mode:
            index = 2
        else:
            index = 1
        self.survey_combobox.setCurrentIndex(index)
        self.min_snr_spinbox.setValue(round(gps_config_data.min_snr))
        self.min_elevation_spinbox.setValue(
            round(gps_config_data.min_elevation))
        self.fixes_spinbox.setValue(gps_config_data.survey_fixes)
        self.antenna_delay_spinbox.setValue(
            int(round(gps_config_data.antenna_delay * 1e9)))
        self.local_offset_spinbox.setValue(gps_config_data.local_time_offset /
                                           3600.0)
        # Connect signals
        dialog_btns.accepted.connect(self.on_ok)
        dialog_btns.rejected.connect(self.reject)

    def is_old_fs740(self):
        return "FS740" == self.model and self.version < 4.00

    def on_ok(self):
        if self.is_old_fs740():
            constellation = 1
        else:
            constellation = 0
            if self.gps_checkbox.isChecked():
                constellation |= 1
            if self.glonass_checkbox.isChecked():
                constellation |= 2
            if self.beidou_checkbox.isChecked():
                constellation |= 4
            if self.galileo_checkbox.isChecked():
                constellation |= 8
        self.gps_config_data.constellation = constellation
        index = self.align_combobox.currentIndex()
        if 1 == index:
            self.gps_config_data.time_alignment = "GPS"
        elif 2 == index:
            self.gps_config_data.time_alignment = "GLON"
        elif 3 == index:
            self.gps_config_data.time_alignment = "BEID"
        elif 4 == index:
            self.gps_config_data.time_alignment = "GAL"
        else:
            self.gps_config_data.time_alignment = "UTC"
        self.gps_config_data.time_quality = "1SAT" if 0 == self.quality_combobox.currentIndex(
        ) else "3SAT"
        self.gps_config_data.min_snr = self.min_snr_spinbox.value()
        self.gps_config_data.min_elevation = self.min_elevation_spinbox.value()
        index = self.survey_combobox.currentIndex()
        if 0 == index:
            self.gps_config_data.survey_mode = "DIS"
        elif 2 == index:
            self.gps_config_data.survey_mode = "REM"
        else:
            self.gps_config_data.survey_mode = "RED"
        self.gps_config_data.survey_fixes = self.fixes_spinbox.value()
        self.gps_config_data.antenna_delay = self.antenna_delay_spinbox.value(
        ) / 1e9
        self.gps_config_data.local_time_offset = int(
            round(self.local_offset_spinbox.value() * 3600))
        # Timing alignment must include a followed constellation
        if 0 == constellation:
            QMessageBox.critical(self, "Error",
                                 "Must track at least one GNSS constellation")
        elif "UTC" == self.gps_config_data.time_alignment or \
                ("GPS" == self.gps_config_data.time_alignment and (self.gps_config_data.constellation & 1)) or \
                ("GLON" == self.gps_config_data.time_alignment and (self.gps_config_data.constellation & 2)) or \
                ("BEID" == self.gps_config_data.time_alignment and (self.gps_config_data.constellation & 4)) or \
                ("GAL" == self.gps_config_data.time_alignment and (self.gps_config_data.constellation & 8)):
            self.accept()
        else:
            QMessageBox.critical(
                self, "Error",
                "Timing alignment must include a tracked constellation")
Exemplo n.º 23
0
class MainWindow(QMainWindow):
    """Main window class."""
    def __init__(self, parent=None):
        """Init class."""
        super(MainWindow, self).__init__()
        QNetworkProxyFactory.setUseSystemConfiguration(True)
        self.statusBar().showMessage(__doc__ + get_nuitka_version())
        self.setWindowTitle(__doc__.strip().capitalize())
        self.setMinimumSize(480, 400)
        self.setMaximumSize(1024, 800)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("python"))
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Exit", lambda: self.close())
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        windowMenu.addSeparator()
        windowMenu.addAction(
            "Increase size", lambda: self.resize(self.size().width() * 1.4,
                                                 self.size().height() * 1.4))
        windowMenu.addAction(
            "Decrease size", lambda: self.resize(self.size().width() // 1.4,
                                                 self.size().height() // 1.4))
        windowMenu.addAction("Minimum size",
                             lambda: self.resize(self.minimumSize()))
        windowMenu.addAction("Maximum size",
                             lambda: self.resize(self.maximumSize()))
        windowMenu.addAction(
            "Horizontal Wide",
            lambda: self.resize(self.maximumSize().width(),
                                self.minimumSize().height()))
        windowMenu.addAction(
            "Vertical Tall", lambda: self.resize(self.minimumSize().width(),
                                                 self.maximumSize().height()))
        windowMenu.addSeparator()
        windowMenu.addAction("Disable Resize",
                             lambda: self.setFixedSize(self.size()))
        windowMenu.addAction("Set Interface Font...",
                             lambda: self.setFont(QFontDialog.getFont()[0]))
        windowMenu.addAction("Load .qss Skin",
                             lambda: self.setStyleSheet(self.skin()))
        helpMenu = self.menuBar().addMenu("&Help")
        helpMenu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self))
        helpMenu.addAction("About Python 3",
                           lambda: open_new_tab('https://www.python.org'))
        helpMenu.addAction("About " + __doc__,
                           lambda: QMessageBox.about(self, __doc__, HELP))
        helpMenu.addSeparator()
        helpMenu.addAction(
            "Keyboard Shortcut",
            lambda: QMessageBox.information(self, __doc__, "<b>Quit = CTRL+Q"))
        if sys.platform.startswith('linux'):
            helpMenu.addAction(
                "View Source Code",
                lambda: call('xdg-open ' + __file__, shell=True))
        helpMenu.addAction("View GitHub Repo", lambda: open_new_tab(__url__))
        helpMenu.addAction("Check Updates", lambda: Downloader(self))
        # process
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self._read_output)
        self.process.readyReadStandardError.connect(self._read_errors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_failed)
        # widgets
        self.group0, self.group1 = QGroupBox("Options"), QGroupBox("Paths")
        self.group4, self.group5 = QGroupBox("Details"), QGroupBox("Miscs")
        g0grid, g1vlay = QGridLayout(self.group0), QGridLayout(self.group1)
        g5vlay, g4vlay = QVBoxLayout(self.group5), QVBoxLayout(self.group4)
        # group 0 the options
        self.module = QCheckBox("Create compiled extension module")
        self.standalone = QCheckBox("Standalone executable binary output")
        self.nofreeze = QCheckBox("No freeze all modules of standard library")
        self.python_debug = QCheckBox("Use Python Debug")
        self.warning = QCheckBox("Warnings for implicit exceptions at compile")
        self.recurse_std = QCheckBox("Recursive compile the standard library")
        self.recurse_not = QCheckBox("Force No recursive compiling")
        self.execute = QCheckBox("Execute the created binary after compiling")
        self.pythonpath = QCheckBox("Keep pythonpath when executing")
        self.enhaced = QCheckBox("Enhaced compile, Not CPython compatible")
        self.nolineno = QCheckBox("No Statements line numbers on compile")
        self.rmbuilddir = QCheckBox("Remove build directory after compile.")
        self.nuitka_debug = QCheckBox("Use Nuitka Debug")
        self.keep_debug = QCheckBox("Keep debug info on compile for GDB")
        self.traced = QCheckBox("Traced execution output")
        self.plusplus = QCheckBox("Compile C++ Only on generated source files")
        self.experimental = QCheckBox("Experimental features")
        self.force_clang = QCheckBox("Force use of CLang")
        self.force_mingw = QCheckBox("Force use of MinGW on MS Windows")
        self.force_lto = QCheckBox("Use link time optimizations LTO")
        self.show_scons = QCheckBox("Show Scons executed commands")
        self.show_progress = QCheckBox("Show progress info and statistics")
        self.show_summary = QCheckBox("Show final summary of included modules")
        self.disable_console = QCheckBox("Disable the Console on MS Windows")
        for i, widget in enumerate(
            (self.module, self.standalone, self.nofreeze, self.python_debug,
             self.warning, self.recurse_std, self.recurse_not, self.execute,
             self.pythonpath, self.enhaced, self.nolineno, self.rmbuilddir,
             self.nuitka_debug, self.keep_debug, self.traced, self.plusplus,
             self.experimental, self.force_clang, self.force_mingw,
             self.force_lto, self.show_scons, self.show_progress,
             self.show_summary, self.disable_console)):
            widget.setToolTip(widget.text())
            g0grid.addWidget(widget, i if i < i + 1 else i - (i - 1), i % 2)
        # group 1 paths
        self.target = QLineEdit()
        self.outdir = QLineEdit(os.path.expanduser("~"))
        self.t_icon = QLineEdit()
        self.target.setToolTip("Python App file you want to Compile to Binary")
        self.outdir.setToolTip("Folder to write Compiled Output Binary files")
        self.t_icon.setToolTip("Icon image file to embed for your Python App")
        self.target.setPlaceholderText("/full/path/to/target/python_app.py")
        self.outdir.setPlaceholderText("/full/path/to/output/folder/")
        self.t_icon.setPlaceholderText("/full/path/to/python_app/icon.png")
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.completer.popup().setStyleSheet("border: 1px solid gray")
        self.completer.popup().setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.outdir.setCompleter(self.completer)
        self.t_icon.setCompleter(self.completer)
        self.target.setCompleter(self.completer)
        self.clear_1 = QPushButton(QIcon.fromTheme("edit-clear"),
                                   "",
                                   self,
                                   clicked=lambda: self.target.clear())
        self.clear_2 = QPushButton(QIcon.fromTheme("edit-clear"),
                                   "",
                                   self,
                                   clicked=lambda: self.t_icon.clear())
        self.clear_3 = QPushButton(QIcon.fromTheme("edit-clear"),
                                   "",
                                   self,
                                   clicked=lambda: self.outdir.clear())
        self.open_1 = QPushButton(
            QIcon.fromTheme("folder-open"),
            "",
            self,
            clicked=lambda: self.target.setText(
                str(
                    QFileDialog.getOpenFileName(
                        self, __doc__, os.path.expanduser("~"),
                        """Python (*.py);;
                    Python for Windows (*.pyw);;All (*.*)""")[0])))
        self.open_2 = QPushButton(
            QIcon.fromTheme("folder-open"),
            "",
            self,
            clicked=lambda: self.t_icon.setText(
                str(
                    QFileDialog.getOpenFileName(
                        self, __doc__, os.path.expanduser("~"),
                        "PNG (*.png);;JPG (*.jpg);;ICO (*.ico);;All (*.*)")[0])
            ))
        self.open_3 = QPushButton(
            QIcon.fromTheme("folder-open"),
            "",
            self,
            clicked=lambda: self.outdir.setText(
                str(
                    QFileDialog.getExistingDirectory(
                        self, __doc__, os.path.expanduser("~")))))
        self.l_icon = QLabel("Target Icon")
        g1vlay.addWidget(QLabel("<b>Target Python"), 0, 0)
        g1vlay.addWidget(self.target, 0, 1)
        g1vlay.addWidget(self.clear_1, 0, 2)
        g1vlay.addWidget(self.open_1, 0, 3)
        g1vlay.addWidget(self.l_icon, 1, 0)
        g1vlay.addWidget(self.t_icon, 1, 1)
        g1vlay.addWidget(self.clear_2, 1, 2)
        g1vlay.addWidget(self.open_2, 1, 3)
        g1vlay.addWidget(QLabel("<b>Output Folder"), 2, 0)
        g1vlay.addWidget(self.outdir, 2, 1)
        g1vlay.addWidget(self.clear_3, 2, 2)
        g1vlay.addWidget(self.open_3, 2, 3)

        # group 4 the dome view mode
        self.jobs = QSpinBox()
        self.jobs.setRange(1, cpu_count())
        self.jobs.setValue(cpu_count())
        self.jobs.setToolTip("Backend Worker Jobs Processes")
        self.python_version = QComboBox()
        self.python_version.addItems(["2.7", "3.2", "3.3", "3.4"])
        self.python_version.setToolTip("Python version to use with Nuitka")
        self.display_tree = QPushButton("Display Tree")
        self.display_tree.clicked.connect(lambda: call(
            NUITKA + " --display-tree {}".format(self.target.text()),
            shell=True))
        self.dump_tree = QPushButton(
            "View Docs",
            clicked=lambda: open_new_tab(
                "http://nuitka.net/doc/user-manual.html"))
        self.open_log = QPushButton("View Logs")
        _log = os.path.join(gettempdir(), "nuitka-gui.log")
        _open = "xdg-open " if sys.platform.startswith("lin") else "open "
        self.open_log.clicked.connect(lambda: call(_open + _log, shell=True))
        self.open_folder = QPushButton("Open Build Folder")
        self.open_folder.clicked.connect(
            lambda: call(_open + str(self.outdir.text()).strip(), shell=True))

        # self.display_tree.clicked.connect(self._display_tree)
        g4vlay.addWidget(QLabel("<b>Worker Jobs"))
        g4vlay.addWidget(self.jobs)
        g4vlay.addWidget(QLabel("<b>Python Version"))
        g4vlay.addWidget(self.python_version)
        g4vlay.addWidget(QLabel("<b>Actions"))
        g4vlay.addWidget(self.display_tree)
        g4vlay.addWidget(self.dump_tree)
        g4vlay.addWidget(self.open_log)
        g4vlay.addWidget(self.open_folder)

        # group 5 miscelaneous stuff
        self.debug, self.scr = QCheckBox("Use Debug"), QCheckBox("Make Script")
        self.chrt, self.ionice = QCheckBox("Slow CPU"), QCheckBox("Slow HDD")
        self.minimi = QCheckBox("Auto Minimize")
        self.chrt.setToolTip("Use Low CPU speed priority (Linux only)")
        self.ionice.setToolTip("Use Low HDD speed priority (Linux only)")
        self.scr.setToolTip("Generate a Bash Script to Compile with Nuitka")
        self.debug.setToolTip("Use Debug Verbose mode")
        self.minimi.setToolTip("Automatically Minimize when compiling starts")
        self.scr.setChecked(True)
        self.chrt.setChecked(True)
        self.ionice.setChecked(True)
        self.minimi.setChecked(True)
        g5vlay.addWidget(self.debug)
        g5vlay.addWidget(self.scr)
        g5vlay.addWidget(self.chrt)
        g5vlay.addWidget(self.ionice)
        g5vlay.addWidget(self.minimi)

        # option to show or hide some widgets on the gui
        self.guimode = QComboBox()
        self.guimode.addItems(('Full UX / UI', 'Simple UX / UI'))
        self.guimode.setCurrentIndex(1)
        self._set_guimode()
        self.guimode.setStyleSheet("""QComboBox{background:transparent;
            margin-left:25px;color:gray;text-decoration:underline;border:0}""")
        self.guimode.currentIndexChanged.connect(self._set_guimode)

        # buttons from bottom to close or proceed
        self.bt = QDialogButtonBox(self)
        self.bt.setStandardButtons(QDialogButtonBox.Ok
                                   | QDialogButtonBox.Close)
        self.bt.rejected.connect(self.close)
        self.bt.accepted.connect(self.run)

        if not sys.platform.startswith('lin'):
            self.scr.setChecked(False)
            self.chrt.setChecked(False)
            self.ionice.setChecked(False)
            self.scr.hide()
            self.chrt.hide()
            self.ionice.hide()
        if not sys.platform.startswith('win'):
            self.l_icon.hide()
            self.t_icon.hide()
            self.clear_2.hide()
            self.open_2.hide()
        if sys.platform.startswith('win'):
            self.display_tree.hide()

        # container for all groups of widgets
        container = QWidget()
        container_layout = QGridLayout(container)  # Y, X
        container_layout.addWidget(self.guimode, 0, 1)
        container_layout.addWidget(self.group0, 1, 1)
        container_layout.addWidget(self.group1, 2, 1)
        container_layout.addWidget(self.group4, 1, 2)
        container_layout.addWidget(self.group5, 2, 2)
        container_layout.addWidget(self.bt, 3, 1)
        self.setCentralWidget(container)

    def check_paths(self):
        """Check that the paths are valid."""
        if not os.path.isfile(self.target.text()):
            log.error("Target File not found or not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target File not found or not valid.")
            return False
        if not str(self.target.text()).endswith((".py", ".pyw")):
            log.error("Target File not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target File not valid.")
            return False
        if not os.path.isdir(self.outdir.text()):
            log.error("Target Folder not found or not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target Folder not found or not valid.")
            return False
        if self.t_icon.text() and not os.path.isfile(self.t_icon.text()):
            log.warning("Target Icon File not found or not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target Icon File not found or not valid.")
            return True
        else:
            return True

    def generate_build_command(self):
        """Generate a build command."""
        return re.sub(
            r"\s+", " ", " ".join(
                ('chrt --verbose --idle 0' if self.chrt.isChecked() else '',
                 'ionice --ignore --class 3'
                 if self.ionice.isChecked() else '', NUITKA,
                 '--debug --verbose' if self.debug.isChecked() else '',
                 '--show-progress' if self.show_progress.isChecked() else '',
                 '--show-scons --show-modules' if self.show_scons.isChecked()
                 else '', '--unstriped' if self.keep_debug.isChecked() else '',
                 '--trace-execution' if self.traced.isChecked() else '',
                 '--remove-output' if self.rmbuilddir.isChecked() else '',
                 '--code-gen-no-statement-lines' if self.nolineno.isChecked()
                 else '', '--execute' if self.execute.isChecked() else '',
                 '--recurse-none'
                 if self.recurse_not.isChecked() else '--recurse-all',
                 '--recurse-stdlib' if self.recurse_std.isChecked() else '',
                 '--clang' if self.force_clang.isChecked() else '',
                 '--lto' if self.force_lto.isChecked() else '',
                 '--c++-only' if self.plusplus.isChecked() else '',
                 '--windows-disable-console'
                 if self.disable_console.isChecked() else '',
                 '--experimental' if self.experimental.isChecked() else '',
                 '--python-debug' if self.python_debug.isChecked() else '',
                 '--module' if self.module.isChecked() else '--standalone',
                 '--nofreeze-stdlib' if self.nofreeze.isChecked() else '',
                 '--mingw' if self.force_mingw.isChecked() else '',
                 '--warn-implicit-exceptions' if self.warning.isChecked() else
                 '', '--execute-with-pythonpath'
                 if self.pythonpath.isChecked() else '',
                 '--enhanced' if self.enhaced.isChecked() else '',
                 '--icon="{}"'.format(self.t_icon.text())
                 if self.t_icon.text() else '', '--python-version={}'.format(
                     self.python_version.currentText()), '--jobs={}'.format(
                         self.jobs.value()), '--output-dir="{}"'.format(
                             self.outdir.text()), '"{}"'.format(
                                 self.target.text()))))

    def run(self):
        """Run the main method and run Nuitka."""
        self.statusBar().showMessage('Working...')
        log.debug("Working...")
        if not self.check_paths():
            return
        command_to_run_nuitka = self.generate_build_command()
        log.debug(command_to_run_nuitka)
        self.process.start(command_to_run_nuitka)
        if not self.process.waitForStarted():
            log.error(self._read_errors())
            return  # ERROR
        if self.scr.isChecked() and sys.platform.startswith("lin"):
            script_file = str(self.target.text()).replace(
                ".py", "-nuitka-compile.sh")
            log.debug("Writing Script {}".format(script_file))
            with open(script_file, "w", encoding="utf-8") as script:
                script.write("#!/usr/bin/env bash\n" + command_to_run_nuitka)
                os.chmod(script_file, 0o755)
        self.statusBar().showMessage(__doc__.title())

    def _process_finished(self):
        """Finished sucessfuly."""
        log.debug("Finished.")
        self.showNormal()

    def _read_output(self):
        """Read and return output."""
        return str(self.process.readAllStandardOutput()).strip()

    def _read_errors(self):
        """Read and return errors."""
        log.debug(self.process.readAllStandardError())
        return str(self.process.readAllStandardError()).strip()

    def _process_failed(self):
        """Read and return errors."""
        self.showNormal()
        self.statusBar().showMessage(" ERROR: Failed ! ")
        log.warning(str(self.process.readAllStandardError()).strip().lower())
        return str(self.process.readAllStandardError()).strip().lower()

    def _set_guimode(self):
        """Switch between simple and full UX."""
        for widget in (self.group0, self.group4, self.group5, self.statusBar(),
                       self.menuBar()):
            widget.hide() if self.guimode.currentIndex() else widget.show()
        self.resize(self.minimumSize() if self.guimode.currentIndex(
        ) else self.maximumSize())
        self.center()

    def skin(self, filename=None):
        """Open QSS from filename,if no QSS return None,if no filename ask."""
        if not filename:
            filename = str(
                QFileDialog.getOpenFileName(
                    self, __doc__ + "-Open QSS Skin file",
                    os.path.expanduser("~"),
                    "CSS Cascading Style Sheet for Qt 5 (*.qss);;All (*.*)")
                [0])
        if filename and os.path.isfile(filename):
            log.debug(filename)
            with open(filename, 'r') as file_to_read:
                text = file_to_read.read().strip()
        if text:
            log.debug(text)
            return text

    def center(self):
        """Center the Window on the Current Screen,with Multi-Monitor support.

        >>> MainWindow().center()
        True
        """
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        return bool(not self.move(window_geometry.topLeft()))

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position.

        >>> MainWindow().move_to_mouse_position()
        True
        """
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        return bool(not self.move(window_geometry.topLeft()))

    def closeEvent(self, event):
        """Ask to Quit."""
        the_conditional_is_true = QMessageBox.question(
            self, __doc__.title(), 'Quit ?.', QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No) == QMessageBox.Yes
        event.accept() if the_conditional_is_true else event.ignore()
Exemplo n.º 24
0
class SongNameCard(QWidget):
    """ 歌名卡 """
    def __init__(self, songName, parent=None):
        super().__init__(parent)
        self.songName = songName
        # 创建小部件
        self.checkBox = QCheckBox(self)
        self.playingLabel = QLabel(self)
        self.songNameLabel = QLabel(songName, self)
        self.buttonGroup = ButtonGroup(self)
        self.playButton = self.buttonGroup.playButton
        self.addToButton = self.buttonGroup.addToButton
        # 初始化
        self.__initWidget()

    def __initWidget(self):
        """ 初始化小部件 """
        self.setFixedHeight(60)
        self.resize(390, 60)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.playingLabel.setPixmap(
            QPixmap(r'resource\images\playing_interface\正在播放_16_16.png'))
        # 隐藏小部件
        self.checkBox.hide()
        self.playingLabel.hide()
        # 分配属性和ID
        self.setObjectName('songNameCard')
        self.songNameLabel.setObjectName('songNameLabel')
        self.checkBox.setProperty('isPlay', 'False')
        self.songNameLabel.setProperty('isPlay', 'False')
        # 计算歌名的长度
        self.__getSongNameWidth()
        self.__initLayout()
        # self.__setQss()

    def __initLayout(self):
        """ 初始化布局 """
        self.checkBox.move(8, 17)
        self.playingLabel.move(43, 22)
        self.songNameLabel.move(41, 20)
        self.__moveButtonGroup()

    def __getSongNameWidth(self):
        """ 计算歌名的长度 """
        fontMetrics = QFontMetrics(QFont('Microsoft YaHei', 9))
        self.songNameWidth = sum([fontMetrics.width(i) for i in self.songName])

    def __setQss(self):
        """ 初始化样式 """
        with open(r'resource\css\playInterfaceSongCard.qss',
                  encoding='utf-8') as f:
            self.setStyleSheet(f.read())

    def setPlay(self, isPlay: bool):
        """ 设置播放状态并移动小部件 """
        self.buttonGroup.setPlay(isPlay)
        self.checkBox.setProperty('isPlay', str(isPlay))
        self.songNameLabel.setProperty('isPlay', str(isPlay))
        # 显示/隐藏正在播放图标并根据情况移动歌名标签
        self.playingLabel.setHidden(not isPlay)
        if isPlay:
            self.songNameLabel.move(68, self.songNameLabel.y())
        else:
            self.songNameLabel.move(41, self.songNameLabel.y())
        # 更新按钮位置
        self.__moveButtonGroup()
        # 更新样式
        self.setStyle(QApplication.style())

    def resizeEvent(self, e):
        """ 改变尺寸时移动按钮 """
        super().resizeEvent(e)
        self.__moveButtonGroup()

    def setWidgetHidden(self, isHidden: bool):
        """ 显示/隐藏小部件 """
        self.buttonGroup.setButtonHidden(isHidden)
        self.checkBox.setHidden(isHidden)

    def __moveButtonGroup(self):
        """ 移动按钮组 """
        if self.songNameWidth + self.songNameLabel.x() >= self.width() - 140:
            x = self.width() - 140
        else:
            x = self.songNameWidth + self.songNameLabel.x()
        self.buttonGroup.move(x, 0)

    def setSongName(self, songName: str):
        """ 更新歌手名标签的文本并调整宽度 """
        self.songName = songName
        self.songNameLabel.setText(songName)
        # 重新计算歌名宽度并移动按钮
        self.__getSongNameWidth()
        self.__moveButtonGroup()
        self.songNameLabel.setFixedWidth(self.songNameWidth)
Exemplo n.º 25
0
class MainUi(QtWidgets.QMainWindow):
    global maxFlag
    maxFlag = True
    global name
    global image1
    image1 = ["1", "2"]
    global file2
    global ifConnect
    ifConnect = False

    def __init__(self):
        super().__init__()
        self.setFixedSize(1000, 720)

        self.main_widget = QtWidgets.QWidget()  # 创建窗口主部件
        self.main_layout = QtWidgets.QGridLayout()  # 创建主部件的网格布局
        self.main_widget.setLayout(self.main_layout)  # 设置窗口主部件布局为网格布局
        self.setCentralWidget(self.main_widget)  # 设置窗口主部件

        # 窗口背景透明
        # self.setWindowOpacity(0.9)  # 设置窗口透明度
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 隐藏边框
        self.main_layout.setSpacing(0)  # 去除缝隙
        self.init_left_ui()
        self.init_right_ui()
        self.setWindowIcon(QIcon('./res/3n.png'))
        self._bottom_rect = [
            QPoint(x, y) for x in range(1, self.width())
            for y in range(0, 100)
        ]
        self.m_flag = False
        self.fundusAnalysis = FundusAnalysis(CONFIG_PATH)

    def maxMin(self):
        global maxFlag
        desktop = QDesktopWidget()

        rect = desktop.screenGeometry(0)  # 获取第一个显示器的分辨率
        if (maxFlag):
            self.setGeometry(
                QtCore.QRect(0, 0,
                             desktop.geometry().width(),
                             desktop.geometry().height()))
            # self.setFixedSize(QSize( desktop.geometry().width(),desktop.geometry().height()))
            self.setFixedSize(rect.width(), rect.height())

            maxFlag = False
            print(maxFlag)
        else:

            self.setGeometry(
                QtCore.QRect(desktop.geometry().width() / 5,
                             desktop.geometry().height() / 5, 1000, 720))
            self.setFixedSize(QSize(1000, 720))
            maxFlag = True
            print(maxFlag)

    def closeEvent(self, event):

        reply = QMessageBox(QMessageBox.Question, self.tr('退出'),
                            self.tr("您即将关闭软件,确定继续吗?"), QMessageBox.NoButton,
                            self)
        yr_btn = reply.addButton(self.tr("是"), QMessageBox.YesRole)
        reply.addButton(self.tr("否"), QMessageBox.NoRole)
        reply.exec_()

        if reply.clickedButton() == yr_btn:
            event.accept()
        else:
            event.ignore()

    def warning(self, event):
        warn = QMessageBox.warning(self, '警告', "请选择需要诊断的图片或者文件夹",
                                   QMessageBox.Yes, QMessageBox.Yes)
        if warn == QMessageBox.Yes:
            event.ignore()

    def init_left_ui(self):
        self.left_widget = QtWidgets.QWidget()  # 创建左侧部件
        self.left_widget.setObjectName('left_widget')
        self.left_layout = QtWidgets.QGridLayout()  # 创建左侧部件的网格布局层
        self.left_widget.setLayout(self.left_layout)  # 设置左侧部件布局为网格
        self.main_layout.addWidget(self.left_widget, 0, 0, 10,
                                   2)  # 左侧部件在第0行第0列,占12行2列
        self.left_close = QtWidgets.QPushButton(
            qtawesome.icon('fa.times', color='gray'), "")  # 关闭按钮

        self.left_mini = QtWidgets.QPushButton(
            qtawesome.icon('fa.minus', color='gray'), "")  # 最小化按钮
        self.left_close.clicked.connect(self.close)
        self.left_mini.clicked.connect(self.showMinimized)

        self.left_label_1 = QtWidgets.QPushButton(
            qtawesome.icon('fa.book', color='white'), "项目")
        self.left_label_1.setObjectName('left_label')
        self.left_label_1.clicked.connect(self.showmessage2)

        self.left_label_2 = QtWidgets.QPushButton(
            qtawesome.icon('fa.tasks', color='white'), "任务中心")
        self.left_label_2.setObjectName('left_label')
        self.left_label_2.clicked.connect(self.showright)
        self.left_label_3 = QtWidgets.QPushButton(
            qtawesome.icon('fa.at', color='white'), "帮助")
        self.left_label_3.setObjectName('left_label')
        self.left_label_3.clicked.connect(self.showmessage1)
        self.left_layout.addWidget(self.left_mini, 0, 2, 1, 1)
        self.left_layout.addWidget(self.left_close, 0, 0, 1, 1)

        self.left_layout.addWidget(self.left_label_1, 1, 0, 1, 3)
        self.left_layout.addWidget(self.left_label_2, 2, 0, 1, 3)
        self.left_layout.addWidget(self.left_label_3, 3, 0, 1, 3)

        # blank
        self.left_button_1 = QLabel("", self)

        self.left_button_2 = QLabel("", self)
        self.left_button_3 = QLabel("", self)
        self.left_button_4 = QLabel("", self)
        self.left_button_5 = QLabel("", self)
        self.left_button_6 = QLabel("", self)

        self.left_button_9 = QLabel(self)
        self.left_button_9.setText(
            "<a href='https://shimo.im/docs/bQeGWqF6C30WBVAU/' style='color:white'>Beta v1.3.1</a>"
        )
        self.left_button_9.setOpenExternalLinks(True)  # 允许访问超链接
        self.left_button_9.linkHovered.connect(self.link_hovered)  # 针对链接光标略过
        self.left_button_9.linkActivated.connect(self.link_clicked)  # 针对链接点击事件

        self.left_button_9.setStyleSheet('''
            QLabel{
            border-width:0;
                border-style:outset;
                font-family:"Microsoft YaHei";
                font-size:10px;
                color:white;

            }
            ''')

        # 空白
        self.left_layout.addWidget(self.left_button_1, 4, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_2, 5, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_3, 6, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_4, 7, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_5, 8, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_6, 9, 0, 1, 3)

        self.left_layout.addWidget(self.left_button_9, 10, 0, 1, 3)

        # 左侧按钮
        self.left_close.setFixedSize(16, 16)  # 设置关闭按钮的大小

        self.left_mini.setFixedSize(16, 16)  # 设置最小化按钮大小
        self.left_close.setStyleSheet(
            '''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}'''
        )

        self.left_mini.setStyleSheet(
            '''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}'''
        )

        self.left_label_1.setStyleSheet(  # left1
            '''
            QPushButton{
                font-family:"Microsoft YaHei";
                border:none;
                color:white;
                font-size:15px;
                height:50px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:LightGray;
            }
        ''')

        self.left_label_2.setStyleSheet(  # left2
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:none;
                color:white;
                font-size:15px;
                height:50px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:LightGray;
            }
        ''')

        self.left_label_3.setStyleSheet(  # left3
            '''
            QPushButton{
                font-family:"Microsoft YaHei";
                border:none;
                color:white;
                font-size:15px;
                height:50px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:LightGray;
            }
        ''')

        # 左侧菜单
        self.left_widget.setStyleSheet('''
            QPushButton{border:none;color:white;}
            QPushButton#left_label{
                border:none;
                border-bottom:1px solid white;
                font-size:18px;
                font-weight:700;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            }
            QPushButton#left_button:hover{border-left:4px solid red;font-weight:700;}
            QWidget#left_widget{
                background:gray;
                border-top:1px solid white;
                border-bottom:1px solid white;
                border-left:1px solid white;
                border-top-left-radius:10px;
                border-bottom-left-radius:10px;}
        ''')

    def link_hovered(self):

        print("光标滑过版本号")

    def link_clicked(self):

        print("点击访问查看更新")

    def init_right_ui(self):
        self.right_widget = QtWidgets.QWidget()  # 创建右侧部件
        self.right_widget.setObjectName('right_widget')
        self.right_layout = QtWidgets.QGridLayout()
        self.right_widget.setLayout(self.right_layout)  # 设置右侧部件布局为网格

        self.right_title = QCheckBox("AIforEye智能辅助诊断系统", self)
        self.right_layout.addWidget(self.right_title, 1, 0, 1, 3)

        self.right_title.setStyleSheet('''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size: 20px;
                font-weight: bold;
                border:none;
                color:black;



    } QCheckBox::indicator {
    width: 40px;
    height: 30px;
    } QCheckBox::indicator:unchecked {
    image: url(./res/3n.png);

    }
    } QCheckBox::indicator:unchecked:pressed {
    image: url(./res/3n.png);

    } 
    QCheckBox::indicator:checked{
    image: url(./res/3n.png);}
    QCheckBox::indicator:checked:pressed {
    image: url(./res/3n.png);}


            ''')

        self.main_layout.addWidget(self.right_widget, 0, 3, 10,
                                   10)  # 右侧部件在第0行第3列,占12行10列

        self.id_icon = QCheckBox('填写病人ID(选填)', self)  # 单选按钮

        self.right_layout.addWidget(self.id_icon, 2, 0, 1, 1)

        self.id_icon.setStyleSheet('''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size: 14px;
                font-weight: bold;
                border:none;
                color:black;



    } QCheckBox::indicator {
    width: 40px;
    height: 30px;
    } QCheckBox::indicator:unchecked {
    image: url(./res/input.png);

    }
    } QCheckBox::indicator:unchecked:pressed {
    image: url(./res/input.png);

    } 
    QCheckBox::indicator:checked{
    image: url(./res/input.png);}
    QCheckBox::indicator:checked:pressed {
    image: url(./res/input.png);}


            ''')

        self.right_bar_widget_id_input = QtWidgets.QLineEdit()
        self.right_bar_widget_id_input.setPlaceholderText("请在此填入病人ID")
        regExp = QRegExp('^[1-9]\d{1,30}$')

        self.right_bar_widget_id_input.setValidator(
            QRegExpValidator(regExp, self))

        # self.right_layout.addWidget(self.id_icon, 2, 0, 1, 1)  # icon

        self.right_layout.addWidget(self.right_bar_widget_id_input, 3, 0, 1,
                                    9)  # 输入栏

        self.open_icon = QCheckBox('打开文件 ', self)  # 单选按钮
        # self.open_icon = QtWidgets.QLabel(chr(0xf115) + ' ' + '打开文件  ')
        # self.open_icon.setFont(qtawesome.font('fa', 14))
        # self.open_icon.setFont(QFont("Microsoft YaHei"))

        self.right_bar_widget_open_input = QtWidgets.QLineEdit()
        self.right_bar_widget_open_input.setPlaceholderText(
            "点击按钮选择图片或文件夹生成源路径")
        self.right_bar_widget_open_input.setEnabled(False)

        self.right_layout.addWidget(self.open_icon, 4, 0, 1, 4)  # icon
        self.right_layout.addWidget(self.right_bar_widget_open_input, 5, 0, 1,
                                    9)  # 输入栏

        self.open_icon.setStyleSheet('''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size: 14px;
                font-weight: bold;
                border:none;
                color:black;



    } QCheckBox::indicator {
    width: 40px;
    height: 30px;
    } QCheckBox::indicator:unchecked {
    image: url(./res/open.png);

    }
    } QCheckBox::indicator:unchecked:pressed {
    image: url(./res/open.png);

    } 
    QCheckBox::indicator:checked{
    image: url(./res/open.png);}
    QCheckBox::indicator:checked:pressed {
    image: url(./res/open.png);}


            ''')

        # checkbox
        self.rb = QCheckBox('血管分析', self)  # 单选按钮
        self.rb.toggled.connect(self.setConnect)

        self.rb.setToolTip("可选择是否进行血管分析")
        self.right_layout.addWidget(self.rb, 7, 0, 1, 2)

        self.rb1 = QCheckBox('DR诊断(必选)', self)
        # self.rb1.setFont(qtawesome.font('fa', 14))

        self.rb1.setToolTip("默认进行DR诊断")
        self.right_layout.addWidget(self.rb1, 7, 2, 1, 2)

        self.diagnose_icon = QCheckBox('选择诊断类型:', self)  # 单选按钮

        self.right_layout.addWidget(self.diagnose_icon, 6, 0, 1, 1)

        self.diagnose_icon.setStyleSheet('''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size: 14px;
                font-weight: bold;
                border:none;
                color:black;



    } QCheckBox::indicator {
    width: 40px;
    height: 30px;
    } QCheckBox::indicator:unchecked {
    image: url(./res/diagnose1.png);

    }
    } QCheckBox::indicator:unchecked:pressed {
    image: url(./res/diagnose1.png);

    } 
    QCheckBox::indicator:checked{
    image: url(./res/diagnose1.png);}
    QCheckBox::indicator:checked:pressed {
    image: url(./res/diagnose1.png);}


            ''')

        # self.id_icon = QtWidgets.QLabel(chr(0xf11c) + ' ' + '填写ID(选填)  ')
        # self.id_icon.setFont(qtawesome.font('fa', 14))

        # self.right_layout.addWidget(self.right_bar_widget1, 1, 0, 1, 9)  # 合起来

        self.photo_icon = QCheckBox('选择图像类型:', self)  # 单选按钮

        self.right_layout.addWidget(self.photo_icon, 8, 0, 1, 1)

        self.photo_icon.setStyleSheet('''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size: 14px;
                font-weight: bold;
                border:none;
                color:black;



    } QCheckBox::indicator {
    width: 40px;
    height: 30px;
    } QCheckBox::indicator:unchecked {
    image: url(./res/photo1.png);

    }
    } QCheckBox::indicator:unchecked:pressed {
    image: url(./res/photo1.png);

    } 
    QCheckBox::indicator:checked{
    image: url(./res/photo1.png);}
    QCheckBox::indicator:checked:pressed {
    image: url(./res/photo1.png);}


            ''')

        self.photochoose = QComboBox(self)
        infomation = ["拓普康", "我要开始学习了"]
        self.photochoose.addItems(infomation)

        self.right_layout.addWidget(self.photochoose, 9, 0, 1, 2)

        self.photochoose.setStyleSheet('''
            QComboBox {

                    border:1px solid black;
                    font-family:"Microsoft YaHei";

                    font-size: 12px;


                    border-radius:8px;


                    padding:1px 18px 1px 3px;

                    min-width:100px;
                }


                QComboBox::drop-down {
                    subcontrol-origin: padding;

                    subcontrol-position: top right;


                    width: 25px;


                    border-left-width: 1px;
                    border-left-color: black;
                    border-left-style: solid;

                    border-top-right-radius: 3px;
                    border-bottom-right-radius: 3px;
                }


                QComboBox::down-arrow {
                    border-image: url(./res/drop4.png);
                }




                QComboBox QAbstractItemView {
                    border: 1px solid darkgray;
                    selection-background-color: #177CB0;
                }

                            ''')

        # 选择文件
        self.right_button_1 = QtWidgets.QPushButton(
            qtawesome.icon('fa.picture-o', color='black'), "选择图片")
        self.right_layout.addWidget(self.right_button_1, 10, 0, 1, 2)
        self.right_button_1.clicked.connect(self.gitfilename)
        # 选择文件夹
        self.right_button_2 = QtWidgets.QPushButton(
            qtawesome.icon('fa.folder', color='black'), "选择文件夹")
        self.right_layout.addWidget(self.right_button_2, 11, 0, 1, 2)
        self.right_button_2.clicked.connect(self.getdirectory)

        self.start = QtWidgets.QPushButton(
            qtawesome.icon('fa.play', color='black'), "选择保存路径并开始")
        self.right_layout.addWidget(self.start, 12, 0, 1, 2)
        self.start.clicked.connect(self.main)

        # 进度条文字
        txt = ""
        # self.proc = QtWidgets.QLabel(chr(0xf110) + ' ' + '任务进度:' + '' + txt)
        self.proc = QCheckBox('任务进度:' + '' + txt, self)  # 单选按钮
        # self.proc.setFont(qtawesome.font('fa', 12))
        self.right_layout.addWidget(self.proc, 13, 0, 1, 9)

        self.proc.setStyleSheet('''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size: 14px;
                font-weight: bold;
                border:none;
                color:black;



    } QCheckBox::indicator {
    width: 40px;
    height: 30px;
    } QCheckBox::indicator:unchecked {
    image: url(./res/loading.png);

    }
    } QCheckBox::indicator:unchecked:pressed {
    image: url(./res/loading.png);

    } 
    QCheckBox::indicator:checked{
    image: url(./res/loading.png);}
    QCheckBox::indicator:checked:pressed {
    image: url(./res/loading.png);}


            ''')

        # 进度条
        self.pbar = QProgressBar(self)

        self.pbar.setToolTip("任务处理进度条")
        self.right_layout.addWidget(self.pbar, 14, 0, 1, 9)

        self.right_message2 = QLabel(self)
        pixmap = QPixmap('./res/4.jpg')
        self.right_message2.setScaledContents(True)
        self.right_message2.setPixmap(pixmap)
        self.right_layout.addWidget(self.right_message2, 1, 0, 1, 9)

        self.right_message1 = QLabel(
            "邮箱: [email protected]\n"
            "地址: 广东省深圳市南山区南方科技大学\n"
            "合作单位: 中山大学中山眼科中心\n", self)

        self.right_message1.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.right_layout.addWidget(self.right_message1, 1, 0, 1, 3)  # 输入栏

        self.right_message1.setStyleSheet('''
                QLabel{

                border-width:0;
                border-style:outset;
                font-family:"Microsoft YaHei";
                font-size:20px;
                height:50px;
                padding-left:0px;
                padding-right:10px;
                text-align:left;

                }

            ''')

        # self.right_message2 = QtWidgets.QTextBrowser()
        # self.right_message2.setText("概况")  # 概况
        # self.right_layout.addWidget(self.right_message2, 0, 0, 1, 9)

        self.right_bar_widget_id_input.setStyleSheet(  # 输入id栏
            '''QLineEdit{
                    font-family:"Microsoft YaHei";
                    border:1px solid gray;
                    width:300px;
                    border-radius:10px;
                    padding:2px 4px;
            }''')

        self.right_bar_widget_open_input.setStyleSheet(  # 选择文件栏
            '''QLineEdit{
            font-family:"Microsoft YaHei";
                    border:1px solid gray;
                    width:300px;
                    border-radius:10px;
                    padding:2px 4px;
            }


            ''')

        self.pbar.setStyleSheet(  # 进度条
            '''QProgressBar{ 
            font-family:"Microsoft YaHei";
               border:1px solid gray;

               border-radius:10px;
               padding:2px 4px;
               text-align: center; 
            }
               QProgressBar::chunk {


               border-radius:10px;
               background:#696969



    }
            ''')

        # background:qlineargradient(spread:pad,x1:0,y1:0,x2:1,y2:0,stop:0 red,stop:1 blue)

        self.rb.setStyleSheet('''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size:14px;

                border:none;
                color:black;



} QCheckBox::indicator {
    width: 40px;
    height: 20px;
} QCheckBox::indicator:unchecked {
    image: url(./res/off1.png);}

QCheckBox::indicator:unchecked:hover {
image: url(./res/off1-hover.png);
}


} QCheckBox::indicator:unchecked:pressed {
    image: url(./res/off1.png);

} 
QCheckBox::indicator:checked{
    image: url(./res/on1.png);}
QCheckBox::indicator:checked:hover {
image: url(./res/on1-hover.png);
}
QCheckBox::indicator:checked:pressed {
    image: url(./res/on1.png);}


            ''')

        self.rb1.setStyleSheet(  # DR
            '''
            QCheckBox{
                font-family:"Microsoft YaHei";
                spacing: 2px;
                color: white;
                font-size: 14px;

                border:none;
                color:black;



    } QCheckBox::indicator {
    width: 40px;
    height: 20px;
    } QCheckBox::indicator:unchecked {
    image: url(./res/on1);

    }
    } QCheckBox::indicator:unchecked:pressed {
    image: url(./res/on1);

    } 
    QCheckBox::indicator:checked{
    image: url(./res/on1);}
    QCheckBox::indicator:checked:pressed {
    image: url(./res/on1);}


            ''')

        self.right_button_1.setStyleSheet(  # 选择图片
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:1px solid #F3F3F5;
                border-radius:10px;
                border:none;
                color:black;
                background:lavender;

                font-size:14px;
                height:40px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:gainsboro ;
            }
        ''')
        self.right_button_2.setStyleSheet(  # 选择文件夹
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:1px solid #F3F3F5;
                border-radius:10px;
                border:none;
                color:black;
                background:lavender;

                font-size:14px;
                height:40px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:gainsboro ;
            }
        ''')

        self.right_widget.setStyleSheet(  # 右边大框
            '''
            QWidget#right_widget{
            font-family:"Microsoft YaHei";
                color:#232C51;
                background:white;
                border-top:1px solid darkGray;
                border-bottom:1px solid darkGray;
                border-right:1px solid darkGray;
                border-top-right-radius:10px;
                border-bottom-right-radius:10px;
            }
            QLabel#right_lable{
                border:none;
                font-size:16px;
                font-weight:700;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            }
        ''')
        self.start.setStyleSheet(  # 开始任务
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:1px solid #F3F3F5;
                border-radius:10px;
                border:none;
                color:black;
                background:lavender;

                font-size:14px;
                height:40px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:gainsboro ;
            }
        ''')
        self.right_message1.hide()
        self.right_message2.hide()

    def showmessage1(self):
        self.start.hide()
        self.right_message1.show()
        self.right_message2.hide()
        self.open_icon.hide()
        self.rb1.hide()
        self.rb.hide()
        self.pbar.hide()
        self.id_icon.hide()
        self.right_bar_widget_id_input.hide()
        self.right_bar_widget_open_input.hide()
        self.right_button_1.hide()
        self.right_button_2.hide()
        self.proc.hide()
        self.right_title.hide()
        self.diagnose_icon.hide()
        self.photochoose.hide()
        self.photo_icon.hide()

    def showmessage2(self):
        self.start.hide()
        self.right_message2.show()
        self.right_message1.hide()
        self.open_icon.hide()
        self.rb1.hide()
        self.rb.hide()
        self.pbar.hide()
        self.id_icon.hide()
        self.right_bar_widget_id_input.hide()
        self.right_bar_widget_open_input.hide()
        self.right_button_1.hide()
        self.right_button_2.hide()
        self.proc.hide()
        self.right_title.hide()
        self.diagnose_icon.hide()
        self.photochoose.hide()
        self.photo_icon.hide()

    def showright(self):
        self.right_message2.hide()
        self.right_message1.hide()
        self.open_icon.show()
        self.rb1.show()
        self.rb.show()
        self.pbar.show()
        self.id_icon.show()
        self.right_bar_widget_id_input.show()
        self.right_bar_widget_open_input.show()
        self.right_button_1.show()
        self.right_button_2.show()
        self.proc.show()
        self.start.show()
        self.right_title.show()
        self.diagnose_icon.show()
        self.photochoose.show()
        self.photo_icon.show()

    def setConnect(self):
        global ifConnect
        if (ifConnect):
            ifConnect = False
        else:
            ifConnect = True
        print(ifConnect)

    def printl(self):
        self.pbar.setValue(0)
        global image1

        self.right_bar_widget_open_input.setEnabled(False)

        if image1[0] == "dir":
            f = open("./res/path/start1.txt")
            lastpath13 = str(f.read())
            print(f.read())
            f.close()
            filename = QFileDialog.getSaveFileName(self, 'save file',
                                                   lastpath13)
            print(filename)
            f = open('./res/path/start1.txt', 'wb+')
            f.truncate()
            f.close()

            f = open('./res/path/start1.txt', 'a')
            f.write(filename[0])
            f.close()
            if filename[0] != "":
                self.dirPDF(image1[1], filename[0])
        elif image1[0] == "f":
            f = open("./res/path/start2.txt")
            lastpath23 = str(f.read())
            print(f.read())
            f.close()
            filename = QFileDialog.getSaveFileName(self, 'save file',
                                                   lastpath23, '(*.pdf)')
            print(filename)
            f = open('./res/path/start2.txt', 'wb+')
            f.truncate()
            f.close()

            f = open('./res/path/start2.txt', 'a')
            f.write(filename[0])
            f.close()
            if filename[0] != "":
                self.pbar.setValue(100)
                self.pic2pdf(image1[1], filename[0])
        else:
            print("null")

        self.right_bar_widget_id_input.clear()

    def dirPDF(self, input_path, output_path):  # 转文件夹
        self.pbar.setValue(0)
        print("start")
        print(input_path)
        print(output_path)
        # 获取输入文件夹中的所有文件/夹,并改变工作空间
        files = os.listdir(input_path)
        os.chdir(input_path)
        # 判断输出文件夹是否存在,不存在则创建
        if (not os.path.exists(output_path)):
            os.makedirs(output_path)
        count = 0
        for file in files:
            if (os.path.isfile(file)):
                count += 1
        now = 0
        for file in files:
            # 判断是否为文件,文件夹不操作
            if (os.path.isfile(file)):
                now += 1
                self.pbar.setValue(now / count * 100)
                # 用.隔开文件名获取图片处理
                point = file.rfind('.')
                rightpart = file[point:]
                leftpart = file[:point]
                print(rightpart)
                if (rightpart == '.jpg' or rightpart == '.png'):
                    #     img = Image.open(file)
                    #     width = int(img.size[0] * 2)
                    #     height = int(img.size[1] * 2)
                    #     img = img.resize((width, height), Image.ANTIALIAS)
                    print(os.path.join(output_path, "New_" + file))
                    #     img.save(os.path.join(output_path, "New_" + file))
                    self.pic2pdf(
                        file,
                        os.path.join(output_path, "New_" + leftpart + ".pdf"))
        self.pbar.setValue(100)

    def pic2pdf(self, img, filePdf):  # 将一张图片转为pdf
        print(1)
        # 读取图片,确保按文件名排序
        print(img)
        imgdoc = Image.open(img)  # 打开图片
        x = imgdoc.size[0]
        y = imgdoc.size[1]
        c = canvas.Canvas(filePdf, [x + 100, y + 100])  # 使用图片创建单页的 PDF
        print(imgdoc.size)
        c.drawImage(img, 50, 0, x, y)
        c.drawString(20, y + 5, filePdf)
        c.showPage()
        c.save()

    def gitfilename(self):
        f = open('./res/path/origin1.txt')
        lastpath = str(f.read())
        print(f.read())
        f.close()

        filename = QFileDialog.getOpenFileName(
            self, "选择文件", lastpath, "Image (*.jpg);;Image(*.png)")  # 这个地方弹出窗口

        if (filename != ""):
            self.right_bar_widget_open_input.setText(filename[0])
            f = open('./res/path/origin1.txt', 'wb+')
            f.truncate()
            f.close()

            f = open('./res/path/origin1.txt', 'a')
            f.write(filename[0])
            f.close()

            global image1
            #  file1+=['ID: '+self.IDmessage.text()]
            image1[0] = "f"
            image1[1] = filename[0]
            print(filename[0])

    def getdirectory(self):
        directory1 = ""
        f = open('./res/path/origin2.txt')
        lastpath = str(f.read())
        print(f.read())
        f.close()

        directory1 = QFileDialog.getExistingDirectory(self, "选取文件夹",
                                                      lastpath)  # 起始路径
        if (directory1 != ""):
            # print(directory1)
            self.right_bar_widget_open_input.setText(directory1)

            f = open('./res/path/origin2.txt', 'wb+')
            f.truncate()
            f.close()

            f = open('./res/path/origin2.txt', 'a')
            f.write(directory1)
            f.close()
            global image1
            image1[0] = 'dir'
            image1[1] = directory1
            print(image1)

    def mousePressEvent(self, event):
        self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
        self.m_flag = False
        if event.button(
        ) == Qt.LeftButton and self.m_Position in self._bottom_rect:
            self.m_flag = True
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):

        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置

            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):

        self.m_flag = False

        self.setCursor(QCursor(Qt.ArrowCursor))

    def main(self):
        self.right_bar_widget_id_input.setEnabled(False)
        self.pbar.setValue(0)

        global image1
        if (not (image1[0] and image1[1])):
            print("null")
            QMessageBox.warning(self, '警告', "请选择需要诊断的图片或者文件夹", QMessageBox.Ok,
                                QMessageBox.Ok)
            return
        else:
            if (image1[0] == "dir"):
                with open("./res/path/start1.txt") as f:
                    lastpath13 = str(f.read())
                    save_directory = QFileDialog.getExistingDirectory(
                        self, "诊断报告保存路径", lastpath13)

                if save_directory:
                    with open('./res/path/start1.txt', 'wb+') as f:
                        f.truncate()

                    with open('./res/path/start1.txt', 'a') as f:
                        f.write(save_directory)

                if not save_directory:
                    return
                images = []
                for dirpath, dirnames, files in os.walk(image1[1]):
                    for file in files:
                        if os.path.splitext(file)[1] in exts:
                            images.append(os.path.join(dirpath, file))
                # images = [
                #     os.path.join(image1[1], image) for image in images
                #     if os.path.splitext(image)[1] in exts
                # ]
                ids = [
                    os.path.splitext(os.path.split(image)[1])[0]
                    for image in images
                ]
                save_paths = [
                    os.path.splitext(image.replace(image1[1],
                                                   save_directory))[0] + '.pdf'
                    for image in images
                ]
                print(save_paths)
                self.thread = AnalysisThread(self.fundusAnalysis, images,
                                             save_paths, ifConnect, ids,
                                             self.start)
                self.thread.signal_bar.connect(self.callback_pbar)
                self.thread.signal_txt.connect(self.callback_proc)
                self.thread.finished.connect(self.thread.quit)
                self.thread.finished.connect(self.thread.deleteLater)
                self.thread.start()

            if (image1[0] == "f"):
                with open("./res/path/start2.txt") as f:
                    lastpath23 = str(f.read())
                    filename, _ = QFileDialog.getSaveFileName(
                        self, '诊断报告保存路径', lastpath23, '(*.pdf)')

                if filename:
                    with open('./res/path/start2.txt', 'wb+') as f:
                        f.truncate()

                    with open('./res/path/start2.txt', 'a') as f:
                        f.write(filename)

                if not filename:
                    return
                # (self, 'save file', '/','(*.png);;(*.jpg);;(*.pdf)')
                #  img = Image.open(image1[1])
                #  width = int(img.size[0] * 2)
                #  height = int(img.size[1] * 2)
                #  img = img.resize((width, height), Image.ANTIALIAS)
                #  print(filename)
                #  dir=os.path.join(os.path.dirname(filename[0]),  os.path.basename(filename[0]))
                #  print(dir)
                #  print(filename[0])
                # img.save(filename[0])
                id_ = self.right_bar_widget_id_input.text()
                if not id_:
                    name = os.path.split(image1[1])[1]
                    id_ = os.path.splitext(name)[0]
                self.thread = AnalysisThread(self.fundusAnalysis, [image1[1]],
                                             [filename], ifConnect, [id_],
                                             self.start)
                self.thread.signal_bar.connect(self.callback_pbar)
                self.thread.signal_txt.connect(self.callback_proc)
                self.thread.finished.connect(self.thread.quit)
                self.thread.finished.connect(self.thread.deleteLater)
                self.thread.start()

        self.right_bar_widget_id_input.clear()
        self.right_bar_widget_id_input.setEnabled(True)

    def callback_pbar(self, value):
        self.pbar.setValue(value)

    def callback_proc(self, txt):
        self.proc.setText(txt)
Exemplo n.º 26
0
class LootWizard(QMainWindow):

	def __init__(self):
		super (LootWizard, self).__init__()
		self.hide()
		self._upToDateMessage = 'is up-to-date'
		self.initUI()

	def kill_on_init(self):
		QTimer.singleShot(0, app.quit)

	def initUI(self):
		data_found = False
		try:
			self.__getFileinfo(sys.argv[1])
		except (IndexError, FileNotFoundError):
			directory = QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation)[0]
			directory += "/My Games/Path of Exile"
			fname = QFileDialog.getOpenFileName(None, 'Open file', directory)
			if fname[0]:
				try:
					self.__getFileinfo(fname[0])
				except FileNotFoundError:
					pass
				else:
					data_found = True
		else:
			data_found = True
		if not data_found:
			self.kill_on_init()
		else:
			self.initWindowUI()

	def initWindowUI(self):
		self.resetButton = QPushButton("Reset")
		self.resetButton.setEnabled(False)
		self.resetButton.clicked.connect(self.reset)
		self.orphanButton = SquareButton("+")
		self.orphanButton.hide()
		self.overwriteButton = QPushButton("Overwrite")
		self.overwriteButton.setStyleSheet("background-color: #EFC795")
		self.overwriteButton.setEnabled(False)
		self.overwriteButton.clicked.connect(self.overwrite)
		self.forceCheckBox = QCheckBox("&Always inherit")
		self.forceCheckBox.setToolTip('Smartblocks inherit from virtual blockgroups.<br/>Check me to change from a <b>smartblock</b> parent.')
		self.forceCheckBox.hide()
		hbox = QHBoxLayout()
		hbox2 = QHBoxLayout()
		hbox2.addWidget(self.forceCheckBox)
		hbox.addLayout(hbox2)
		hbox.addWidget(self.orphanButton)
		hbox.addStretch(1)
		hbox.addWidget(self.overwriteButton)
		hbox.addWidget(self.resetButton)
		vbox = QVBoxLayout()
		self.setWindowTitle('Loot Wizard')
		self.view = QTreeView()
		self.setCentralWidget(QWidget())
		self.scrollLayout = QFormLayout()
		self.scrollWidget = QWidget()
		self.scrollWidget.setLayout(self.scrollLayout)
		self.orphanDialog = OrphanDialog(self)
		self.orphanButton.clicked.connect(self.openOrphans)
		vbox.addWidget(self.view)
		vbox.addLayout(hbox)
		self.scrollLayout.addRow(self.view)
		self.centralWidget().setLayout(vbox)
		self.model = SmartblockModel(self.file_content, self)
		self.statusBar().showMessage(self.file_info.fileName() + ' ' + self._upToDateMessage)
		self.forceCheckBox.stateChanged.connect(self.switchforce)
		self.view.setModel(self.model)
		self.view.expandAll()
		self.view.setAlternatingRowColors(True)
		self.resize(300, 600)
		self.show()

	def inform(self, flag, external_call = False, end_process = False):
		reset_flag = False # hidden first
		if flag:
			if external_call:
				message = 'has non-updated changes'
			else:
				message = 'has changed'
				reset_flag = True
		else:
			if end_process:
				message = 'is saved'
			else:
				message = self._upToDateMessage
		self.statusBar().showMessage(self.file_info.fileName() + ' ' + message)
		self.resetButton.setEnabled(reset_flag)
		self.overwriteButton.setEnabled(flag)

	def displayOrphan(self, display = True):
		# self.displayButton(self.orphanButton, display)
		pass

	def displayInheritance(self, display = True):
		self.displayButton(self.forceCheckBox, display)

	def displayButton(self, btn, display = True):
		if display:
			btn.show()
		else:
			btn.hide()

	def switchforce(self, state):
		self.model.forceInheritance = state == Qt.Checked

	def overwrite(self):
		self.overwriteButton.setEnabled(False)
		self.resetButton.setEnabled(False) # TODO: disable from elsewhere ?!
		if self.model.save(self.file_info.absoluteFilePath()):
			self.inform(False, False, True)

	def reset(self):
		self.model.resetStatus()

	def __getFileinfo(self, filename):
		self.file_content = ''.join(fileinput.input(filename))
		self.file_info = QFileInfo(filename)

	def openOrphans(self):
		self.orphanDialog.show()
Exemplo n.º 27
0
class NTFSLogFileDialog(QDialog, QObject):
    complete = pyqtSignal()

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        QObject.__init__(self)
        self.selected_partition = -1
        self.ui()

    def ui(self):
        self.setWindowTitle("Import File System Log File")
        self.setFixedSize(self.sizeHint())
        self.layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        spacer_item1 = QSpacerItem(10, 5)
        self.layout.addItem(spacer_item1)
        self.setLayout(self.layout)

        # First Group
        self.disk_raw_chk_box = QCheckBox(
            "In this case, it's possible to carve some files.", self)
        self.disk_raw_chk_box.stateChanged.connect(
            lambda: self.select_type(self.disk_raw_chk_box))
        self.disk_raw_group_box = QGroupBox(self)
        self.disk_raw_group_box.setStyleSheet("margin-top: 0;")
        self.disk_raw_group_box.setDisabled(True)
        disk_raw_group_box_layout = QHBoxLayout(self.disk_raw_group_box)
        self.disk_raw_group_box.setLayout(disk_raw_group_box_layout)

        self.disk_raw_label = QLabel("Disk Raw: ", self)
        self.disk_raw_text_box = QLineEdit()
        self.disk_raw_text_box.setReadOnly(True)
        self.disk_raw_text_box.setFixedWidth(400)

        self.browse_disk_raw_btn = QPushButton("...", self)
        self.browse_disk_raw_btn.setFixedWidth(50)
        self.browse_disk_raw_btn.clicked.connect(self.btn_clicekd)
        self.browse_disk_raw_btn.setCursor(QCursor(Qt.PointingHandCursor))

        disk_raw_group_box_layout.addWidget(self.disk_raw_label)
        disk_raw_group_box_layout.addWidget(self.disk_raw_text_box)
        disk_raw_group_box_layout.addWidget(self.browse_disk_raw_btn)

        self.layout.addWidget(self.disk_raw_chk_box)
        self.layout.addWidget(self.disk_raw_group_box)

        # Second Group
        self.ntfs_log_file_chk_box = QCheckBox(
            "In this case, NTFS Log analysis only supported.", self)
        self.ntfs_log_file_chk_box.stateChanged.connect(
            lambda: self.select_type(self.ntfs_log_file_chk_box))

        self.ntfs_log_group_box = QGroupBox(self)
        self.ntfs_log_group_box.setStyleSheet("margin-top: 0;")
        self.ntfs_log_group_box.setDisabled(True)
        ntfs_log_group_box_layout = QGridLayout(self)
        self.ntfs_log_group_box.setLayout(ntfs_log_group_box_layout)

        self.mft_label = QLabel("$MFT: ", self)
        self.mft_path_text_box = QLineEdit(self)
        self.mft_path_text_box.setReadOnly(True)
        self.mft_path_text_box.setFixedWidth(400)
        self.browse_mft_btn = QPushButton("...", self)
        self.browse_mft_btn.setFixedWidth(50)
        self.browse_mft_btn.clicked.connect(self.btn_clicekd)
        self.browse_mft_btn.setCursor(QCursor(Qt.PointingHandCursor))

        self.usnjrnl_label = QLabel("$UsnJrnl: ", self)
        self.usnjrnl_path_text_box = QLineEdit(self)
        self.usnjrnl_path_text_box.setReadOnly(True)
        self.usnjrnl_path_text_box.setFixedWidth(400)
        self.browse_usnjrnl_btn = QPushButton("...", self)
        self.browse_usnjrnl_btn.setFixedWidth(50)
        self.browse_usnjrnl_btn.clicked.connect(self.btn_clicekd)
        self.browse_usnjrnl_btn.setCursor(QCursor(Qt.PointingHandCursor))

        self.logfile_label = QLabel("$LogFile: ", self)
        self.logfile_path_text_box = QLineEdit(self)
        self.logfile_path_text_box.setReadOnly(True)
        self.logfile_path_text_box.setFixedWidth(400)
        self.browse_logfile_btn = QPushButton("...", self)
        self.browse_logfile_btn.setFixedWidth(50)
        self.browse_logfile_btn.clicked.connect(self.btn_clicekd)
        self.browse_logfile_btn.setCursor(QCursor(Qt.PointingHandCursor))

        ntfs_log_group_box_layout.addWidget(self.mft_label, 0, 0)
        ntfs_log_group_box_layout.addWidget(self.mft_path_text_box, 0, 1)
        ntfs_log_group_box_layout.addWidget(self.browse_mft_btn, 0, 2)
        ntfs_log_group_box_layout.addWidget(self.usnjrnl_label, 1, 0)
        ntfs_log_group_box_layout.addWidget(self.usnjrnl_path_text_box, 1, 1)
        ntfs_log_group_box_layout.addWidget(self.browse_usnjrnl_btn, 1, 2)
        ntfs_log_group_box_layout.addWidget(self.logfile_label, 2, 0)
        ntfs_log_group_box_layout.addWidget(self.logfile_path_text_box, 2, 1)
        ntfs_log_group_box_layout.addWidget(self.browse_logfile_btn, 2, 2)

        self.submit_btn = QPushButton("Submit", self)
        self.submit_btn.setFixedSize(100, 40)
        self.submit_btn.setCursor(QCursor(Qt.PointingHandCursor))

        self.logging_label = QLabel("Loading...", self)
        self.logging_label.setFixedHeight(20)
        self.logging_label.setAlignment(Qt.AlignCenter)
        self.logging_label.hide()

        self.loading_bar = QProgressBar(self)
        self.loading_bar.setFixedHeight(10)
        self.loading_bar.setTextVisible(False)
        self.loading_bar.hide()

        self.bar_thread = LoadingBarThread(self)
        self.bar_thread.change_value.connect(self.loading_bar.setValue)

        self.spacer_item2 = QSpacerItem(10, 15)
        self.spacer_item3 = QSpacerItem(10, 20)
        self.layout.addItem(self.spacer_item2)
        self.layout.addWidget(self.ntfs_log_file_chk_box)
        self.layout.addWidget(self.ntfs_log_group_box)
        self.layout.addItem(self.spacer_item3)
        self.layout.addWidget(self.submit_btn, alignment=Qt.AlignHCenter)

        # self.setWindowModality(Qt.WindowModal)
        self.setWindowFlag(Qt.WindowCloseButtonHint | Qt.WindowModal)
        self.show()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.close()

    def select_type(self, b):
        if b is self.disk_raw_chk_box:
            if b.isChecked():
                self.ntfs_log_file_chk_box.setChecked(False)
                self.ntfs_log_group_box.setDisabled(True)
                self.disk_raw_group_box.setDisabled(False)
            else:
                self.disk_raw_group_box.setDisabled(True)
        else:
            if b.isChecked():
                self.disk_raw_chk_box.setChecked(False)
                self.disk_raw_group_box.setDisabled(True)
                self.ntfs_log_group_box.setDisabled(False)
            else:
                self.ntfs_log_group_box.setDisabled(True)

    def btn_clicekd(self):
        sender = self.sender()
        fileName = QFileDialog.getOpenFileName(self)
        if sender is self.browse_disk_raw_btn:
            self.disk_raw_text_box.setText(fileName[0])
        elif sender is self.browse_mft_btn:
            self.mft_path_text_box.setText(fileName[0])
        elif sender is self.browse_usnjrnl_btn:
            self.usnjrnl_path_text_box.setText(fileName[0])
        elif sender is self.browse_logfile_btn:
            self.logfile_path_text_box.setText(fileName[0])

    def ready(self):
        self.submit_btn.hide()
        self.layout.removeWidget(self.submit_btn)
        self.layout.addWidget(self.logging_label,
                              alignment=Qt.AlignBottom | Qt.AlignHCenter)
        self.layout.addWidget(self.loading_bar)
        self.logging_label.show()
        self.loading_bar.show()
        self.bar_thread.start()

    def resume(self):
        if self.bar_thread.cnt < 50:
            self.bar_thread.cnt = 100
            return
        self.bar_thread.toggle_status()

    def change_interface(self, contents):
        from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem
        self.layout.removeWidget(self.disk_raw_chk_box)
        self.disk_raw_chk_box.hide()
        self.layout.removeWidget(self.disk_raw_group_box)
        self.disk_raw_group_box.hide()
        self.layout.removeItem(self.spacer_item2)
        self.layout.removeWidget(self.ntfs_log_file_chk_box)
        self.ntfs_log_file_chk_box.hide()
        self.layout.removeWidget(self.ntfs_log_group_box)
        self.ntfs_log_group_box.hide()
        self.layout.removeItem(self.spacer_item3)
        self.layout.removeWidget(self.submit_btn)

        self.disk_name_label = QLabel("Image Name:\t" + contents[0][0], self)
        self.disk_size_label = QLabel(
            "Image Size:\t{} Bytes".format(contents[0][1]), self)
        self.disk_size_label.setFixedHeight(20)
        self.disk_size_label.setAlignment(Qt.AlignVCenter)
        self.disk_part_label = QLabel("Partition:", self)
        self.disk_part_label.setFixedHeight(20)
        self.disk_part_label.setAlignment(Qt.AlignBottom)

        self.partition_tree = QTreeWidget(self)
        self.partition_tree.setHeaderLabels([
            "Order", "File System", "Active", "Starting Offset",
            "Total Sector", "Size"
        ])
        self.partition_tree.item_changed.connect(self.item_changed)
        self.partition_tree.resizeColumnToContents(2)
        self.partition_tree.resizeColumnToContents(3)
        self.partition_tree.resizeColumnToContents(4)
        self.partition_tree.headerItem().setTextAlignment(0, Qt.AlignCenter)
        self.partition_tree.headerItem().setTextAlignment(1, Qt.AlignCenter)

        self.partition_items = []
        for row in range(1, 5):
            self.partition_tree.headerItem().setTextAlignment(
                row + 1, Qt.AlignCenter)
            item = QTreeWidgetItem(self.partition_tree)
            item.setText(0, str(row))
            item.setTextAlignment(0, Qt.AlignLeft)
            if not contents[row]:
                item.setText(1, "None")
                item.setCheckState(0, Qt.Unchecked)
                item.setDisabled(True)
                continue
            for col in range(5):
                item.setText(col + 1, contents[row][col])
                item.setTextAlignment(col + 1, Qt.AlignCenter)
            item.setTextAlignment(1, Qt.AlignLeft)
            item.setCheckState(0, Qt.Unchecked)
            self.partition_items.append(item)

        self.layout.addWidget(self.disk_name_label)
        self.layout.addWidget(self.disk_size_label)
        self.layout.addWidget(self.disk_part_label)
        self.layout.addWidget(self.partition_tree)
        self.layout.addItem(QSpacerItem(10, 10))
        self.layout.addWidget(self.submit_btn, alignment=Qt.AlignCenter)

    def item_changed(self, changed_item, p_int):
        if changed_item.checkState(0) == Qt.Checked:
            self.selected_partition = int(changed_item.text(0))
            for item in self.partition_items:
                if item is not changed_item:
                    item.setCheckState(0, Qt.Unchecked)
Exemplo n.º 28
0
class RunICADialog(QDialog):
    def __init__(self, parent, nchan, have_picard=True, have_sklearn=True):
        super().__init__(parent)
        self.setWindowTitle("Run ICA")
        vbox = QVBoxLayout(self)
        grid = QGridLayout()
        grid.addWidget(QLabel("Method:"), 0, 0)
        self.method = QComboBox()
        self.methods = {"Infomax": "infomax"}
        if have_sklearn:
            self.methods["FastICA"] = "fastica"
        if have_picard:
            self.methods["Picard"] = "picard"
        self.method.addItems(self.methods.keys())
        if have_picard:
            self.method.setCurrentText("Picard")
        else:
            self.method.setCurrentText("Infomax")
        min_len = max(len(key) for key in self.methods.keys())
        self.method.setMinimumContentsLength(min_len)
        grid.addWidget(self.method, 0, 1)

        self.extended_label = QLabel("Extended:")
        grid.addWidget(self.extended_label, 1, 0)
        self.extended = QCheckBox()
        self.extended.setChecked(True)
        grid.addWidget(self.extended, 1, 1)

        self.ortho_label = QLabel("Orthogonal:")
        grid.addWidget(self.ortho_label, 2, 0)
        self.ortho = QCheckBox()
        self.ortho.setChecked(False)
        grid.addWidget(self.ortho, 2, 1)

        self.toggle_options()
        self.method.currentIndexChanged.connect(self.toggle_options)

        grid.addWidget(QLabel("Number of components:"), 3, 0)
        self.n_components = QSpinBox()
        self.n_components.setMinimum(0)
        self.n_components.setMaximum(nchan)
        self.n_components.setValue(nchan)
        self.n_components.setAlignment(Qt.AlignRight)
        grid.addWidget(self.n_components, 3, 1)
        grid.addWidget(QLabel("Exclude bad segments:"), 4, 0)
        self.exclude_bad_segments = QCheckBox()
        self.exclude_bad_segments.setChecked(True)
        grid.addWidget(self.exclude_bad_segments)
        vbox.addLayout(grid)
        buttonbox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        vbox.addWidget(buttonbox)
        buttonbox.accepted.connect(self.accept)
        buttonbox.rejected.connect(self.reject)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)

    @pyqtSlot()
    def toggle_options(self):
        """Toggle extended options.
        """
        if self.method.currentText() == "Picard":
            self.extended_label.show()
            self.extended.show()
            self.ortho_label.show()
            self.ortho.show()
        elif self.method.currentText() == "Infomax":
            self.extended_label.show()
            self.extended.show()
            self.ortho_label.hide()
            self.ortho.hide()
        else:
            self.extended_label.hide()
            self.extended.hide()
            self.ortho_label.hide()
            self.ortho.hide()
Exemplo n.º 29
0
class Dialog(QDialog):
    MESSAGE = (
        "<p>Message boxes have a caption, a text, and up to three "
        "buttons, each with standard or custom texts.</p>"
        "<p>Click a button to close the message box. Pressing the Esc "
        "button will activate the detected escape button (if any).</p>"
    )

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.openFilesPath = ""

        self.errorMessageDialog = QErrorMessage(self)

        frameStyle = QFrame.Sunken | QFrame.Panel

        self.integerLabel = QLabel()
        self.integerLabel.setFrameStyle(frameStyle)
        self.integerButton = QPushButton("QInputDialog.get&Int()")

        self.doubleLabel = QLabel()
        self.doubleLabel.setFrameStyle(frameStyle)
        self.doubleButton = QPushButton("QInputDialog.get&Double()")

        self.itemLabel = QLabel()
        self.itemLabel.setFrameStyle(frameStyle)
        self.itemButton = QPushButton("QInputDialog.getIte&m()")

        self.textLabel = QLabel()
        self.textLabel.setFrameStyle(frameStyle)
        self.textButton = QPushButton("QInputDialog.get&Text()")

        self.colorLabel = QLabel()
        self.colorLabel.setFrameStyle(frameStyle)
        self.colorButton = QPushButton("QColorDialog.get&Color()")

        self.fontLabel = QLabel()
        self.fontLabel.setFrameStyle(frameStyle)
        self.fontButton = QPushButton("QFontDialog.get&Font()")

        self.directoryLabel = QLabel()
        self.directoryLabel.setFrameStyle(frameStyle)
        self.directoryButton = QPushButton("QFileDialog.getE&xistingDirectory()")

        self.openFileNameLabel = QLabel()
        self.openFileNameLabel.setFrameStyle(frameStyle)
        self.openFileNameButton = QPushButton("QFileDialog.get&OpenFileName()")

        self.openFileNamesLabel = QLabel()
        self.openFileNamesLabel.setFrameStyle(frameStyle)
        self.openFileNamesButton = QPushButton("QFileDialog.&getOpenFileNames()")

        self.saveFileNameLabel = QLabel()
        self.saveFileNameLabel.setFrameStyle(frameStyle)
        self.saveFileNameButton = QPushButton("QFileDialog.get&SaveFileName()")

        self.criticalLabel = QLabel()
        self.criticalLabel.setFrameStyle(frameStyle)
        self.criticalButton = QPushButton("QMessageBox.critica&l()")

        self.informationLabel = QLabel()
        self.informationLabel.setFrameStyle(frameStyle)
        self.informationButton = QPushButton("QMessageBox.i&nformation()")

        self.questionLabel = QLabel()
        self.questionLabel.setFrameStyle(frameStyle)
        self.questionButton = QPushButton("QMessageBox.&question()")

        self.warningLabel = QLabel()
        self.warningLabel.setFrameStyle(frameStyle)
        self.warningButton = QPushButton("QMessageBox.&warning()")

        self.errorLabel = QLabel()
        self.errorLabel.setFrameStyle(frameStyle)
        self.errorButton = QPushButton("QErrorMessage.show&M&essage()")

        self.integerButton.clicked.connect(self.setInteger)
        self.doubleButton.clicked.connect(self.setDouble)
        self.itemButton.clicked.connect(self.setItem)
        self.textButton.clicked.connect(self.setText)
        self.colorButton.clicked.connect(self.setColor)
        self.fontButton.clicked.connect(self.setFont)
        self.directoryButton.clicked.connect(self.setExistingDirectory)
        self.openFileNameButton.clicked.connect(self.setOpenFileName)
        self.openFileNamesButton.clicked.connect(self.setOpenFileNames)
        self.saveFileNameButton.clicked.connect(self.setSaveFileName)
        self.criticalButton.clicked.connect(self.criticalMessage)
        self.informationButton.clicked.connect(self.informationMessage)
        self.questionButton.clicked.connect(self.questionMessage)
        self.warningButton.clicked.connect(self.warningMessage)
        self.errorButton.clicked.connect(self.errorMessage)

        self.native = QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)
        layout.addWidget(self.integerButton, 0, 0)
        layout.addWidget(self.integerLabel, 0, 1)
        layout.addWidget(self.doubleButton, 1, 0)
        layout.addWidget(self.doubleLabel, 1, 1)
        layout.addWidget(self.itemButton, 2, 0)
        layout.addWidget(self.itemLabel, 2, 1)
        layout.addWidget(self.textButton, 3, 0)
        layout.addWidget(self.textLabel, 3, 1)
        layout.addWidget(self.colorButton, 4, 0)
        layout.addWidget(self.colorLabel, 4, 1)
        layout.addWidget(self.fontButton, 5, 0)
        layout.addWidget(self.fontLabel, 5, 1)
        layout.addWidget(self.directoryButton, 6, 0)
        layout.addWidget(self.directoryLabel, 6, 1)
        layout.addWidget(self.openFileNameButton, 7, 0)
        layout.addWidget(self.openFileNameLabel, 7, 1)
        layout.addWidget(self.openFileNamesButton, 8, 0)
        layout.addWidget(self.openFileNamesLabel, 8, 1)
        layout.addWidget(self.saveFileNameButton, 9, 0)
        layout.addWidget(self.saveFileNameLabel, 9, 1)
        layout.addWidget(self.criticalButton, 10, 0)
        layout.addWidget(self.criticalLabel, 10, 1)
        layout.addWidget(self.informationButton, 11, 0)
        layout.addWidget(self.informationLabel, 11, 1)
        layout.addWidget(self.questionButton, 12, 0)
        layout.addWidget(self.questionLabel, 12, 1)
        layout.addWidget(self.warningButton, 13, 0)
        layout.addWidget(self.warningLabel, 13, 1)
        layout.addWidget(self.errorButton, 14, 0)
        layout.addWidget(self.errorLabel, 14, 1)
        layout.addWidget(self.native, 15, 0)
        self.setLayout(layout)

        self.setWindowTitle("Standard Dialogs")

    def setInteger(self):
        i, ok = QInputDialog.getInt(
            self, "QInputDialog.getInt()", "Percentage:", 25, 0, 100, 1
        )
        if ok:
            self.integerLabel.setText("%d%%" % i)

    def setDouble(self):
        d, ok = QInputDialog.getDouble(
            self, "QInputDialog.getDouble()", "Amount:", 37.56, -10000, 10000, 2
        )
        if ok:
            self.doubleLabel.setText("$%g" % d)

    def setItem(self):
        items = ("Spring", "Summer", "Fall", "Winter")

        item, ok = QInputDialog.getItem(
            self, "QInputDialog.getItem()", "Season:", items, 0, False
        )
        if ok and item:
            self.itemLabel.setText(item)

    def setText(self):
        text, ok = QInputDialog.getText(
            self,
            "QInputDialog.getText()",
            "User name:",
            QLineEdit.Normal,
            QDir.home().dirName(),
        )
        if ok and text != "":
            self.textLabel.setText(text)

    def setColor(self):
        color = QColorDialog.getColor(Qt.green, self)
        if color.isValid():
            self.colorLabel.setText(color.name())
            self.colorLabel.setPalette(QPalette(color))
            self.colorLabel.setAutoFillBackground(True)

    def setFont(self):
        font, ok = QFontDialog.getFont(QFont(self.fontLabel.text()), self)
        if ok:
            self.fontLabel.setText(font.key())
            self.fontLabel.setFont(font)

    def setExistingDirectory(self):
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        directory = QFileDialog.getExistingDirectory(
            self,
            "QFileDialog.getExistingDirectory()",
            self.directoryLabel.text(),
            options=options,
        )
        if directory:
            self.directoryLabel.setText(directory)

    def setOpenFileName(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            self.openFileNameLabel.text(),
            "All Files (*);;Text Files (*.txt)",
            options=options,
        )
        if fileName:
            self.openFileNameLabel.setText(fileName)

    def setOpenFileNames(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(
            self,
            "QFileDialog.getOpenFileNames()",
            self.openFilesPath,
            "All Files (*);;Text Files (*.txt)",
            options=options,
        )
        if files:
            self.openFilesPath = files[0]
            self.openFileNamesLabel.setText("[%s]" % ", ".join(files))

    def setSaveFileName(self):
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(
            self,
            "QFileDialog.getSaveFileName()",
            self.saveFileNameLabel.text(),
            "All Files (*);;Text Files (*.txt)",
            options=options,
        )
        if fileName:
            self.saveFileNameLabel.setText(fileName)

    def criticalMessage(self):
        reply = QMessageBox.critical(
            self,
            "QMessageBox.critical()",
            Dialog.MESSAGE,
            QMessageBox.Abort | QMessageBox.Retry | QMessageBox.Ignore,
        )
        if reply == QMessageBox.Abort:
            self.criticalLabel.setText("Abort")
        elif reply == QMessageBox.Retry:
            self.criticalLabel.setText("Retry")
        else:
            self.criticalLabel.setText("Ignore")

    def informationMessage(self):
        reply = QMessageBox.information(
            self, "QMessageBox.information()", Dialog.MESSAGE
        )
        if reply == QMessageBox.Ok:
            self.informationLabel.setText("OK")
        else:
            self.informationLabel.setText("Escape")

    def questionMessage(self):
        reply = QMessageBox.question(
            self,
            "QMessageBox.question()",
            Dialog.MESSAGE,
            QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
        )
        if reply == QMessageBox.Yes:
            self.questionLabel.setText("Yes")
        elif reply == QMessageBox.No:
            self.questionLabel.setText("No")
        else:
            self.questionLabel.setText("Cancel")

    def warningMessage(self):
        msgBox = QMessageBox(
            QMessageBox.Warning,
            "QMessageBox.warning()",
            Dialog.MESSAGE,
            QMessageBox.NoButton,
            self,
        )
        msgBox.addButton("Save &Again", QMessageBox.AcceptRole)
        msgBox.addButton("&Continue", QMessageBox.RejectRole)
        if msgBox.exec_() == QMessageBox.AcceptRole:
            self.warningLabel.setText("Save Again")
        else:
            self.warningLabel.setText("Continue")

    def errorMessage(self):
        self.errorMessageDialog.showMessage(
            "This dialog shows and remembers "
            "error messages. If the checkbox is checked (as it is by "
            "default), the shown message will be shown again, but if the "
            "user unchecks the box the message will not appear again if "
            "QErrorMessage.showMessage() is called with the same message."
        )
        self.errorLabel.setText(
            "If the box is unchecked, the message won't " "appear again."
        )
Exemplo n.º 30
0
class TYW(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    # Global vars:
    global data_db
    data_db = os.getcwd() + os.sep + 'db.dat'
    global db
    db = open(data_db, 'rb')
    global data
    data = pickle.load(db)
    global save_path
    save_path = os.getcwd() + os.sep + 'saved_wallpapper/'
    global default_path
    default_path = data[1]
    global user_name
    user_name = getpass.getuser()
    global startup_dir
    startup_dir = "C:/Users/" + user_name + "/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/"
    global al_path
    al_path = os.getcwd() + os.sep + 'dw_autoload.exe'
    global al_exe
    al_exe = 'dw_autoload.exe'
    global name_jpg
    name_jpg = os.getcwd() + os.sep + 'dw.jpg'
    global bg
    bg = os.getcwd() + os.sep + 'img/' + 'bg.jpg'
    global name_save
    name_save = os.getcwd() + os.sep + '/saved_wallpapper/' + time.strftime(
        '%d_%h_%Y') + '.jpg'

    def initUI(self):
        # button Update
        self.button1 = QPushButton("Update", self)
        self.button1.clicked.connect(self.main_f)
        self.button1.move(128, 85)
        self.button1.setStyleSheet("""
        QPushButton:hover { color: #333; border: 1px solid #7E3FF0; font: 10pt "Segoe UI"; background: #fff;}
        QPushButton:!hover { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(253, 232, 89);}
        QPushButton:pressed { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(254, 251, 208);}   
                                    """)
        # Checkbox autoload
        self.cb = QCheckBox('Auto-update', self)
        self.cb.move(10, 100)
        self.cb.setToolTip('Enable at startup')
        self.cb.setStyleSheet("""
        QCheckBox { spacing: 5px; color: rgb(180,180,180); }
        QCheckBox::indicator { width: 15px; height: 15px; }
        QCheckBox::indicator:unchecked { image: url(img/cb2.png);}
        QCheckBox::indicator:unchecked:hover { image: url(img/cb2_h.png);}
        QCheckBox::indicator:unchecked:pressed { image: url(img/cb2_p.png);}
        QCheckBox::indicator:checked { image: url(img/cb1.png);}
        QCheckBox::indicator:checked:hover { image: url(img/cb1_h.png);}
        QCheckBox::indicator:checked:pressed { image: url(img/cb1_p.png);}
        QToolTip { color: #333; border: 1px solid #7E3FF0; font: 9pt "Segoe UI"; background: #c2e8ff; }               
                                    """)
        self.cb.stateChanged.connect(self.autoload)
        # button Save
        self.button2 = QPushButton("Save", self)
        self.button2.setToolTip('Save in: ' + save_path)
        self.button2.clicked.connect(self.saving)
        self.button2.move(128, 85)
        self.button2.setStyleSheet("""
        QPushButton:hover { color: #333; border: 1px solid #7E3FF0; font: 10pt "Segoe UI"; background: #fff;}
        QPushButton:!hover { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(253, 232, 89);}
        QPushButton:pressed { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(254, 251, 208);}  
        QToolTip { color: #333; border: 1px solid #7E3FF0; font: 9pt "Segoe UI"; background: #c2e8ff; min-width: 60px; }                
                                    """)
        self.button2.hide()
        # button First 'No'
        self.button31 = QPushButton("No", self)
        self.button31.clicked.connect(self.choice_s)
        self.button31.move(22, 85)
        self.button31.setStyleSheet("""
        QPushButton:hover { color: #333; border: 1px solid #7E3FF0; font: 10pt "Segoe UI"; background: #fff;}
        QPushButton:!hover { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(253, 232, 89);}
        QPushButton:pressed { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(254, 251, 208);}   
                                    """)
        self.button31.hide()
        # button Second 'No'
        self.button3 = QPushButton("No", self)
        self.button3.clicked.connect(self.status_ex)
        self.button3.move(22, 85)
        self.button3.setStyleSheet("""
        QPushButton:hover { color: #333; border: 1px solid #7E3FF0; font: 10pt "Segoe UI"; background: #fff;}
        QPushButton:!hover { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(253, 232, 89);}
        QPushButton:pressed { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(254, 251, 208);}   
                                    """)
        self.button3.hide()
        # button - Return the default wallpaper
        self.button4 = QPushButton("Return", self)
        self.button4.clicked.connect(self.return_def_wall)
        self.button4.setToolTip(default_path)
        self.button4.move(128, 85)
        self.button4.setStyleSheet("""
        QPushButton:hover { color: #333; border: 1px solid #7E3FF0; font: 10pt "Segoe UI"; background: #fff;}
        QPushButton:!hover { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(253, 232, 89);}
        QPushButton:pressed { border: 1px solid #555; font: 10pt "Segoe UI"; background: rgb(254, 251, 208);}  
        QToolTip { color: #333; border: 1px solid #7E3FF0; font: 9pt "Segoe UI"; background: #c2e8ff; min-width: 60px; }                
                                    """)
        self.button4.hide()
        #button5 - Set the default wallpaper
        self.button5 = QPushButton("Set default", self)
        self.button5.clicked.connect(self.set_default_path)
        self.button5.setToolTip('You can change the default wallpapper')
        self.button5.setGeometry(QtCore.QRect(10, 90, 80, 15))
        self.button5.setStyleSheet("""
        QPushButton:hover { color: #333; border: 1px solid #7E3FF0; font: 9pt "Segoe UI"; background: #c2e8ff;}
        QPushButton:!hover {color: rgb(180, 180, 180); border: 1px solid #0062a1; font: 9pt "Segoe UI"; background: #0062a1;}
        QPushButton:pressed { border: 1px solid #555; font: 9pt "Segoe UI"; background: rgb(254, 251, 208);} 
        QToolTip { color: #333; border: 1px solid #7E3FF0; font: 9pt "Segoe UI"; background: #c2e8ff; min-width: 200px;}    
                                    """)
        #button6 - Close button
        self.button6 = QPushButton(self)
        self.button6.clicked.connect(self.quit_e)
        self.button6.move(220, 0)
        self.button6.setMaximumHeight(30)
        self.button6.setMaximumWidth(30)
        self.button6.setStyleSheet("""
        QPushButton:!hover {
            border-image: url(img/cl.png) 10 10 10 10;
            border-top: 10px transparent;
            border-bottom: 10px transparent;
            border-right: 10px transparent;
            border-left: 10px transparent;}
        QPushButton:hover {
            border-image: url(img/cl_h.png) 10 10 10 10;
            border-top: 10px transparent;
            border-bottom: 10px transparent;
            border-right: 10px transparent;
            border-left: 10px transparent;}
        QPushButton:pressed {
            border-image: url(img/cl_p.png) 10 10 10 10;
            border-top: 10px transparent;
            border-bottom: 10px transparent;
            border-right: 10px transparent;
            border-left: 10px transparent;} 
                                    """)
        # Title label
        self.label_title = QLabel(self)
        self.label_title.setGeometry(QtCore.QRect(15, 0, 200, 35))
        self.label_title.setStyleSheet("font: 13pt \"Segoe UI\";color: #333;")
        # Text output
        self.label = QLabel(self)
        self.label.setGeometry(QtCore.QRect(15, 40, 220, 35))
        # Window_form
        oImage = QImage(bg)
        sImage = oImage.scaled(QSize(250, 141))
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))
        self.setPalette(palette)
        self.setGeometry(300, 300, 250, 141)
        self.setFixedSize(250, 141)
        self.setWindowTitle('Daily Wallpapper')
        self.setWindowIcon(QIcon('icoo.ico'))
        self.statusBar().showMessage('ver. 0.61' + " " * 85 + 'by samwl')
        self.statusBar().setStyleSheet(
            "font: 6pt \"Segoe UI\";color: rgb(180, 180, 180);")
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.initial_message()
        self.label_title.setText("Daily Wallpapper")
        self.show()

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

    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()

    def mouseMoveEvent(self, event):
        delta = QPoint(event.globalPos() - self.oldPos)
        self.move(self.x() + delta.x(), self.y() + delta.y())
        self.oldPos = event.globalPos()

    def autoload(self, state):
        """Checkbox func"""
        if state == Qt.Checked:
            self.autoload_on()
        else:
            self.autoload_off()

    def autoload_off(self):
        """Delete autoload app from startup dir"""
        list_d = os.listdir(startup_dir)
        if al_exe in list_d:
            os.remove(startup_dir + al_exe)
        self.label.setText('Autoload - OFF')

    def autoload_on(self):
        """Copy autoload app to startup dir"""
        list_d = os.listdir(startup_dir)
        if al_exe not in list_d:
            shutil.copyfile(al_path,
                            startup_dir + al_exe,
                            follow_symlinks=True)
        self.label.setText('Autoload - ON')

    def initial_message(self):
        self.label.setText("Hello! Press 'Update' to get \ntoday wallpapper")

    def status_ex(self):
        """Auto exit"""
        self.label.setText("Exit after a few seconds")
        QTimer.singleShot(2000, self.quit_e)

    def quit_e(self):
        app.quit()

    def pars(self, name_arg):
        """Download image from bing.com"""
        #user32 = ctypes.windll.user32
        #user32.SetProcessDPIAware()
        #[width, height] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)] - choice requred resolution not work now
        js = urllib.request.urlopen(
            'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1')
        js_obj = json.load(js)
        url = 'http://www.bing.com' + js_obj['images'][0]['url']
        js.close()
        img = urllib.request.urlopen(url).read()
        out = open(name_arg, "wb")
        out.write(img)
        out.close()

    def saving(self):
        """Save today wallpapper to current dir"""
        list_d = os.listdir()
        a_folder = "saved_wallpapper"
        if a_folder in list_d:
            shutil.copyfile(name_jpg, name_save, follow_symlinks=True)
        else:
            path = os.getcwd() + os.sep + "/saved_wallpapper"
            os.mkdir(path)
            shutil.copyfile(name_jpg, name_save, follow_symlinks=True)
        self.label.setText("Saved")
        QTimer.singleShot(1000, self.status_ex)

    def set_wallpapper(self):
        """Set new desk wallpaper"""
        SPI_SETDESKWALLPAPER = 20
        ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0,
                                                   name_jpg, 0)

    def save_data(self):
        """Save current change"""
        data = self.read_db()
        data[0] = str(datetime.date.today())
        self.write_db(data)

    def read_db(self):
        """Read save data from db.DAT"""
        try:
            db = open(data_db, 'rb')
        except FileNotFoundError:
            self.open_error_message()
        else:
            data = pickle.load(db)
            return data

    def write_db(self, data):
        """Save updated data to db.DAT"""
        try:
            db = open(data_db, 'wb')
        except FileNotFoundError:
            self.open_error_message()
        else:
            pickle.dump(data, db)
            db.close()

    def main_f(self):
        """Main update func"""
        yday_date = data[0]
        if str(datetime.date.today()) > str(yday_date):
            try:
                self.pars(name_jpg)
            except urllib.error.URLError:
                self.connection_error_message()
                QTimer.singleShot(2000, self.status_ex)
            else:
                self.set_wallpapper()
                self.save_data()
                self.button2.show()
                self.button31.show()
                self.label.setText("Updated")
                self.button1.hide()
                self.button5.hide()
                self.cb.hide()
                QTimer.singleShot(1500, self.message_s)
        else:
            self.label.setText("Installed the latest wallpapers")
            self.button1.hide()
            self.button5.hide()
            self.cb.hide()
            self.choice_s()

    def open_error_message(self):
        self.label.setText("Please check - db.dat")
        QTimer.singleShot(1000, self.status_ex)

    def connection_error_message(self):
        self.label.setText("Сheck internet connection")
        QTimer.singleShot(1000, self.status_ex)

    def message_s(self):
        self.label.setText("Do you like it? Save?")

    def message_c(self):
        self.label.setText("Return the default wallpaper?")

    def choice_s(self):
        """Return choice"""
        self.button3.show()
        self.button4.show()
        QTimer.singleShot(1300, self.message_c)

    def return_def_wall(self):
        """Return to default wall"""
        data = self.read_db()
        ctypes.windll.user32.SystemParametersInfoW(20, 0, data[2], 0)
        data[0] = '2010-00-00'
        self.write_db(data)
        QTimer.singleShot(1000, self.status_ex)

    def set_default_path(self):
        """Set path to default wallpapper"""
        fname = QFileDialog.getOpenFileName(self, 'Select default wallpaper',
                                            '/home')[0]
        dir_name = os.path.dirname(fname)
        file_name = os.path.basename(fname)
        data = self.read_db()
        data[2] = dir_name + '/' + file_name
        self.write_db(data)
Exemplo n.º 31
0
class NetworkChoiceLayout(object):
    def __init__(self, network, config, wizard=False):
        self.network = network
        self.config = config
        self.protocol = None
        self.tor_proxy = None
        self.filling_in = False

        self.tabs = tabs = QTabWidget()
        tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        server_tab = QWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(server_tab, _('Server'))
        tabs.addTab(proxy_tab, _('Proxy'))

        if wizard:
            tabs.setCurrentIndex(1)

        # server tab
        grid = QGridLayout(server_tab)
        grid.setSpacing(8)

        self.server_host = QLineEdit()
        self.server_host.setFixedWidth(200)
        self.server_port = QLineEdit()
        self.server_port.setFixedWidth(60)
        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))

        self.server_host.editingFinished.connect(self.set_server)
        self.server_port.editingFinished.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self._on_autoconnect_toggled)
        self.autoconnect_cb.clicked.connect(self.update)

        msg = ' '.join([
            _("If auto-connect is enabled, ElectrumSV will always use a server that "
              "is on the longest blockchain."),
            _("If it is disabled, you have to choose a server you want to use. "
              "ElectrumSV will warn you if your server is lagging.")
        ])
        grid.addWidget(self.autoconnect_cb, 0, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_host, 1, 1, 1, 2)
        grid.addWidget(self.server_port, 1, 3)

        label = _('Server peers') if network.is_connected() else _(
            'Default Servers')
        grid.addWidget(QLabel(label), 2, 0, 1, 5)
        self.servers_list = ServerListWidget(self)
        grid.addWidget(self.servers_list, 3, 0, 1, 5)

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(list(SVProxy.kinds))
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(200)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(100)
        self.proxy_username = QLineEdit()
        self.proxy_username.setPlaceholderText(_("Proxy user"))
        self.proxy_username.setFixedWidth(self.proxy_host.width())
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_username.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(
            self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_username.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('Proxy settings apply to all connections: both '
                  'ElectrumSV servers and third-party services.')), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_username, 5, 2, Qt.AlignTop)
        grid.addWidget(self.proxy_password, 5, 3, Qt.AlignTop)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        blockchain_layout = QVBoxLayout(blockchain_tab)

        form = FormSectionWidget()
        self.status_label = QLabel('')
        form.add_row(_('Status'), self.status_label, True)
        self.server_label = QLabel('')
        form.add_row(_('Server'), self.server_label, True)
        self.height_label = QLabel('')
        form.add_row(_('Blockchain'), self.height_label, True)

        blockchain_layout.addWidget(form)

        self.split_label = QLabel('')
        form.add_row(QLabel(""), self.split_label)

        self.nodes_list_widget = NodesListWidget(self)
        blockchain_layout.addWidget(self.nodes_list_widget)
        blockchain_layout.addStretch(1)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.last_values = None

        self.fill_in_proxy_settings()
        self.update()

    def check_disable_proxy(self, b):
        if not self.config.is_modifiable('proxy'):
            b = False
        for w in [
                self.proxy_mode, self.proxy_host, self.proxy_port,
                self.proxy_username, self.proxy_password
        ]:
            w.setEnabled(b)

    def enable_set_server(self):
        if self.config.is_modifiable('server'):
            enabled = not self.autoconnect_cb.isChecked()
            self.server_host.setEnabled(enabled)
            self.server_port.setEnabled(enabled)
            self.servers_list.setEnabled(enabled)
        else:
            for w in [
                    self.autoconnect_cb, self.server_host, self.server_port,
                    self.servers_list
            ]:
                w.setEnabled(False)

    def update(self):
        server = self.network.main_server
        self.server_host.setText(server.host)
        self.server_port.setText(str(server.port))
        self.autoconnect_cb.setChecked(self.network.auto_connect())

        host = server.host if self.network.is_connected() else _('None')
        self.server_label.setText(host)

        self.set_protocol(server.protocol)
        self.servers = self.network.get_servers()
        self.servers_list.update(self.servers, self.protocol,
                                 self.tor_cb.isChecked())
        self.enable_set_server()

        height_str = "%d " % (self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.sessions)
        status = _("Connected to {:d} servers.").format(n) if n else _(
            "Not connected")
        self.status_label.setText(status)
        chains = self.network.sessions_by_chain().keys()
        if len(chains) > 1:
            our_chain = self.network.chain()
            heights = set()
            for chain in chains:
                if chain != our_chain:
                    _chain, common_height = our_chain.common_chain_and_height(
                        chain)
                    heights.add(common_height + 1)
            msg = _('Chain split detected at height(s) {}\n').format(','.join(
                f'{height:,d}' for height in sorted(heights)))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(self.network)

    def fill_in_proxy_settings(self):
        self.filling_in = True
        self.check_disable_proxy(self.network.proxy is not None)
        self.proxy_cb.setChecked(self.network.proxy is not None)
        proxy = self.network.proxy or SVProxy('localhost:9050', 'SOCKS5', None)
        self.proxy_mode.setCurrentText(proxy.kind())
        self.proxy_host.setText(proxy.host())
        self.proxy_port.setText(str(proxy.port()))
        self.proxy_username.setText(proxy.username())
        self.proxy_password.setText(proxy.password())
        self.filling_in = False

    def layout(self):
        return self.layout_

    def set_protocol(self, protocol):
        if protocol != self.protocol:
            self.protocol = protocol

    def change_protocol(self, use_ssl):
        p = 's' if use_ssl else 't'
        host = self.server_host.text()
        pp = self.servers.get(host, Net.DEFAULT_PORTS)
        if p not in pp.keys():
            p = list(pp.keys())[0]
        port = pp[p]
        self.server_host.setText(host)
        self.server_port.setText(port)
        self.set_protocol(p)
        self.set_server()

    def follow_server(self, server):
        self.network.set_server(server, self.network.auto_connect())
        self.update()

    def server_changed(self, x):
        if x:
            self.change_server(str(x.text(0)), self.protocol)

    def change_server(self, host, protocol):
        pp = self.servers.get(host, Net.DEFAULT_PORTS)
        if protocol:
            port = pp.get(protocol)
            if port is None:
                protocol = None
        if not protocol:
            if 's' in pp.keys():
                protocol = 's'
                port = pp.get(protocol)
            else:
                protocol = list(pp.keys())[0]
                port = pp.get(protocol)
        self.server_host.setText(host)
        self.server_port.setText(port)

    def accept(self):
        pass

    def _on_autoconnect_toggled(self, _checked):
        self.set_server()

    def set_server(self, server=None):
        # EditingFinished can fire twice in Qt (a bug).  More generally, prevent repeats
        # on e.g. dialog exit
        values = (self.server_host.text(), self.server_port.text(),
                  self.network.main_server.protocol,
                  self.autoconnect_cb.isChecked())
        if values != self.last_values:
            self.last_values = values
            try:
                if not server:
                    server = SVServer.unique(*values[:3])
                self.network.set_server(server,
                                        self.autoconnect_cb.isChecked())
            except Exception as e:
                MessageBox.show_error(str(e))

    def set_proxy(self):
        if self.filling_in:
            return
        proxy = None
        if self.proxy_cb.isChecked():
            try:
                address = NetAddress(self.proxy_host.text(),
                                     self.proxy_port.text())
                if self.proxy_username.text():
                    auth = SVUserAuth(self.proxy_username.text(),
                                      self.proxy_password.text())
                else:
                    auth = None
                proxy = SVProxy(address, self.proxy_mode.currentText(), auth)
            except Exception:
                logger.exception('error setting proxy')
        if not proxy:
            self.tor_cb.setChecked(False)
        self.network.set_proxy(proxy)

    def suggest_proxy(self, found_proxy):
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if (self.proxy_cb.isChecked()
                and self.proxy_mode.currentText() == 'SOCKS5'
                and self.proxy_host.text() == found_proxy[0]
                and self.proxy_port.text() == str(found_proxy[1])):
            self.tor_cb.setChecked(True)
        self.tor_cb.show()

    def use_tor_proxy(self, use_it):
        if use_it:
            self.proxy_mode.setCurrentText('SOCKS5')
            self.proxy_host.setText(self.tor_proxy[0])
            self.proxy_port.setText(str(self.tor_proxy[1]))
            self.proxy_username.setText("")
            self.proxy_password.setText("")
            self.proxy_cb.setChecked(True)
        else:
            self.proxy_cb.setChecked(False)
        self.check_disable_proxy(use_it)
        self.set_proxy()

    def proxy_settings_changed(self):
        self.tor_cb.setChecked(False)
Exemplo n.º 32
0
class App(QWidget):
    
    def __init__(self):
        super().__init__()

        self.title = 'Excel Formatter'
        self.left = 30
        self.top = 50
        self.width = 640
        self.height = 480
        self.initUI()
        
        
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)        
        self.setFixedSize(800, 550)
        
        browse = QPushButton('Browse: ', self)
        browse.setToolTip('Browse for files to be Formatted: ')
        browse.clicked.connect(lambda: self.browse_on_click(App))
        browse.setMinimumHeight(25)
        browse.setMaximumHeight(25)
        browse.setMinimumWidth(135)
        browse.setMaximumWidth(135)
        
        self.browseFunc = QPushButton('Import Script: ', self)
        self.browseFunc.setToolTip('Import Bespoke Python Script: ')
        self.browseFunc.clicked.connect(lambda: self.importScript(App))
        self.browseFunc.setMinimumHeight(25)
        self.browseFunc.setMaximumHeight(25)
        self.browseFunc.setMinimumWidth(135)
        self.browseFunc.setMaximumWidth(135)
      
        self.saveTo = QPushButton('Save to: ', self)
        self.saveTo.setToolTip('Select location to save output: ')
        self.saveTo.clicked.connect(lambda: self.saveTo_on_click(App))
        self.saveTo.setMinimumHeight(25)
        self.saveTo.setMaximumHeight(25)
        self.saveTo.setMinimumWidth(135)
        self.saveTo.setMaximumWidth(135)
        self.saveTo.setEnabled(False)
        
        self.run = QPushButton('Run: ', self)
        self.run.setToolTip('Run Program: ')
        self.run.clicked.connect(self.run_on_click)
        self.run.setMinimumHeight(25)
        self.run.setMaximumHeight(25)
        self.run.setMinimumWidth(135)
        self.run.setMaximumWidth(135)
        
        reset = QPushButton('Reset View', self)
        reset.setToolTip('Reset UI Elements: ')
        reset.clicked.connect(self.reset_on_click)
        reset.setMinimumHeight(25)
        reset.setMaximumHeight(25)
        reset.setMinimumWidth(135)
        reset.setMaximumWidth(135)        
        
        self.sheets = QCheckBox('Cont. Sheets?')
        self.sheets.setChecked(False)
        self.combine = QCheckBox('Combine Files?')
        self.combine.setChecked(True)
        self.combine.setEnabled(True)
        self.zip = QCheckBox('Zip Files?')
        self.zip.hide()
        self.zip.setChecked(False)
        self.zip.setEnabled(False)
        self.zip.toggled.connect(self.onClicked)
        self.noForm = QCheckBox('No Formatting?')
        self.noForm.setChecked(False)
        self.noForm.toggled.connect(self.noFormOnClicked) 
        
        self.delimIn = QComboBox()
        self.delimIn.addItems(['Input CSV Delim: ',',','|','@',';'])
        self.delimIn.setEditable(True)
        self.delimIn.lineEdit().setAlignment(Qt.AlignCenter)
        self.delimIn.lineEdit().setReadOnly(True)
        self.delimIn.setMinimumHeight(25)
        self.delimIn.setMaximumHeight(25)
        self.delimIn.setMinimumWidth(135)
        self.delimIn.setMaximumWidth(135)    
        
        self.delimOut = QComboBox()
        self.delimOut.addItems(['Output CSV Delim: ',',','|','@',';'])
        self.delimOut.setEditable(True)
        self.delimOut.lineEdit().setAlignment(Qt.AlignCenter)
        self.delimOut.lineEdit().setReadOnly(True)
        self.delimOut.setMinimumHeight(25)
        self.delimOut.setMaximumHeight(25)
        self.delimOut.setMinimumWidth(135)
        self.delimOut.setMaximumWidth(135) 
        
        
        self.threads = QComboBox()
        self.threads.addItems(['No of Threads: ','1', '2', '3', '4', '6', '8', '12', '16', '20']) 
        self.threads.setEditable(True)
        self.threads.lineEdit().setAlignment(Qt.AlignCenter)
        self.threads.lineEdit().setReadOnly(True)
        self.threads.setMinimumHeight(25)
        self.threads.setMaximumHeight(25)
        self.threads.setMinimumWidth(135)
        self.threads.setMaximumWidth(135)        
        
        self.files = []
        self.saveFile = ''
        self.imprt = ''
        
        self.financialSystem  = QComboBox()
        self.financialSystem.addItems(['Financial System:', 'No Formatting', 'Sage200 - ACr'])
        self.financialSystem.setEditable(True)
        self.financialSystem.lineEdit().setAlignment(Qt.AlignCenter)
        self.financialSystem.lineEdit().setReadOnly(True)
        self.financialSystem.setMinimumHeight(25)
        self.financialSystem.setMaximumHeight(25)
        self.financialSystem.setMinimumWidth(135)
        self.financialSystem.setMaximumWidth(135)   
        
        self.serverName = 'UKDC250016'
        
        self.engine = sa.create_engine('mssql+pyodbc://'+self.serverName+'/master?driver=SQL+Server')

        conn = self.engine.connect()
        rows = conn.execute("select name FROM sys.databases;")
        dbs= []
        for row in rows:
            dbs.append(row["name"])        
        
        self.server = QComboBox()
        self.server.addItem('Server: ', dbs) 
        self.server.setEditable(True)
        self.server.lineEdit().setAlignment(Qt.AlignCenter)
        self.server.lineEdit().setReadOnly(True)
        self.server.setMinimumHeight(25)
        self.server.setMaximumHeight(25)
        self.server.setMinimumWidth(180)
        self.server.setMaximumWidth(180)
        
        self.server.addItem('UKDC250016', dbs)
        self.server.addItem('UKDC250016\SQL2016', dbs)        
        self.server.addItem('UKDC110029', dbs)
        self.server.addItem('UKDC210033', dbs)
        self.server.addItem('UKDC210033\SQL2016', dbs)
        self.server.addItem('UKDC150016', dbs)
        self.server.addItem('UKDC150016\SQL2016', dbs)
        self.server.addItem('UKDC103023', dbs)
        self.server.addItem('UKDC203023', dbs) 
        self.server.currentIndexChanged.connect(self.indexChanged)        
        
        self.database = QComboBox()
        self.database.addItem('Database: ', dbs) 
        self.database.setEditable(True)
        self.database.lineEdit().setAlignment(Qt.AlignCenter)
        self.database.lineEdit().setReadOnly(True)
        self.database.setMinimumHeight(25)
        self.database.setMaximumHeight(25)
        self.database.setMinimumWidth(286)
        self.database.setMaximumWidth(286)   
        
        self.step = 0
        self.timer = QBasicTimer()
        
        self.linePathBrowse = QLineEdit(self)
        self.linePathSave = QLineEdit(self)
        
        self.output = QTextEdit()
        self.output.setReadOnly(True)
        
        self.pbar = QProgressBar(self)
        self.pbar.setTextVisible(False)          
 
        self.grid = QGridLayout()
        self.grid.setSpacing(10)
        
        self.setLayout(self.grid)   
        
        self.process = QTextEdit()
        self.process.moveCursor(QTextCursor.Start)
        self.process.ensureCursorVisible()
        self.process.setLineWrapColumnOrWidth(128)
        self.process.setLineWrapMode(QTextEdit.FixedPixelWidth)
        self.process.setMinimumWidth(135)
        self.process.setMaximumWidth(135) 
        
        self.process2 = QTextEdit()
        self.process2.moveCursor(QTextCursor.Start)
        self.process2.ensureCursorVisible()
        self.process2.setLineWrapColumnOrWidth(128)
        self.process2.setLineWrapMode(QTextEdit.FixedPixelWidth)
        self.process2.setMinimumWidth(135)
        self.process2.setMaximumWidth(135) 
        
        self.sql   = QCheckBox('To DB')
        self.sql.setChecked(True)
        self.sql.toggled.connect(self.SQLOnClicked)
        self.sql.setMinimumWidth(65)
        self.sql.setMaximumWidth(65)  
        
        self.csv   = QCheckBox('To CSV')
        self.csv.toggled.connect(self.SQLOnClicked)
        self.csv.setMinimumWidth(67)
        self.csv.setMaximumWidth(67)
        
        sublayout1 = QHBoxLayout()
        sublayout1.addWidget(self.csv)
        sublayout1.addWidget(self.sql)
        
        self.tableName = QPushButton('Table Name:')
        self.tableName.setMinimumHeight(25)
        self.tableName.setMaximumHeight(25)
        self.tableName.setMinimumWidth(135)
        self.tableName.setMaximumWidth(135)   

        self.grid.addWidget(browse, 1, 1)
        self.grid.addWidget(self.linePathBrowse, 1, 2, 1, 3)
        self.grid.addWidget(self.saveTo, 3, 1)
        self.saveTo.hide()
        self.grid.addWidget(self.tableName, 3, 1)        
        self.grid.addWidget(self.linePathSave, 3, 2, 1, 3)
        self.grid.addWidget(self.sheets, 5, 1)
        self.grid.addWidget(self.combine, 6, 1)
        self.grid.addWidget(self.threads, 12, 5)
        self.grid.addWidget(self.zip, 7, 1)
        self.grid.addWidget(self.delimIn, 7, 1)
        self.grid.addWidget(self.delimOut, 8, 1)
        self.grid.addWidget(reset, 10, 1)
        self.grid.addWidget(self.run, 13, 5) 
        self.grid.addLayout(sublayout1, 2, 1)
        self.grid.addWidget(self.server, 2, 2)
        self.grid.addWidget(self.database, 2, 3, 1, 2)
        self.grid.addWidget(self.financialSystem, 3, 5)
        self.grid.addWidget(self.noForm, 1, 5)
        self.grid.addWidget(self.browseFunc, 2, 5)
        self.grid.addWidget(self.output, 4, 2, 9, 3)
        self.grid.addWidget(self.pbar, 13, 1, 1, 4) 
        self.spacer= QLabel()
        self.grid.addWidget(self.spacer, 5, 1)
        self.grid.addWidget(self.spacer, 9, 1)
        self.grid.addWidget(self.process, 11, 1, 2, 1)
        self.grid.addWidget(self.process2, 4, 5, 8, 1)
        
        self.show()
        
    def runControl(self):
        if self.run.isEnabled() == True:
            self.run.setEnabled(False)
        else:
            self.run.setEnabled(True)
        
    def indexChanged(self, index):
        if index == 0:
            self.database.clear()
            self.database.addItem('Database: ')
        else:
            self.database.clear()
            data = self.server.itemData(index)
            self.serverName = str(self.server.currentText())
            self.engine = sa.create_engine('mssql+pyodbc://'+self.serverName+'/master?driver=SQL+Server')
            conn = self.engine.connect()
            rows = conn.execute("select name FROM sys.databases;")
            dbs= []
            for row in rows:
                dbs.append(row["name"])
            if data is not None:
                self.database.addItems(dbs)
        
    def noFormOnClicked(self):
        if self.noForm.isChecked():
            self.financialSystem.setEnabled(False)
            self.browseFunc.setEnabled(False)
        else:
            self.financialSystem.setEnabled(True)
            self.browseFunc.setEnabled(True)            
            
    def SQLOnClicked(self):
        if self.csv.isChecked() and self.sql.isChecked():
            self.server.setEnabled(True)
            self.database.setEnabled(True)
            self.saveTo.setEnabled(True)
            self.combine.setEnabled(True)
            self.zip.setEnabled(True)
            self.saveTo.show()
            self.tableName.hide()
            self.linePathSave.setText('')
            self.linePathSave.setReadOnly(True)
        elif self.csv.isChecked():
            self.server.setEnabled(False)
            self.database.setEnabled(False)
            self.saveTo.setEnabled(True)
            self.combine.setEnabled(True)
            self.zip.setEnabled(True)
            self.saveTo.show()
            self.tableName.hide()
            self.linePathSave.setText('')
            self.linePathSave.setReadOnly(True)
        else:
            self.server.setEnabled(True)
            self.database.setEnabled(True)
            self.saveTo.setEnabled(False)
            self.combine.setEnabled(True)
            self.zip.setEnabled(False)
            self.saveTo.hide()
            self.tableName.show()
            self.linePathSave.setText('')
            self.linePathSave.setReadOnly(False)
            
    def onClicked(self):
        if self.zip.isChecked():
            self.output.clear()
        else:
            self.output.append('Highly Recommended for large data sets!')        
        
    def reset_on_click(self):
        self.linePathBrowse.setText('')
        self.linePathSave.setText('')
        self.browseFunc.setText('Import Script: ') 
        self.process.setText('')
        self.sheets.setChecked(False)
        self.combine.setChecked(True)
        self.zip.setChecked(True)
        self.sql.setChecked(True)
        self.csv.setChecked(False)
        self.combine.setEnabled(True)
        self.zip.setEnabled(False)
        self.saveTo.hide()
        self.tableName.show()
        self.noForm.setChecked(False)
        self.browseFunc.setEnabled(True)
        self.financialSystem.setEnabled(True)
        self.server.setCurrentIndex(0)
        self.database.setCurrentIndex(0)
        self.financialSystem.setCurrentIndex(0)
        self.threads.setCurrentIndex(0)
        self.output.clear()
        self.process2.setText('')
    
    def outputToUI(self, text):
        self.output.append(text)
        
    def setTimer(self, timerValue):
        self.pbar.setValue(timerValue)
        
    def importScript(self, App):
        files = self.importDialog()
        return files
    
    def importDialog(self):
        options = QFileDialog.Options()
        #options |= QFileDialog.DontUseNativeDialog
        imprt, _ = QFileDialog.getOpenFileNames(self, "Open Formatting Script: ", "K:/A & A/Cardiff/Audit/Clients/Open/S/Spotlight/2. Staff Folders/JWalters/__Python/Formatting Scripts", "Python Script (*.py)", options = options)
        if basename('; '.join(imprt)) == '': 
            self.browseFunc.setText('Import Script: ')
        else:
            self.browseFunc.setText(basename('; '.join(imprt))) 
        self.imprt = imprt
            
    def openFileNamesDialog(self):
        options = QFileDialog.Options()
        #options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(self, "Open Files to be Formatted: ", "K:/A & A/Cardiff/Audit/Clients/Open/S/Spotlight/2. Staff Folders/JWalters/__Python/Test Data and VBA", "All Files (*);;Excel Workbook (*.xls);;Excel Workbook (*.xlsx);; Excel Macro-Enabled Workbook (*.xlsm)", options = options)
        self.linePathBrowse.setText('; '.join(files)) 
        self.files = files
        
    def saveFileDialog(self):
        options = QFileDialog.Option()
        #options |= QFileDialog.DontUseNativeDialog
        saveFile, _ = QFileDialog.getSaveFileName(self,"Save Output As: ","K:/A & A/Cardiff/Audit/Clients/Open/S/Spotlight/2. Staff Folders/JWalters/__Python/Test Data and VBA/Formatted.csv","All Files (*);;CSV Files (*.csv)", options=options)
        self.linePathSave.setText(left(saveFile, len(saveFile) -4)) 
        self.saveFile = saveFile
            
    def browse_on_click(self, App):
        files = self.openFileNamesDialog()
        return files
    
    def saveTo_on_click(self, App):
        saveFile = self.saveFileDialog()
        return saveFile
    
    def run_on_click(self, files):
        if self.delimIn.currentText() == 'Input CSV Delim: ':
            delimIn = ','
        else:
            delimIn = self.delimIn.currentText()
        if self.delimOut.currentText() == 'Output CSV Delim: ':
            delimOut = ','
        else:
            delimOut = self.delimOut.currentText()
        if self.csv.isChecked() == True and self.sql.isChecked() == False:
            server = ''
            database = ''
        else:
            server = self.server.currentText()
            database = self.database.currentText()
            
        if self.csv.isChecked() == False:
            saveFileTemp = ''
        else:
            saveFileTemp = self.linePathSave.text()
        
        try:
            if self.files == []:
                self.output.append('No Source File(s) Selected.')
            elif self.saveFile == '' and self.csv.isChecked():
                self.output.append('No Destination Selected.')
            elif self.sql.isChecked() and self.database.currentText() == 'Database: ':
                self.output.append('Please Select Destination Server and Database.')
            elif self.sql.isChecked() and self.linePathSave.text() == '':
                self.output.append('Please Enter Table Name:')
            elif self.noForm.isChecked() == False and ((self.imprt == '' or self.imprt == []) and (self.financialSystem.currentText() == 'Financial System:' or self.financialSystem.currentText() == '')):  
                self.output.append('Please Import Formatting Script: ')
            elif self.csv.isChecked() == False and self.sql.isChecked() == False:
                self.output.append('Please Select Output (SQL/CSV)')
            elif self.financialSystem.currentText() != 'Financial System:' and self.financialSystem.currentText() != '':
                self.imprt = self.financialSystem.currentText()
                self.output.clear()
                if self.threads.currentText() == 'No of Threads: ':
                    self.output.append('No Thread Count Selected:')
                    self.output.append('     Defaulting to 4 Threads.')
                    self.output.append('')
                else:
                    pass
                if os.path.exists(basename('; '.join(self.imprt))) == True:
                    pass
                else:
                    copy('K:/A & A/Cardiff/Audit/Clients/Open/S/Spotlight/2. Staff Folders/JWalters/__Python/python/System Scripts/' + basename(self.imprt) +'.py', '.')
                impModule = 'K:/A & A/Cardiff/Audit/Clients/Open/S/Spotlight/2. Staff Folders/JWalters/__Python/python/System Scripts/' + basename(self.imprt) +'.py'
                self.workerThread = WorkerThread(files = self.files, 
                                                 saveFile = saveFileTemp, 
                                                 system = impModule,
                                                 filename = self.imprt,  
                                                 server = server,
                                                 database = database,
                                                 sheets = self.sheets.isChecked(), 
                                                 threads = self.threads.currentText(),
                                                 combine = self.combine.isChecked(),
                                                 zipped = self.zip.isChecked(),
                                                 noForm = self.noForm.isChecked(),
                                                 tableName = self.linePathSave.text(),
                                                 CSVDelimIn = delimIn,
                                                 CSVDelimOut = delimOut) 
                self.runControl()
                self.workerThread.value.connect(self.outputToUI)
                self.workerThread.timerValue.connect(self.setTimer)
                self.workerThread.startValue.connect(self.startTimer)
                self.workerThread.endValue.connect(self.stopTimer)
                self.workerThread.runCont.connect(self.runControl)
                self.workerThread.start()
            else:
                self.output.clear()
                if self.threads.currentText() == 'No of Threads: ':
                    self.output.append('No Thread Count Selected:')
                    self.output.append('     Defaulting to 4 Threads.')
                    self.output.append('')
                else:
                    pass
                try:
                    os.remove(basename('; '.join(self.imprt)))
                except:
                    pass
                if os.path.exists(basename('; '.join(self.imprt))) == True:
                    pass
                elif self.noForm.isChecked() == False:
                    copy('; '.join(self.imprt), '.') 
                    impModule = ('; '.join(self.imprt))
                else:
                    impModule = ''                                
                
                self.workerThread = WorkerThread(files = self.files, 
                                                 saveFile = saveFileTemp, 
                                                 system = impModule,
                                                 filename = self.imprt,  
                                                 server = server,
                                                 database = database,
                                                 sheets = self.sheets.isChecked(), 
                                                 threads = self.threads.currentText(),
                                                 combine = self.combine.isChecked(),
                                                 zipped = self.zip.isChecked(),
                                                 noForm = self.noForm.isChecked(),
                                                 tableName = self.linePathSave.text(),
                                                 CSVDelimIn = delimIn,
                                                 CSVDelimOut = delimOut)
                self.runControl()
                self.workerThread.value.connect(self.outputToUI)
                self.workerThread.timerValue.connect(self.setTimer)
                self.workerThread.startValue.connect(self.startTimer)
                self.workerThread.endValue.connect(self.stopTimer)                
                self.workerThread.runCont.connect(self.runControl)
                self.workerThread.start()
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
            print(e)
            
    def startTimer(self,startValue):
        self.pbar.setMaximum(startValue)
        self.timer.start(startValue, self)
            
    def timerEvent(self, tevent):
        value = self.pbar.value()
        if value < 35 :
            value += 1
            self.pbar.setValue(value)
        else:
            self.pbar.setValue(0)
    
    def stopTimer(self, inp):
        if inp == 1:
            self.timer.stop()
Exemplo n.º 33
0
class NetworkChoiceLayout(object):

    def __init__(self, network: Network, config, wizard=False):
        self.network = network
        self.config = config
        self.protocol = None
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        server_tab = QWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(server_tab, _('Server'))
        tabs.addTab(proxy_tab, _('Proxy'))

        # server tab
        grid = QGridLayout(server_tab)
        grid.setSpacing(8)

        self.server_host = QLineEdit()
        self.server_host.setFixedWidth(200)
        self.server_port = QLineEdit()
        self.server_port.setFixedWidth(60)
        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(self.config.is_modifiable('auto_connect'))

        self.server_host.editingFinished.connect(self.set_server)
        self.server_port.editingFinished.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)

        msg = ' '.join([
            _("If auto-connect is enabled, Electrum will always use a server that is on the longest blockchain."),
            _("If it is disabled, you have to choose a server you want to use. Electrum will warn you if your server is lagging.")
        ])
        grid.addWidget(self.autoconnect_cb, 0, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_host, 1, 1, 1, 2)
        grid.addWidget(self.server_port, 1, 3)

        label = _('Server peers') if network.is_connected() else _('Default Servers')
        grid.addWidget(QLabel(label), 2, 0, 1, 5)
        self.servers_list = ServerListWidget(self)
        grid.addWidget(self.servers_list, 3, 0, 1, 5)

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(['SOCKS4', 'SOCKS5'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(200)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(60)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_password = QLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))
        self.proxy_password.setEchoMode(QLineEdit.Password)
        self.proxy_password.setFixedWidth(60)

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_user.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_user.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(HelpButton(_('Proxy settings apply to all connections: with Electrum servers, but also with third-party services.')), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_user, 5, 2)
        grid.addWidget(self.proxy_password, 5, 3)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg =  ' '.join([
            _("Electrum connects to several nodes in order to download block headers and find out the longest blockchain."),
            _("This blockchain is used to verify the transactions sent by your transaction server.")
        ])
        self.status_label = QLabel('')
        grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
        grid.addWidget(self.status_label, 0, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        self.server_label = QLabel('')
        msg = _("Electrum sends your wallet addresses to a single server, in order to receive your transaction history.")
        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_label, 1, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.height_label = QLabel('')
        msg = _('This is the height of your local copy of the blockchain.')
        grid.addWidget(QLabel(_('Blockchain') + ':'), 2, 0)
        grid.addWidget(self.height_label, 2, 1)
        grid.addWidget(HelpButton(msg), 2, 4)

        self.split_label = QLabel('')
        grid.addWidget(self.split_label, 3, 0, 1, 3)

        self.nodes_list_widget = NodesListWidget(self)
        grid.addWidget(self.nodes_list_widget, 5, 0, 1, 5)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.fill_in_proxy_settings()
        self.update()

    def check_disable_proxy(self, b):
        if not self.config.is_modifiable('proxy'):
            b = False
        for w in [self.proxy_mode, self.proxy_host, self.proxy_port, self.proxy_user, self.proxy_password]:
            w.setEnabled(b)

    def enable_set_server(self):
        if self.config.is_modifiable('server'):
            enabled = not self.autoconnect_cb.isChecked()
            self.server_host.setEnabled(enabled)
            self.server_port.setEnabled(enabled)
            self.servers_list.setEnabled(enabled)
        else:
            for w in [self.autoconnect_cb, self.server_host, self.server_port, self.servers_list]:
                w.setEnabled(False)

    def update(self):
        net_params = self.network.get_parameters()
        host, port, protocol = net_params.host, net_params.port, net_params.protocol
        proxy_config, auto_connect = net_params.proxy, net_params.auto_connect
        self.server_host.setText(host)
        self.server_port.setText(str(port))
        self.autoconnect_cb.setChecked(auto_connect)

        interface = self.network.interface
        host = interface.host if interface else _('None')
        self.server_label.setText(host)

        self.set_protocol(protocol)
        self.servers = self.network.get_servers()
        self.servers_list.update(self.servers, self.protocol, self.tor_cb.isChecked())
        self.enable_set_server()

        height_str = "%d "%(self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.get_interfaces())
        status = _("Connected to {0} nodes.").format(n) if n else _("Not connected")
        self.status_label.setText(status)
        chains = self.network.get_blockchains()
        if len(chains) > 1:
            chain = self.network.blockchain()
            forkpoint = chain.get_max_forkpoint()
            name = chain.get_name()
            msg = _('Chain split detected at block {0}').format(forkpoint) + '\n'
            msg += (_('You are following branch') if auto_connect else _('Your server is on branch'))+ ' ' + name
            msg += ' (%d %s)' % (chain.get_branch_size(), _('blocks'))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(self.network)

    def fill_in_proxy_settings(self):
        proxy_config = self.network.get_parameters().proxy
        if not proxy_config:
            proxy_config = {"mode": "none", "host": "localhost", "port": "9050"}

        b = proxy_config.get('mode') != "none"
        self.check_disable_proxy(b)
        if b:
            self.proxy_cb.setChecked(True)
            self.proxy_mode.setCurrentIndex(
                self.proxy_mode.findText(str(proxy_config.get("mode").upper())))

        self.proxy_host.setText(proxy_config.get("host"))
        self.proxy_port.setText(proxy_config.get("port"))
        self.proxy_user.setText(proxy_config.get("user", ""))
        self.proxy_password.setText(proxy_config.get("password", ""))

    def layout(self):
        return self.layout_

    def set_protocol(self, protocol):
        if protocol != self.protocol:
            self.protocol = protocol

    def change_protocol(self, use_ssl):
        p = 's' if use_ssl else 't'
        host = self.server_host.text()
        pp = self.servers.get(host, constants.net.DEFAULT_PORTS)
        if p not in pp.keys():
            p = list(pp.keys())[0]
        port = pp[p]
        self.server_host.setText(host)
        self.server_port.setText(port)
        self.set_protocol(p)
        self.set_server()

    def follow_branch(self, chain_id):
        self.network.run_from_another_thread(self.network.follow_chain_given_id(chain_id))
        self.update()

    def follow_server(self, server):
        self.network.run_from_another_thread(self.network.follow_chain_given_server(server))
        self.update()

    def server_changed(self, x):
        if x:
            self.change_server(str(x.text(0)), self.protocol)

    def change_server(self, host, protocol):
        pp = self.servers.get(host, constants.net.DEFAULT_PORTS)
        if protocol and protocol not in protocol_letters:
            protocol = None
        if protocol:
            port = pp.get(protocol)
            if port is None:
                protocol = None
        if not protocol:
            if 's' in pp.keys():
                protocol = 's'
                port = pp.get(protocol)
            else:
                protocol = list(pp.keys())[0]
                port = pp.get(protocol)
        self.server_host.setText(host)
        self.server_port.setText(port)

    def accept(self):
        pass

    def set_server(self):
        net_params = self.network.get_parameters()
        net_params = net_params._replace(host=str(self.server_host.text()),
                                         port=str(self.server_port.text()),
                                         auto_connect=self.autoconnect_cb.isChecked())
        self.network.run_from_another_thread(self.network.set_parameters(net_params))

    def set_proxy(self):
        net_params = self.network.get_parameters()
        if self.proxy_cb.isChecked():
            proxy = { 'mode':str(self.proxy_mode.currentText()).lower(),
                      'host':str(self.proxy_host.text()),
                      'port':str(self.proxy_port.text()),
                      'user':str(self.proxy_user.text()),
                      'password':str(self.proxy_password.text())}
        else:
            proxy = None
            self.tor_cb.setChecked(False)
        net_params = net_params._replace(proxy=proxy)
        self.network.run_from_another_thread(self.network.set_parameters(net_params))

    def suggest_proxy(self, found_proxy):
        if found_proxy is None:
            self.tor_cb.hide()
            return
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if self.proxy_mode.currentIndex() == self.proxy_mode.findText('SOCKS5') \
            and self.proxy_host.text() == "127.0.0.1" \
                and self.proxy_port.text() == str(found_proxy[1]):
            self.tor_cb.setChecked(True)
        self.tor_cb.show()

    def use_tor_proxy(self, use_it):
        if not use_it:
            self.proxy_cb.setChecked(False)
        else:
            socks5_mode_index = self.proxy_mode.findText('SOCKS5')
            if socks5_mode_index == -1:
                print_error("[network_dialog] can't find proxy_mode 'SOCKS5'")
                return
            self.proxy_mode.setCurrentIndex(socks5_mode_index)
            self.proxy_host.setText("127.0.0.1")
            self.proxy_port.setText(str(self.tor_proxy[1]))
            self.proxy_user.setText("")
            self.proxy_password.setText("")
            self.tor_cb.setChecked(True)
            self.proxy_cb.setChecked(True)
        self.check_disable_proxy(use_it)
        self.set_proxy()

    def proxy_settings_changed(self):
        self.tor_cb.setChecked(False)
Exemplo n.º 34
0
class MainUi(QtWidgets.QMainWindow):
    # global maxFlag;
    # maxFlag=True;
    global name
    global image1
    image1 = ["1", "2"]
    global file2
    global ifConnect
    ifConnect = False

    def __init__(self):
        super().__init__()
        self.setFixedSize(960, 720)

        self.main_widget = QtWidgets.QWidget()  # 创建窗口主部件
        self.main_layout = QtWidgets.QGridLayout()  # 创建主部件的网格布局
        self.main_widget.setLayout(self.main_layout)  # 设置窗口主部件布局为网格布局
        self.setCentralWidget(self.main_widget)  # 设置窗口主部件

        # 窗口背景透明
        self.setWindowOpacity(0.9)  # 设置窗口透明度
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 隐藏边框
        self.main_layout.setSpacing(0)  # 去除缝隙
        self.init_left_ui()
        self.init_right_ui()
        self.setWindowIcon(
            QIcon('C:/Users/yuanz/PycharmProjects/untitled1/res/3.jpg'))
        self._bottom_rect = [
            QPoint(x, y) for x in range(1, self.width())
            for y in range(0, 100)
        ]
        # self.init_right_ui()

        # self.left_xxx = QtWidgets.QPushButton(" ")

    '''def maxMin(self):
      global maxFlag
      desktop = QDesktopWidget()
      if(maxFlag)    :
        self.setGeometry(QtCore.QRect(0, 0, desktop.geometry().width(),desktop.geometry().height()))
        self.setFixedSize(QSize( desktop.geometry().width(),desktop.geometry().height()))
        
        maxFlag=False
        print(maxFlag)
      else :
        
        self.setGeometry(QtCore.QRect(desktop.geometry().width()/5,desktop.geometry().height()/5,960, 700))
        self.setFixedSize(QSize( 960, 700))
        maxFlag=True
        print(maxFlag)
'''

    def init_left_ui(self):
        self.left_widget = QtWidgets.QWidget()  # 创建左侧部件
        self.left_widget.setObjectName('left_widget')
        self.left_layout = QtWidgets.QGridLayout()  # 创建左侧部件的网格布局层
        self.left_widget.setLayout(self.left_layout)  # 设置左侧部件布局为网格
        self.main_layout.addWidget(self.left_widget, 0, 0, 12,
                                   2)  # 左侧部件在第0行第0列,占12行2列
        self.left_close = QtWidgets.QPushButton(
            qtawesome.icon('fa.ban', color='gray'), "")  # 关闭按钮
        # self.left_visit = QtWidgets.QPushButton("")  # 空白按钮
        self.left_mini = QtWidgets.QPushButton(
            qtawesome.icon('fa.minus', color='gray'), "")  # 最小化按钮
        self.left_close.clicked.connect(self.close)
        self.left_mini.clicked.connect(self.showMinimized)
        # self.left_visit.clicked.connect(self.maxMin)
        # self.left_visit.clicked.connect(self.showMaximized)
        self.left_label_1 = QtWidgets.QPushButton(
            qtawesome.icon('fa.book', color='white'), "项        目")
        self.left_label_1.setObjectName('left_label')
        self.left_label_1.clicked.connect(self.showmessage2)
        # self.left_label_1.setFont(QFont("Microsoft YaHei"))

        self.left_label_2 = QtWidgets.QPushButton(
            qtawesome.icon('fa.tasks', color='white'), "任        务")
        self.left_label_2.setObjectName('left_label')
        self.left_label_2.clicked.connect(self.showright)
        self.left_label_3 = QtWidgets.QPushButton(
            qtawesome.icon('fa.phone', color='white'), "帮        助")
        self.left_label_3.setObjectName('left_label')
        self.left_label_3.clicked.connect(self.showmessage1)
        self.left_layout.addWidget(self.left_mini, 0, 2, 1, 1)
        self.left_layout.addWidget(self.left_close, 0, 0, 1, 1)
        # self.left_layout.addWidget(self.left_visit, 0, 1, 1, 1)
        self.left_layout.addWidget(self.left_label_1, 1, 0, 1, 3)
        self.left_layout.addWidget(self.left_label_2, 2, 0, 1, 3)
        self.left_layout.addWidget(self.left_label_3, 3, 0, 1, 3)

        #blank
        self.left_button_1 = QLabel("", self)
        #self.left_button_1 = QtWidgets.QPushButton("")
        #self.left_button_1.setObjectName('left_button')
        self.left_button_2 = QLabel("", self)
        self.left_button_3 = QLabel("", self)
        self.left_button_4 = QLabel("", self)
        self.left_button_5 = QLabel("", self)
        self.left_button_6 = QLabel("", self)
        self.left_button_7 = QLabel("", self)
        self.left_button_8 = QLabel("", self)
        self.left_button_9 = QLabel("@betav0.2", self)

        self.left_button_9.setStyleSheet('''
            QLabel{
            border-width:0;
                border-style:outset;
                font-family:"Microsoft YaHei";
                font-size:10px;
                color:white;
            
            }
            ''')

        #空白
        self.left_layout.addWidget(self.left_button_1, 4, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_2, 5, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_3, 6, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_4, 7, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_5, 8, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_6, 9, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_7, 10, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_8, 11, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_9, 12, 0, 1, 3)

        # 左侧按钮
        self.left_close.setFixedSize(16, 16)  # 设置关闭按钮的大小
        # self.left_visit.setFixedSize(15, 15)  # 设置按钮大小
        self.left_mini.setFixedSize(16, 16)  # 设置最小化按钮大小
        self.left_close.setStyleSheet(
            '''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}'''
        )
        # self.left_visit.setStyleSheet(
        # '''QPushButton{background:#F7D674;border-radius:5px;}QPushButton:hover{background:yellow;}''')
        self.left_mini.setStyleSheet(
            '''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}'''
        )

        self.left_label_1.setStyleSheet(  # left1
            '''
            QPushButton{
                font-family:"Microsoft YaHei";
                border:none;
                color:white;
                font-size:15px;
                height:50px;
                padding-left:15px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:LightGray;
            }
        ''')

        self.left_label_2.setStyleSheet(  # left2
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:none;
                color:white;
                font-size:15px;
                height:50px;
                padding-left:15px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:LightGray;
            }
        ''')

        self.left_label_3.setStyleSheet(  # left3
            '''
            QPushButton{
                font-family:"Microsoft YaHei";
                border:none;
                color:white;
                font-size:15px;
                height:50px;
                padding-left:15px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:LightGray;
            }
        ''')

        # 左侧菜单
        self.left_widget.setStyleSheet('''
            QPushButton{border:none;color:white;}
            QPushButton#left_label{
                border:none;
                border-bottom:1px solid white;
                font-size:18px;
                font-weight:700;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            }
            QPushButton#left_button:hover{border-left:4px solid red;font-weight:700;}
            QWidget#left_widget{
                background:gray;
                border-top:1px solid white;
                border-bottom:1px solid white;
                border-left:1px solid white;
                border-top-left-radius:10px;
                border-bottom-left-radius:10px;}
        ''')

    def init_right_ui(self):
        self.right_widget = QtWidgets.QWidget()  # 创建右侧部件
        self.right_widget.setObjectName('right_widget')
        self.right_layout = QtWidgets.QGridLayout()
        self.right_widget.setLayout(self.right_layout)  # 设置右侧部件布局为网格

        self.right_title = QLabel("AIforEye智能辅助诊断系统", self)  #标题
        self.right_layout.addWidget(self.right_title, 1, 0, 1, 9)

        self.right_title.setStyleSheet('''
            QLabel{
                
                border-width:0;
                border-style:outset;
                font-family:"Microsoft YaHei";
                font-size:20px;
                height:50px;
                padding-left:0px;
                padding-right:10px;
                text-align:left;
                
                }
            ''')

        self.main_layout.addWidget(self.right_widget, 0, 2, 12,
                                   10)  # 右侧部件在第0行第3列,占8行9列

        self.open_icon = QtWidgets.QLabel(chr(0xf115) + ' ' + '打开文件  ')
        self.open_icon.setFont(qtawesome.font('fa', 14))
        # self.open_icon.setFont(QFont("Microsoft YaHei"))

        self.right_bar_widget_open_input = QtWidgets.QLineEdit()
        self.right_bar_widget_open_input.setPlaceholderText(
            "点击按钮选择文件或文件夹生成源路径")

        self.right_layout.addWidget(self.open_icon, 4, 0, 1, 1)  # icon
        self.right_layout.addWidget(self.right_bar_widget_open_input, 5, 0, 1,
                                    9)  # 输入栏

        self.id_icon = QtWidgets.QLabel(chr(0xf11c) + ' ' + '填写ID(选填)  ')
        self.id_icon.setFont(qtawesome.font('fa', 14))
        self.right_bar_widget_id_input = QtWidgets.QLineEdit()
        self.right_bar_widget_id_input.setPlaceholderText("请在此填入报告ID")

        self.right_layout.addWidget(self.id_icon, 2, 0, 1, 1)  # icon
        self.right_layout.addWidget(self.right_bar_widget_id_input, 3, 0, 1,
                                    9)  # 输入栏

        # self.right_layout.addWidget(self.right_bar_widget1, 1, 0, 1, 9)  # 合起来

        # 选择文件
        self.right_button_1 = QtWidgets.QPushButton(
            qtawesome.icon('fa.picture-o', color='black'), "选择图片")
        self.right_layout.addWidget(self.right_button_1, 8, 0, 1, 2)
        self.right_button_1.clicked.connect(self.gitfilename)
        # 选择文件夹
        self.right_button_2 = QtWidgets.QPushButton(
            qtawesome.icon('fa.folder', color='black'), "选择文件夹")
        self.right_layout.addWidget(self.right_button_2, 9, 0, 1, 2)
        self.right_button_2.clicked.connect(self.getdirectory)

        # checkbox
        self.rb = QCheckBox('血管分析', self)  # 单选按钮

        # self.rb.toggled.connect(self.setConnect)  # ifConnect 判断是否被选 ,true是被选中
        self.rb.setToolTip("可选择是否进行血管分析")
        self.right_layout.addWidget(self.rb, 6, 0, 1, 2)

        self.rb1 = QtWidgets.QLabel(chr(0xf058) + ' ' + 'DR诊断  ')
        self.rb1.setFont(qtawesome.font('fa', 14))

        # self.rb1 = QCheckBox('DR诊断', self)  # 单选按钮

        # self.rb1.setChecked(True)
        self.rb1.setToolTip("默认进行DR诊断")
        self.right_layout.addWidget(self.rb1, 6, 2, 1, 2)

        # 进度条
        self.pbar = QProgressBar(self)

        self.pbar.setToolTip("任务处理进度条")
        self.right_layout.addWidget(self.pbar, 12, 0, 1, 9)

        # 进度条文字
        txt = ""
        self.proc = QtWidgets.QLabel(chr(0xf110) + ' ' + '任务进度:' + '' + txt)
        self.proc.setFont(qtawesome.font('fa', 12))
        self.right_layout.addWidget(self.proc, 11, 0, 1, 9)

        self.start = QtWidgets.QPushButton(
            qtawesome.icon('fa.play', color='black'), "开始")
        self.right_layout.addWidget(self.start, 10, 0, 1, 2)
        self.start.clicked.connect(self.printl)

        self.right_message2 = QtWidgets.QToolButton()
        # self.right_message2.setText("荣耀征战")
        self.right_message2.setIcon(
            QtGui.QIcon('C:/Users/yuanz/PycharmProjects/untitled1/res/4.jpg'))
        self.right_message2.setIconSize(QtCore.QSize(760, 720))
        # self.right_message2.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.right_layout.addWidget(self.right_message2, 0, 0, 9, 9)

        self.right_message2.setStyleSheet('''
                QToolButton{border:none;}
                QToolButton:hover{border:none;}
            ''')

        self.right_message1 = QLabel(
            "邮箱:[email protected]\n地址:广东省深圳市南山区南方科技大学\n合作单位:中山大学中山眼科中心",
            self)

        self.right_layout.addWidget(self.right_message1, 1, 0, 1, 3)  # 输入栏

        self.right_message1.setStyleSheet('''
                QLabel{
                
                border-width:0;
                border-style:outset;
                font-family:"Microsoft YaHei";
                font-size:20px;
                height:50px;
                padding-left:0px;
                padding-right:10px;
                text-align:left;
                
                }
                
            ''')

        # self.right_message2 = QtWidgets.QTextBrowser()
        # self.right_message2.setText("概况")  # 概况
        # self.right_layout.addWidget(self.right_message2, 0, 0, 1, 9)

        self.right_bar_widget_id_input.setStyleSheet(  # 输入id栏
            '''QLineEdit{
                    font-family:"Microsoft YaHei";
                    border:1px solid gray;
                    width:300px;
                    border-radius:10px;
                    padding:2px 4px;
            }''')

        self.right_bar_widget_open_input.setStyleSheet(  # 选择文件栏
            '''QLineEdit{
            font-family:"Microsoft YaHei";
                    border:1px solid gray;
                    width:300px;
                    border-radius:10px;
                    padding:2px 4px;
            }
                 
            
            ''')

        self.pbar.setStyleSheet(  # 进度条
            '''QProgressBar{ 
            font-family:"Microsoft YaHei";
               border:1px solid gray;
               width:300px;
               border-radius:10px;
               padding:2px 4px;
               text-align: center; 
            }
               QProgressBar::chunk {
               background-color: lavender;
        
    }
            ''')

        self.rb.setStyleSheet(  # 血管分析
            '''
            QCheckBox:unchecked{
            font-family:"Microsoft YaHei";
                
                border:none;
                color:gray;
                
                font-size:14px;
                height:40px;
                padding-left:0px;
                padding-right:10px;
                text-align:left;
            }
            QChecked:checked{
            font-family:"Microsoft YaHei";
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:LightGray;
                
                
            }
        ''')

        self.rb1.setStyleSheet(  # DR
            '''
            QLabel{
                
                border:none;
                color:black;
                
                
                
                
            }
            
        ''')

        self.right_button_1.setStyleSheet(  # 选择图片
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:1px solid #F3F3F5;
                border-radius:10px;
                border:none;
                color:black;
                background:lavender;
                
                font-size:14px;
                height:40px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:gainsboro ;
            }
        ''')
        self.right_button_2.setStyleSheet(  # 选择文件夹
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:1px solid #F3F3F5;
                border-radius:10px;
                color:black;
                background:lavender;
                
                font-size:14px;
                height:40px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:gainsboro ;
            }
        ''')

        self.right_widget.setStyleSheet(  # 右边大框
            '''
            QWidget#right_widget{
            font-family:"Microsoft YaHei";
                color:#232C51;
                background:white;
                border-top:1px solid darkGray;
                border-bottom:1px solid darkGray;
                border-right:1px solid darkGray;
                border-top-right-radius:10px;
                border-bottom-right-radius:10px;
            }
            QLabel#right_lable{
                border:none;
                font-size:16px;
                font-weight:700;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            }
        ''')
        self.start.setStyleSheet(  # 开始任务
            '''
            QPushButton{
            font-family:"Microsoft YaHei";
                border:1px solid #F3F3F5;
                border-radius:10px;
                color:black;
                background:lavender;
                
                font-size:14px;
                height:40px;
                padding-left:10px;
                padding-right:10px;
                text-align:left;
            }
            QPushButton:hover{
                color:black;
                border:1px solid #F3F3F5;
                border-radius:10px;
                background:gainsboro ;
            }
        ''')
        self.right_message1.hide()
        self.right_message2.hide()

    def showmessage1(self):
        self.start.hide()
        self.right_message1.show()
        self.right_message2.hide()
        self.open_icon.hide()
        self.rb1.hide()
        self.rb.hide()
        self.pbar.hide()
        self.id_icon.hide()
        self.right_bar_widget_id_input.hide()
        self.right_bar_widget_open_input.hide()
        self.right_button_1.hide()
        self.right_button_2.hide()
        self.proc.hide()
        self.right_title.hide()

    def showmessage2(self):
        self.start.hide()
        self.right_message2.show()
        self.right_message1.hide()
        self.open_icon.hide()
        self.rb1.hide()
        self.rb.hide()
        self.pbar.hide()
        self.id_icon.hide()
        self.right_bar_widget_id_input.hide()
        self.right_bar_widget_open_input.hide()
        self.right_button_1.hide()
        self.right_button_2.hide()
        self.proc.hide()
        self.right_title.hide()

    def showright(self):
        self.right_message2.hide()
        self.right_message1.hide()
        self.open_icon.show()
        self.rb1.show()
        self.rb.show()
        self.pbar.show()
        self.id_icon.show()
        self.right_bar_widget_id_input.show()
        self.right_bar_widget_open_input.show()
        self.right_button_1.show()
        self.right_button_2.show()
        self.proc.show()
        self.start.show()
        self.right_title.show()

    def printl(self):
        self.pbar.setValue(0)
        global image1

        if image1[0] == "dir":
            filename = QFileDialog.getSaveFileName(self, 'save file', '/')
            print(filename)
            if filename[0] != "":
                self.dirPDF(image1[1], filename[0])
        elif image1[0] == "f":
            filename = QFileDialog.getSaveFileName(self, 'save file', '/',
                                                   '(*.pdf)')
            print(filename)
            if filename[0] != "":
                self.pbar.setValue(100)
                self.pic2pdf(image1[1], filename[0])
        else:
            print("null")

    def dirPDF(self, input_path, output_path):  # 转文件夹
        self.pbar.setValue(0)
        print("start")
        print(input_path)
        print(output_path)
        # 获取输入文件夹中的所有文件/夹,并改变工作空间
        files = os.listdir(input_path)
        os.chdir(input_path)
        # 判断输出文件夹是否存在,不存在则创建
        if (not os.path.exists(output_path)):
            os.makedirs(output_path)
        count = 0
        for file in files:
            if (os.path.isfile(file)):
                count += 1
        now = 0
        for file in files:
            # 判断是否为文件,文件夹不操作
            if (os.path.isfile(file)):
                now += 1
                self.pbar.setValue(now / count * 100)
                # 用.隔开文件名获取图片处理
                point = file.rfind('.')
                rightpart = file[point:]
                leftpart = file[:point]
                print(rightpart)
                if (rightpart == '.jpg' or rightpart == '.png'):
                    #     img = Image.open(file)
                    #     width = int(img.size[0] * 2)
                    #     height = int(img.size[1] * 2)
                    #     img = img.resize((width, height), Image.ANTIALIAS)
                    print(os.path.join(output_path, "New_" + file))
                    #     img.save(os.path.join(output_path, "New_" + file))
                    self.pic2pdf(
                        file,
                        os.path.join(output_path, "New_" + leftpart + ".pdf"))
        self.pbar.setValue(100)

    def pic2pdf(self, img, filePdf):  # 将一张图片转为pdf
        print(1)
        # 读取图片,确保按文件名排序
        print(img)
        imgdoc = Image.open(img)  # 打开图片
        x = imgdoc.size[0]
        y = imgdoc.size[1]
        c = canvas.Canvas(filePdf, [x + 100, y + 100])  # 使用图片创建单页的 PDF
        print(imgdoc.size)
        c.drawImage(img, 50, 0, x, y)
        c.drawString(20, y + 5, filePdf)
        c.showPage()
        c.save()

    def gitfilename(self):
        filename = QFileDialog.getOpenFileName(
            self, "选择文件", "./", "Image (*.jpg);;Image(*.png)")  # 这个地方弹出窗口
        if (filename != ""):
            self.right_bar_widget_open_input.setText(
                self.right_bar_widget_open_input.text() + filename[0])
            global image1
            #  file1+=['ID: '+self.IDmessage.text()]
            image1[0] = "f"
            image1[1] = filename[0]
            print(filename[0])

    def getdirectory(self):
        directory1 = ""
        directory1 = QFileDialog.getExistingDirectory(self, "选取文件夹",
                                                      "./")  # 起始路径
        if (directory1 != ""):
            # print(directory1)
            self.right_bar_widget_open_input.setText(
                self.right_bar_widget_open_input.text() + directory1)
            global image1
            image1[0] = 'dir'
            image1[1] = directory1
            print(image1)

    def mousePressEvent(self, event):
        self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
        self.m_flag = False
        if event.button(
        ) == Qt.LeftButton and self.m_Position in self._bottom_rect:
            self.m_flag = True
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):

        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置

            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):

        self.m_flag = False

        self.setCursor(QCursor(Qt.ArrowCursor))
Exemplo n.º 35
0
class Dialog(QDialog):
    MESSAGE = "<p>Message boxes have a caption, a text, and up to three " \
            "buttons, each with standard or custom texts.</p>" \
            "<p>Click a button to close the message box. Pressing the Esc " \
            "button will activate the detected escape button (if any).</p>"

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.openFilesPath = ''

        self.errorMessageDialog = QErrorMessage(self)

        frameStyle = QFrame.Sunken | QFrame.Panel

        self.integerLabel = QLabel()
        self.integerLabel.setFrameStyle(frameStyle)
        self.integerButton = QPushButton("QInputDialog.get&Int()")

        self.doubleLabel = QLabel()
        self.doubleLabel.setFrameStyle(frameStyle)
        self.doubleButton = QPushButton("QInputDialog.get&Double()")

        self.itemLabel = QLabel()
        self.itemLabel.setFrameStyle(frameStyle)
        self.itemButton = QPushButton("QInputDialog.getIte&m()")

        self.textLabel = QLabel()
        self.textLabel.setFrameStyle(frameStyle)
        self.textButton = QPushButton("QInputDialog.get&Text()")

        self.colorLabel = QLabel()
        self.colorLabel.setFrameStyle(frameStyle)
        self.colorButton = QPushButton("QColorDialog.get&Color()")

        self.fontLabel = QLabel()
        self.fontLabel.setFrameStyle(frameStyle)
        self.fontButton = QPushButton("QFontDialog.get&Font()")

        self.directoryLabel = QLabel()
        self.directoryLabel.setFrameStyle(frameStyle)
        self.directoryButton = QPushButton("QFileDialog.getE&xistingDirectory()")

        self.openFileNameLabel = QLabel()
        self.openFileNameLabel.setFrameStyle(frameStyle)
        self.openFileNameButton = QPushButton("QFileDialog.get&OpenFileName()")

        self.openFileNamesLabel = QLabel()
        self.openFileNamesLabel.setFrameStyle(frameStyle)
        self.openFileNamesButton = QPushButton("QFileDialog.&getOpenFileNames()")

        self.saveFileNameLabel = QLabel()
        self.saveFileNameLabel.setFrameStyle(frameStyle)
        self.saveFileNameButton = QPushButton("QFileDialog.get&SaveFileName()")

        self.criticalLabel = QLabel()
        self.criticalLabel.setFrameStyle(frameStyle)
        self.criticalButton = QPushButton("QMessageBox.critica&l()")

        self.informationLabel = QLabel()
        self.informationLabel.setFrameStyle(frameStyle)
        self.informationButton = QPushButton("QMessageBox.i&nformation()")

        self.questionLabel = QLabel()
        self.questionLabel.setFrameStyle(frameStyle)
        self.questionButton = QPushButton("QMessageBox.&question()")

        self.warningLabel = QLabel()
        self.warningLabel.setFrameStyle(frameStyle)
        self.warningButton = QPushButton("QMessageBox.&warning()")

        self.errorLabel = QLabel()
        self.errorLabel.setFrameStyle(frameStyle)
        self.errorButton = QPushButton("QErrorMessage.show&M&essage()")

        self.integerButton.clicked.connect(self.setInteger)
        self.doubleButton.clicked.connect(self.setDouble)
        self.itemButton.clicked.connect(self.setItem)
        self.textButton.clicked.connect(self.setText)
        self.colorButton.clicked.connect(self.setColor)
        self.fontButton.clicked.connect(self.setFont)
        self.directoryButton.clicked.connect(self.setExistingDirectory)
        self.openFileNameButton.clicked.connect(self.setOpenFileName)
        self.openFileNamesButton.clicked.connect(self.setOpenFileNames)
        self.saveFileNameButton.clicked.connect(self.setSaveFileName)
        self.criticalButton.clicked.connect(self.criticalMessage)
        self.informationButton.clicked.connect(self.informationMessage)
        self.questionButton.clicked.connect(self.questionMessage)
        self.warningButton.clicked.connect(self.warningMessage)
        self.errorButton.clicked.connect(self.errorMessage)

        self.native = QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)
        layout.addWidget(self.integerButton, 0, 0)
        layout.addWidget(self.integerLabel, 0, 1)
        layout.addWidget(self.doubleButton, 1, 0)
        layout.addWidget(self.doubleLabel, 1, 1)
        layout.addWidget(self.itemButton, 2, 0)
        layout.addWidget(self.itemLabel, 2, 1)
        layout.addWidget(self.textButton, 3, 0)
        layout.addWidget(self.textLabel, 3, 1)
        layout.addWidget(self.colorButton, 4, 0)
        layout.addWidget(self.colorLabel, 4, 1)
        layout.addWidget(self.fontButton, 5, 0)
        layout.addWidget(self.fontLabel, 5, 1)
        layout.addWidget(self.directoryButton, 6, 0)
        layout.addWidget(self.directoryLabel, 6, 1)
        layout.addWidget(self.openFileNameButton, 7, 0)
        layout.addWidget(self.openFileNameLabel, 7, 1)
        layout.addWidget(self.openFileNamesButton, 8, 0)
        layout.addWidget(self.openFileNamesLabel, 8, 1)
        layout.addWidget(self.saveFileNameButton, 9, 0)
        layout.addWidget(self.saveFileNameLabel, 9, 1)
        layout.addWidget(self.criticalButton, 10, 0)
        layout.addWidget(self.criticalLabel, 10, 1)
        layout.addWidget(self.informationButton, 11, 0)
        layout.addWidget(self.informationLabel, 11, 1)
        layout.addWidget(self.questionButton, 12, 0)
        layout.addWidget(self.questionLabel, 12, 1)
        layout.addWidget(self.warningButton, 13, 0)
        layout.addWidget(self.warningLabel, 13, 1)
        layout.addWidget(self.errorButton, 14, 0)
        layout.addWidget(self.errorLabel, 14, 1)
        layout.addWidget(self.native, 15, 0)
        self.setLayout(layout)

        self.setWindowTitle("Standard Dialogs")

    def setInteger(self):    
        i, ok = QInputDialog.getInt(self, "QInputDialog.getInt()",
                "Percentage:", 25, 0, 100, 1)
        if ok:
            self.integerLabel.setText("%d%%" % i)

    def setDouble(self):    
        d, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()",
                "Amount:", 37.56, -10000, 10000, 2)
        if ok:
            self.doubleLabel.setText("$%g" % d)

    def setItem(self):    
        items = ("Spring", "Summer", "Fall", "Winter")

        item, ok = QInputDialog.getItem(self, "QInputDialog.getItem()",
                "Season:", items, 0, False)
        if ok and item:
            self.itemLabel.setText(item)

    def setText(self):
        text, ok = QInputDialog.getText(self, "QInputDialog.getText()",
                "User name:", QLineEdit.Normal, QDir.home().dirName())
        if ok and text != '':
            self.textLabel.setText(text)

    def setColor(self):    
        color = QColorDialog.getColor(Qt.green, self)
        if color.isValid(): 
            self.colorLabel.setText(color.name())
            self.colorLabel.setPalette(QPalette(color))
            self.colorLabel.setAutoFillBackground(True)

    def setFont(self):    
        font, ok = QFontDialog.getFont(QFont(self.fontLabel.text()), self)
        if ok:
            self.fontLabel.setText(font.key())
            self.fontLabel.setFont(font)

    def setExistingDirectory(self):    
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        directory = QFileDialog.getExistingDirectory(self,
                "QFileDialog.getExistingDirectory()",
                self.directoryLabel.text(), options=options)
        if directory:
            self.directoryLabel.setText(directory)

    def setOpenFileName(self):    
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,
                "QFileDialog.getOpenFileName()", self.openFileNameLabel.text(),
                "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            self.openFileNameLabel.setText(fileName)

    def setOpenFileNames(self):    
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(self,
                "QFileDialog.getOpenFileNames()", self.openFilesPath,
                "All Files (*);;Text Files (*.txt)", options=options)
        if files:
            self.openFilesPath = files[0]
            self.openFileNamesLabel.setText("[%s]" % ', '.join(files))

    def setSaveFileName(self):    
        options = QFileDialog.Options()
        if not self.native.isChecked():
            options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(self,
                "QFileDialog.getSaveFileName()",
                self.saveFileNameLabel.text(),
                "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            self.saveFileNameLabel.setText(fileName)

    def criticalMessage(self):    
        reply = QMessageBox.critical(self, "QMessageBox.critical()",
                Dialog.MESSAGE,
                QMessageBox.Abort | QMessageBox.Retry | QMessageBox.Ignore)
        if reply == QMessageBox.Abort:
            self.criticalLabel.setText("Abort")
        elif reply == QMessageBox.Retry:
            self.criticalLabel.setText("Retry")
        else:
            self.criticalLabel.setText("Ignore")

    def informationMessage(self):    
        reply = QMessageBox.information(self,
                "QMessageBox.information()", Dialog.MESSAGE)
        if reply == QMessageBox.Ok:
            self.informationLabel.setText("OK")
        else:
            self.informationLabel.setText("Escape")

    def questionMessage(self):    
        reply = QMessageBox.question(self, "QMessageBox.question()",
                Dialog.MESSAGE,
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
        if reply == QMessageBox.Yes:
            self.questionLabel.setText("Yes")
        elif reply == QMessageBox.No:
            self.questionLabel.setText("No")
        else:
            self.questionLabel.setText("Cancel")

    def warningMessage(self):    
        msgBox = QMessageBox(QMessageBox.Warning, "QMessageBox.warning()",
                Dialog.MESSAGE, QMessageBox.NoButton, self)
        msgBox.addButton("Save &Again", QMessageBox.AcceptRole)
        msgBox.addButton("&Continue", QMessageBox.RejectRole)
        if msgBox.exec_() == QMessageBox.AcceptRole:
            self.warningLabel.setText("Save Again")
        else:
            self.warningLabel.setText("Continue")

    def errorMessage(self):    
        self.errorMessageDialog.showMessage("This dialog shows and remembers "
                "error messages. If the checkbox is checked (as it is by "
                "default), the shown message will be shown again, but if the "
                "user unchecks the box the message will not appear again if "
                "QErrorMessage.showMessage() is called with the same message.")
        self.errorLabel.setText("If the box is unchecked, the message won't "
                "appear again.")
Exemplo n.º 36
0
class theMainWindow(QMainWindow):
    keyPressed = pyqtSignal(QEvent)

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

        self.smallAsteroidPixMap = QPixmap('./images/asteroid1.png').scaled(
            smallAsteroidSize, smallAsteroidSize, Qt.IgnoreAspectRatio)
        self.mediumAsteroidPixMap = QPixmap('./images/asteroid1.png').scaled(
            mediumAsteroidSize, mediumAsteroidSize, Qt.IgnoreAspectRatio)
        self.bigAsteroidPixMap = QPixmap('./images/asteroid1.png').scaled(
            bigAsteroidSize, bigAsteroidSize, Qt.IgnoreAspectRatio)
        self.goldAsteroidPixmap = QPixmap('./images/gold_asteroid.png').scaled(
            bigAsteroidSize, bigAsteroidSize, Qt.IgnoreAspectRatio)

        self.asteroidCount = 1

        self.initUI()

    def initUI(self):
        self.mode = "INITIATING"
        self.setGeometry(200, 200, 750, 750)
        background = QImage("./images/start_page.webp")
        background = background.scaled(QSize(750, 750))

        self.scoreLabel = [
            QLabel('', self),
            QLabel('', self),
            QLabel('', self),
            QLabel('', self)
        ]

        #self.scoreLabel.setGeometry(10, 10, 200, 50);
        #self.scoreLabel.setStyleSheet("font: 20pt Times new roman; color: green");
        #self.scoreLabel.hide()
        self.numberOfPlayers = 0
        self.points = 0
        self.currentLevel = 0

        palette = QPalette()
        palette.setBrush(QPalette.Window, QBrush(background))
        self.setPalette(palette)
        self.labelPlayers = QLabel("Players", self)
        self.labelPlayers.move(320, 250)
        self.labelPlayers.setFont(QFont("Times new roman", 25))
        self.labelPlayers.setFixedSize(300, 200)
        self.labelPlayers.setStyleSheet("color:white")
        self.inputNumbers = QLineEdit(self)
        self.inputNumbers.setGeometry(450, 345, 25, 20)
        self.rect = QRect(300, 250, 200, 300)
        self.startButton = QPushButton("Start", self)
        self.startButton.setGeometry(305, 490, 190, 50)
        self.startButton.clicked.connect(self.setPlayers)
        self.tournamentTick = QCheckBox("", self)
        self.tournamentTick.setGeometry(450, 370, 100, 100)
        self.tournamentLabel = QLabel("Tournament", self)
        self.tournamentLabel.move(320, 400)
        self.tournamentLabel.setFixedSize(125, 35)
        self.tournamentLabel.setFont(QFont("Times new roman", 18))
        self.tournamentLabel.setStyleSheet("color:white")
        self.tournament = False

        self.livesLabel = [
            QLabel("Player 1: ", self),
            QLabel("Player 2: ", self),
            QLabel("Player 3: ", self),
            QLabel("Player 4: ", self)
        ]
        i = 0
        colors = ['red', 'green', 'yellow', 'magenta']
        colorNum = 0
        for label in self.livesLabel:
            label.setGeometry(580, 10 + i, 200, 50)
            label.setStyleSheet("font: 20pt Times new roman; color:" +
                                colors[colorNum])
            colorNum += 1
            i += 30
            label.hide()

        self.lifeBox = []

        self.show()

    def createBonusAsteroid(self):
        randomDirection = randint(0, 1)
        posX = randrange(1, 750)
        posY = randrange(1, 750)

        x = 200
        y = 200
        goldAsteroid = Asteroid(3, posX, posY, 3, randomDirection)
        goldAsteroid.points = 300
        golAsteroidLabel = QLabel(self)
        golAsteroidLabel.setPixmap(self.goldAsteroidPixmap)
        goldAsteroid.whatSizeAmI = 'BIG'
        golAsteroidLabel.setGeometry(posX, posY, 100, 100)

        asteroids.append(goldAsteroid)
        asteroidLabels.append(golAsteroidLabel)

        self.showAsteroids()

    def showAllLives(self):
        i = 1

        pixmaps = [
            QPixmap("./images/lives/redLife.png").scaled(20, 20),
            QPixmap("./images/lives/greenLife.png").scaled(20, 20),
            QPixmap("./images/lives/yellowLife.png").scaled(20, 20),
            QPixmap("./images/lives/magentaLife.png").scaled(20, 20)
        ]

        if (self.lifeBox.__len__() > 0):
            for box in self.lifeBox:
                box.hide()

        for num in range(self.numberOfPlayers):
            self.livesLabel[num].setText("Player " + i.__str__() + ": ")
            for j in range(spaceShip[i - 1].lives):
                self.lifeBox[j + (num * 3)].setPixmap(pixmaps[i - 1])
                self.lifeBox[j + (num * 3)].setGeometry(
                    680 + (j * 20), 25 + (i - 1) * 30, 20, 20)
                self.lifeBox[j + (num * 3)].show()

            i += 1

            if self.livesLabel[num].isHidden():
                self.livesLabel[num].show()

    def setPlayers(self):
        if (self.inputNumbers.text() == '1' or self.inputNumbers.text() == '2'
                or self.inputNumbers.text() == '3' or self.inputNumbers.text()
                == '4') or self.tournamentTick.isChecked() == True:
            self.startAsteroids()
            #self.startBonus()

            if self.tournamentTick.isChecked():
                self.numberOfPlayers = 4
            else:
                self.numberOfPlayers = self.inputNumbers.text()
                self.numberOfPlayers = int(self.numberOfPlayers)

            self.asteroidCountLabel = QLabel(
                'Alive Count: ' + str(self.aliveAsteroidsCount()), self)
            self.asteroidCountLabel.setGeometry(10, 70, 200, 50)
            self.asteroidCountLabel.setStyleSheet(
                "font: 20pt Times new roman; color: green")
            self.asteroidCountLabel.show()

            self.levelCountLabel = QLabel('', self)
            self.levelCountLabel.setGeometry(10, 100, 200, 50)
            self.levelCountLabel.setStyleSheet(
                "font: 20pt Times new roman; color: green")
            self.levelCountLabel.show()

            self.startGame()
            self.rect.setHeight(0)
            self.rect.setWidth(0)
            self.startButton.hide()
            self.labelPlayers.hide()
            self.inputNumbers.focusWidget().clearFocus()
            self.inputNumbers.hide()
            self.tournamentLabel.hide()
            self.tournamentTick.hide()
            self.showScore()
            self.tournamentTick.focusWidget().clearFocus()
            if self.tournamentTick.isChecked():
                self.tournament = True
                self.ucesnik1Index = self.generateRandomNumber([-1])
                self.ucesnik2Index = self.generateRandomNumber(
                    [self.ucesnik1Index])
                spaceShip[
                    self.ucesnik1Index].tournamentPlaying = PLAY_WAIT.PLAY
                spaceShip[
                    self.ucesnik2Index].tournamentPlaying = PLAY_WAIT.PLAY

                for i in range(spaceShip.__len__()):
                    if (i != self.ucesnik1Index and i != self.ucesnik2Index):
                        spaceShip[i].tournamentPlaying = PLAY_WAIT.WAIT
            else:
                self.tournament = False

            numOfLives = 3
            for i in range(self.numberOfPlayers):
                self.scoreLabel[i].show()
                for j in range(numOfLives):
                    self.lifeBox.append(QLabel(self))

            self.showAllLives()
            self.repaint()

    def generateRandomNumber(self, number):
        exclude = number
        randomNum = randint(0, 3)
        return self.generateRandomNumber(
            number) if randomNum in exclude else randomNum

    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        lock = RLock()
        if self.tournament == False:
            for i in range(int(self.numberOfPlayers)):
                lock.acquire()
                if (spaceShip[i].lives > 0):
                    if (spaceShip[i].isDead == False):
                        qp.setPen(spaceShip[i].color)
                        qp.drawLine(spaceShip[i].points[0],
                                    spaceShip[i].points[1])
                        qp.drawLine(spaceShip[i].points[1],
                                    spaceShip[i].points[2])
                        qp.drawLine(spaceShip[i].points[2],
                                    spaceShip[i].points[3])
                        qp.drawLine(spaceShip[i].points[3],
                                    spaceShip[i].points[0])
                        qp.drawLine(spaceShip[i].points[2],
                                    spaceShip[i].points[0])
                        qp.setPen(QPen(spaceShip[i].colorOfProjectile))
                        qp.setBrush(QBrush(spaceShip[i].colorOfProjectile))
                        qp.drawEllipse(spaceShip[i].projectile, 5, 5)
                elif (spaceShip[i].isDead == False):
                    spaceShip[i].isDead = True
                    spaceShip[i].x = None
                    spaceShip[i].y = None
                lock.release()
        else:
            for i in range(int(self.numberOfPlayers)):

                if (spaceShip[i].tournamentPlaying == PLAY_WAIT.PLAY
                        and spaceShip[i].lives > 0):
                    qp.setPen(spaceShip[i].color)
                    qp.drawLine(spaceShip[i].points[0], spaceShip[i].points[1])
                    qp.drawLine(spaceShip[i].points[1], spaceShip[i].points[2])
                    qp.drawLine(spaceShip[i].points[2], spaceShip[i].points[3])
                    qp.drawLine(spaceShip[i].points[3], spaceShip[i].points[0])
                    qp.drawLine(spaceShip[i].points[2], spaceShip[i].points[0])
                    qp.setPen(QPen(spaceShip[i].colorOfProjectile))
                    qp.setBrush(QBrush(spaceShip[i].colorOfProjectile))
                    qp.drawEllipse(spaceShip[i].projectile, 5, 5)

        qp.setBrush(QBrush(Qt.black))
        qp.drawRect(self.rect)

    def startGame(self):
        self.mode = "PLAYING"
        if (self.numberOfPlayers == '1'):
            del spaceShip[-1]
        background = QImage("./images/space.jpg")
        background = background.scaled(750, 750)
        palette = QPalette()
        palette.setBrush(QPalette.Window, QBrush(background))
        self.setPalette(palette)

        #OVDE se pokrece checkIfDead !!!
        check = Thread(target=self.checkIfDead, args=())
        check.start()

        self.repaint()

    def moveIt(self):
        for x in range(10):
            spaceShip.move()
            self.repaint()

    def rotate_spaceShip(self, angle, spaceShip):
        i = 0
        for point in spaceShip.points:
            (x, y) = spaceShip.rotate_point(point, angle, MOVE_ROTATE.ROTATE,
                                            (spaceShip.x, spaceShip.y))
            spaceShip.points[i] = QPointF(x, y)
            i += 1
        (vecX, vecY) = spaceShip.rotate(spaceShip.vector, angle)
        spaceShip.vector.setX(vecX)
        spaceShip.vector.setY(vecY)

        return spaceShip

    def puppetShow(self):

        if Qt.Key_Up in theKeys and self.mode == "PLAYING" and spaceShip[
                0].isDead == False and spaceShip[
                    0].tournamentPlaying != PLAY_WAIT.WAIT:
            # moving = multiprocessing.Process(target=self.spaceShip[0].move(),args=());
            # moving.start()

            spaceShip[0].move()

            self.repaint()

        if Qt.Key_W in theKeys and self.mode == "PLAYING" and int(
                self.numberOfPlayers
        ) > 1 and spaceShip[1].isDead == False and spaceShip[
                1].tournamentPlaying != PLAY_WAIT.WAIT:
            # moving = multiprocessing.Process(target=self.spaceShip[0].move(), args=());
            # moving.start()

            spaceShip[1].move()

            self.repaint()
        if Qt.Key_I in theKeys and self.mode == "PLAYING" and int(
                self.numberOfPlayers
        ) > 2 and spaceShip[2].isDead == False and spaceShip[
                2].tournamentPlaying != PLAY_WAIT.WAIT:
            # moving = multiprocessing.Process(target=self.spaceShip[0].move(), args=());
            # moving.start()
            spaceShip[2].move()
            self.repaint()
        if Qt.Key_8 in theKeys and self.mode == "PLAYING" and int(
                self.numberOfPlayers
        ) > 3 and spaceShip[3].isDead == False and spaceShip[
                3].tournamentPlaying != PLAY_WAIT.WAIT:
            # moving = multiprocessing.Process(target=self.spaceShip[0].move(), args=());
            # moving.start()
            spaceShip[3].move()
            self.repaint()
        if (Qt.Key_Left in theKeys and self.mode == "PLAYING"
                and spaceShip[0].tournamentPlaying != PLAY_WAIT.WAIT) or (
                    Qt.Key_Right in theKeys and self.mode == "PLAYING"
                    and spaceShip[0].isDead == False
                    and spaceShip[0].tournamentPlaying != PLAY_WAIT.WAIT):
            angle = 0
            if (Qt.Key_Left in theKeys):
                angle = -10
            else:
                angle = 10

            spaceShip[0] = self.rotate_spaceShip(angle, spaceShip=spaceShip[0])

            self.repaint()
        if ((Qt.Key_A in theKeys and self.mode == "PLAYING"
             and spaceShip[1].tournamentPlaying != PLAY_WAIT.WAIT) or
            (Qt.Key_D in theKeys and self.mode == "PLAYING"
             and spaceShip[1].tournamentPlaying != PLAY_WAIT.WAIT)) and int(
                 self.numberOfPlayers) > 1 and spaceShip[1].isDead == False:
            angle = 0
            if (Qt.Key_A in theKeys):
                angle = -10
            else:
                angle = 10
            spaceShip[1] = self.rotate_spaceShip(angle, spaceShip=spaceShip[1])

            self.repaint()
        if ((Qt.Key_J in theKeys and self.mode == "PLAYING"
             and spaceShip[2].tournamentPlaying != PLAY_WAIT.WAIT) or
            (Qt.Key_L in theKeys and self.mode == "PLAYING"
             and spaceShip[2].tournamentPlaying != PLAY_WAIT.WAIT)) and int(
                 self.numberOfPlayers) > 2 and spaceShip[2].isDead == False:
            angle = 0
            if (Qt.Key_J in theKeys):
                angle = -10
            else:
                angle = 10
            spaceShip[2] = self.rotate_spaceShip(angle, spaceShip=spaceShip[2])

            self.repaint()
        if ((Qt.Key_4 in theKeys and self.mode == "PLAYING"
             and spaceShip[3].tournamentPlaying != PLAY_WAIT.WAIT) or
            (Qt.Key_6 in theKeys and self.mode == "PLAYING"
             and spaceShip[3].tournamentPlaying != PLAY_WAIT.WAIT)) and int(
                 self.numberOfPlayers) > 3 and spaceShip[3].isDead == False:
            angle = 0
            if (Qt.Key_4 in theKeys):
                angle = -10
            else:
                angle = 10
            spaceShip[3] = self.rotate_spaceShip(angle, spaceShip=spaceShip[3])

            self.repaint()
        if (Qt.Key_NumLock in theKeys
                and spaceShip[0].tournamentPlaying != PLAY_WAIT.WAIT):
            l = RLock()
            l.acquire()
            que = queue.Queue()
            t = Thread(target=self.shoot, args=(spaceShip[0], que))
            t.start()
            t.join()
            l.release()

        if (Qt.Key_Space in theKeys and int(self.numberOfPlayers) > 1
                and spaceShip[1].tournamentPlaying != PLAY_WAIT.WAIT):
            l = RLock()
            l.acquire()
            que = queue.Queue()
            t = Thread(target=self.shoot, args=(spaceShip[1], que))
            t.start()
            t.join()
            l.release()

        if (Qt.Key_Delete in theKeys and int(self.numberOfPlayers) > 2
                and spaceShip[2].tournamentPlaying != PLAY_WAIT.WAIT):
            l = RLock()
            l.acquire()
            que = queue.Queue()
            t = Thread(target=self.shoot, args=(spaceShip[2], que))
            t.start()
            t.join()
            l.release()

        if (Qt.Key_Plus in theKeys and int(self.numberOfPlayers) > 3
                and spaceShip[3].tournamentPlaying != PLAY_WAIT.WAIT):
            l = RLock()
            l.acquire()
            que = queue.Queue()
            t = Thread(target=self.shoot, args=(spaceShip[3], que))
            t.start()
            t.join()
            l.release()

    def keyPressEvent(self, e):
        lock = RLock()
        if self.mode == "PLAYING":
            lock.acquire()
            theKeys.add(e.key())
            t = Thread(target=self.puppetShow, args=())
            t.start()
            t.join()
            lock.release()

    def keyReleaseEvent(self, e):
        lock = RLock()
        if (self.mode == "PLAYING"):
            if (theKeys.__contains__(e.key())):
                lock.acquire()
                theKeys.remove(e.key())
                lock.release()

    def shoot(self, ship, queue):
        ship.colorOfProjectile = ship.color
        ship.projectile = QPointF(ship.points[0])
        lock = RLock()
        while ((ship.projectile.x() < 760 and ship.projectile.x() > -10)
               and (ship.projectile.y() < 760 and ship.projectile.y() > -10)):
            ship.projectile.setX(ship.projectile.x() +
                                 ship.vector.x() * ship.velocity)
            ship.projectile.setY(ship.projectile.y() +
                                 ship.vector.y() * ship.velocity)
            for i in range(len(asteroids)):
                if (asteroids[i] != 'DESTROYED' and
                    (ship.projectile.x() >= asteroids[i].theMiddleX -
                     (asteroids[i].posMaxX - asteroids[i].posMinX)
                     and ship.projectile.x() <= asteroids[i].theMiddleX +
                     (asteroids[i].posMaxX - asteroids[i].posMinX))
                        and (ship.projectile.y() >= asteroids[i].theMiddleY -
                             (asteroids[i].posMaxY - asteroids[i].posMinY)
                             and ship.projectile.y() <= asteroids[i].posMaxY +
                             (asteroids[i].posMaxY - asteroids[i].posMinY))):
                    ship.reloadProjectile()
                    self.destroyAsteroid(asteroids[i], ship)
                    self.repaint()
                    queue.put(ship)
                    return ship
            self.repaint()
        ship.reloadProjectile()
        queue.put(ship)
        return ship

    def checkIfDead(self):
        found = False
        lock = RLock()
        while True:
            time.sleep(0.07)
            for num in range(self.numberOfPlayers):

                found = False
                if (spaceShip[num].isDead == False):
                    for point in spaceShip[num].points:
                        for i in range(len(asteroids)):
                            if (asteroids[i] != 'DESTROYED'
                                    and asteroids[i].isHidden == False
                                    and point.x() <= asteroids[i].posMaxX
                                    and point.x() >= asteroids[i].posMinX
                                    and point.y() >= asteroids[i].posMinY
                                    and point.y() <= asteroids[i].posMaxY
                                    and spaceShip[num].justSpawnedTimer == 0):
                                spaceShip[num].die()
                                lock.acquire()
                                self.showAllLives()
                                self.repaint()
                                lock.release()
                                spaceShip[num].justSpawnedTimer = 5
                                t = Thread(target=spaceShip[num].
                                           countDownSpawnedTimer(),
                                           args=())
                                t.start()
                                t.join()
                                print("preziveo repaint")
                                found = True
                                break

                        if found:
                            break

    def startAsteroids(self):
        #self.createAsteroids()
        self.thread = AsteroidsThread()
        self.thread.signal.connect(self.update)
        self.thread.start()

    def startBonus(self):
        self.bonusThread = BonusAsteroidThread()
        self.bonusThread.signal.connect(self.createBonusAsteroid)
        self.bonusThread.start()

    def update(self):
        self.asteroidCountLabel.setText('Alive: ' +
                                        str(self.aliveAsteroidsCount()))
        self.createAsteroids()

        for l in asteroidLabels:
            if l != 'DESTROYED':
                l.hide()

        for i in range(len(asteroids)):
            if asteroids[i] != 'DESTROYED':
                if asteroids[i].isHidden == False:
                    if asteroids[i].posX > self.frameGeometry().height():
                        asteroids[i].posX = 0
                    elif asteroids[i].posX <= 0:
                        asteroids[i].posX = 750
                    if asteroids[i].posY > self.frameGeometry().width():
                        asteroids[i].posY = 0
                    elif asteroids[i].posY <= 0:
                        asteroids[i].posY = 750
                    asteroidLabels[i].setGeometry(asteroids[i].posX,
                                                  asteroids[i].posY, 100, 100)
                    asteroidLabels[i].show()

    def createAsteroids(self):
        if self.aliveAsteroidsCount() == 0:
            self.currentLevel += 1
            self.levelCountLabel.setText('Level: ' + str(self.currentLevel))

            #Na svakom nivou ima 2 vise asteroida
            self.asteroidCount += 20

            for i in range(self.asteroidCount):
                randomDirection = randint(0, 1)
                posX = randrange(1, 750)
                posY = randrange(1, 750)
                size = randrange(1, 4)
                asteroid = Asteroid(size, posX, posY, 3, randomDirection)

                lab = QLabel(self)

                if size == 1:
                    lab.setPixmap(self.smallAsteroidPixMap)
                    asteroid.whatSizeAmI = 'SMALL'
                elif size == 2:
                    lab.setPixmap(self.mediumAsteroidPixMap)
                    asteroid.whatSizeAmI = 'MEDIUM'
                    a = Asteroid(1, 1, 1, 3, 0)
                    a.whatSizeAmI = 'SMALL'
                    a.isHidden = True
                    a.wasHidden = True
                    a1 = Asteroid(1, 2, 2, 3, 1)
                    a1.whatSizeAmI = 'SMALL'
                    a1.wasHidden = True
                    a1.isHidden = True
                    asteroids.append(a)
                    asteroids.append(a1)
                    l = QLabel(self)
                    l.setPixmap(self.smallAsteroidPixMap)
                    l1 = QLabel(self)
                    l1.setPixmap(self.smallAsteroidPixMap)
                    asteroidLabels.append(l)
                    asteroidLabels.append(l1)
                else:
                    lab.setPixmap(self.bigAsteroidPixMap)
                    asteroid.whatSizeAmI = 'BIG'
                    a = Asteroid(2, 3, 3, 3, 0)
                    a.whatSizeAmI = 'MEDIUM'
                    a.isHidden = True
                    a.wasHidden = True
                    a1 = Asteroid(2, 4, 4, 3, 1)
                    a1.whatSizeAmI = 'MEDIUM'
                    a1.wasHidden = True
                    a1.isHidden = True
                    asteroids.append(a)
                    asteroids.append(a1)
                    l = QLabel(self)
                    l.setPixmap(self.mediumAsteroidPixMap)
                    l1 = QLabel(self)
                    l1.setPixmap(self.mediumAsteroidPixMap)
                    asteroidLabels.append(l)
                    asteroidLabels.append(l1)

                lab.setGeometry(asteroid.posX, asteroid.posY, 100, 100)
                asteroids.append(asteroid)
                asteroidLabels.append(lab)

            self.showAsteroids()

    def showAsteroids(self):
        for i in range(len(asteroidLabels)):
            if asteroidLabels[i] != 'DESTROYED':
                if asteroids[i].isHidden == False:
                    asteroidLabels[i].show()

    def showScore(self):
        i = 1
        colors = ['red', 'green', 'yellow', 'magenta']
        for num in range(self.numberOfPlayers):
            self.scoreLabel[num].hide()
            self.scoreLabel[num].setText("Score(Player " + i.__str__() +
                                         "): " +
                                         spaceShip[num].score.__str__())
            self.scoreLabel[num].setGeometry(20, 20 + (num * 30), 300, 30)
            self.scoreLabel[num].setStyleSheet(
                "font: 20pt Times new roman; color:" + colors[num])
            self.scoreLabel[num].show()
            i += 1

    def destroyAsteroid(self, asteroid, ship):
        asteroidIndex = asteroids.index(asteroid)
        ship.score += asteroid.points
        self.showScore()

        if asteroid.size == 1:
            asteroids[asteroidIndex] = 'DESTROYED'
            asteroidLabels[asteroidIndex].hide()
            asteroidLabels[asteroidIndex] = 'DESTROYED'
            print('Small asteroid has been destroyed')
        elif asteroid.size == 2 and asteroid.wasHidden == False:
            if asteroids[asteroidIndex - 2] != 'DESTROYED':
                asteroids[asteroidIndex - 2].isHidden = False
                asteroids[asteroidIndex - 2].posX = asteroid.posX
                asteroids[asteroidIndex - 2].posY = asteroid.posY
            if asteroids[asteroidIndex - 1] != 'DESTROYED':
                asteroids[asteroidIndex - 1].isHidden = False
                asteroids[asteroidIndex - 1].posX = asteroid.posX
                asteroids[asteroidIndex - 1].posY = asteroid.posY

            asteroids[asteroidIndex] = 'DESTROYED'
            asteroidLabels[asteroidIndex].hide()
            asteroidLabels[asteroidIndex] = 'DESTROYED'
            print('Medium asteroid has been destroyed')
        elif asteroid.size == 2 and asteroid.wasHidden:
            asteroids[asteroidIndex] = 'DESTROYED'
            asteroidLabels[asteroidIndex].hide()
            asteroidLabels[asteroidIndex] = 'DESTROYED'
            print('Medium asteroid has been destroyed')
        elif asteroid.size == 3 and asteroid.points != 300 and asteroid.wasHidden:
            asteroids[asteroidIndex] = 'DESTROYED'
            asteroidLabels[asteroidIndex].hide()
            asteroidLabels[asteroidIndex] = 'DESTROYED'

        elif asteroid.size == 3 and asteroid.points != 300 and asteroid.wasHidden == False:
            if asteroids[asteroidIndex - 2] != 'DESTROYED':
                asteroids[asteroidIndex - 2].isHidden = False
                asteroids[asteroidIndex - 2].posX = asteroid.posX
                asteroids[asteroidIndex - 2].posY = asteroid.posY
            if asteroids[asteroidIndex - 1] != 'DESTROYED':
                asteroids[asteroidIndex - 1].isHidden = False
                asteroids[asteroidIndex - 1].posX = asteroid.posX
                asteroids[asteroidIndex - 1].posY = asteroid.posY

            asteroids[asteroidIndex] = 'DESTROYED'
            asteroidLabels[asteroidIndex].hide()
            asteroidLabels[asteroidIndex] = 'DESTROYED'

            print('Big asteroid has been destroyed')
        elif asteroid.size == 3 and asteroid.points == 300:
            asteroids[asteroidIndex] = 'DESTROYED'
            asteroidLabels[asteroidIndex].hide()
            asteroidLabels[asteroidIndex] = 'DESTROYED'

            print('Gold asteroid has been destroyed')

    def createSmallAsteroid(self, x, y, direction, size):
        newAsteroid = Asteroid(size, x, y, 3, direction)

        lab = QLabel(self)
        if size == 1:
            newAsteroid.whatSizeAmI = 'SMALL'
            lab.setPixmap(self.smallAsteroidPixMap)
        else:
            newAsteroid.whatSizeAmI = 'MEDIUM'
            lab.setPixmap(self.mediumAsteroidPixMap)
        lab.setGeometry(x, y, 100, 100)
        asteroids.append(newAsteroid)
        asteroidLabels.append(lab)
        self.showAsteroids()

    def aliveAsteroidsCount(self):
        count = 0
        for a in asteroids:
            if a != 'DESTROYED':
                if not a.isHidden:
                    count += 1
        return count

    def destoryRandomAsteroid(self):
        asteroid = ''
        while True:
            randomAsteroidIndex = randint(0, len(asteroids) - 1)
            asteroid = asteroids[randomAsteroidIndex]
            if asteroid != 'DESTROYED':
                self.destroyAsteroid(asteroid)
                break
Exemplo n.º 37
0
class TabLaTeX(Panel_simple):
    titre = "Tableaux LaTeX" # Donner un titre a chaque module

    def __init__(self, *args, **kw):
        Panel_simple.__init__(self, *args, **kw)

        self.sizer = QVBoxLayout()

        self.entree = LigneCommande(self, longueur = 500, action = self.generer_code)
        self.sizer.addWidget(self.entree)

        self.sizer_type = QHBoxLayout()
        self.type_tableau = QComboBox(self)
        self.type_tableau.addItems(["Tableau de variations", "Tableau de signes",
                                    "Tableau de valeurs"])
        self.type_tableau.setCurrentIndex(self._param_.mode)
        self.sizer_type.addWidget(QLabel("Type de tableau :", self))
        self.sizer_type.addWidget(self.type_tableau)
        self.sizer_type.addSpacing(15)

        self.utiliser_cellspace = QCheckBox("Utiliser le paquetage cellspace.", self)
        self.utiliser_cellspace.setChecked(self._param_.utiliser_cellspace)
        self.utiliser_cellspace.setToolTip("Le paquetage cellspace évite que "
                "certains objets (comme les fractions) touchent les bordures du tableaux.")
        self.sizer_type.addSpacing(10)
        self.sizer_type.addWidget(self.utiliser_cellspace)

        self.derivee = QCheckBox("Dérivée.", self)
        self.derivee.setChecked(self._param_.derivee)
        self.derivee.setToolTip("Afficher une ligne indiquant le signe de la dérivée.")
        self.sizer_type.addSpacing(10)
        self.sizer_type.addWidget(self.derivee)

        self.limites = QCheckBox("Limites.", self)
        self.limites.setChecked(self._param_.limites)
        self.limites.setToolTip("Afficher les limites dans le tableau de variations.")
        self.sizer_type.addSpacing(10)
        self.sizer_type.addWidget(self.limites)

        self.decimales_tabvar_tabsign = QSpinBox()
        self.decimales_tabvar_tabsign.setRange(-1, 20)
        self.decimales_tabvar_tabsign.setSuffix(" décimales")
        self.decimales_tabvar_tabsign.setSpecialValueText("Valeurs exactes")
        self.decimales_tabvar_tabsign.setValue(self._param_.decimales_tabvar_tabsign)
        ##self.decimales_tabvar_tabsign.setAccelerated(True)
        aide = "Nombre de décimales pour l'affichage des extrema, ou valeur exacte."
        self.decimales_tabvar_tabsign.setToolTip(aide)
        self.sizer_type.addSpacing(10)
        self.sizer_type.addWidget(self.decimales_tabvar_tabsign)

        self.decimales_tabval = QSpinBox()
        self.decimales_tabval.setRange(0, 20)
        self.decimales_tabval.setSuffix(" décimales")
        self.decimales_tabval.setValue(self._param_.decimales_tabval)
        ##self.decimales_tabval.setAccelerated(True)
        aide = "Nombre de décimales pour les valeurs du tableau."
        self.decimales_tabval.setToolTip(aide)
        self.sizer_type.addSpacing(10)
        self.sizer_type.addWidget(self.decimales_tabval)

        self.sizer_type.addSpacing(15)
        self.lbl_formatage = lbl = QLabel("Formatage des résultats :")
        self.sizer_type.addWidget(lbl)
        self.formatage_images = QLineEdit()
        ##self.formatage_images.setMinimumWidth(200)
        self.formatage_images.setText(self._param_.formatage_images)
        aide = "Formatage à appliquer au résultat (VAL est la valeur du résultat)."
        lbl.setToolTip(aide)
        self.formatage_images.setToolTip(aide)
        self.sizer_type.addSpacing(10)
        self.sizer_type.addWidget(self.formatage_images)

        self.sizer_type.addStretch()

        self.sizer.addLayout(self.sizer_type)

        box = QGroupBox("Code LaTeX permettant de de générer le tableau", self)
        self.bsizer = QVBoxLayout()
        box.setLayout(self.bsizer)

        self.code_tableau = QTextEdit(self)
        self.code_tableau.setMinimumSize(700, 200)
        self.code_tableau.setReadOnly(True)
        self.bsizer.addWidget(self.code_tableau)

        self.copier_code = QPushButton("Copier dans le presse-papier", self)
        self.bsizer.addWidget(self.copier_code)

        txt = "Pensez à rajouter dans l'entête de votre fichier LaTeX la ligne suivante :"
        self.bsizer.addWidget(QLabel(txt, self))

        self.sizer_entete = QHBoxLayout()
        self.code_entete = QLineEdit(self)
        self.code_entete.setMinimumWidth(200)
        self.code_entete.setReadOnly(True)
        self.code_entete.setText("\\usepackage{tabvar}")
        self.sizer_entete.addWidget(self.code_entete)
        self.copier_entete = QPushButton("Copier cette ligne", self)
        self.sizer_entete.addWidget(self.copier_entete)

        self.bsizer.addLayout(self.sizer_entete)

        self.sizer.addWidget(box)


        self.cb = QCheckBox("Copier automatiquement le code LaTeX dans le presse-papier.", self)
        self.cb.setChecked(self._param_.copie_automatique)
        self.sizer.addWidget(self.cb)

        self.setLayout(self.sizer)
        self.adjustSize()

        self.type_tableau.currentIndexChanged.connect(self.EvtChoix)
        self.EvtChoix()

        def copier_code():
            return self.vers_presse_papier(self.code_tableau.toPlainText())
        self.copier_code.clicked.connect(copier_code)

        def copier_entete():
            return self.vers_presse_papier(self.code_entete.text())
        self.copier_entete.clicked.connect(copier_entete)

        def regler_mode_copie():
            self._param_.copie_automatique = self.cb.isChecked()
            if self._param_.copie_automatique:
                copier_code()
        self.cb.stateChanged.connect(regler_mode_copie)

        def regler_cellspace():
            self._param_.utiliser_cellspace = self.utiliser_cellspace.isChecked()
            if self._param_.utiliser_cellspace:
                self.code_entete.setText("\\usepackage{cellspace}")
            else:
                self.code_entete.setText("")
            self.valider()
        self.utiliser_cellspace.stateChanged.connect(regler_cellspace)

        def regler_parametres(event=None):
            self._param_.derivee = self.derivee.isChecked()
            self._param_.limites = self.limites.isChecked()
            self._param_.formatage_images = self.formatage_images.text()
            self.valider()

        def regler_decimales(event=None):
            try:
                self.focus_widget = app.focusWidget()
                self._param_.decimales_tabvar_tabsign = self.decimales_tabvar_tabsign.value()
                self._param_.decimales_tabval = self.decimales_tabval.value()
                self.valider()
            finally:
                self.focus_widget = self.entree

        self.derivee.stateChanged.connect(regler_parametres)
        self.limites.stateChanged.connect(regler_parametres)
        self.formatage_images.editingFinished.connect(regler_parametres)
        self.decimales_tabvar_tabsign.valueChanged.connect(regler_decimales)
        self.decimales_tabval.valueChanged.connect(regler_decimales)

        self.focus_widget = self.entree


    def activer(self):
        Panel_simple.activer(self)
        # Actions à effectuer lorsque l'onglet devient actif
        self.entree.setFocus()


    def generer_code(self, commande, **kw):
        if not commande.strip():
            return
        # Utilisé pour la sauvegarde automatique:x+3

        self.modifie = True
        try:
            if self._param_.mode == 0:
                code_latex = tabvar(commande, derivee=self._param_.derivee,
                                    limites=self._param_.limites,
                                    decimales=self._param_.decimales_tabvar_tabsign,
                                    approche=(self._param_.decimales_tabvar_tabsign != -1))
            elif self._param_.mode == 1:
                code_latex = tabsign(commande, cellspace=self._param_.utiliser_cellspace,
                                    decimales=self._param_.decimales_tabvar_tabsign,
                                    approche=(self._param_.decimales_tabvar_tabsign != -1))
            elif self._param_.mode == 2:
                code_latex = tabval(commande,
                    formatage_antecedents=self._param_.formatage_antecedents,
                    formatage_images=self._param_.formatage_images,
                    precision=10**-self._param_.decimales_tabval)
            else:
                warning("Type de tableau non reconnu.")

            self.code_tableau.setText(code_latex)
            if self._param_.copie_automatique:
                self.vers_presse_papier(texte = code_latex)
            self.focus_widget.setFocus()
            self.message("Le code LaTeX a bien été généré.")
        except BaseException as erreur:
            self.message("Impossible de générer le code LaTeX. " + message(erreur))
            self.code_tableau.setText("<i><b>Erreur.</b> Impossible de générer le code LaTeX.</i>")
            self.entree.setFocus()
            if param.debug:
                raise


    def EvtChoix(self, event = None):
        self._param_.mode = self.type_tableau.currentIndex()
        # Tableaux de variations
        if self._param_.mode == 0:
            self.code_entete.setText("\\usepackage{tabvar}")
            self.entree.setToolTip(tabvar.__doc__)
            self.utiliser_cellspace.hide()
            self.derivee.show()
            self.limites.show()
            self.decimales_tabvar_tabsign.show()
            self.formatage_images.hide()
            self.lbl_formatage.hide()
            self.decimales_tabval.hide()
        # Tableaux de signes
        elif self._param_.mode == 1:
            self.utiliser_cellspace.show()
            self.derivee.hide()
            self.limites.hide()
            self.formatage_images.hide()
            self.lbl_formatage.hide()
            self.decimales_tabvar_tabsign.show()
            self.decimales_tabval.hide()
            self.entree.setToolTip(tabsign.__doc__)
            if self._param_.utiliser_cellspace:
                self.code_entete.setText("\\usepackage{cellspace}")
            else:
                self.code_entete.setText("")
        # Tableaux de valeurs
        elif self._param_.mode == 2:
            self.utiliser_cellspace.hide()
            self.derivee.hide()
            self.limites.hide()
            self.decimales_tabvar_tabsign.hide()
            self.decimales_tabval.show()
            self.lbl_formatage.show()
            self.formatage_images.show()
            self.entree.setToolTip(tabval.__doc__)
            self.code_entete.setText("")
        self.valider()


    def valider(self):
        try:
            self.entree.valider()
        except Exception:
            print_error()
Exemplo n.º 38
0
class LaserRangeFinder(PluginBase):
    def __init__(self, *args):
        super().__init__(BrickletLaserRangeFinder, *args)

        self.lrf = self.device

        # the firmware version of a EEPROM Bricklet can (under common circumstances)
        # not change during the lifetime of an EEPROM Bricklet plugin. therefore,
        # it's okay to make final decisions based on it here
        self.has_sensor_hardware_version_api = self.firmware_version >= (2, 0, 3)
        self.has_configuration_api = self.firmware_version >= (2, 0, 3)

        self.cbe_distance = CallbackEmulator(self,
                                             self.lrf.get_distance,
                                             None,
                                             self.cb_distance,
                                             self.increase_error_count)
        self.cbe_velocity = CallbackEmulator(self,
                                             self.lrf.get_velocity,
                                             None,
                                             self.cb_velocity,
                                             self.increase_error_count)

        self.current_distance = CurveValueWrapper() # int, cm
        self.current_velocity = CurveValueWrapper() # float, m/s

        plots_distance = [('Distance', Qt.red, self.current_distance, format_distance)]
        plots_velocity = [('Velocity', Qt.red, self.current_velocity, '{:.2f} m/s'.format)]
        self.plot_widget_distance = PlotWidget('Distance [cm]', plots_distance, y_resolution=1.0)
        self.plot_widget_velocity = PlotWidget('Velocity [m/s]', plots_velocity, y_resolution=0.01)

        self.mode_label = QLabel('Mode:')
        self.mode_combo = QComboBox()
        self.mode_combo.addItem("Distance: 1cm resolution, 40m max")
        self.mode_combo.addItem("Velocity: 0.10 m/s resolution, 12.70m/s max")
        self.mode_combo.addItem("Velocity: 0.25 m/s resolution, 31.75m/s max")
        self.mode_combo.addItem("Velocity: 0.50 m/s resolution, 63.50m/s max")
        self.mode_combo.addItem("Velocity: 1.00 m/s resolution, 127.00m/s max")
        self.mode_combo.currentIndexChanged.connect(self.mode_changed)
        self.mode_combo.hide()

        self.label_average_distance = QLabel('Moving Average for Distance:')

        self.spin_average_distance = QSpinBox()
        self.spin_average_distance.setMinimum(0)
        self.spin_average_distance.setMaximum(50)
        self.spin_average_distance.setSingleStep(1)
        self.spin_average_distance.setValue(10)
        self.spin_average_distance.editingFinished.connect(self.spin_average_finished)

        self.label_average_velocity = QLabel('Moving Average for Velocity:')

        self.spin_average_velocity = QSpinBox()
        self.spin_average_velocity.setMinimum(0)
        self.spin_average_velocity.setMaximum(50)
        self.spin_average_velocity.setSingleStep(1)
        self.spin_average_velocity.setValue(10)
        self.spin_average_velocity.editingFinished.connect(self.spin_average_finished)

        self.enable_laser = QCheckBox("Enable Laser")
        self.enable_laser.stateChanged.connect(self.enable_laser_changed)

        self.label_acquisition_count = QLabel('Acquisition Count:')
        self.spin_acquisition_count = QSpinBox()
        self.spin_acquisition_count.setMinimum(1)
        self.spin_acquisition_count.setMaximum(255)
        self.spin_acquisition_count.setSingleStep(1)
        self.spin_acquisition_count.setValue(128)

        self.enable_qick_termination = QCheckBox("Quick Termination")

        self.label_threshold = QLabel('Threshold:')
        self.threshold = QCheckBox("Automatic Threshold")

        self.spin_threshold = QSpinBox()
        self.spin_threshold.setMinimum(1)
        self.spin_threshold.setMaximum(255)
        self.spin_threshold.setSingleStep(1)
        self.spin_threshold.setValue(1)

        self.label_frequency = QLabel('Frequency [Hz]:')
        self.frequency = QCheckBox("Automatic Frequency (Disable for Velocity)")

        self.spin_frequency = QSpinBox()
        self.spin_frequency.setMinimum(10)
        self.spin_frequency.setMaximum(500)
        self.spin_frequency.setSingleStep(1)
        self.spin_frequency.setValue(10)

        self.spin_acquisition_count.editingFinished.connect(self.configuration_changed)
        self.enable_qick_termination.stateChanged.connect(self.configuration_changed)
        self.spin_threshold.editingFinished.connect(self.configuration_changed)
        self.threshold.stateChanged.connect(self.configuration_changed)
        self.spin_frequency.editingFinished.connect(self.configuration_changed)
        self.frequency.stateChanged.connect(self.configuration_changed)

        layout_h1 = QHBoxLayout()
        layout_h1.addWidget(self.plot_widget_distance)
        layout_h1.addWidget(self.plot_widget_velocity)

        layout_h2 = QHBoxLayout()
        layout_h2.addWidget(self.mode_label)
        layout_h2.addWidget(self.mode_combo)
        layout_h2.addWidget(self.label_average_distance)
        layout_h2.addWidget(self.spin_average_distance)
        layout_h2.addWidget(self.label_average_velocity)
        layout_h2.addWidget(self.spin_average_velocity)
        layout_h2.addStretch()
        layout_h2.addWidget(self.enable_laser)

        layout_h3 = QHBoxLayout()
        layout_h3.addWidget(self.label_frequency)
        layout_h3.addWidget(self.spin_frequency)
        layout_h3.addWidget(self.frequency)
        layout_h3.addStretch()
        layout_h3.addWidget(self.enable_qick_termination)

        layout_h4 = QHBoxLayout()
        layout_h4.addWidget(self.label_threshold)
        layout_h4.addWidget(self.spin_threshold)
        layout_h4.addWidget(self.threshold)
        layout_h4.addStretch()
        layout_h4.addWidget(self.label_acquisition_count)
        layout_h4.addWidget(self.spin_acquisition_count)

        self.widgets_distance = [self.plot_widget_distance, self.spin_average_distance, self.label_average_distance]
        self.widgets_velocity = [self.plot_widget_velocity, self.spin_average_velocity, self.label_average_velocity]

        for w in self.widgets_distance:
            w.hide()

        for w in self.widgets_velocity:
            w.hide()

        line = QFrame()
        line.setObjectName("line")
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h1)
        layout.addWidget(line)
        layout.addLayout(layout_h2)
        layout.addLayout(layout_h3)
        layout.addLayout(layout_h4)

    def start(self):
        if self.has_sensor_hardware_version_api:
            async_call(self.lrf.get_sensor_hardware_version, None, self.get_sensor_hardware_version_async, self.increase_error_count)
        else:
            self.get_sensor_hardware_version_async(1)

        if self.has_configuration_api:
            async_call(self.lrf.get_configuration, None, self.get_configuration_async, self.increase_error_count)

        async_call(self.lrf.get_mode, None, self.get_mode_async, self.increase_error_count)
        async_call(self.lrf.is_laser_enabled, None, self.enable_laser.setChecked, self.increase_error_count)
        async_call(self.lrf.get_moving_average, None, self.get_moving_average_async, self.increase_error_count)

        self.cbe_distance.set_period(25)
        self.cbe_velocity.set_period(25)

        self.plot_widget_distance.stop = False
        self.plot_widget_velocity.stop = False

    def stop(self):
        self.cbe_distance.set_period(0)
        self.cbe_velocity.set_period(0)

        self.plot_widget_distance.stop = True
        self.plot_widget_velocity.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletLaserRangeFinder.DEVICE_IDENTIFIER

    def enable_laser_changed(self, state):
        if state == Qt.Checked:
            self.lrf.enable_laser()
        else:
            self.lrf.disable_laser()

    def mode_changed(self, value):
        if value < 0 or value > 4:
            return

        self.lrf.set_mode(value)
        if value == 0:
            for w in self.widgets_velocity:
                w.hide()
            for w in self.widgets_distance:
                w.show()
        else:
            for w in self.widgets_distance:
                w.hide()
            for w in self.widgets_velocity:
                w.show()

    def cb_distance(self, distance):
        self.current_distance.value = distance

    def cb_velocity(self, velocity):
        self.current_velocity.value = velocity / 100.0

    def configuration_changed(self):
        acquisition_count = self.spin_acquisition_count.value()
        enable_quick_termination = self.enable_qick_termination.isChecked()

        if self.threshold.isChecked():
            threshold = 0
        else:
            threshold = self.spin_threshold.value()

        if self.frequency.isChecked():
            frequency = 0
            for w in self.widgets_velocity:
                w.hide()
        else:
            frequency = self.spin_frequency.value()
            for w in self.widgets_velocity:
                w.show()

        self.spin_threshold.setDisabled(threshold == 0)
        self.spin_frequency.setDisabled(frequency == 0)

        self.lrf.set_configuration(acquisition_count, enable_quick_termination, threshold, frequency)

    def get_configuration_async(self, conf):
        self.spin_acquisition_count.blockSignals(True)
        self.spin_acquisition_count.setValue(conf.acquisition_count)
        self.spin_acquisition_count.blockSignals(False)

        self.enable_qick_termination.blockSignals(True)
        self.enable_qick_termination.setChecked(conf.enable_quick_termination)
        self.enable_qick_termination.blockSignals(False)

        self.spin_threshold.blockSignals(True)
        self.spin_threshold.setValue(conf.threshold_value)
        self.spin_threshold.setDisabled(conf.threshold_value == 0)
        self.spin_threshold.blockSignals(False)

        self.spin_frequency.blockSignals(True)
        self.spin_frequency.setValue(conf.measurement_frequency)
        self.spin_frequency.setDisabled(conf.measurement_frequency == 0)
        self.spin_frequency.blockSignals(False)

        self.threshold.blockSignals(True)
        self.threshold.setChecked(conf.threshold_value == 0)
        self.threshold.blockSignals(False)

        self.frequency.blockSignals(True)
        self.frequency.setChecked(conf.measurement_frequency == 0)
        self.frequency.blockSignals(False)

        self.configuration_changed()

    def get_sensor_hardware_version_async(self, value):
        if value == 1:
            self.mode_combo.show()
            self.mode_label.show()
            self.label_acquisition_count.hide()
            self.spin_acquisition_count.hide()
            self.enable_qick_termination.hide()
            self.label_threshold.hide()
            self.spin_threshold.hide()
            self.threshold.hide()
            self.label_frequency.hide()
            self.spin_frequency.hide()
            self.frequency.hide()
        else:
            self.mode_combo.hide()
            self.mode_label.hide()
            self.label_acquisition_count.show()
            self.spin_acquisition_count.show()
            self.enable_qick_termination.show()
            self.label_threshold.show()
            self.spin_threshold.show()
            self.threshold.show()
            self.label_frequency.show()
            self.spin_frequency.show()
            self.frequency.show()

            for w in self.widgets_distance:
                w.show()
            for w in self.widgets_velocity:
                w.show()

    def get_mode_async(self, value):
        self.mode_combo.setCurrentIndex(value)
        self.mode_changed(value)

    def get_moving_average_async(self, avg):
        self.spin_average_distance.setValue(avg.distance_average_length)
        self.spin_average_velocity.setValue(avg.velocity_average_length)

    def spin_average_finished(self):
        self.lrf.set_moving_average(self.spin_average_distance.value(), self.spin_average_velocity.value())
Exemplo n.º 39
0
class MainWindow(QMainWindow):

    """Main window class."""

    def __init__(self, parent=None):
        """Init class."""
        super(MainWindow, self).__init__()
        QNetworkProxyFactory.setUseSystemConfiguration(True)
        self.statusBar().showMessage(__doc__ + get_nuitka_version())
        self.setWindowTitle(__doc__.strip().capitalize())
        self.setMinimumSize(480, 400)
        self.setMaximumSize(1024, 800)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("python"))
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Exit", lambda: self.close())
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        windowMenu.addSeparator()
        windowMenu.addAction(
            "Increase size", lambda:
            self.resize(self.size().width() * 1.4, self.size().height() * 1.4))
        windowMenu.addAction("Decrease size", lambda: self.resize(
            self.size().width() // 1.4, self.size().height() // 1.4))
        windowMenu.addAction("Minimum size", lambda:
                             self.resize(self.minimumSize()))
        windowMenu.addAction("Maximum size", lambda:
                             self.resize(self.maximumSize()))
        windowMenu.addAction("Horizontal Wide", lambda: self.resize(
            self.maximumSize().width(), self.minimumSize().height()))
        windowMenu.addAction("Vertical Tall", lambda: self.resize(
            self.minimumSize().width(), self.maximumSize().height()))
        windowMenu.addSeparator()
        windowMenu.addAction("Disable Resize", lambda:
                             self.setFixedSize(self.size()))
        windowMenu.addAction("Set Interface Font...", lambda:
                             self.setFont(QFontDialog.getFont()[0]))
        windowMenu.addAction(
            "Load .qss Skin", lambda: self.setStyleSheet(self.skin()))
        helpMenu = self.menuBar().addMenu("&Help")
        helpMenu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self))
        helpMenu.addAction("About Python 3",
                           lambda: open_new_tab('https://www.python.org'))
        helpMenu.addAction("About " + __doc__,
                           lambda: QMessageBox.about(self, __doc__, HELP))
        helpMenu.addSeparator()
        helpMenu.addAction(
            "Keyboard Shortcut",
            lambda: QMessageBox.information(self, __doc__, "<b>Quit = CTRL+Q"))
        if sys.platform.startswith('linux'):
            helpMenu.addAction("View Source Code", lambda:
                               call('xdg-open ' + __file__, shell=True))
        helpMenu.addAction("View GitHub Repo", lambda: open_new_tab(__url__))
        helpMenu.addAction("Check Updates", lambda: Downloader(self))
        # process
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self._read_output)
        self.process.readyReadStandardError.connect(self._read_errors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_failed)
        # widgets
        self.group0, self.group1 = QGroupBox("Options"), QGroupBox("Paths")
        self.group4, self.group5 = QGroupBox("Details"), QGroupBox("Miscs")
        g0grid, g1vlay = QGridLayout(self.group0), QGridLayout(self.group1)
        g5vlay, g4vlay = QVBoxLayout(self.group5), QVBoxLayout(self.group4)
        # group 0 the options
        self.module = QCheckBox("Create compiled extension module")
        self.standalone = QCheckBox("Standalone executable binary output")
        self.nofreeze = QCheckBox("No freeze all modules of standard library")
        self.python_debug = QCheckBox("Use Python Debug")
        self.warning = QCheckBox("Warnings for implicit exceptions at compile")
        self.recurse_std = QCheckBox("Recursive compile the standard library")
        self.recurse_not = QCheckBox("Force No recursive compiling")
        self.execute = QCheckBox("Execute the created binary after compiling")
        self.pythonpath = QCheckBox("Keep pythonpath when executing")
        self.enhaced = QCheckBox("Enhaced compile, Not CPython compatible")
        self.nolineno = QCheckBox("No Statements line numbers on compile")
        self.rmbuilddir = QCheckBox("Remove build directory after compile.")
        self.nuitka_debug = QCheckBox("Use Nuitka Debug")
        self.keep_debug = QCheckBox("Keep debug info on compile for GDB")
        self.traced = QCheckBox("Traced execution output")
        self.plusplus = QCheckBox("Compile C++ Only on generated source files")
        self.experimental = QCheckBox("Experimental features")
        self.force_clang = QCheckBox("Force use of CLang")
        self.force_mingw = QCheckBox("Force use of MinGW on MS Windows")
        self.force_lto = QCheckBox("Use link time optimizations LTO")
        self.show_scons = QCheckBox("Show Scons executed commands")
        self.show_progress = QCheckBox("Show progress info and statistics")
        self.show_summary = QCheckBox("Show final summary of included modules")
        self.disable_console = QCheckBox("Disable the Console on MS Windows")
        for i, widget in enumerate((
            self.module, self.standalone, self.nofreeze, self.python_debug,
            self.warning, self.recurse_std, self.recurse_not, self.execute,
            self.pythonpath, self.enhaced, self.nolineno, self.rmbuilddir,
            self.nuitka_debug, self.keep_debug, self.traced, self.plusplus,
            self.experimental, self.force_clang, self.force_mingw,
            self.force_lto, self.show_scons, self.show_progress,
                self.show_summary, self.disable_console)):
            widget.setToolTip(widget.text())
            g0grid.addWidget(widget, i if i < i + 1 else i - (i - 1), i % 2)
        # group 1 paths
        self.target = QLineEdit()
        self.outdir = QLineEdit(os.path.expanduser("~"))
        self.t_icon = QLineEdit()
        self.target.setToolTip("Python App file you want to Compile to Binary")
        self.outdir.setToolTip("Folder to write Compiled Output Binary files")
        self.t_icon.setToolTip("Icon image file to embed for your Python App")
        self.target.setPlaceholderText("/full/path/to/target/python_app.py")
        self.outdir.setPlaceholderText("/full/path/to/output/folder/")
        self.t_icon.setPlaceholderText("/full/path/to/python_app/icon.png")
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.completer.popup().setStyleSheet("border: 1px solid gray")
        self.completer.popup().setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.outdir.setCompleter(self.completer)
        self.t_icon.setCompleter(self.completer)
        self.target.setCompleter(self.completer)
        self.clear_1 = QPushButton(QIcon.fromTheme("edit-clear"), "", self,
                                   clicked=lambda: self.target.clear())
        self.clear_2 = QPushButton(QIcon.fromTheme("edit-clear"), "", self,
                                   clicked=lambda: self.t_icon.clear())
        self.clear_3 = QPushButton(QIcon.fromTheme("edit-clear"), "", self,
                                   clicked=lambda: self.outdir.clear())
        self.open_1 = QPushButton(
            QIcon.fromTheme("folder-open"), "", self, clicked=lambda:
                self.target.setText(str(QFileDialog.getOpenFileName(
                    self, __doc__, os.path.expanduser("~"), """Python (*.py);;
                    Python for Windows (*.pyw);;All (*.*)""")[0])))
        self.open_2 = QPushButton(
            QIcon.fromTheme("folder-open"), "", self, clicked=lambda:
                self.t_icon.setText(str(QFileDialog.getOpenFileName(
                    self, __doc__, os.path.expanduser("~"),
                    "PNG (*.png);;JPG (*.jpg);;ICO (*.ico);;All (*.*)")[0])))
        self.open_3 = QPushButton(
            QIcon.fromTheme("folder-open"), "", self, clicked=lambda:
                self.outdir.setText(str(QFileDialog.getExistingDirectory(
                    self, __doc__, os.path.expanduser("~")))))
        self.l_icon = QLabel("Target Icon")
        g1vlay.addWidget(QLabel("<b>Target Python"), 0, 0)
        g1vlay.addWidget(self.target, 0, 1)
        g1vlay.addWidget(self.clear_1, 0, 2)
        g1vlay.addWidget(self.open_1, 0, 3)
        g1vlay.addWidget(self.l_icon, 1, 0)
        g1vlay.addWidget(self.t_icon, 1, 1)
        g1vlay.addWidget(self.clear_2, 1, 2)
        g1vlay.addWidget(self.open_2, 1, 3)
        g1vlay.addWidget(QLabel("<b>Output Folder"), 2, 0)
        g1vlay.addWidget(self.outdir, 2, 1)
        g1vlay.addWidget(self.clear_3, 2, 2)
        g1vlay.addWidget(self.open_3, 2, 3)

        # group 4 the dome view mode
        self.jobs = QSpinBox()
        self.jobs.setRange(1, cpu_count())
        self.jobs.setValue(cpu_count())
        self.jobs.setToolTip("Backend Worker Jobs Processes")
        self.python_version = QComboBox()
        self.python_version.addItems(["2.7", "3.2", "3.3", "3.4"])
        self.python_version.setToolTip("Python version to use with Nuitka")
        self.display_tree = QPushButton("Display Tree")
        self.display_tree.clicked.connect(
            lambda: call(NUITKA + " --display-tree {}".format(
                self.target.text()), shell=True))
        self.dump_tree = QPushButton(
            "View Docs", clicked=lambda:
                open_new_tab("http://nuitka.net/doc/user-manual.html"))
        self.open_log = QPushButton("View Logs")
        _log = os.path.join(gettempdir(), "nuitka-gui.log")
        _open = "xdg-open " if sys.platform.startswith("lin") else "open "
        self.open_log.clicked.connect(lambda: call(_open + _log, shell=True))
        self.open_folder = QPushButton("Open Build Folder")
        self.open_folder.clicked.connect(lambda: call(
            _open + str(self.outdir.text()).strip(), shell=True))

        # self.display_tree.clicked.connect(self._display_tree)
        g4vlay.addWidget(QLabel("<b>Worker Jobs"))
        g4vlay.addWidget(self.jobs)
        g4vlay.addWidget(QLabel("<b>Python Version"))
        g4vlay.addWidget(self.python_version)
        g4vlay.addWidget(QLabel("<b>Actions"))
        g4vlay.addWidget(self.display_tree)
        g4vlay.addWidget(self.dump_tree)
        g4vlay.addWidget(self.open_log)
        g4vlay.addWidget(self.open_folder)

        # group 5 miscelaneous stuff
        self.debug, self.scr = QCheckBox("Use Debug"), QCheckBox("Make Script")
        self.chrt, self.ionice = QCheckBox("Slow CPU"), QCheckBox("Slow HDD")
        self.minimi = QCheckBox("Auto Minimize")
        self.chrt.setToolTip("Use Low CPU speed priority (Linux only)")
        self.ionice.setToolTip("Use Low HDD speed priority (Linux only)")
        self.scr.setToolTip("Generate a Bash Script to Compile with Nuitka")
        self.debug.setToolTip("Use Debug Verbose mode")
        self.minimi.setToolTip("Automatically Minimize when compiling starts")
        self.scr.setChecked(True)
        self.chrt.setChecked(True)
        self.ionice.setChecked(True)
        self.minimi.setChecked(True)
        g5vlay.addWidget(self.debug)
        g5vlay.addWidget(self.scr)
        g5vlay.addWidget(self.chrt)
        g5vlay.addWidget(self.ionice)
        g5vlay.addWidget(self.minimi)

        # option to show or hide some widgets on the gui
        self.guimode = QComboBox()
        self.guimode.addItems(('Full UX / UI', 'Simple UX / UI'))
        self.guimode.setCurrentIndex(1)
        self._set_guimode()
        self.guimode.setStyleSheet("""QComboBox{background:transparent;
            margin-left:25px;color:gray;text-decoration:underline;border:0}""")
        self.guimode.currentIndexChanged.connect(self._set_guimode)

        # buttons from bottom to close or proceed
        self.bt = QDialogButtonBox(self)
        self.bt.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Close)
        self.bt.rejected.connect(self.close)
        self.bt.accepted.connect(self.run)

        if not sys.platform.startswith('lin'):
            self.scr.setChecked(False)
            self.chrt.setChecked(False)
            self.ionice.setChecked(False)
            self.scr.hide()
            self.chrt.hide()
            self.ionice.hide()
        if not sys.platform.startswith('win'):
            self.l_icon.hide()
            self.t_icon.hide()
            self.clear_2.hide()
            self.open_2.hide()
        if sys.platform.startswith('win'):
            self.display_tree.hide()

        # container for all groups of widgets
        container = QWidget()
        container_layout = QGridLayout(container)  # Y, X
        container_layout.addWidget(self.guimode, 0, 1)
        container_layout.addWidget(self.group0, 1, 1)
        container_layout.addWidget(self.group1, 2, 1)
        container_layout.addWidget(self.group4, 1, 2)
        container_layout.addWidget(self.group5, 2, 2)
        container_layout.addWidget(self.bt, 3, 1)
        self.setCentralWidget(container)

    def check_paths(self):
        """Check that the paths are valid."""
        if not os.path.isfile(self.target.text()):
            log.error("Target File not found or not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target File not found or not valid.")
            return False
        if not str(self.target.text()).endswith((".py", ".pyw")):
            log.error("Target File not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target File not valid.")
            return False
        if not os.path.isdir(self.outdir.text()):
            log.error("Target Folder not found or not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target Folder not found or not valid.")
            return False
        if self.t_icon.text() and not os.path.isfile(self.t_icon.text()):
            log.warning("Target Icon File not found or not valid.")
            QMessageBox.warning(self, __doc__.title(),
                                "Target Icon File not found or not valid.")
            return True
        else:
            return True

    def generate_build_command(self):
        """Generate a build command."""
        return re.sub(r"\s+", " ", " ".join((
            'chrt --verbose --idle 0' if self.chrt.isChecked() else '',
            'ionice --ignore --class 3' if self.ionice.isChecked() else '',
            NUITKA,
            '--debug --verbose' if self.debug.isChecked() else '',
            '--show-progress' if self.show_progress.isChecked() else '',
            '--show-scons --show-modules' if self.show_scons.isChecked() else '',
            '--unstriped' if self.keep_debug.isChecked() else '',
            '--trace-execution' if self.traced.isChecked() else '',
            '--remove-output' if self.rmbuilddir.isChecked() else '',
            '--code-gen-no-statement-lines' if self.nolineno.isChecked() else '',
            '--execute' if self.execute.isChecked() else '',
            '--recurse-none' if self.recurse_not.isChecked() else '--recurse-all',
            '--recurse-stdlib' if self.recurse_std.isChecked() else '',
            '--clang' if self.force_clang.isChecked() else '',
            '--lto' if self.force_lto.isChecked() else '',
            '--c++-only' if self.plusplus.isChecked() else '',
            '--windows-disable-console' if self.disable_console.isChecked() else '',
            '--experimental' if self.experimental.isChecked() else '',
            '--python-debug' if self.python_debug.isChecked() else '',
            '--module' if self.module.isChecked() else '--standalone',
            '--nofreeze-stdlib' if self.nofreeze.isChecked() else '',
            '--mingw' if self.force_mingw.isChecked() else '',
            '--warn-implicit-exceptions' if self.warning.isChecked() else '',
            '--execute-with-pythonpath' if self.pythonpath.isChecked() else '',
            '--enhanced' if self.enhaced.isChecked() else '',
            '--icon="{}"'.format(self.t_icon.text()) if self.t_icon.text() else '',
            '--python-version={}'.format(self.python_version.currentText()),
            '--jobs={}'.format(self.jobs.value()),
            '--output-dir="{}"'.format(self.outdir.text()),
            '"{}"'.format(self.target.text()))))

    def run(self):
        """Run the main method and run Nuitka."""
        self.statusBar().showMessage('Working...')
        log.debug("Working...")
        if not self.check_paths():
            return
        command_to_run_nuitka = self.generate_build_command()
        log.debug(command_to_run_nuitka)
        self.process.start(command_to_run_nuitka)
        if not self.process.waitForStarted():
            log.error(self._read_errors())
            return  # ERROR
        if self.scr.isChecked() and sys.platform.startswith("lin"):
            script_file = str(self.target.text()).replace(".py",
                                                          "-nuitka-compile.sh")
            log.debug("Writing Script {}".format(script_file))
            with open(script_file, "w", encoding="utf-8") as script:
                script.write("#!/usr/bin/env bash\n" + command_to_run_nuitka)
                os.chmod(script_file, 0o755)
        self.statusBar().showMessage(__doc__.title())

    def _process_finished(self):
        """Finished sucessfuly."""
        log.debug("Finished.")
        self.showNormal()

    def _read_output(self):
        """Read and return output."""
        return str(self.process.readAllStandardOutput()).strip()

    def _read_errors(self):
        """Read and return errors."""
        log.debug(self.process.readAllStandardError())
        return str(self.process.readAllStandardError()).strip()

    def _process_failed(self):
        """Read and return errors."""
        self.showNormal()
        self.statusBar().showMessage(" ERROR: Failed ! ")
        log.warning(str(self.process.readAllStandardError()).strip().lower())
        return str(self.process.readAllStandardError()).strip().lower()

    def _set_guimode(self):
        """Switch between simple and full UX."""
        for widget in (self.group0, self.group4,
                       self.group5, self.statusBar(), self.menuBar()):
            widget.hide() if self.guimode.currentIndex() else widget.show()
        self.resize(self.minimumSize()
                    if self.guimode.currentIndex() else self.maximumSize())
        self.center()

    def skin(self, filename=None):
        """Open QSS from filename,if no QSS return None,if no filename ask."""
        if not filename:
            filename = str(QFileDialog.getOpenFileName(
                self, __doc__ + "-Open QSS Skin file", os.path.expanduser("~"),
                "CSS Cascading Style Sheet for Qt 5 (*.qss);;All (*.*)")[0])
        if filename and os.path.isfile(filename):
            log.debug(filename)
            with open(filename, 'r') as file_to_read:
                text = file_to_read.read().strip()
        if text:
            log.debug(text)
            return text

    def center(self):
        """Center the Window on the Current Screen,with Multi-Monitor support.

        >>> MainWindow().center()
        True
        """
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        return bool(not self.move(window_geometry.topLeft()))

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position.

        >>> MainWindow().move_to_mouse_position()
        True
        """
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        return bool(not self.move(window_geometry.topLeft()))

    def closeEvent(self, event):
        """Ask to Quit."""
        the_conditional_is_true = QMessageBox.question(
            self, __doc__.title(), 'Quit ?.', QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No) == QMessageBox.Yes
        event.accept() if the_conditional_is_true else event.ignore()
Exemplo n.º 40
0
class GalleryDialog(QWidget):
    """
    A window for adding/modifying gallery.
    Pass a list of QModelIndexes to edit their data
    or pass a path to preset path
    """

    def __init__(self, parent, arg=None):
        super().__init__(parent, Qt.Dialog)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAutoFillBackground(True)
        self.parent_widget = parent
        m_l = QVBoxLayout()
        self.main_layout = QVBoxLayout()
        dummy = QWidget(self)
        scroll_area = QScrollArea(self)
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameStyle(scroll_area.StyledPanel)
        dummy.setLayout(self.main_layout)
        scroll_area.setWidget(dummy)
        m_l.addWidget(scroll_area, 3)

        final_buttons = QHBoxLayout()
        final_buttons.setAlignment(Qt.AlignRight)
        m_l.addLayout(final_buttons)
        self.done = QPushButton("Done")
        self.done.setDefault(True)
        cancel = QPushButton("Cancel")
        final_buttons.addWidget(cancel)
        final_buttons.addWidget(self.done)
        self._multiple_galleries = False
        self._edit_galleries = []

        def new_gallery():
            self.setWindowTitle('Add a new gallery')
            self.newUI()
            self.commonUI()
            self.done.clicked.connect(self.accept)
            cancel.clicked.connect(self.reject)

        if arg:
            if isinstance(arg, (list, gallerydb.Gallery)):
                if isinstance(arg, gallerydb.Gallery):
                    self.setWindowTitle('Edit gallery')
                    self._edit_galleries.append(arg)
                else:
                    self.setWindowTitle('Edit {} galleries'.format(len(arg)))
                    self._multiple_galleries = True
                    self._edit_galleries.extend(arg)
                self.commonUI()
                self.setGallery(arg)
                self.done.clicked.connect(self.accept_edit)
                cancel.clicked.connect(self.reject_edit)
            elif isinstance(arg, str):
                new_gallery()
                self.choose_dir(arg)
        else:
            new_gallery()

        log_d('GalleryDialog: Create UI: successful')
        self.setLayout(m_l)
        if self._multiple_galleries:
            self.resize(500, 480)
        else:
            self.resize(500, 600)
        frect = self.frameGeometry()
        frect.moveCenter(QDesktopWidget().availableGeometry().center())
        self.move(frect.topLeft())
        self._fetch_inst = fetch.Fetch()
        self._fetch_thread = QThread(self)
        self._fetch_thread.setObjectName("GalleryDialog metadata thread")
        self._fetch_inst.moveToThread(self._fetch_thread)
        self._fetch_thread.started.connect(self._fetch_inst.auto_web_metadata)

    def commonUI(self):
        if not self._multiple_galleries:
            f_web = QGroupBox("Metadata from the Web")
            f_web.setCheckable(False)
            self.main_layout.addWidget(f_web)
            web_main_layout = QVBoxLayout()
            web_info = misc.ClickedLabel("Which gallery URLs are supported? (hover)", parent=self)
            web_info.setToolTip(app_constants.SUPPORTED_METADATA_URLS)
            web_info.setToolTipDuration(999999999)
            web_main_layout.addWidget(web_info)
            web_layout = QHBoxLayout()
            web_main_layout.addLayout(web_layout)
            f_web.setLayout(web_main_layout)
            def basic_web(name):
                return QLabel(name), QLineEdit(), QPushButton("Get metadata"), QProgressBar()

            url_lbl, self.url_edit, url_btn, url_prog = basic_web("URL:")
            url_btn.clicked.connect(lambda: self.web_metadata(self.url_edit.text(), url_btn,
                                                url_prog))
            url_prog.setTextVisible(False)
            url_prog.setMinimum(0)
            url_prog.setMaximum(0)
            web_layout.addWidget(url_lbl, 0, Qt.AlignLeft)
            web_layout.addWidget(self.url_edit, 0)
            web_layout.addWidget(url_btn, 0, Qt.AlignRight)
            web_layout.addWidget(url_prog, 0, Qt.AlignRight)
            self.url_edit.setPlaceholderText("Insert supported gallery URLs or just press the button!")
            url_prog.hide()

        f_gallery = QGroupBox("Gallery Info")
        f_gallery.setCheckable(False)
        self.main_layout.addWidget(f_gallery)
        gallery_layout = QFormLayout()
        f_gallery.setLayout(gallery_layout)

        def checkbox_layout(widget):
            if self._multiple_galleries:
                l = QHBoxLayout()
                l.addWidget(widget.g_check)
                widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
                l.addWidget(widget)
                return l
            else:
                widget.g_check.setChecked(True)
                widget.g_check.hide()
                return widget

        def add_check(widget):
            widget.g_check = QCheckBox(self)
            return widget

        self.title_edit = add_check(QLineEdit())
        self.author_edit = add_check(QLineEdit())
        author_completer = misc.GCompleter(self, False, True, False)
        author_completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.author_edit.setCompleter(author_completer)
        self.descr_edit = add_check(QTextEdit())
        self.descr_edit.setAcceptRichText(True)
        self.lang_box = add_check(QComboBox())
        self.lang_box.addItems(app_constants.G_LANGUAGES)
        self.lang_box.addItems(app_constants.G_CUSTOM_LANGUAGES)
        self.rating_box = add_check(QSpinBox())
        self.rating_box.setMaximum(5)
        self.rating_box.setMinimum(0)
        self._find_combobox_match(self.lang_box, app_constants.G_DEF_LANGUAGE, 0)
        tags_l = QVBoxLayout()
        tag_info = misc.ClickedLabel("How do i write namespace & tags? (hover)", parent=self)
        tag_info.setToolTip("Ways to write tags:\n\nNormal tags:\ntag1, tag2, tag3\n\n"+
                      "Namespaced tags:\nns1:tag1, ns1:tag2\n\nNamespaced tags with one or more"+
                      " tags under same namespace:\nns1:[tag1, tag2, tag3], ns2:[tag1, tag2]\n\n"+
                      "Those three ways of writing namespace & tags can be combined freely.\n"+
                      "Tags are seperated by a comma, NOT whitespace.\nNamespaces will be capitalized while tags"+
                      " will be lowercased.")
        tag_info.setToolTipDuration(99999999)
        tags_l.addWidget(tag_info)
        self.tags_edit = add_check(misc.CompleterTextEdit())
        self.tags_edit.setCompleter(misc.GCompleter(self, False, False))
        self.tags_append = QCheckBox("Append tags", self)
        self.tags_append.setChecked(False)
        if not self._multiple_galleries:
            self.tags_append.hide()
        if self._multiple_galleries:
            self.tags_append.setChecked(app_constants.APPEND_TAGS_GALLERIES)
            tags_ml = QVBoxLayout()
            tags_ml.addWidget(self.tags_append)
            tags_ml.addLayout(checkbox_layout(self.tags_edit), 5)
            tags_l.addLayout(tags_ml, 3)
        else:
            tags_l.addWidget(checkbox_layout(self.tags_edit), 5)
        self.tags_edit.setPlaceholderText("Press Tab to autocomplete (Ctrl + E to show popup)")
        self.type_box = add_check(QComboBox())
        self.type_box.addItems(app_constants.G_TYPES)
        self._find_combobox_match(self.type_box, app_constants.G_DEF_TYPE, 0)
        #self.type_box.currentIndexChanged[int].connect(self.doujin_show)
        #self.doujin_parent = QLineEdit()
        #self.doujin_parent.setVisible(False)
        self.status_box = add_check(QComboBox())
        self.status_box.addItems(app_constants.G_STATUS)
        self._find_combobox_match(self.status_box, app_constants.G_DEF_STATUS, 0)
        self.pub_edit = add_check(QDateEdit())
        self.pub_edit.setCalendarPopup(True)
        self.pub_edit.setDate(QDate.currentDate())
        self.path_lbl = misc.ClickedLabel("")
        self.path_lbl.setWordWrap(True)
        self.path_lbl.clicked.connect(lambda a: utils.open_path(a, a) if a else None)

        link_layout = QHBoxLayout()
        self.link_lbl = add_check(QLabel(""))
        self.link_lbl.setWordWrap(True)
        self.link_edit = QLineEdit()
        link_layout.addWidget(self.link_edit)
        if self._multiple_galleries:
            link_layout.addLayout(checkbox_layout(self.link_lbl))
        else:
            link_layout.addWidget(checkbox_layout(self.link_lbl))
        self.link_edit.hide()
        self.link_btn = QPushButton("Modify")
        self.link_btn.setFixedWidth(50)
        self.link_btn2 = QPushButton("Set")
        self.link_btn2.setFixedWidth(40)
        self.link_btn.clicked.connect(self.link_modify)
        self.link_btn2.clicked.connect(self.link_set)
        link_layout.addWidget(self.link_btn)
        link_layout.addWidget(self.link_btn2)
        self.link_btn2.hide()
        
        rating_ = checkbox_layout(self.rating_box)
        lang_ = checkbox_layout(self.lang_box)
        if self._multiple_galleries:
            rating_.insertWidget(0, QLabel("Rating:"))
            lang_.addLayout(rating_)
            lang_l = lang_
        else:
            lang_l = QHBoxLayout()
            lang_l.addWidget(lang_)
            lang_l.addWidget(QLabel("Rating:"), 0, Qt.AlignRight)
            lang_l.addWidget(rating_)


        gallery_layout.addRow("Title:", checkbox_layout(self.title_edit))
        gallery_layout.addRow("Author:", checkbox_layout(self.author_edit))
        gallery_layout.addRow("Description:", checkbox_layout(self.descr_edit))
        gallery_layout.addRow("Language:", lang_l)
        gallery_layout.addRow("Tags:", tags_l)
        gallery_layout.addRow("Type:", checkbox_layout(self.type_box))
        gallery_layout.addRow("Status:", checkbox_layout(self.status_box))
        gallery_layout.addRow("Publication Date:", checkbox_layout(self.pub_edit))
        gallery_layout.addRow("Path:", self.path_lbl)
        gallery_layout.addRow("URL:", link_layout)

        self.title_edit.setFocus()

    def resizeEvent(self, event):
        self.tags_edit.setFixedHeight(event.size().height()//8)
        self.descr_edit.setFixedHeight(event.size().height()//12.5)
        return super().resizeEvent(event)

    def _find_combobox_match(self, combobox, key, default):
        f_index = combobox.findText(key, Qt.MatchFixedString)
        if f_index != -1:
            combobox.setCurrentIndex(f_index)
            return True
        else:
            combobox.setCurrentIndex(default)
            return False

    def setGallery(self, gallery):
        "To be used for when editing a gallery"
        if isinstance(gallery, gallerydb.Gallery):
            self.gallery = gallery

            if not self._multiple_galleries:
                self.url_edit.setText(gallery.link)

            self.title_edit.setText(gallery.title)
            self.author_edit.setText(gallery.artist)
            self.descr_edit.setText(gallery.info)
            self.rating_box.setValue(gallery.rating)

            self.tags_edit.setText(utils.tag_to_string(gallery.tags))


            if not self._find_combobox_match(self.lang_box, gallery.language, 1):
                self._find_combobox_match(self.lang_box, app_constants.G_DEF_LANGUAGE, 1)
            if not self._find_combobox_match(self.type_box, gallery.type, 0):
                self._find_combobox_match(self.type_box, app_constants.G_DEF_TYPE, 0)
            if not self._find_combobox_match(self.status_box, gallery.status, 0):
                self._find_combobox_match(self.status_box, app_constants.G_DEF_STATUS, 0)

            gallery_pub_date = "{}".format(gallery.pub_date).split(' ')
            try:
                self.gallery_time = datetime.strptime(gallery_pub_date[1], '%H:%M:%S').time()
            except IndexError:
                pass
            qdate_pub_date = QDate.fromString(gallery_pub_date[0], "yyyy-MM-dd")
            self.pub_edit.setDate(qdate_pub_date)

            self.link_lbl.setText(gallery.link)
            self.path_lbl.setText(gallery.path)

        elif isinstance(gallery, list):
            g = gallery[0]
            if all(map(lambda x: x.title == g.title, gallery)):
                self.title_edit.setText(g.title)
                self.title_edit.g_check.setChecked(True)
            if all(map(lambda x: x.artist == g.artist, gallery)):
                self.author_edit.setText(g.artist)
                self.author_edit.g_check.setChecked(True)
            if all(map(lambda x: x.info == g.info, gallery)):
                self.descr_edit.setText(g.info)
                self.descr_edit.g_check.setChecked(True)
            if all(map(lambda x: x.tags == g.tags, gallery)):
                self.tags_edit.setText(utils.tag_to_string(g.tags))
                self.tags_edit.g_check.setChecked(True)
            if all(map(lambda x: x.language == g.language, gallery)):
                if not self._find_combobox_match(self.lang_box, g.language, 1):
                    self._find_combobox_match(self.lang_box, app_constants.G_DEF_LANGUAGE, 1)
                self.lang_box.g_check.setChecked(True)
            if all(map(lambda x: x.rating == g.rating, gallery)):
                self.rating_box.setValue(g.rating)
                self.rating_box.g_check.setChecked(True)
            if all(map(lambda x: x.type == g.type, gallery)):
                if not self._find_combobox_match(self.type_box, g.type, 0):
                    self._find_combobox_match(self.type_box, app_constants.G_DEF_TYPE, 0)
                self.type_box.g_check.setChecked(True)
            if all(map(lambda x: x.status == g.status, gallery)):
                if not self._find_combobox_match(self.status_box, g.status, 0):
                    self._find_combobox_match(self.status_box, app_constants.G_DEF_STATUS, 0)
                self.status_box.g_check.setChecked(True)
            if all(map(lambda x: x.pub_date == g.pub_date, gallery)):
                gallery_pub_date = "{}".format(g.pub_date).split(' ')
                try:
                    self.gallery_time = datetime.strptime(gallery_pub_date[1], '%H:%M:%S').time()
                except IndexError:
                    pass
                qdate_pub_date = QDate.fromString(gallery_pub_date[0], "yyyy-MM-dd")
                self.pub_edit.setDate(qdate_pub_date)
                self.pub_edit.g_check.setChecked(True)
            if all(map(lambda x: x.link == g.link, gallery)):
                self.link_lbl.setText(g.link)
                self.link_lbl.g_check.setChecked(True)

    def newUI(self):

        f_local = QGroupBox("Directory/Archive")
        f_local.setCheckable(False)
        self.main_layout.addWidget(f_local)
        local_layout = QHBoxLayout()
        f_local.setLayout(local_layout)

        choose_folder = QPushButton("From Directory")
        choose_folder.clicked.connect(lambda: self.choose_dir('f'))
        local_layout.addWidget(choose_folder)

        choose_archive = QPushButton("From Archive")
        choose_archive.clicked.connect(lambda: self.choose_dir('a'))
        local_layout.addWidget(choose_archive)

        self.file_exists_lbl = QLabel()
        local_layout.addWidget(self.file_exists_lbl)
        self.file_exists_lbl.hide()

    def choose_dir(self, mode):
        """
        Pass which mode to open the folder explorer in:
        'f': directory
        'a': files
        Or pass a predefined path
        """
        self.done.show()
        self.file_exists_lbl.hide()
        if mode == 'a':
            name = QFileDialog.getOpenFileName(self, 'Choose archive',
                                              filter=utils.FILE_FILTER)
            name = name[0]
        elif mode == 'f':
            name = QFileDialog.getExistingDirectory(self, 'Choose folder')
        elif mode:
            if os.path.exists(mode):
                name = mode
            else:
                return None
        if not name:
            return
        head, tail = os.path.split(name)
        name = os.path.join(head, tail)
        parsed = utils.title_parser(tail)
        self.title_edit.setText(parsed['title'])
        self.author_edit.setText(parsed['artist'])
        self.path_lbl.setText(name)
        if not parsed['language']:
            parsed['language'] = app_constants.G_DEF_LANGUAGE
        l_i = self.lang_box.findText(parsed['language'])
        if l_i != -1:
            self.lang_box.setCurrentIndex(l_i)
        if gallerydb.GalleryDB.check_exists(name):
            self.file_exists_lbl.setText('<font color="red">Gallery already exists.</font>')
            self.file_exists_lbl.show()
        # check galleries
        gs = 1
        if name.endswith(utils.ARCHIVE_FILES):
            gs = len(utils.check_archive(name))
        elif os.path.isdir(name):
            g_dirs, g_archs = utils.recursive_gallery_check(name)
            gs = len(g_dirs) + len(g_archs)
        if gs == 0:
            self.file_exists_lbl.setText('<font color="red">Invalid gallery source.</font>')
            self.file_exists_lbl.show()
            self.done.hide()
        if app_constants.SUBFOLDER_AS_GALLERY:
            if gs > 1:
                self.file_exists_lbl.setText('<font color="red">More than one galleries detected in source! Use other methods to add.</font>')
                self.file_exists_lbl.show()
                self.done.hide()

    def check(self):
        if not self._multiple_galleries:
            if len(self.title_edit.text()) is 0:
                self.title_edit.setFocus()
                self.title_edit.setStyleSheet("border-style:outset;border-width:2px;border-color:red;")
                return False
            elif len(self.author_edit.text()) is 0:
                self.author_edit.setText("Unknown")

            if len(self.path_lbl.text()) == 0 or self.path_lbl.text() == 'No path specified':
                self.path_lbl.setStyleSheet("color:red")
                self.path_lbl.setText('No path specified')
                return False

        return True

    def reject(self):
        if self.check():
            msgbox = QMessageBox()
            msgbox.setText("<font color='red'><b>Noo oniichan! You were about to add a new gallery.</b></font>")
            msgbox.setInformativeText("Do you really want to discard?")
            msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            msgbox.setDefaultButton(QMessageBox.No)
            if msgbox.exec() == QMessageBox.Yes:
                self.close()
        else:
            self.close()

    def web_metadata(self, url, btn_widget, pgr_widget):
        if not self.path_lbl.text():
            return
        self.link_lbl.setText(url)
        btn_widget.hide()
        pgr_widget.show()

        def status(stat):
            def do_hide():
                try:
                    pgr_widget.hide()
                    btn_widget.show()
                except RuntimeError:
                    pass

            if stat:
                do_hide()
            else:
                danger = """QProgressBar::chunk {
                    background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,stop: 0 #FF0350,stop: 0.4999 #FF0020,stop: 0.5 #FF0019,stop: 1 #FF0000 );
                    border-bottom-right-radius: 5px;
                    border-bottom-left-radius: 5px;
                    border: .px solid black;}"""
                pgr_widget.setStyleSheet(danger)
                QTimer.singleShot(3000, do_hide)

        def gallery_picker(gallery, title_url_list, q):
            self.parent_widget._web_metadata_picker(gallery, title_url_list, q, self)

        try:
            dummy_gallery = self.make_gallery(self.gallery, False)
        except AttributeError:
            dummy_gallery = self.make_gallery(gallerydb.Gallery(), False, True)
        if not dummy_gallery:
            status(False)
            return None

        dummy_gallery._g_dialog_url = url
        self._fetch_inst.galleries = [dummy_gallery]
        self._disconnect()
        self._fetch_inst.GALLERY_PICKER.connect(gallery_picker)
        self._fetch_inst.GALLERY_EMITTER.connect(self.set_web_metadata)
        self._fetch_inst.FINISHED.connect(status)
        self._fetch_thread.start()
            
    def set_web_metadata(self, metadata):
        assert isinstance(metadata, gallerydb.Gallery)
        self.link_lbl.setText(metadata.link)
        self.title_edit.setText(metadata.title)
        self.author_edit.setText(metadata.artist)
        tags = ""
        lang = ['English', 'Japanese']
        self._find_combobox_match(self.lang_box, metadata.language, 2)
        self.tags_edit.setText(utils.tag_to_string(metadata.tags))
        pub_string = "{}".format(metadata.pub_date)
        pub_date = QDate.fromString(pub_string.split()[0], "yyyy-MM-dd")
        self.pub_edit.setDate(pub_date)
        self._find_combobox_match(self.type_box, metadata.type, 0)

    def make_gallery(self, new_gallery, add_to_model=True, new=False):
        def is_checked(widget):
            return widget.g_check.isChecked()
        if self.check():
            if is_checked(self.title_edit):
                new_gallery.title = self.title_edit.text()
                log_d('Adding gallery title')
            if is_checked(self.author_edit):
                new_gallery.artist = self.author_edit.text()
                log_d('Adding gallery artist')
            if not self._multiple_galleries:
                new_gallery.path = self.path_lbl.text()
                log_d('Adding gallery path')
            if is_checked(self.descr_edit):
                new_gallery.info = self.descr_edit.toPlainText()
                log_d('Adding gallery descr')
            if is_checked(self.type_box):
                new_gallery.type = self.type_box.currentText()
                log_d('Adding gallery type')
            if is_checked(self.lang_box):
                new_gallery.language = self.lang_box.currentText()
                log_d('Adding gallery lang')
            if is_checked(self.rating_box):
                new_gallery.rating = self.rating_box.value()
                log_d('Adding gallery rating')
            if is_checked(self.status_box):
                new_gallery.status = self.status_box.currentText()
                log_d('Adding gallery status')
            if is_checked(self.tags_edit):
                if self.tags_append.isChecked():
                    new_gallery.tags = utils.tag_to_dict(utils.tag_to_string(new_gallery.tags)+","+ self.tags_edit.toPlainText())
                else:
                    new_gallery.tags = utils.tag_to_dict(self.tags_edit.toPlainText())
                log_d('Adding gallery: tagging to dict')
            if is_checked(self.pub_edit):
                qpub_d = self.pub_edit.date().toString("ddMMyyyy")
                dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date()
                try:
                    d_t = self.gallery_time
                except AttributeError:
                    d_t = datetime.now().time().replace(microsecond=0)
                dpub_d = datetime.combine(dpub_d, d_t)
                new_gallery.pub_date = dpub_d
                log_d('Adding gallery pub date')
            if is_checked(self.link_lbl):
                new_gallery.link = self.link_lbl.text()
                log_d('Adding gallery link')

            if new:
                if not new_gallery.chapters:
                    log_d('Starting chapters')
                    thread = threading.Thread(target=utils.make_chapters, args=(new_gallery,))
                    thread.start()
                    thread.join()
                    log_d('Finished chapters')
                    if new and app_constants.MOVE_IMPORTED_GALLERIES:
                        app_constants.OVERRIDE_MONITOR = True
                        new_gallery.move_gallery()
                if add_to_model:
                    self.parent_widget.default_manga_view.add_gallery(new_gallery, True)
                    log_i('Sent gallery to model')
            else:
                if add_to_model:
                    self.parent_widget.default_manga_view.replace_gallery([new_gallery], False)
            return new_gallery


    def link_set(self):
        t = self.link_edit.text()
        self.link_edit.hide()
        self.link_lbl.show()
        self.link_lbl.setText(t)
        self.link_btn2.hide()
        self.link_btn.show() 

    def link_modify(self):
        t = self.link_lbl.text()
        self.link_lbl.hide()
        self.link_edit.show()
        self.link_edit.setText(t)
        self.link_btn.hide()
        self.link_btn2.show()

    def _disconnect(self):
        try:
            self._fetch_inst.GALLERY_PICKER.disconnect()
            self._fetch_inst.GALLERY_EMITTER.disconnect()
            self._fetch_inst.FINISHED.disconnect()
        except TypeError:
            pass

    def delayed_close(self):
        if self._fetch_thread.isRunning():
            self._fetch_thread.finished.connect(self.close)
            self.hide()
        else:
            self.close()

    def accept(self):
        self.make_gallery(gallerydb.Gallery(), new=True)
        self.delayed_close()

    def accept_edit(self):
        gallerydb.execute(database.db.DBBase.begin, True)
        app_constants.APPEND_TAGS_GALLERIES = self.tags_append.isChecked()
        settings.set(app_constants.APPEND_TAGS_GALLERIES, 'Application', 'append tags to gallery')
        for g in self._edit_galleries:
            self.make_gallery(g)
        self.delayed_close()
        gallerydb.execute(database.db.DBBase.end, True)

    def reject_edit(self):
        self.delayed_close()