def setupUi(self): self.log.debug("Initializing UI.") self.load_ui("dta.ui") # set up source/target autocompletion type_completion_list = [str(t) for t in self.policy.types()] type_completer_model = QStringListModel(self) type_completer_model.setStringList(sorted(type_completion_list)) self.type_completion = QCompleter() self.type_completion.setModel(type_completer_model) self.source.setCompleter(self.type_completion) self.target.setCompleter(self.type_completion) # setup indications of errors on source/target/default self.orig_palette = self.source.palette() self.error_palette = self.source.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_source_error() self.clear_target_error() # set up processing thread self.thread = QThread() self.worker = ResultsUpdater(self.query) self.worker.moveToThread(self.thread) self.worker.raw_line.connect(self.raw_results.appendPlainText) self.worker.finished.connect(self.thread.quit) self.thread.started.connect(self.worker.update) self.thread.finished.connect(self.update_complete) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.canceled.connect(self.thread.requestInterruption) self.busy.reset() # update busy dialog from DTA INFO logs self.handler = LogHandlerToSignal() self.handler.message.connect(self.busy.setLabelText) logging.getLogger("setools.dta").addHandler(self.handler) # Ensure settings are consistent with the initial .ui state self.max_path_length.setEnabled(self.all_paths.isChecked()) self.source.setEnabled(not self.flows_in.isChecked()) self.target.setEnabled(not self.flows_out.isChecked()) self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) # connect signals self.buttonBox.clicked.connect(self.run) self.source.textEdited.connect(self.clear_source_error) self.source.editingFinished.connect(self.set_source) self.target.textEdited.connect(self.clear_target_error) self.target.editingFinished.connect(self.set_target) self.all_paths.toggled.connect(self.all_paths_toggled) self.flows_in.toggled.connect(self.flows_in_toggled) self.flows_out.toggled.connect(self.flows_out_toggled) self.reverse.stateChanged.connect(self.reverse_toggled) self.exclude_types.clicked.connect(self.choose_excluded_types)
def set_auto_completion(self, string_list): completer = QCompleter() model = QStringListModel() model.setStringList(string_list) completer.setModel(model) completer.activated.connect(self.search, type=Qt.QueuedConnection) self.combobox_search.setCompleter(completer)
def _make_expression_completer(owner, data_type): model = QStringListModel() comp = QCompleter(owner) comp.setCaseSensitivity(Qt.CaseSensitive) if isinstance(data_type, str): data_type = uavcan.TYPENAMES[data_type] # TODO: implement proper completion, requires Python lexer # TODO: IPython/Jupyter solves the same task splendidly, might make sense to take a closer look at their code def make_suggestions(t): """Builds a flat list of fields in a given data type""" if t.category == t.CATEGORY_COMPOUND: out = [] for a in t.fields + t.constants: if (a.type.category != a.type.CATEGORY_COMPOUND) and \ (a.type.category != a.type.CATEGORY_VOID) and \ (a.type.category != a.type.CATEGORY_ARRAY or a.type.value_type.category == a.type.value_type.CATEGORY_PRIMITIVE): out.append(a.name) out += [(a.name + x) for x in make_suggestions(a.type)] return [('.' + x) for x in out] elif t.category == t.CATEGORY_ARRAY: base = '[0]' if t.value_type.category == t.CATEGORY_COMPOUND: return [(base + x) for x in make_suggestions(t.value_type)] else: return [base] return [] suggestions = [(EXPRESSION_VARIABLE_FOR_MESSAGE + x) for x in make_suggestions(data_type)] model.setStringList(suggestions) comp.setModel(model) return comp
class Completer(QGraphicsProxyWidget, object): ''' Class for handling text autocompletion in the SDL scene ''' def __init__(self, parent): ''' Create an autocompletion list popup ''' widget = QListWidget() super(Completer, self).__init__(parent) self.setWidget(widget) self.string_list = QStringListModel() self._completer = QCompleter() self.parent = parent self._completer.setCaseSensitivity(Qt.CaseInsensitive) # For some reason the default minimum size is (61,61) # Set it to 0 so that the size of the box is not taken # into account when it is hidden. self.setMinimumSize(0, 0) self.prepareGeometryChange() self.resize(0, 0) self.hide() def set_completer_list(self): ''' Set list of items for the autocompleter popup ''' compl = [item.replace('-', '_') for item in self.parent.parentItem().completion_list] self.string_list.setStringList(compl) self._completer.setModel(self.string_list) def set_completion_prefix(self, completion_prefix): ''' Set the current completion prefix (user-entered text) and set the corresponding list of words in the popup widget ''' self._completer.setCompletionPrefix(completion_prefix) self.widget().clear() count = self._completer.completionCount() for i in xrange(count): self._completer.setCurrentRow(i) self.widget().addItem(self._completer.currentCompletion()) self.prepareGeometryChange() if count: self.resize(self.widget().sizeHintForColumn(0) + 40, 70) else: self.resize(0, 0) return count # pylint: disable=C0103 def keyPressEvent(self, e): super(Completer, self).keyPressEvent(e) if e.key() == Qt.Key_Escape: self.parentItem().setFocus() # Consume the event so that it is not repeated at EditableText level e.accept() # pylint: disable=C0103 def focusOutEvent(self, event): ''' When the user leaves the popup, return focus to parent ''' super(Completer, self).focusOutEvent(event) self.hide() self.resize(0, 0) self.parentItem().setFocus()
class OrderItemsDialog(QDialog, Ui_OrderItemsDialog): """ This class is a dialog for changing the order of qualitative parameter's values The dialog lists the values and allow changing the order using Up and Down buttons which replace the selected value with the one before/after it in the list """ def __init__(self, parent, listToOrder: list): """ Initialize the change order dialog Args: parent : (QDialog) - The parent dialog listToOrder : (list) - The list to set the order for """ QDialog.__init__(self, parent) self.setupUi(self) self.listToOrder = listToOrder self.model = QStringListModel(self) self.model.setStringList(listToOrder) self.listView_items.setModel(self.model) self.pushButton_up.clicked.connect(self.pushButton_up_clicked) self.pushButton_down.clicked.connect(self.pushButton_down_clicked) def pushButton_up_clicked(self): """ Replace the selected item with the one before it """ selectedIndex = self.listView_items.currentIndex().row() self.replaceItems(selectedIndex, selectedIndex - 1) def pushButton_down_clicked(self): """ Replace the selected item with the one after it """ selectedIndex = self.listView_items.currentIndex().row() self.replaceItems(selectedIndex, selectedIndex + 1) def replaceItems(self, fromIndex, toIndex): """ Replace 2 items Args: fromIndex : (int) - the index of the selected item toIndex : (int) - the target index of the selected item """ if toIndex in range(len(self.listToOrder)): temp = self.listToOrder[toIndex] self.listToOrder[toIndex] = self.listToOrder[fromIndex] self.listToOrder[fromIndex] = temp self.model.setStringList(self.listToOrder) self.model.dataChanged.emit( self.listView_items.indexAt(QPoint(0, 0)), self.listView_items.indexAt(QPoint(len(self.listToOrder), 0))) index = self.model.createIndex(toIndex, 0) self.listView_items.setCurrentIndex(index)
def __init__(self,expdat): super(DBAnnotateSave, self).__init__() print("DBAnnotateSave") uic.loadUi(os.path.join(hs.heatsequerdir,'ui/manualdata.py'), self) self.bplus.clicked.connect(self.plus) self.bminus.clicked.connect(self.minus) self.bontoinput.returnPressed.connect(self.plus) self.bstudyinfo.clicked.connect(self.studyinfo) self.bisa.toggled.connect(self.radiotoggle) self.bdiffpres.toggled.connect(self.radiotoggle) self.bisatype.currentIndexChanged.connect(self.isatypechanged) self.bhistory.clicked.connect(self.history) self.cexp=expdat self.lnumbact.setText(str(len(expdat.selectedseqs))) completer = QCompleter() self.bontoinput.setCompleter(completer) scdb=hs.scdb self.scdb=scdb self.dataid=hs.supercooldb.finddataid(scdb,datamd5=self.cexp.datamd5,mapmd5=self.cexp.mapmd5) model = QStringListModel() completer.setModel(model) # completer.setCompletionMode(QCompleter.InlineCompletion) completer.maxVisibleItems=10 completer.setCaseSensitivity(Qt.CaseInsensitive) # make the completer selection also erase the text edit completer.activated.connect(self.cleartext,type=Qt.QueuedConnection) # in qt5 should work with middle complete as well... # completer.setFilterMode(Qt.MatchContains) if not hs.scdb.ontologyfromid: hs.scdb=hs.supercooldb.loaddbonto(hs.scdb) self.ontology=hs.scdb.ontology self.ontologyfromid=hs.scdb.ontologyfromid nlist=list(self.ontology.keys()) # nlist=sorted(nlist) nlist=sorted(nlist, key=lambda s: s.lower()) print("sorted ontology") model.setStringList(nlist) self.setWindowTitle(self.cexp.studyname) try: tt=hs.lastdatamd5 except: hs.lastdatamd5='' if self.cexp.datamd5==hs.lastdatamd5: self.fillfromcuration(hs.lastcurations[-1],onlyall=True) self.prefillinfo() self.bontoinput.setFocus()
def loadUi(self): self.setWindowTitle("Pick your ISO") layout = QVBoxLayout(self) ui = loadUi("ui/iso.ui") self.resize(ui.size()) layout.addWidget(ui) model = QStringListModel(ui) view = ui.findChild(QListView, 'isoList') model.setStringList(self.isos) view.setModel(model) self.distList = view add = ui.findChild(QPushButton, 'add') add.clicked.connect(self.selectDistribution)
def setDifficulty(self): if self.diffiModel is None: self.diffiModel=QStringListModel() self.cmbDifficulty.setModel(self.diffiModel) self.diffiModel.setStringList(self.arith.difficulties) self.cmbDifficulty.setCurrentIndex(self.arith.diffiLevel) return
def __init__(self, data, info, parent=None): """ Constructor @param data contents to be edited (string) @param info info string to show at the header (string) @param parent reference to the parent widget (QWidget) """ super(SpellingDictionaryEditDialog, self).__init__(parent) self.setupUi(self) self.infoLabel.setText(info) self.__model = QStringListModel(data.splitlines(), self) self.__model.sort(0) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.__proxyModel.setDynamicSortFilter(True) self.__proxyModel.setSourceModel(self.__model) self.wordList.setModel(self.__proxyModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.wordList.removeSelected) self.removeAllButton.clicked.connect(self.wordList.removeAll)
def setMode(self): # only called once for initialization of main window if self.modeModel is None: self.modeModel = QStringListModel() self.cmbMode.setModel(self.modeModel) self.modeModel.setStringList(self.arith.modeTexts[self.arith.diffiLevel]) self.cmbMode.setCurrentIndex(self.arith.mode) return
def setArith_old(self,arith): self.arith=arith if self.diffiModel is None: self.diffiModel = QStringListModel() self.diffiModel.setStringList(self.arith.difficulties) self.cmbDifficulty.setModel(self.diffiModel) else: self.diffiModel.setStringList(self.arith.difficulties) if self.modeModel is None: self.modeModel = QStringListModel() self.modeModel.setStringList(self.arith.modeTexts[self.arith.diffiLevel]) self.cmbMode.setModel(self.modeModel) else: self.modeModel.setStringList(self.arith.modeTexts[self.arith.diffiLevel]) self.showArith() self.setParameters(arith) return
def reloadArtist(self): query = QSqlQuery() query.prepare("SELECT id, name FROM t_artist") query.setForwardOnly(1) query.exec_() artistlist = [] while query.next(): artistlist.append(str(query.value(0)) + ' - ' + query.value(1)) self.modelright = QStringListModel() self.modelright.setStringList(artistlist) self.listView_ArtistList.setModel(self.modelright) pass
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(HelpLanguagesDialog, self).__init__(parent) self.setupUi(self) self.__model = QStringListModel() self.languagesList.setModel(self.__model) self.languagesList.selectionModel().currentChanged.connect( self.__currentChanged) languages = Preferences.toList(Preferences.Prefs.settings.value( "Help/AcceptLanguages", self.defaultAcceptLanguages())) self.__model.setStringList(languages) allLanguages = [] for index in range(QLocale.C + 1, QLocale.LastLanguage + 1): allLanguages += self.expand(QLocale.Language(index)) self.__allLanguagesModel = QStringListModel() self.__allLanguagesModel.setStringList(allLanguages) self.addCombo.setModel(self.__allLanguagesModel)
def __init__(self, parent): QVBoxLayout.__init__(self, parent) self.scroll_area = QScrollArea() # A ListView is a widget, instead of a layout, so there should be no need for additional containers self.list_view = QListView() self.scroll_area.setWidget(self.list_view) self.addWidget(self.list_view) self.view_model = QStringListModel() self.list_view.setModel(self.view_model)
def __init__(self): super(WiFiPresetDialog, self).__init__(None, Qt.WindowCloseButtonHint) self.setupUi(self) self.selected_ip = None self.selected_port = None self.selected_password = None self.presetsListView.doubleClicked.connect(self.select_preset) self.addButton.clicked.connect(self.add_preset) self.removeButton.clicked.connect(self.remove_preset) self.model = QStringListModel() self.presetsListView.setModel(self.model) self.update_preset_list()
def __init__(self, parent): ''' Create an autocompletion list popup ''' widget = QListWidget() super(Completer, self).__init__(parent) self.setWidget(widget) self.string_list = QStringListModel() self._completer = QCompleter() self.parent = parent self._completer.setCaseSensitivity(Qt.CaseInsensitive) # For some reason the default minimum size is (61,61) # Set it to 0 so that the size of the box is not taken # into account when it is hidden. self.setMinimumSize(0, 0) self.prepareGeometryChange() self.resize(0, 0) self.hide()
def __init__(self, parent, listToOrder: list): """ Initialize the change order dialog Args: parent : (QDialog) - The parent dialog listToOrder : (list) - The list to set the order for """ QDialog.__init__(self, parent) self.setupUi(self) self.listToOrder = listToOrder self.model = QStringListModel(self) self.model.setStringList(listToOrder) self.listView_items.setModel(self.model) self.pushButton_up.clicked.connect(self.pushButton_up_clicked) self.pushButton_down.clicked.connect(self.pushButton_down_clicked)
def __init__(self): QMainWindow.__init__(self) self._bibReader = None self._keyFields = [] self.ui = uic.loadUi('UI/MainWindow.ui', self) self.ui.actionOpen.triggered.connect(self.onActionOpenFile) self.ui.actionSave_as.triggered.connect(self.onActionSaveAs) self._modelFields = QStringListModel() self.ui.lv_fields.setModel(self._modelFields) self.ui.lv_fields.selectedIndicesChanged.connect(self.onFieldSelectionChanged) self.ui.pb_clearSelection.clicked.connect(self.onButtonClearSelectionClicked) self.ui.pb_preview.clicked.connect(self.onButtonPreviewClicked)
class SpellingDictionaryEditDialog(QDialog, Ui_SpellingDictionaryEditDialog): """ Class implementing a dialog to edit the various spell checking dictionaries. """ def __init__(self, data, info, parent=None): """ Constructor @param data contents to be edited (string) @param info info string to show at the header (string) @param parent reference to the parent widget (QWidget) """ super(SpellingDictionaryEditDialog, self).__init__(parent) self.setupUi(self) self.infoLabel.setText(info) self.__model = QStringListModel(data.splitlines(), self) self.__model.sort(0) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.__proxyModel.setDynamicSortFilter(True) self.__proxyModel.setSourceModel(self.__model) self.wordList.setModel(self.__proxyModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.wordList.removeSelected) self.removeAllButton.clicked.connect(self.wordList.removeAll) @pyqtSlot() def on_addButton_clicked(self): """ Private slot to handle adding an entry. """ self.__model.insertRow(self.__model.rowCount()) self.wordList.edit( self.__proxyModel.index(self.__model.rowCount() - 1, 0)) def getData(self): """ Public method to get the data. @return data of the dialog (string) """ return os.linesep.join( [line for line in self.__model.stringList() if line])
def list_mcu_files(self): file_list = [] try: file_list = self._connection.list_files() except OperationError: QMessageBox().critical(self, "Operation failed", "Could not list files.", QMessageBox.Ok) return self._mcu_files_model = QStringListModel() for file in file_list: idx = self._mcu_files_model.rowCount() self._mcu_files_model.insertRow(idx) self._mcu_files_model.setData(self._mcu_files_model.index(idx), file) self.mcuFilesListView.setModel(self._mcu_files_model) self.mcu_file_selection_changed()
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(E5StringListEditWidget, self).__init__(parent) self.setupUi(self) self.__model = QStringListModel(self) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.__proxyModel.setSourceModel(self.__model) self.stringList.setModel(self.__proxyModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.stringList.removeSelected) self.removeAllButton.clicked.connect(self.stringList.removeAll)
def __init__(self, namespace, parent): """Constructor. Args: namespace: The local namespace of the interpreter. """ super().__init__(parent) self.update_font() objreg.get('config').changed.connect(self.update_font) self.textChanged.connect(self.on_text_changed) self._rlcompleter = rlcompleter.Completer(namespace) qcompleter = QCompleter(self) self._model = QStringListModel(qcompleter) qcompleter.setModel(self._model) qcompleter.setCompletionMode( QCompleter.UnfilteredPopupCompletion) qcompleter.setModelSorting( QCompleter.CaseSensitivelySortedModel) self.setCompleter(qcompleter) self._history = cmdhistory.History() self.returnPressed.connect(self.on_return_pressed)
def __init__(self, messageFilters, parent=None): """ Constructor @param messageFilters list of message filters to be edited (list of strings) @param parent reference to the parent widget (QWidget) """ super(E5ErrorMessageFilterDialog, self).__init__(parent) self.setupUi(self) self.__model = QStringListModel(messageFilters, self) self.__model.sort(0) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.__proxyModel.setSourceModel(self.__model) self.filterList.setModel(self.__proxyModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.filterList.removeSelected) self.removeAllButton.clicked.connect(self.filterList.removeAll)
def __init__(self, controller): super(AppletNoticeWindow, self).__init__() self.__controller = controller self.__pkglist = [] # setup widgets self.__vbox_up = QVBoxLayout() self.__critical_label = QLabel() self.__critical_label.setWordWrap(True) self.__list_model = QStringListModel() self.__list_view = QListView() self.__list_view.setModel(self.__list_model) self.__vbox_up.addWidget(self.__critical_label) self.__vbox_up.addWidget(self.__list_view) # bottom buttons self.__vbox = QVBoxLayout() self.__vbox.addLayout(self.__vbox_up) self.__button_hbox = QHBoxLayout() self.__close_button = QPushButton(_("Close")) self.__launch_pm_button = QPushButton(_("Launch Application Browser")) self.__button_hbox.addWidget(self.__launch_pm_button) self.__button_hbox.addWidget(self.__close_button) self.__vbox.addLayout(self.__button_hbox) self.setLayout(self.__vbox) # set window settings self.resize(400, 200) self.setWindowTitle(_("Application updates")) self.__close_button.clicked.connect(self.on_close) self.__launch_pm_button.clicked.connect(self.on_pm)
def __init__(self, whitelist, parent=None): """ Constructor @param whitelist list of whitelisted hosts (list of string) @param parent reference to the parent widget (QWidget) """ super(ClickToFlashWhitelistDialog, self).__init__(parent) self.setupUi(self) self.iconLabel.setPixmap(UI.PixmapCache.getPixmap("flashBlock48.png")) self.__model = QStringListModel(whitelist[:], self) self.__model.sort(0) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.__proxyModel.setSourceModel(self.__model) self.whitelist.setModel(self.__proxyModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.whitelist.removeSelected) self.removeAllButton.clicked.connect(self.whitelist.removeAll)
class E5ErrorMessageFilterDialog(QDialog, Ui_E5ErrorMessageFilterDialog): """ Class implementing a dialog to manage the list of messages to be ignored. """ def __init__(self, messageFilters, parent=None): """ Constructor @param messageFilters list of message filters to be edited (list of strings) @param parent reference to the parent widget (QWidget) """ super(E5ErrorMessageFilterDialog, self).__init__(parent) self.setupUi(self) self.__model = QStringListModel(messageFilters, self) self.__model.sort(0) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.__proxyModel.setSourceModel(self.__model) self.filterList.setModel(self.__proxyModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.filterList.removeSelected) self.removeAllButton.clicked.connect(self.filterList.removeAll) @pyqtSlot() def on_addButton_clicked(self): """ Private slot to add an entry to the list. """ filter, ok = QInputDialog.getText( self, self.tr("Error Messages Filter"), self.tr("Enter message filter to add to the list:"), QLineEdit.Normal) if ok and filter != "" and filter not in self.__model.stringList(): self.__model.insertRow(self.__model.rowCount()) self.__model.setData( self.__model.index(self.__model.rowCount() - 1), filter) self.__model.sort(0) def getFilters(self): """ Public method to get the list of message filters. @return error message filters (list of strings) """ return self.__model.stringList()[:]
def initData(self): vals = ["0", "1", "2", "3", "4"] self.model = QStringListModel(vals)
class MyControlPanel(QWidget): flagselected = pyqtSignal(int) def __init__(self, model, parent=None): QWidget.__init__(self, parent) self.ui = Ui_ControlPanel() self.ui.setupUi(self) self.model = model sortmenu = QMenu() for i, col in enumerate( sorted(set(self.model.cols) - self.model.cfg.internalCols, key=self.model.prettyname)): # Sort Menu a = sortmenu.addAction(self.model.prettyname(col)) a.setData(col) a.triggered.connect(self.onAddSortField) # Sort self.ui.addSortField.setMenu(sortmenu) self.ui.sortByListWidget.itemSelectionChanged.connect( self.onSelectionChange) self.onSelectionChange() self.ui.removeSortField.clicked.connect(self.onRemoveSortField) self.ui.moveSortField.clicked.connect(self.onMoveSortFieldUp) self.ui.sortAscendingCheckBox.clicked.connect( self.onSortAscendingChange) # Legend self.legendWidget = partitionWidget.MyPartitionWidget( model, self.model.setStacks, model.cfg.legendInitial, True, True, self) self.legendWidget.ui.description.setText( "Change field and colors for stacked histograms. Double click to edit color. Single click on selected to edit label. Checkboxes only affect visibility, not the selected items." ) self.legendWidget.ui.groupBox.setTitle("Histogram Legends") self.ui.verticalLayout_7.insertWidget(1, self.legendWidget) # Partition self.partWidget = partitionWidget.MyPartitionWidget( model, self.model.setPartition, model.cfg.partitionInitial, True, False, self) self.partWidget.ui.description.setText( "Partition the data. Selecting a partition changes the full dataset shown in plots to just match the partition. When partitions are active, output is split with one output for each partition." ) self.partWidget.ui.groupBox.setTitle("Partitions") self.ui.verticalLayout_7.insertWidget(2, self.partWidget) # Flags if self.model.flagFilter.isActive(): self.ui.flagIgnore.setChecked(True) if self.model.flagFilter.invert: self.ui.flagExclude.setChecked(True) else: self.ui.flagKeep.setChecked(True) else: self.ui.flagIgnore.setChecked(True) self.model.flagFilter.filterchange.connect(self.onFlagChange) self.flagModel = QStringListModel() self.ui.flaggedList.setModel(self.flagModel) self.ui.flagIgnore.clicked.connect(self.onIgnoreFlags) self.ui.flagExclude.clicked.connect(self.onExcludeFlags) self.ui.flagKeep.clicked.connect(self.onOnlyFlags) self.ui.flaggedList.selectionModel().currentChanged.connect( self.onSelectFlag) # Limits self.ui.limitCheckBox.clicked.connect(self.onLimitChange) self.ui.limTopButton.clicked.connect(self.onLimitChange) self.ui.limRandomButton.clicked.connect(self.onLimitChange) self.ui.limitSpinBox.editingFinished.connect(self.onLimitChange) self.onLimitChange() # Filters self.filtermodel = FilterModel(model.topfilter, model) self.ui.filterTreeView.setEditTriggers( QAbstractItemView.AllEditTriggers) self.ui.filterTreeView.setModel(self.filtermodel) if qt5: self.ui.filterTreeView.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self.ui.filterTreeView.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) else: self.ui.filterTreeView.header().setResizeMode( 0, QHeaderView.ResizeToContents) self.ui.filterTreeView.header().setResizeMode( 1, QHeaderView.ResizeToContents) self.ui.filterTreeView.setItemDelegate( filterEditDelegate.FilterItemDelegate()) self.filtermodel.rowsInserted.connect(self.ui.filterTreeView.expandAll) self.ui.filterTreeView.expandAll() # Filters Save/Load self.ui.saveFiltersButton.clicked.connect(self.onSaveFilters) self.ui.loadFiltersButton.clicked.connect(self.onLoadFilters) # Sorting def onAddSortField(self): field = self.sender().data() self.ui.sortByListWidget.addItem(self.model.prettyname(field)) self.model.sortlst.append(field) self.model.onSortChange() def onSelectionChange(self): hasSelection = bool(len(self.ui.sortByListWidget.selectedItems())) self.ui.removeSortField.setEnabled(hasSelection) canMove = hasSelection for item in self.ui.sortByListWidget.selectedItems(): canMove &= self.ui.sortByListWidget.row(item) != 0 self.ui.moveSortField.setEnabled(canMove) def onRemoveSortField(self): rows = [] for item in self.ui.sortByListWidget.selectedItems(): rows.append(self.ui.sortByListWidget.row(item)) for r in sorted(rows, reverse=True): del self.model.sortlst[r] self.ui.sortByListWidget.takeItem(r) self.model.onSortChange() self.onSelectionChange() def onMoveSortFieldUp(self): rows = [] for item in self.ui.sortByListWidget.selectedItems(): rows.append(self.ui.sortByListWidget.row(item)) for r in sorted(rows): self.model.sortlst.insert(r - 1, self.model.sortlst.pop(r)) self.ui.sortByListWidget.insertItem( r - 1, self.ui.sortByListWidget.takeItem(r)) self.ui.sortByListWidget.setCurrentItem( self.ui.sortByListWidget.item(r - 1)) self.model.onSortChange() def setSort(self, lst): for field in lst: self.ui.sortByListWidget.addItem(self.model.prettyname(field)) self.model.sortlst.append(field) self.model.onSortChange() def onSortAscendingChange(self): self.model.reverseSort = not self.ui.sortAscendingCheckBox.isChecked() self.model.onSortChange() # Flags def onFlagChange(self): slist = [] for i in np.where(self.model.flagFilter.keep)[0]: slist.append(str(i)) self.flagModel.setStringList(slist) def onIgnoreFlags(self, checked): if checked: self.model.flagFilter.setActive(False) def onExcludeFlags(self, checked): if checked: self.model.flagFilter.setInvert(True) self.model.flagFilter.setActive(True) def onOnlyFlags(self, checked): if checked: self.model.flagFilter.setInvert(False) self.model.flagFilter.setActive(True) def onSelectFlag(self): row = int( self.flagModel.data( self.ui.flaggedList.selectionModel().currentIndex(), Qt.DisplayRole)) self.flagselected.emit(row) # Limits def onLimitChange(self): if self.ui.limitCheckBox.isChecked(): self.model.limit = self.ui.limitSpinBox.value() else: self.model.limit = None self.model.limitModeRandom = self.ui.limRandomButton.isChecked() def setLimit(self, l): self.ui.limitSpinBox.setValue(l) self.ui.limitCheckBox.setChecked(True) self.onLimitChange() # Filters def onSaveFilters(self): name = QFileDialog.getSaveFileName(self, 'Save Filters As', filter='*.xml') if qt5: if name: self.model.saveFilters(name[0]) elif name is not None and len(name): self.model.saveFilters(name) def onLoadFilters(self): name = QFileDialog.getOpenFileName(self, 'Load Filter File', filter='*.xml') if qt5: if name: self.model.loadFilters(name[0]) elif name is not None and len(name): self.model.loadFilters(name)
class OrgEditWidget(Ui_orgEdit, QWidget): def __init__(self, conn, parent=None): super().__init__() self.setupUi(self) # 保存数据库连接 self.conn = conn # 初始化UI界面及各个控件 self.initUI() self.org_name = "" # 显示widget self.show() def initOrgListView(self): """ 初始化组织列表 """ self.OrgModel = QStringListModel() self.orgList = self.loadOrganizationData() # 加载所有的组织 self.OrgModel.setStringList(self.orgList) self.orgListView.setModel(self.OrgModel) def initMemberListView(self): """ 初始化成员列表 """ self.MemberModel = QStringListModel() self.memberList = [] self.MemberModel.setStringList(self.memberList) self.memberListView.setModel(self.MemberModel) def clearMember(self): """ 清空成员列表 """ self.memberList = [] self.MemberModel.setStringList(self.memberList) def addMember(self, name, number): """ 在成员列表里面新增一个人员 """ self.memberList.append(name + "\t" + number) self.MemberModel.setStringList(self.memberList) def initUI(self): """ 初始化UI界面及各个控件 """ self.orgListView.setEditTriggers( QAbstractItemView.NoEditTriggers) # 不可编辑内容 self.memberListView.setEditTriggers( QAbstractItemView.NoEditTriggers) # 不可编辑内容 self.initOrgListView() self.initMemberListView() self.orgListView.clicked.connect(self.displayStudent) self.addMemberBtn.clicked.connect(self.addOrgMember) def addOrgMember(self): org_name = self.org_name if org_name == "": QMessageBox(QMessageBox.Warning, '警告', '请先选择组织!').exec_() return self.OrgAddMember = OrgAddStudentWidget(self.conn, org_name, self) def displayStudent(self, index): """ 每次单击组织名称后更新右边的学生列表 """ self.clearMember() org_id = query_org_id_by_org_name(self.conn, index.data()) org_name = index.data() self.org_name = org_name students = query_stus_by_org_id(self.conn, org_id) pairs = [] for student in students: student_record = query_student_by_id(self.conn, student[1]) pairs.append((student_record[1], student_record[4])) for pair in pairs: self.addMember(pair[0], pair[1]) def loadOrganizationData(self): orgs = query_all_organization(self.conn) return [i[1] for i in orgs]
class MainWindow(QMainWindow): def __init__(self, parent=None, data_set = ""): super(MainWindow, self).__init__(parent) self.current_sum = 0 self.emg = [] self.imu = [] self.myo = None self.check_timer = PTimer(self, self.check_sample) self.read_data_set(data_set) self.initUI() def read_data_set(self, data_set): with open(data_set) as f: self.project = json.load(f) def initUI(self): self.setWindowTitle(self.project["name"]) self.setGeometry(240, 120, WIDTH, HEIGHT) self.setFixedSize(QSize(WIDTH, HEIGHT)) files_group = QGroupBox(self) files_group.setGeometry(20, 10, 590, 300) files_group.setTitle("Files") files_group.setStyleSheet(ll_ss) act_group = QGroupBox(self) act_group.setGeometry(630, 10, 170, 300) act_group.setTitle("Actions") act_group.setStyleSheet(ll_ss) log_group = QGroupBox(self) log_group.setGeometry(20, 320, 430, 190) log_group.setTitle("Log") log_group.setStyleSheet(ll_ss) device_group = QGroupBox(self) device_group.setGeometry(470, 320, 160, 190) device_group.setTitle("Device") device_group.setStyleSheet(ll_ss) status_group = QGroupBox(self) status_group.setGeometry(650, 320, 150, 190) status_group.setTitle("Status") status_group.setStyleSheet(ll_ss) self.wheres = QComboBox(act_group) self.gestures = QComboBox(act_group) self.wheres.setGeometry(10, 30, 150, 25) for w in self.project["sets"]: self.wheres.addItem(w) self.wheres.currentIndexChanged.connect(self.refresh_list) self.gestures.setGeometry(10, 70, 150, 25) for g in self.project["gestures"]: self.gestures.addItem(g) self.gestures.currentIndexChanged.connect(self.refresh_list) lbl = QLabel(act_group) lbl.setText("EMG(Hz):") lbl.move(18, 111) self.emg_freq = QSpinBox(act_group) self.emg_freq.setMinimum(1) self.emg_freq.setMaximum(200) self.emg_freq.setValue(self.project["emg_freq"]) self.emg_freq.move(act_group.width() - 65, 110) lbl = QLabel(act_group) lbl.setText("IMU(Hz):") lbl.move(18, 146) self.imu_freq = QSpinBox(act_group) self.imu_freq.setMinimum(1) self.imu_freq.setMaximum(50) self.imu_freq.setValue(self.project["emg_freq"]) self.imu_freq.setGeometry(act_group.width() - 65, 145, 49, 20) lbl = QLabel(act_group) lbl.setText("Time(ms):") lbl.move(18, 181) self.dur = QSpinBox(act_group) self.dur.setMinimum(1) self.dur.setSingleStep(10) self.dur.setMaximum(5000) self.dur.setValue(self.project["duration"]) self.dur.setGeometry(act_group.width() - 71, 181, 55, 20) self.imu_check = QCheckBox(act_group) self.imu_check.setText("Include IMU") self.imu_check.setChecked(self.project["imu_check"] == 1) self.imu_check.move(16, 215) self.startbtn = QPushButton(act_group) self.startbtn.setText("Start") self.startbtn.setStyleSheet("QPushButton::disabled{background-color: rgb(245, 245, 245);color: rgb(140, 140, 140); border: none; border-radius:5px;} QPushButton::enabled{background-color: rgb(0, 99, 225);color: white; border: none; border-radius:5px;}") self.startbtn.setGeometry(15, 250, 140, 22) self.startbtn.clicked.connect(self.start) self.startbtn.setEnabled(False) self.log_txt = QPlainTextEdit(log_group) self.log_txt.setStyleSheet(ll_ss_txt) self.log_txt.setGeometry(15, 25, log_group.width() - 30, log_group.height() - 40) self.log_txt.textChanged.connect(self.scroll_log_view) self.log_txt.setReadOnly(True) self.add_log("Application Started") self.dev_name = QLabel(device_group) self.dev_name.setText("Name: <unknown>") self.dev_name.setMaximumWidth(device_group.width() - 30) self.dev_name.move(15, 25) self.dev_batt = QLabel(device_group) self.dev_batt.setText("Battery: <unknown>") self.dev_batt.setMaximumWidth(device_group.width() - 30) self.dev_batt.move(15, 55) dev_con = QLabel(device_group) dev_con.setText("Connected: ") dev_con.setMaximumWidth(device_group.width() - 30) dev_con.move(15, 85) self.dev_con_color = QFrame(device_group) self.dev_con_color.setStyleSheet("background-color:red;border-radius:10px;") self.dev_con_color.setGeometry(device_group.width() - 15 - 20, 83, 20, 20) self.conbtn = QPushButton(device_group) self.conbtn.setText("Connect") self.conbtn.setEnabled(True) self.conbtn.setGeometry(10, 110, device_group.width() - 20, 25) self.conbtn.clicked.connect(self.connection) self.discbtn = QPushButton(device_group) self.discbtn.setText("Disconnect") self.discbtn.setGeometry(10, 145, device_group.width() - 20, 25) self.discbtn.setEnabled(False) self.discbtn.clicked.connect(self.disconnection) reclbl = QLabel(status_group) reclbl.setText("Recording: ") reclbl.setMaximumWidth(status_group.width() - 30) reclbl.move(15, 25) self.rec_con_color = QFrame(status_group) self.rec_con_color.setStyleSheet("background-color:red;border-radius:10px;") self.rec_con_color.setGeometry(status_group.width() - 15 - 20, 23, 20, 20) self.rec_proglbl = QLabel(status_group) self.rec_proglbl.setText("Progress: 0%") self.rec_proglbl.setMaximumWidth(status_group.width() - 30) self.rec_proglbl.setGeometry(15, 55, status_group.width() - 30, 25) self.rec_prog = QProgressBar(status_group) self.rec_prog.setMaximum(100) self.rec_prog.setGeometry(15, 90, status_group.width() - 30, 10) self.fileslbl = QLabel(status_group) self.fileslbl.setText("Files: ") self.fileslbl.setMaximumWidth(status_group.width() - 30) self.fileslbl.setGeometry(15, 110, status_group.width() - 30, 25) self.listview = PListView(files_group, ll_ss_txt, self.project) self.listview.setGeometry(15, 25, files_group.width() - 30, files_group.height() - 40) self.listview.setSelectionMode(QAbstractItemView.ExtendedSelection) self.listview.doubleClicked.connect(self.view_data) self.listview.contextMenuShowed.connect(self.view_data) self.listview.contextMenuDifferenced.connect(self.show_diff_data) self.listview.contextMenuAveraged.connect(self.show_ave_data) self.listview.contextMenuShowedFinder.connect(self.show_finder) self.listview.contextMenuMoved.connect(self.move_data) self.listview.contextMenuDeleted.connect(self.delete_data) self.model = QStringListModel() self.listview.setModel(self.model) self.list_data_for_set_and_gesture(self.project["sets"][0], self.project["gestures"][0]) self.add_log("Loading dataset...") total = 0 for set in self.project["sets"]: for gesture in self.project["gestures"]: path = self.project["location"] + "/" + set + "/" + gesture sum = 0 for f in os.listdir(path): if not f.startswith("."): sum = sum + 1 total = total + sum self.add_log("Found " + str(sum) + " files at " + set + "/" + gesture, False) self.add_log("Found " + str(total) + " files") def connection(self): if not self.myo: self.myo = MyoManager(sender=self) if not self.myo.connected: self.myo.connect() def disconnection(self): if self.myo: if self.myo.connected: self.myo.disconnect() def view_data(self): for index in self.listview.selectedIndexes(): path = self.project["location"] + "/" + self.project["sets"][self.wheres.currentIndex()] + "/" + self.project["gestures"][self.gestures.currentIndex()] + "/" + index.data() + ".json" w = ViewDataWindow(self, [path]) w.show() def show_diff_data(self): paths = [] for index in self.listview.selectedIndexes(): paths.append(self.project["location"] + "/" + self.project["sets"][self.wheres.currentIndex()] + "/" + self.project["gestures"][self.gestures.currentIndex()] + "/" + index.data() + ".json") w = ViewDataWindow(self, paths, 'diff') w.show() def show_ave_data(self): paths = [] for index in self.listview.selectedIndexes(): paths.append(self.project["location"] + "/" + self.project["sets"][self.wheres.currentIndex()] + "/" + self.project["gestures"][self.gestures.currentIndex()] + "/" + index.data() + ".json") w = ViewDataWindow(self, paths, 'ave') w.show() def show_finder(self): args = ["open", "-R"] for index in self.listview.selectedIndexes(): args.append(self.project["location"] + "/" + self.project["sets"][self.wheres.currentIndex()] + "/" + self.project["gestures"][self.gestures.currentIndex()] + "/" + index.data() + ".json") call(args) def move_data(self, action:QAction): tmp = {} for index in self.listview.selectedIndexes(): tmp[str(index.row())] = index.data() for row, data in sorted(tmp.items(), reverse=True): self.current_sum = self.current_sum - 1 where = action.parent().title() gesture = action.text() src = self.project["location"] + "/" + self.project["sets"][self.wheres.currentIndex()] + "/" + self.project["gestures"][self.gestures.currentIndex()] + "/" + data + ".json" dest = self.project["location"] + "/" + where + "/" + gesture + "/" + data + ".json" shutil.copy(src, dest) os.remove(src) self.model.removeRow(int(row)) self.fileslbl.setText("Files: " + str(self.current_sum)) def delete_data(self): result = QMessageBox.question( self, 'Yes', 'Are you sure you want to delete this file', QMessageBox.Yes | QMessageBox.No, defaultButton=QMessageBox.Yes) if result == QMessageBox.Yes: tmp = {} for index in self.listview.selectedIndexes(): tmp[str(index.row())] = index.data() for row, data in sorted(tmp.items(), reverse=True): self.current_sum = self.current_sum - 1 path = self.project["location"] + "/" + self.project["sets"][self.wheres.currentIndex()] + "/" + self.project["gestures"][self.gestures.currentIndex()] + "/" + data + ".json" os.remove(path) self.model.removeRow(int(row)) self.fileslbl.setText("Files: " + str(self.current_sum)) def scroll_log_view(self): self.log_txt.verticalScrollBar().setValue(self.log_txt.document().size().height()) def list_data_for_set_and_gesture(self, set, gesture): self.model.setStringList({}) path = self.project["location"] + "/" + set + "/" + gesture os.chdir(path) files = filter(os.path.isfile, os.listdir(path)) files = [os.path.join(path, f) for f in files] # add path to each file files.sort(key=lambda x: os.path.getmtime(x)) self.current_sum = 0 for file in files: f = os.path.basename(file).replace(".json", "") if f.startswith("."): continue self.current_sum = self.current_sum + 1 self.model.insertRow(self.model.rowCount()) index = self.model.index(self.model.rowCount() - 1) self.model.setData(index, f) self.fileslbl.setText("Files: " + str(self.current_sum)) def add_log(self, str, date = True): if date: #self.log_txt.insertHtml("<p>[" + datetime.datetime.now().strftime("%H:%M:%S") + "]: " + str + "<br></p>") self.log_txt.appendPlainText("[" + datetime.datetime.now().strftime("%H:%M:%S") + "]: " + str) else: #self.log_txt.insertHtml("<p>" + str + "<br></p>") self.log_txt.appendPlainText(str) #self.log_txt.repaint() def refresh_list(self): set = self.project["sets"][self.wheres.currentIndex()] gesture = self.project["gestures"][self.gestures.currentIndex()] self.list_data_for_set_and_gesture(set, gesture) def start(self): if self.startbtn.isEnabled(): self.listview.clearFocus() # index = QModelIndex() # self.listview.setCurrentIndex(index) self.startbtn.setEnabled(False) self.start_sampling() def callback(self, dict): type = dict["type"] data = dict["data"] if type == EventType.connected: self.dev_con_color.setStyleSheet("background-color:green;border-radius:10px;") self.dev_name.setText("Name: " + repr(data["name"])) self.dev_batt.setText("Battery: <unknown>") self.conbtn.setEnabled(False) self.discbtn.setEnabled(True) self.startbtn.setEnabled(True) elif type == EventType.battery_level: self.dev_batt.setText("Battery: " + str(data["battery"]) + "%") elif type == EventType.disconnected: self.dev_con_color.setStyleSheet("background-color:red;border-radius:10px;") self.dev_name.setText("Name: <unknown>") self.dev_batt.setText("Battery: <unknown>") self.conbtn.setEnabled(True) self.discbtn.setEnabled(False) self.startbtn.setEnabled(False) self.repaint() def start_sampling(self): self.add_log("Started sampling data") self.rec_con_color.setStyleSheet("background-color:green;border-radius:10px;") self.rec_con_color.repaint() self.emg.clear() self.imu.clear() duration = self.dur.value() / 1000 emg_timer = PTimer(self, self.sample_emg) emg_timer.setTickCount(int(duration * self.emg_freq.value())) emg_timer.start(1000 / self.emg_freq.value()) if self.imu_check.isChecked(): imu_timer = PTimer(self, self.sample_imu) imu_timer.setTickCount(int(duration * self.imu_freq.value())) imu_timer.start(1000 / self.imu_freq.value()) self.check_timer.start(100) def check_sample(self): duration = self.dur.value() / 1000 emg_ended = len(self.emg) == duration * self.emg_freq.value() imu_ended = (len(self.imu) == duration * self.imu_freq.value()) if emg_ended and (not self.imu_check.isChecked() or (self.imu_check.isChecked() and imu_ended)): self.sample_ended() self.check_timer.stop() def sample_emg(self): self.emg.append(self.myo.listener.emg) perc = int(len(self.emg) * 100 / (self.dur.value() / 1000 * self.emg_freq.value())) self.rec_proglbl.setText("Progress: " + str(perc) + "%") self.rec_prog.setValue(perc) def sample_imu(self): self.imu.append(self.myo.listener.data) def sample_ended(self): self.rec_con_color.setStyleSheet("background-color:red;border-radius:10px;") self.rec_con_color.repaint() self.add_log("Sampled ended") self.add_log("Saving data") name = str(uuid.uuid4()) path = self.project["location"] + "/" + self.project["sets"][self.wheres.currentIndex()] + "/" + self.project["gestures"][self.gestures.currentIndex()] + "/" + name + ".json" data = { "date" : datetime.datetime.now().strftime("%d/%m/%y/%H:%M:%S"), "duration" : self.dur.value(), "emg" : { "frequency" : self.emg_freq.value(), "data" : self.emg } } if self.imu_check.isChecked(): data["imu"] = { "frequency": self.imu_freq.value(), "data": self.imu } with open(path, 'w') as outfile: json.dump(data, outfile) self.add_log("Data saved") self.model.insertRow(self.model.rowCount()) index = self.model.index(self.model.rowCount() - 1) self.model.setData(index, name) self.startbtn.setEnabled(True) self.current_sum = self.current_sum + 1 self.fileslbl.setText("Files: " + str(self.current_sum)) def keyPressEvent(self, event): if event.key() == 16777216: self.disconnection() elif event.key() == 16777220: if not self.listview.hasFocus() or len(self.listview.selectedIndexes()) == 0: if self.myo: if self.myo.connected: self.start() def closeEvent(self, QCloseEvent): self.parent().show() self.disconnection()
def on_wyInputData_clicked(self): self.inputData_name = QFileDialog.getOpenFileName( self, 'Choose the file', '.', 'H5 files(*.h5)')[0] if len(self.inputData_name) == 0: pass else: if len(self.openfile_name) != 0: self.horizontalSliderPatch.hide() self.horizontalSliderSlice.hide() self.labelPatch.hide() self.labelSlice.hide() self.lcdNumberSlice.hide() self.lcdNumberPatch.hide() self.matplotlibwidget_static.mpl.fig.clf() self.inputData = h5py.File(self.inputData_name, 'r') # the number of the input for i in self.inputData: if i == 'X_test_p2' or i == 'y_test_p2': self.twoInput = True break if self.inputData['X_test'].ndim == 4: self.modelDimension = '2D' X_test = self.inputData['X_test'][:, 2052:2160, :, :] X_test = np.transpose(np.array(X_test), (1, 0, 2, 3)) self.subset_selection = X_test if self.twoInput: X_test_p2 = self.inputData[ 'X_test_p2'][:, 2052:2160, :, :] X_test_p2 = np.transpose(np.array(X_test_p2), (1, 0, 2, 3)) self.subset_selection_2 = X_test_p2 elif self.inputData['X_test'].ndim == 5: self.modelDimension = '3D' X_test = self.inputData['X_test'][:, 0:20, :, :, :] X_test = np.transpose(np.array(X_test), (1, 0, 2, 3, 4)) self.subset_selection = X_test if self.twoInput: X_test_p2 = self.inputData['X_test_p2'][:, 0:20, :, :, :] X_test_p2 = np.transpose(np.array(X_test_p2), (1, 0, 2, 3, 4)) self.subset_selection_2 = X_test_p2 else: print('the dimension of X_test should be 4 or 5') if self.twoInput: self.radioButton_3.show() self.radioButton_4.show() plot_model(self.model, 'model.png') if self.twoInput: self.modelInput = self.model.input[0] self.modelInput2 = self.model.input[1] else: self.modelInput = self.model.input self.layer_index_name = {} for i, layer in enumerate(self.model.layers): self.layer_index_name[layer.name] = i for i, layer in enumerate(self.model.input_layers): get_activations = K.function( [layer.input, K.learning_phase()], [ layer.output, ]) if i == 0: self.act[layer.name] = get_activations( [self.subset_selection, 0])[0] elif i == 1: self.act[layer.name] = get_activations( [self.subset_selection_2, 0])[0] else: print('no output of the input layer is created') for i, layer in enumerate(self.model.layers): # input_len=layer.input.len() if hasattr(layer.input, "__len__"): if len(layer.input) == 2: inputLayerNameList = [] for ind_li, layerInput in enumerate(layer.input): inputLayerNameList.append( self.simpleName(layerInput.name)) get_activations = K.function([ layer.input[0], layer.input[1], K.learning_phase() ], [ layer.output, ]) self.act[layer.name] = get_activations([ self.act[inputLayerNameList[0]], self.act[inputLayerNameList[1]], 0 ])[0] elif len(layer.input) == 3: inputLayerNameList = [] for ind_li, layerInput in enumerate(layer.input): inputLayerNameList.append( self.simpleName(layerInput.name)) get_activations = K.function([ layer.input[0], layer.input[1], layer.input[2], K.learning_phase() ], [ layer.output, ]) self.act[layer.name] = get_activations([ self.act[inputLayerNameList[0]], self.act[inputLayerNameList[1]], self.act[inputLayerNameList[2]], 0 ])[0] elif len(layer.input) == 4: inputLayerNameList = [] for ind_li, layerInput in enumerate(layer.input): inputLayerNameList.append( self.simpleName(layerInput.name)) get_activations = K.function([ layer.input[0], layer.input[1], layer.input[2], layer.input[3], K.learning_phase() ], [ layer.output, ]) self.act[layer.name] = get_activations([ self.act[inputLayerNameList[0]], self.act[inputLayerNameList[1]], self.act[inputLayerNameList[2]], self.act[inputLayerNameList[3]], 0 ])[0] elif len(layer.input) == 5: inputLayerNameList = [] for ind_li, layerInput in enumerate(layer.input): inputLayerNameList.append( self.simpleName(layerInput.name)) get_activations = K.function([ layer.input[0], layer.input[1], layer.input[2], layer.input[3], layer.input[4], K.learning_phase() ], [ layer.output, ]) self.act[layer.name] = get_activations([ self.act[inputLayerNameList[0]], self.act[inputLayerNameList[1]], self.act[inputLayerNameList[2]], self.act[inputLayerNameList[3]], self.act[inputLayerNameList[4]], 0 ])[0] else: print('the number of input is more than 5') else: get_activations = K.function( [layer.input, K.learning_phase()], [ layer.output, ]) inputLayerName = self.simpleName(layer.input.name) self.act[layer.name] = get_activations( [self.act[inputLayerName], 0])[0] dot = model_to_dot(self.model, show_shapes=False, show_layer_names=True, rankdir='TB') if hasattr(self.model, "layers_by_depth"): self.layers_by_depth = self.model.layers_by_depth elif hasattr(self.model.model, "layers_by_depth"): self.layers_by_depth = self.model.model.layers_by_depth else: print( 'the model or model.model should contain parameter layers_by_depth' ) maxCol = 0 for i in range(len(self.layers_by_depth)): for ind, layer in enumerate( self.layers_by_depth[i] ): # the layers in No i layer in the model if maxCol < ind: maxCow = ind if len(layer.weights) == 0: w = 0 else: w = layer.weights[0] init = tf.global_variables_initializer() with tf.Session() as sess_i: sess_i.run(init) # print(sess_i.run(w)) w = sess_i.run(w) self.weights[layer.name] = w if self.modelDimension == '3D': for i in self.weights: # a=self.weights[i] # b=a.ndim if hasattr(self.weights[i], "ndim"): if self.weights[i].ndim == 5: self.LayerWeights[i] = np.transpose( self.weights[i], (4, 3, 2, 0, 1)) else: self.LayerWeights[i] = self.weights[i] elif self.modelDimension == '2D': for i in self.weights: if hasattr(self.weights[i], "ndim"): if self.weights[i].ndim == 4: self.LayerWeights[i] = np.transpose( self.weights[i], (3, 2, 0, 1)) else: self.LayerWeights[i] = self.weights[i] else: print('the dimesnion of the weights should be 2D or 3D') self.show_layer_name() self.totalSS = len(self.subset_selection) # show the activations' name in the List slm = QStringListModel() slm.setStringList(self.qList) self.listView.setModel(slm) else: self.showChooseFileDialog()
class ClickToFlashWhitelistDialog(QDialog, Ui_ClickToFlashWhitelistDialog): """ Class implementing a dialog to manage the ClickToFlash whitelist. """ def __init__(self, whitelist, parent=None): """ Constructor @param whitelist list of whitelisted hosts (list of string) @param parent reference to the parent widget (QWidget) """ super(ClickToFlashWhitelistDialog, self).__init__(parent) self.setupUi(self) self.iconLabel.setPixmap(UI.PixmapCache.getPixmap("flashBlock48.png")) self.__model = QStringListModel(whitelist[:], self) self.__model.sort(0) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.__proxyModel.setSourceModel(self.__model) self.whitelist.setModel(self.__proxyModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.whitelist.removeSelected) self.removeAllButton.clicked.connect(self.whitelist.removeAll) @pyqtSlot() def on_addButton_clicked(self): """ Private slot to add an entry to the whitelist. """ host, ok = QInputDialog.getText( self, self.tr("ClickToFlash Whitelist"), self.tr("Enter host name to add to whitelist:"), QLineEdit.Normal) if ok and host != "" and host not in self.__model.stringList(): self.__model.insertRow(self.__model.rowCount()) self.__model.setData( self.__model.index(self.__model.rowCount() - 1), host) self.__model.sort(0) def getWhitelist(self): """ Public method to get the whitelisted hosts. @return list of whitelisted hosts (list of string) """ return self.__model.stringList()
class TriblerWindow(QMainWindow): resize_event = pyqtSignal() escape_pressed = pyqtSignal() received_search_completions = pyqtSignal(object) def on_exception(self, *exc_info): # Stop the download loop self.downloads_page.stop_loading_downloads() if not self.core_manager.shutting_down: self.core_manager.stop(stop_app_on_shutdown=False) self.setHidden(True) if self.debug_window: self.debug_window.setHidden(True) exception_text = "".join(traceback.format_exception(*exc_info)) logging.error(exception_text) if not self.feedback_dialog_is_open: dialog = FeedbackDialog( self, exception_text, self.core_manager.events_manager.tribler_version) self.feedback_dialog_is_open = True _ = dialog.exec_() def __init__(self, api_port=8085): QMainWindow.__init__(self) self.api_port = api_port self.navigation_stack = [] self.feedback_dialog_is_open = False self.tribler_started = False self.tribler_settings = None self.debug_window = None self.core_manager = CoreManager(self.api_port) self.pending_requests = {} self.pending_uri_requests = [] self.download_uri = None self.dialog = None self.request_mgr = None self.search_request_mgr = None self.search_suggestion_mgr = None self.selected_torrent_files = [] sys.excepthook = self.on_exception uic.loadUi(get_ui_file_path('mainwindow.ui'), self) TriblerRequestManager.window = self self.magnet_handler = MagnetHandler(self.window) QDesktopServices.setUrlHandler("magnet", self.magnet_handler, "on_open_magnet_link") QCoreApplication.setOrganizationDomain("nl") QCoreApplication.setOrganizationName("TUDelft") QCoreApplication.setApplicationName("Tribler") QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) self.read_settings() # Remove the focus rect on OS X for widget in self.findChildren(QLineEdit) + self.findChildren( QListWidget) + self.findChildren(QTreeWidget): widget.setAttribute(Qt.WA_MacShowFocusRect, 0) self.menu_buttons = [ self.left_menu_button_home, self.left_menu_button_my_channel, self.left_menu_button_subscriptions, self.left_menu_button_video_player, self.left_menu_button_settings, self.left_menu_button_downloads, self.left_menu_button_discovered ] self.video_player_page.initialize_player() self.search_results_page.initialize_search_results_page() self.settings_page.initialize_settings_page() self.subscribed_channels_page.initialize() self.edit_channel_page.initialize_edit_channel_page() self.downloads_page.initialize_downloads_page() self.home_page.initialize_home_page() self.loading_page.initialize_loading_page() self.discovering_page.initialize_discovering_page() self.discovered_page.initialize_discovered_page() self.stackedWidget.setCurrentIndex(PAGE_LOADING) # Create the system tray icon if QSystemTrayIcon.isSystemTrayAvailable(): self.tray_icon = QSystemTrayIcon() self.tray_icon.setIcon( QIcon(QPixmap(get_image_path('tribler.png')))) self.tray_icon.show() self.hide_left_menu_playlist() self.left_menu_button_debug.setHidden(True) self.top_menu_button.setHidden(True) self.left_menu.setHidden(True) self.add_torrent_button.setHidden(True) self.top_search_bar.setHidden(True) # Set various icons self.top_menu_button.setIcon(QIcon(get_image_path('menu.png'))) self.search_completion_model = QStringListModel() completer = QCompleter() completer.setModel(self.search_completion_model) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.item_delegate = QStyledItemDelegate() completer.popup().setItemDelegate(self.item_delegate) completer.popup().setStyleSheet(""" QListView { background-color: #404040; } QListView::item { color: #D0D0D0; padding-top: 5px; padding-bottom: 5px; } QListView::item:hover { background-color: #707070; } """) self.top_search_bar.setCompleter(completer) # Toggle debug if developer mode is enabled self.window().left_menu_button_debug.setHidden(not get_gui_setting( self.gui_settings, "debug", False, is_bool=True)) self.core_manager.start() self.core_manager.events_manager.received_search_result_channel.connect( self.search_results_page.received_search_result_channel) self.core_manager.events_manager.received_search_result_torrent.connect( self.search_results_page.received_search_result_torrent) self.core_manager.events_manager.torrent_finished.connect( self.on_torrent_finished) self.core_manager.events_manager.new_version_available.connect( self.on_new_version_available) self.core_manager.events_manager.tribler_started.connect( self.on_tribler_started) # Install signal handler for ctrl+c events def sigint_handler(*_): self.close_tribler() signal.signal(signal.SIGINT, sigint_handler) self.installEventFilter(self.video_player_page) self.show() def on_torrent_finished(self, torrent_info): self.window().tray_icon.showMessage( "Download finished", "Download of %s has finished." % torrent_info["name"]) def show_loading_screen(self): self.top_menu_button.setHidden(True) self.left_menu.setHidden(True) self.add_torrent_button.setHidden(True) self.top_search_bar.setHidden(True) self.stackedWidget.setCurrentIndex(PAGE_LOADING) def on_tribler_started(self): self.tribler_started = True self.top_menu_button.setHidden(False) self.left_menu.setHidden(False) self.add_torrent_button.setHidden(False) self.top_search_bar.setHidden(False) # fetch the variables, needed for the video player port self.request_mgr = TriblerRequestManager() self.request_mgr.perform_request("variables", self.received_variables) self.downloads_page.start_loading_downloads() self.home_page.load_popular_torrents() if not self.gui_settings.value( "first_discover", False) and not self.core_manager.use_existing_core: self.window().gui_settings.setValue("first_discover", True) self.discovering_page.is_discovering = True self.stackedWidget.setCurrentIndex(PAGE_DISCOVERING) else: self.clicked_menu_button_home() # process pending file requests (i.e. someone clicked a torrent file when Tribler was closed) for uri in self.pending_uri_requests: if uri.startswith('file'): self.on_selected_torrent_file(uri[5:]) elif uri.startswith('magnet'): self.on_added_magnetlink(uri) def perform_start_download_request(self, uri, anon_download, safe_seeding, destination, selected_files, total_files=0): selected_files_uri = "" if len(selected_files) != total_files: # Not all files included selected_files_uri = '&' + ''.join( u"selected_files[]=%s&" % file for file in selected_files)[:-1].encode('utf-8') anon_hops = int(self.tribler_settings['Tribler'] ['default_number_hops']) if anon_download else 0 safe_seeding = 1 if safe_seeding else 0 post_data = str( "uri=%s&anon_hops=%d&safe_seeding=%d&destination=%s%s" % (uri, anon_hops, safe_seeding, destination, selected_files_uri)) request_mgr = TriblerRequestManager() self.pending_requests[request_mgr.request_id] = request_mgr request_mgr.perform_request("downloads", self.on_download_added, method='PUT', data=post_data) def on_new_version_available(self, version): if version == str(self.gui_settings.value('last_reported_version')): return self.dialog = ConfirmationDialog( self, "New version available", "Version %s of Tribler is available.Do you want to visit the website to " "download the newest version?" % version, [('ignore', BUTTON_TYPE_NORMAL), ('later', BUTTON_TYPE_NORMAL), ('ok', BUTTON_TYPE_NORMAL)]) self.dialog.button_clicked.connect( lambda action: self.on_new_version_dialog_done(version, action)) self.dialog.show() def on_new_version_dialog_done(self, version, action): if action == 0: # ignore self.gui_settings.setValue("last_reported_version", version) elif action == 2: # ok import webbrowser webbrowser.open("https://tribler.org") self.dialog.setParent(None) self.dialog = None def read_settings(self): self.gui_settings = QSettings() center = QApplication.desktop().availableGeometry(self).center() pos = self.gui_settings.value( "pos", QPoint(center.x() - self.width() * 0.5, center.y() - self.height() * 0.5)) size = self.gui_settings.value("size", self.size()) self.move(pos) self.resize(size) def on_search_text_change(self, text): self.search_suggestion_mgr = TriblerRequestManager() self.search_suggestion_mgr.perform_request( "search/completions?q=%s" % text, self.on_received_search_completions) def on_received_search_completions(self, completions): self.received_search_completions.emit(completions) self.search_completion_model.setStringList(completions["completions"]) def received_variables(self, variables): self.video_player_page.video_player_port = variables["variables"][ "ports"]["video~port"] self.fetch_settings() def fetch_settings(self): self.request_mgr = TriblerRequestManager() self.request_mgr.perform_request("settings", self.received_settings) def received_settings(self, settings): self.tribler_settings = settings['settings'] # Disable various components based on the settings if not self.tribler_settings['search_community']['enabled']: self.window().top_search_bar.setHidden(True) if not self.tribler_settings['video']['enabled']: self.left_menu_button_video_player.setHidden(True) def on_top_search_button_click(self): self.deselect_all_menu_buttons() self.stackedWidget.setCurrentIndex(PAGE_SEARCH_RESULTS) self.search_results_page.perform_search(self.top_search_bar.text()) self.search_request_mgr = TriblerRequestManager() self.search_request_mgr.perform_request( "search?q=%s" % self.top_search_bar.text(), None) def on_add_torrent_button_click(self, pos): menu = TriblerActionMenu(self) browse_files_action = QAction('Import torrent from file', self) browse_directory_action = QAction('Import torrents from directory', self) add_url_action = QAction('Import torrent from URL', self) browse_files_action.triggered.connect(self.on_add_torrent_browse_file) browse_directory_action.triggered.connect( self.on_add_torrent_browse_dir) add_url_action.triggered.connect(self.on_add_torrent_from_url) menu.addAction(browse_files_action) menu.addAction(browse_directory_action) menu.addAction(add_url_action) menu.exec_(self.mapToGlobal(self.add_torrent_button.pos())) def on_add_torrent_browse_file(self): filename = QFileDialog.getOpenFileName( self, "Please select the .torrent file", "", "Torrent files (*.torrent)") if len(filename[0]) > 0: self.on_selected_torrent_file(filename[0]) def on_added_magnetlink(self, magnet_link): self.download_uri = magnet_link self.dialog = StartDownloadDialog(self.window().stackedWidget, self.download_uri, self.download_uri) self.dialog.button_clicked.connect(self.on_start_download_action) self.dialog.show() def on_selected_torrent_file(self, filepath): self.download_uri = u"file:%s" % filepath if get_gui_setting(self.gui_settings, "ask_download_settings", True, is_bool=True): self.dialog = StartDownloadDialog(self.window().stackedWidget, self.download_uri, filepath) self.dialog.button_clicked.connect(self.on_start_download_action) self.dialog.show() else: self.window().perform_start_download_request( self.download_uri, get_gui_setting(self.gui_settings, "default_anonymity_enabled", True, is_bool=True), get_gui_setting(self.gui_settings, "default_safeseeding_enabled", True, is_bool=True), self.tribler_settings['downloadconfig']['saveas'], [], 0) def on_start_download_action(self, action): if action == 1: self.window().perform_start_download_request( self.download_uri, self.dialog.dialog_widget.anon_download_checkbox.isChecked(), self.dialog.dialog_widget.safe_seed_checkbox.isChecked(), self.dialog.dialog_widget.destination_input.text(), self.dialog.get_selected_files(), self.dialog.dialog_widget.files_list_view.topLevelItemCount()) self.dialog.request_mgr.cancel_request() self.dialog.setParent(None) self.dialog = None def on_add_torrent_browse_dir(self): chosen_dir = QFileDialog.getExistingDirectory( self, "Please select the directory containing the .torrent files", "", QFileDialog.ShowDirsOnly) if len(chosen_dir) != 0: self.selected_torrent_files = [ torrent_file for torrent_file in glob.glob(chosen_dir + "/*.torrent") ] self.dialog = ConfirmationDialog( self, "Add torrents from directory", "Are you sure you want to add %d torrents to Tribler?" % len(self.selected_torrent_files), [('add', BUTTON_TYPE_NORMAL), ('cancel', BUTTON_TYPE_CONFIRM)]) self.dialog.button_clicked.connect( self.on_confirm_add_directory_dialog) self.dialog.show() def on_confirm_add_directory_dialog(self, action): if action == 0: for torrent_file in self.selected_torrent_files: escaped_uri = quote_plus( (u"file:%s" % torrent_file).encode('utf-8')) self.perform_start_download_request( escaped_uri, get_gui_setting(self.gui_settings, "default_anonymity_enabled", True, is_bool=True), get_gui_setting(self.gui_settings, "default_safeseeding_enabled", True, is_bool=True), [], 0) self.dialog.setParent(None) self.dialog = None def on_add_torrent_from_url(self): self.dialog = ConfirmationDialog( self, "Add torrent from URL/magnet link", "Please enter the URL/magnet link in the field below:", [('add', BUTTON_TYPE_NORMAL), ('cancel', BUTTON_TYPE_CONFIRM)], show_input=True) self.dialog.dialog_widget.dialog_input.setPlaceholderText( 'URL/magnet link') self.dialog.button_clicked.connect( self.on_torrent_from_url_dialog_done) self.dialog.show() def on_torrent_from_url_dialog_done(self, action): self.download_uri = self.dialog.dialog_widget.dialog_input.text() # Remove first dialog self.dialog.setParent(None) self.dialog = None if action == 0: self.dialog = StartDownloadDialog(self.window().stackedWidget, self.download_uri, self.download_uri) self.dialog.button_clicked.connect(self.on_start_download_action) self.dialog.show() def on_download_added(self, result): self.window().left_menu_button_downloads.click() def on_top_menu_button_click(self): if self.left_menu.isHidden(): self.left_menu.show() else: self.left_menu.hide() def deselect_all_menu_buttons(self, except_select=None): for button in self.menu_buttons: if button == except_select: button.setEnabled(False) continue button.setEnabled(True) button.setChecked(False) def clicked_menu_button_home(self): self.deselect_all_menu_buttons(self.left_menu_button_home) self.stackedWidget.setCurrentIndex(PAGE_HOME) self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_discovered(self): self.deselect_all_menu_buttons(self.left_menu_button_discovered) self.stackedWidget.setCurrentIndex(PAGE_DISCOVERED) self.discovered_page.load_discovered_channels() self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_my_channel(self): self.deselect_all_menu_buttons(self.left_menu_button_my_channel) self.stackedWidget.setCurrentIndex(PAGE_EDIT_CHANNEL) self.edit_channel_page.load_my_channel_overview() self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_video_player(self): self.deselect_all_menu_buttons(self.left_menu_button_video_player) self.stackedWidget.setCurrentIndex(PAGE_VIDEO_PLAYER) self.navigation_stack = [] self.show_left_menu_playlist() def clicked_menu_button_downloads(self): self.deselect_all_menu_buttons(self.left_menu_button_downloads) self.stackedWidget.setCurrentIndex(PAGE_DOWNLOADS) self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_settings(self): self.deselect_all_menu_buttons(self.left_menu_button_settings) self.stackedWidget.setCurrentIndex(PAGE_SETTINGS) self.settings_page.load_settings() self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_debug(self): self.debug_window = DebugWindow() self.debug_window.show() def clicked_menu_button_subscriptions(self): self.deselect_all_menu_buttons(self.left_menu_button_subscriptions) self.subscribed_channels_page.load_subscribed_channels() self.stackedWidget.setCurrentIndex(PAGE_SUBSCRIBED_CHANNELS) self.navigation_stack = [] self.hide_left_menu_playlist() def hide_left_menu_playlist(self): self.left_menu_seperator.setHidden(True) self.left_menu_playlist_label.setHidden(True) self.left_menu_playlist.setHidden(True) def show_left_menu_playlist(self): self.left_menu_seperator.setHidden(False) self.left_menu_playlist_label.setHidden(False) self.left_menu_playlist.setHidden(False) def on_channel_item_click(self, channel_list_item): list_widget = channel_list_item.listWidget() from TriblerGUI.widgets.channel_list_item import ChannelListItem if isinstance(list_widget.itemWidget(channel_list_item), ChannelListItem): channel_info = channel_list_item.data(Qt.UserRole) self.channel_page.initialize_with_channel(channel_info) self.navigation_stack.append(self.stackedWidget.currentIndex()) self.stackedWidget.setCurrentIndex(PAGE_CHANNEL_DETAILS) def on_playlist_item_click(self, playlist_list_item): list_widget = playlist_list_item.listWidget() from TriblerGUI.widgets.playlist_list_item import PlaylistListItem if isinstance(list_widget.itemWidget(playlist_list_item), PlaylistListItem): playlist_info = playlist_list_item.data(Qt.UserRole) self.playlist_page.initialize_with_playlist(playlist_info) self.navigation_stack.append(self.stackedWidget.currentIndex()) self.stackedWidget.setCurrentIndex(PAGE_PLAYLIST_DETAILS) def on_page_back_clicked(self): prev_page = self.navigation_stack.pop() self.stackedWidget.setCurrentIndex(prev_page) def on_edit_channel_clicked(self): self.stackedWidget.setCurrentIndex(PAGE_EDIT_CHANNEL) self.navigation_stack = [] self.channel_page.on_edit_channel_clicked() def resizeEvent(self, _): # Resize home page cells cell_width = self.home_page_table_view.width( ) / 3 - 3 # We have some padding to the right cell_height = cell_width / 2 + 60 for i in range(0, 3): self.home_page_table_view.setColumnWidth(i, cell_width) self.home_page_table_view.setRowHeight(i, cell_height) self.resize_event.emit() def exit_full_screen(self): self.top_bar.show() self.left_menu.show() self.video_player_page.is_full_screen = False self.showNormal() def close_tribler(self): if not self.core_manager.shutting_down: self.show_loading_screen() self.gui_settings.setValue("pos", self.pos()) self.gui_settings.setValue("size", self.size()) if self.core_manager.use_existing_core: # Don't close the core that we are using QApplication.quit() self.core_manager.stop() self.core_manager.shutting_down = True self.downloads_page.stop_loading_downloads() def closeEvent(self, close_event): self.close_tribler() close_event.ignore() def keyReleaseEvent(self, event): if event.key() == Qt.Key_Escape: self.escape_pressed.emit() if self.isFullScreen(): self.exit_full_screen()
def setupUi(self): self.load_ui("apol/terulequery.ui") # set up source/target autocompletion typeattr_completion_list = [str(t) for t in self.policy.types()] typeattr_completion_list.extend( str(a) for a in self.policy.typeattributes()) typeattr_completer_model = QStringListModel(self) typeattr_completer_model.setStringList( sorted(typeattr_completion_list)) self.typeattr_completion = QCompleter() self.typeattr_completion.setModel(typeattr_completer_model) self.source.setCompleter(self.typeattr_completion) self.target.setCompleter(self.typeattr_completion) # set up default autocompletion type_completion_list = [str(t) for t in self.policy.types()] type_completer_model = QStringListModel(self) type_completer_model.setStringList(sorted(type_completion_list)) self.type_completion = QCompleter() self.type_completion.setModel(type_completer_model) self.default_type.setCompleter(self.type_completion) # setup indications of errors on source/target/default self.errors = set() self.orig_palette = self.source.palette() self.error_palette = self.source.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_source_error() self.clear_target_error() self.clear_default_error() self.clear_xperm_error() # populate class list self.class_model = SEToolsListModel(self) self.class_model.item_list = sorted(self.policy.classes()) self.tclass.setModel(self.class_model) # populate perm list self.perms_model = PermListModel(self, self.policy) self.perms.setModel(self.perms_model) # populate bool list self.bool_model = SEToolsListModel(self) self.bool_model.item_list = sorted(self.policy.bools()) self.bool_criteria.setModel(self.bool_model) # set up results self.table_results_model = TERuleTableModel(self) self.sort_proxy = QSortFilterProxyModel(self) self.sort_proxy.setSourceModel(self.table_results_model) self.table_results.setModel(self.sort_proxy) self.table_results.sortByColumn(0, Qt.AscendingOrder) # set up processing thread self.thread = QThread() self.worker = QueryResultsUpdater(self.query, self.table_results_model) self.worker.moveToThread(self.thread) self.worker.raw_line.connect(self.raw_results.appendPlainText) self.worker.finished.connect(self.update_complete) self.worker.finished.connect(self.thread.quit) self.thread.started.connect(self.worker.update) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.canceled.connect(self.thread.requestInterruption) self.busy.reset() # update busy dialog from query INFO logs self.handler = LogHandlerToSignal() self.handler.message.connect(self.busy.setLabelText) logging.getLogger("setools.terulequery").addHandler(self.handler) # Ensure settings are consistent with the initial .ui state self.set_source_regex(self.source_regex.isChecked()) self.set_target_regex(self.target_regex.isChecked()) self.set_default_regex(self.default_regex.isChecked()) self.toggle_xperm_criteria() self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) # connect signals self.buttonBox.clicked.connect(self.run) self.allowxperm.toggled.connect(self.toggle_xperm_criteria) self.auditallowxperm.toggled.connect(self.toggle_xperm_criteria) self.neverallowxperm.toggled.connect(self.toggle_xperm_criteria) self.dontauditxperm.toggled.connect(self.toggle_xperm_criteria) self.clear_ruletypes.clicked.connect(self.clear_all_ruletypes) self.all_ruletypes.clicked.connect(self.set_all_ruletypes) self.source.textEdited.connect(self.clear_source_error) self.source.editingFinished.connect(self.set_source) self.source_regex.toggled.connect(self.set_source_regex) self.target.textEdited.connect(self.clear_target_error) self.target.editingFinished.connect(self.set_target) self.target_regex.toggled.connect(self.set_target_regex) self.tclass.selectionModel().selectionChanged.connect(self.set_tclass) self.invert_class.clicked.connect(self.invert_tclass_selection) self.perms.selectionModel().selectionChanged.connect(self.set_perms) self.invert_perms.clicked.connect(self.invert_perms_selection) self.xperms.textEdited.connect(self.clear_xperm_error) self.xperms.editingFinished.connect(self.set_xperm) self.default_type.textEdited.connect(self.clear_default_error) self.default_type.editingFinished.connect(self.set_default_type) self.default_regex.toggled.connect(self.set_default_regex) self.bool_criteria.selectionModel().selectionChanged.connect( self.set_bools)
class MinDataUi_Dialog(Ui_dialog): #QtWidgets.QWidget def setupUi(self, Dialog): super().setupUi(Dialog) Dialog.setObjectName("dlg") self.dqljwj_2.clicked.connect(self.on_dqljwj_2_click) #查询 self.listView.clicked.connect(self.on_listview_click) self.ljxz.clicked.connect(self.on_ljxz_click) # now_time = datetime.now() #现在 end = now_time.strftime("%Y-%m-%d") yesterday = now_time + timedelta(days=-1) start = yesterday.strftime('%Y-%m-%d') self.dateEdit.setDate(QDate.fromString(start, 'yyyy-MM-dd')) #start time self.dateEdit_2.setDate(QDate.fromString(end, 'yyyy-MM-dd')) #end time # self.xzlsFs_2.clicked.connect(self.on_xzlsFs_2_click) self.xzdtfs.clicked.connect(self.on_xzdtfs_click) self.hbbb.clicked.connect(self.on_hbbb_click) self.xzlsFs_3.clicked.connect(self.on_xzlsFs_3_click) #提示打开股票代码文件 填加代码 # #实例化列表模型,添加数据 self.qsL = QStringListModel() self.Test = [] #设置模型列表视图,加载数据列表 self.qsL.setStringList(self.Test) #设置列表视图的模型 self.listView_2.setModel(self.qsL) self.progressBar.setValue(0) self.progressBar_2.setValue(0) # self.savePath = None self.Main = StockMinuteData() if (self.savePath is None): self.savePath = self.Main.destPath self.bclj_2.setText(self.savePath) # self.dqlj.setText(self.savePath) self.Main.signal.connect(self.callbacklog) self.th1 = None #合并xls self.th2 = None #下载数据 def on_xzlsFs_3_click(self): reply = QMessageBox.information( self, "标题", "请打开文件stockList.txt,填加股票代码。股票代码例如:sz000651", QMessageBox.Yes) def on_hbbb_click(self): code = self.gpdmHb.text() if (self.th1 is None): self.th1 = threading.Thread(target=self.Main.MergeMinData, args=(code, ), name='hbbb') self.th1.start() else: if (self.th1.is_alive() == False): self.th1 = threading.Thread(target=self.Main.MergeMinData, args=(code, ), name='hbbb') self.th1.start() def on_xzdtfs_click(self): ''' 当天分时 ''' self.downData('1') def on_xzlsFs_2_click(self): ''' 多个股票下载历史分时 ''' self.downData('2') def downData(self, typeL): ''' 股票下载 ''' startDay = self.dateEdit.dateTime() startTime = startDay.toString('yyyy-MM-dd') endDay = self.dateEdit_2.dateTime() endTime = endDay.toString('yyyy-MM-dd') if (self.th2 is None): self.Main.setPara('', startTime, endTime, typeL, self.savePath, "stockList.txt") self.th2 = threading.Thread(target=self.Main.getDataWithTimeSpan, args=(startTime, endTime), name='funciton') self.th2.start() else: if (self.th2.is_alive() == False): self.Main.setPara('', startTime, endTime, typeL, self.savePath, "stockList.txt") self.th2 = threading.Thread( target=self.Main.getDataWithTimeSpan, args=(startTime, endTime), name='funciton') self.th2.start() def callbacklog(self, msg, processInt, processHb): # 奖回调数据输出到文本框 listText = msg.replace('------', '') now_time = datetime.now() dateL = now_time.strftime('%H:%M:%S') if (len(listText) > 0): self.addListViewMessage("[%s]:%s" % (dateL, listText)) self.setProcessBarPos(processInt, processHb) def on_listview_click(self, qModelIndex): txtN = self.strlist[qModelIndex.row()] txtN = txtN[0:8] self.gpdmHb.setText(txtN) def on_ljxz_click(self): ''' 判断线程是否在运行,如果运行不进行路径设置 ''' fLag = True if (self.th2 is None): pass else: if (self.th2.is_alive() == True): fLag = False if (self.th1 is None): pass else: if (self.th1.is_alive() == True): fLag = False if (fLag == False): return self.savePath = QtWidgets.QFileDialog.getExistingDirectory( self, "浏览", ".\\") if (len(self.savePath) > 0): self.Main.destPath = self.savePath + '/' self.bclj_2.setText(self.Main.destPath) def on_dqljwj_2_click(self): ''' 查询指定文件路径下的文件合并 ''' path = self.bclj_2.text() files = os.listdir(path) self.strlist = [] for fi in files: fi_d = os.path.join(path, fi) if os.path.isdir(fi_d): continue else: fi_d = fi_d.replace(path + '/', '') if (fi_d.find('.xls') > 0): self.strlist.append(fi) #实例化列表模型,添加数据 slm = QStringListModel() #设置模型列表视图,加载数据列表 slm.setStringList(self.strlist) #设置列表视图的模型 self.listView.setModel(slm) def addListViewMessage(self, msg): self.Test.append(msg) #设置模型列表视图,加载数据列表 self.qsL.setStringList(self.Test) pass def setProcessBarPos(self, processBar, processHb): self.progressBar.setValue(processBar) self.progressBar_2.setValue(processHb)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication, QListView from PyQt5.QtCore import QStringListModel if __name__ == "__main__": app = QApplication(sys.argv) model = QStringListModel( ["An element", "Another element", "Yay! Another one."]) view = QListView() view.setModel(model) view.show() sys.exit(app.exec_())
def setupUi(self): self.log.debug("Initializing UI.") self.load_ui("infoflow.ui") # set up error message for missing perm map self.error_msg = QMessageBox(self) self.error_msg.setStandardButtons(QMessageBox.Ok) # set up perm map editor self.permmap_editor = PermissionMapEditor(self, False) # set up source/target autocompletion type_completion_list = [str(t) for t in self.policy.types()] type_completer_model = QStringListModel(self) type_completer_model.setStringList(sorted(type_completion_list)) self.type_completion = QCompleter() self.type_completion.setModel(type_completer_model) self.source.setCompleter(self.type_completion) self.target.setCompleter(self.type_completion) # setup indications of errors on source/target/default self.errors = set() self.orig_palette = self.source.palette() self.error_palette = self.source.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_source_error() self.clear_target_error() # set up processing thread self.thread = ResultsUpdater(self.query) self.thread.raw_line.connect(self.raw_results.appendPlainText) self.thread.finished.connect(self.update_complete) self.thread.flows.connect(self.reset_browser) # set up browser thread self.browser_thread = BrowserUpdater(self.query) self.browser_thread.flows.connect(self.add_browser_children) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.setCancelButton(None) self.busy.reset() # update busy dialog from infoflow INFO logs self.handler = LogHandlerToSignal() self.handler.message.connect(self.busy.setLabelText) logging.getLogger("setools.infoflow").addHandler(self.handler) # Ensure settings are consistent with the initial .ui state self.max_path_length.setEnabled(self.all_paths.isChecked()) self.source.setEnabled(not self.flows_in.isChecked()) self.target.setEnabled(not self.flows_out.isChecked()) self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) self.browser_tab.setEnabled(self.flows_in.isChecked() or self.flows_out.isChecked()) # connect signals self.buttonBox.clicked.connect(self.run) self.source.textEdited.connect(self.clear_source_error) self.source.editingFinished.connect(self.set_source) self.target.textEdited.connect(self.clear_target_error) self.target.editingFinished.connect(self.set_target) self.all_paths.toggled.connect(self.all_paths_toggled) self.flows_in.toggled.connect(self.flows_in_toggled) self.flows_out.toggled.connect(self.flows_out_toggled) self.min_perm_weight.valueChanged.connect(self.set_min_weight) self.exclude_types.clicked.connect(self.choose_excluded_types) self.edit_permmap.clicked.connect(self.open_permmap_editor) self.browser.currentItemChanged.connect(self.browser_item_selected)
def __init__(self): QMainWindow.__init__(self) self.navigation_stack = [] self.feedback_dialog_is_open = False self.tribler_started = False self.tribler_settings = None self.debug_window = None self.core_manager = CoreManager() self.pending_requests = {} self.pending_uri_requests = [] self.download_uri = None self.dialog = None self.new_version_dialog = None self.start_download_dialog_active = False self.request_mgr = None self.search_request_mgr = None self.search_suggestion_mgr = None self.selected_torrent_files = [] self.vlc_available = True self.has_search_results = False self.last_search_query = None self.last_search_time = None self.start_time = time.time() self.exception_handler_called = False sys.excepthook = self.on_exception uic.loadUi(get_ui_file_path('mainwindow.ui'), self) TriblerRequestManager.window = self self.tribler_status_bar.hide() # Load dynamic widgets uic.loadUi(get_ui_file_path('torrent_channel_list_container.ui'), self.channel_page_container) self.channel_torrents_list = self.channel_page_container.items_list self.channel_torrents_detail_widget = self.channel_page_container.details_tab_widget self.channel_torrents_detail_widget.initialize_details_widget() self.channel_torrents_list.itemClicked.connect(self.channel_page.clicked_item) uic.loadUi(get_ui_file_path('torrent_channel_list_container.ui'), self.search_page_container) self.search_results_list = self.search_page_container.items_list self.search_torrents_detail_widget = self.search_page_container.details_tab_widget self.search_torrents_detail_widget.initialize_details_widget() self.search_results_list.itemClicked.connect(self.on_channel_item_click) self.search_results_list.itemClicked.connect(self.search_results_page.clicked_item) def on_state_update(new_state): self.loading_text_label.setText(new_state) self.core_manager.core_state_update.connect(on_state_update) self.magnet_handler = MagnetHandler(self.window) QDesktopServices.setUrlHandler("magnet", self.magnet_handler, "on_open_magnet_link") QCoreApplication.setOrganizationDomain("nl") QCoreApplication.setOrganizationName("TUDelft") QCoreApplication.setApplicationName("Tribler") QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) self.read_settings() self.debug_pane_shortcut = QShortcut(QKeySequence("Ctrl+d"), self) self.debug_pane_shortcut.activated.connect(self.clicked_menu_button_debug) # Remove the focus rect on OS X for widget in self.findChildren(QLineEdit) + self.findChildren(QListWidget) + self.findChildren(QTreeWidget): widget.setAttribute(Qt.WA_MacShowFocusRect, 0) self.menu_buttons = [self.left_menu_button_home, self.left_menu_button_search, self.left_menu_button_my_channel, self.left_menu_button_subscriptions, self.left_menu_button_video_player, self.left_menu_button_downloads, self.left_menu_button_discovered] self.video_player_page.initialize_player() self.search_results_page.initialize_search_results_page() self.settings_page.initialize_settings_page() self.subscribed_channels_page.initialize() self.edit_channel_page.initialize_edit_channel_page() self.downloads_page.initialize_downloads_page() self.home_page.initialize_home_page() self.loading_page.initialize_loading_page() self.discovering_page.initialize_discovering_page() self.discovered_page.initialize_discovered_page() self.trust_page.initialize_trust_page() self.stackedWidget.setCurrentIndex(PAGE_LOADING) # Create the system tray icon if QSystemTrayIcon.isSystemTrayAvailable(): self.tray_icon = QSystemTrayIcon() use_monochrome_icon = get_gui_setting(self.gui_settings, "use_monochrome_icon", False, is_bool=True) self.update_tray_icon(use_monochrome_icon) else: self.tray_icon = None self.hide_left_menu_playlist() self.left_menu_button_debug.setHidden(True) self.top_menu_button.setHidden(True) self.left_menu.setHidden(True) self.trust_button.setHidden(True) self.settings_button.setHidden(True) self.add_torrent_button.setHidden(True) self.top_search_bar.setHidden(True) # Set various icons self.top_menu_button.setIcon(QIcon(get_image_path('menu.png'))) self.search_completion_model = QStringListModel() completer = QCompleter() completer.setModel(self.search_completion_model) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.item_delegate = QStyledItemDelegate() completer.popup().setItemDelegate(self.item_delegate) completer.popup().setStyleSheet(""" QListView { background-color: #404040; } QListView::item { color: #D0D0D0; padding-top: 5px; padding-bottom: 5px; } QListView::item:hover { background-color: #707070; } """) self.top_search_bar.setCompleter(completer) # Toggle debug if developer mode is enabled self.window().left_menu_button_debug.setHidden( not get_gui_setting(self.gui_settings, "debug", False, is_bool=True)) self.core_manager.start() self.core_manager.events_manager.received_search_result_channel.connect( self.search_results_page.received_search_result_channel) self.core_manager.events_manager.received_search_result_torrent.connect( self.search_results_page.received_search_result_torrent) self.core_manager.events_manager.torrent_finished.connect(self.on_torrent_finished) self.core_manager.events_manager.new_version_available.connect(self.on_new_version_available) self.core_manager.events_manager.tribler_started.connect(self.on_tribler_started) # Install signal handler for ctrl+c events def sigint_handler(*_): self.close_tribler() signal.signal(signal.SIGINT, sigint_handler) self.installEventFilter(self.video_player_page) self.show()
def __init__(self, model, parent=None): QWidget.__init__(self, parent) self.ui = Ui_ControlPanel() self.ui.setupUi(self) self.model = model sortmenu = QMenu() for i, col in enumerate( sorted(set(self.model.cols) - self.model.cfg.internalCols, key=self.model.prettyname)): # Sort Menu a = sortmenu.addAction(self.model.prettyname(col)) a.setData(col) a.triggered.connect(self.onAddSortField) # Sort self.ui.addSortField.setMenu(sortmenu) self.ui.sortByListWidget.itemSelectionChanged.connect( self.onSelectionChange) self.onSelectionChange() self.ui.removeSortField.clicked.connect(self.onRemoveSortField) self.ui.moveSortField.clicked.connect(self.onMoveSortFieldUp) self.ui.sortAscendingCheckBox.clicked.connect( self.onSortAscendingChange) # Legend self.legendWidget = partitionWidget.MyPartitionWidget( model, self.model.setStacks, model.cfg.legendInitial, True, True, self) self.legendWidget.ui.description.setText( "Change field and colors for stacked histograms. Double click to edit color. Single click on selected to edit label. Checkboxes only affect visibility, not the selected items." ) self.legendWidget.ui.groupBox.setTitle("Histogram Legends") self.ui.verticalLayout_7.insertWidget(1, self.legendWidget) # Partition self.partWidget = partitionWidget.MyPartitionWidget( model, self.model.setPartition, model.cfg.partitionInitial, True, False, self) self.partWidget.ui.description.setText( "Partition the data. Selecting a partition changes the full dataset shown in plots to just match the partition. When partitions are active, output is split with one output for each partition." ) self.partWidget.ui.groupBox.setTitle("Partitions") self.ui.verticalLayout_7.insertWidget(2, self.partWidget) # Flags if self.model.flagFilter.isActive(): self.ui.flagIgnore.setChecked(True) if self.model.flagFilter.invert: self.ui.flagExclude.setChecked(True) else: self.ui.flagKeep.setChecked(True) else: self.ui.flagIgnore.setChecked(True) self.model.flagFilter.filterchange.connect(self.onFlagChange) self.flagModel = QStringListModel() self.ui.flaggedList.setModel(self.flagModel) self.ui.flagIgnore.clicked.connect(self.onIgnoreFlags) self.ui.flagExclude.clicked.connect(self.onExcludeFlags) self.ui.flagKeep.clicked.connect(self.onOnlyFlags) self.ui.flaggedList.selectionModel().currentChanged.connect( self.onSelectFlag) # Limits self.ui.limitCheckBox.clicked.connect(self.onLimitChange) self.ui.limTopButton.clicked.connect(self.onLimitChange) self.ui.limRandomButton.clicked.connect(self.onLimitChange) self.ui.limitSpinBox.editingFinished.connect(self.onLimitChange) self.onLimitChange() # Filters self.filtermodel = FilterModel(model.topfilter, model) self.ui.filterTreeView.setEditTriggers( QAbstractItemView.AllEditTriggers) self.ui.filterTreeView.setModel(self.filtermodel) if qt5: self.ui.filterTreeView.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self.ui.filterTreeView.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) else: self.ui.filterTreeView.header().setResizeMode( 0, QHeaderView.ResizeToContents) self.ui.filterTreeView.header().setResizeMode( 1, QHeaderView.ResizeToContents) self.ui.filterTreeView.setItemDelegate( filterEditDelegate.FilterItemDelegate()) self.filtermodel.rowsInserted.connect(self.ui.filterTreeView.expandAll) self.ui.filterTreeView.expandAll() # Filters Save/Load self.ui.saveFiltersButton.clicked.connect(self.onSaveFilters) self.ui.loadFiltersButton.clicked.connect(self.onLoadFilters)
class MainApp(QWidget): STRANGER_DANGER = 350 IMAGE_SIZE = (100, 100) stranger_color = (179, 20, 20) recognized_color = (59, 235, 62) def __init__(self, fps=30, parent=None): # type: (int, Optional[QWidget]) -> None super().__init__(parent=parent) self.pkg_path = path.dirname(path.dirname(path.abspath(__file__))) self.training_data_dir = path.join(self.pkg_path, 'train') self.models_dir = path.join(self.pkg_path, 'models') self.model_fname = 'fisherfaces.p' try: self.model = data_provider.load_model( path.join(self.models_dir, self.model_fname)) except AssertionError: self.model = None self.existing_labels = QStringListModel(self.get_existing_labels()) self.fps = fps self.video_size = QSize(640, 480) self.gray_image = None self.detected_faces = [] # Setup the UI self.main_layout = QHBoxLayout() self.setLayout(self.main_layout) self.control_layout = QVBoxLayout() self.control_layout.setSpacing(8) self.main_layout.addItem(self.control_layout) # Setup the existing label view self.labels_view = QListView(parent=self) self.labels_view.setModel(self.existing_labels) self.labels_view.setSelectionMode(QListView.SingleSelection) self.labels_view.setItemDelegate(CapitalizeDelegate(self)) self.control_layout.addWidget(self.labels_view) self.new_label_txt = QLineEdit(self) self.new_label_txt.returnPressed.connect(self.add_new_label) self.new_label_txt.returnPressed.connect(self.new_label_txt.clear) self.control_layout.addWidget(self.new_label_txt) self.add_button = QPushButton('Add Label', self) self.add_button.clicked.connect(self.add_new_label) self.control_layout.addWidget(self.add_button) # Setup the training area train_box = QGroupBox('Train', self) train_box_layout = QVBoxLayout() train_box.setLayout(train_box_layout) self.control_layout.addWidget(train_box) self.train_btn = QPushButton('Train', self) self.train_btn.clicked.connect(self.train) train_box_layout.addWidget(self.train_btn) self.control_layout.addStretch(0) # Add take picture shortcut self.take_picture_btn = QPushButton('Take picture', self) self.take_picture_btn.clicked.connect(self.take_picture) self.control_layout.addWidget(self.take_picture_btn) shortcut = QShortcut(QKeySequence('Space'), self, self.take_picture) shortcut.setWhatsThis('Take picture and add to training data.') # Add quit shortcut shortcut = QShortcut(QKeySequence('Esc'), self, self.close) shortcut.setWhatsThis('Quit') # Setup the main camera area self.image_label = QLabel(self) self.image_label.setFixedSize(self.video_size) self.main_layout.addWidget(self.image_label) # Setup the camera self.capture = cv2.VideoCapture(0) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.video_size.width()) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.video_size.height()) self.timer = QTimer() self.timer.timeout.connect(self.display_video_stream) self.timer.start(int(1000 / self.fps)) def classify_face(self, image): if self.model is None: return label_idx, distances = self.model.predict(image.ravel(), True) label_idx, distance = label_idx[0], distances[0][label_idx] labels = self.existing_labels.stringList() return labels[label_idx], distance def get_training_data(self): """Read the images from disk into an n*(w*h) matrix.""" return data_provider.get_image_data_from_directory( self.training_data_dir) def train(self): X, y, mapping = self.get_training_data() # Inspect scree plot to determine appropriate number of PCA components classifier = PCALDAClassifier( n_components=2, pca_components=200, metric='euclidean', ).fit(X, y) # Replace the existing running model self.model = classifier # Save the classifier to file data_provider.save_model( classifier, path.join(self.models_dir, self.model_fname)) def add_new_label(self): new_label = self.new_label_txt.text() new_label = new_label.lower() # Prevent empty entries if len(new_label) < 3: return string_list = self.existing_labels.stringList() if new_label not in string_list: string_list.append(new_label) string_list.sort() self.existing_labels.setStringList(string_list) # Automatically select the added label selection_model = self.labels_view.selectionModel() index = self.existing_labels.index(string_list.index(new_label)) selection_model.setCurrentIndex(index, QItemSelectionModel.Select) def display_video_stream(self): """Read frame from camera and repaint QLabel widget.""" _, frame = self.capture.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.flip(frame, 1) # Use the Viola-Jones face detector to detect faces to classify face_cascade = cv2.CascadeClassifier(path.join( self.pkg_path, 'resources', 'haarcascade_frontalface_default.xml')) self.gray_image = gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) self.detected_faces = face_cascade.detectMultiScale(gray, 1.3, 5) for x, y, w, h in self.detected_faces: # Label the detected face as per the model face = gray[y:y + h, x:x + w] face = cv2.resize(face, self.IMAGE_SIZE) result = self.classify_face(face) # If a model is loaded, we can predict if result: predicted, distance = self.classify_face(face) if distance > self.STRANGER_DANGER: predicted = 'Stranger danger!' color = self.stranger_color else: predicted = predicted.capitalize() color = self.recognized_color # Draw a rectangle around the detected face cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) text = '%s (%.1f)' % (predicted, distance) cv2.putText(frame, text, (x, y + h + 15), cv2.FONT_HERSHEY_TRIPLEX, 0.5, color) else: # Draw a rectangle around the detected face cv2.rectangle(frame, (x, y), (x + w, y + h), self.stranger_color, 2) cv2.putText(frame, 'Stranger danger!', (x, y + h + 15), cv2.FONT_HERSHEY_TRIPLEX, 0.5, self.stranger_color) # Display the image in the image area image = QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QImage.Format_RGB888) self.image_label.setPixmap(QPixmap.fromImage(image)) @contextmanager def stop_camera_feed(self): """Temporarly stop the feed and face detection.""" try: self.timer.stop() yield finally: self.timer.start(int(1000 / self.fps)) def take_picture(self): # Notify the user there were no faces detected if self.detected_faces is None or len(self.detected_faces) < 1: return raise NoFacesError() if len(self.detected_faces) > 1: return raise MultipleFacesError() with self.stop_camera_feed(): x, y, w, h = self.detected_faces[0] face = self.gray_image[y:y + h, x:x + w] face = cv2.resize(face, self.IMAGE_SIZE) denoised_image = cv2.fastNlMeansDenoising(face) if not self.selected_label: return self.save_image(denoised_image, self.selected_label) @property def selected_label(self): index = self.labels_view.selectedIndexes() if len(index) < 1: return None label = self.existing_labels.data(index[0], Qt.DisplayRole) return label def get_existing_labels(self): """Get a list of the currently existing labels""" return data_provider.get_folder_names(self.training_data_dir) def save_image(self, image: np.ndarray, label: str) -> None: """Save an image to disk in the appropriate directory.""" if not path.exists(self.training_data_dir): mkdir(self.training_data_dir) label_path = path.join(self.training_data_dir, label) if not path.exists(label_path): mkdir(label_path) existing_files = listdir(label_path) existing_files = map(lambda p: path.splitext(p)[0], existing_files) existing_files = list(map(int, existing_files)) last_fname = sorted(existing_files)[-1] if len(existing_files) else 0 fname = path.join(label_path, '%03d.png' % (last_fname + 1)) cv2.imwrite(fname, image)
def setupUi(self): self.load_ui("constraintquery.ui") # set up user autocompletion user_completion_list = [str(u) for u in self.policy.users()] user_completer_model = QStringListModel(self) user_completer_model.setStringList(sorted(user_completion_list)) self.user_completion = QCompleter() self.user_completion.setModel(user_completer_model) self.user.setCompleter(self.user_completion) # set up role autocompletion role_completion_list = [str(r) for r in self.policy.roles()] role_completer_model = QStringListModel(self) role_completer_model.setStringList(sorted(role_completion_list)) self.role_completion = QCompleter() self.role_completion.setModel(role_completer_model) self.role.setCompleter(self.role_completion) # set up type autocompletion type_completion_list = [str(t) for t in self.policy.types()] type_completer_model = QStringListModel(self) type_completer_model.setStringList(sorted(type_completion_list)) self.type_completion = QCompleter() self.type_completion.setModel(type_completer_model) self.type_.setCompleter(self.type_completion) # populate class list self.class_model = SEToolsListModel(self) self.class_model.item_list = sorted(self.policy.classes()) self.tclass.setModel(self.class_model) # populate perm list self.perms_model = PermListModel(self, self.policy) self.perms.setModel(self.perms_model) # setup indications of errors self.orig_palette = self.type_.palette() self.error_palette = self.type_.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_user_error() self.clear_type_error() self.clear_role_error() # set up results self.table_results_model = ConstraintTableModel(self) self.sort_proxy = QSortFilterProxyModel(self) self.sort_proxy.setSourceModel(self.table_results_model) self.table_results.setModel(self.sort_proxy) self.table_results.sortByColumn(0, Qt.AscendingOrder) # set up processing thread self.thread = QThread() self.worker = QueryResultsUpdater(self.query, self.table_results_model) self.worker.moveToThread(self.thread) self.worker.raw_line.connect(self.raw_results.appendPlainText) self.worker.finished.connect(self.update_complete) self.worker.finished.connect(self.thread.quit) self.thread.started.connect(self.worker.update) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.canceled.connect(self.thread.requestInterruption) self.busy.reset() # update busy dialog from query INFO logs self.handler = LogHandlerToSignal() self.handler.message.connect(self.busy.setLabelText) logging.getLogger("setools.constraintquery").addHandler(self.handler) # Ensure settings are consistent with the initial .ui state self.set_user_regex(self.user_regex.isChecked()) self.set_role_regex(self.role_regex.isChecked()) self.set_type_regex(self.type_regex.isChecked()) self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) # MLS constraints available only if policy is MLS if not self.policy.mls: self.mlsconstrain.setEnabled(False) self.mlsvalidatetrans.setEnabled(False) self.mlsconstrain.setToolTip("MLS is disabled in this policy.") self.mlsvalidatetrans.setToolTip("MLS is disabled in this policy.") # connect signals self.buttonBox.clicked.connect(self.run) self.clear_ruletypes.clicked.connect(self.clear_all_ruletypes) self.all_ruletypes.clicked.connect(self.set_all_ruletypes) self.user.textEdited.connect(self.clear_user_error) self.user.editingFinished.connect(self.set_user) self.user_regex.toggled.connect(self.set_user_regex) self.role.textEdited.connect(self.clear_role_error) self.role.editingFinished.connect(self.set_role) self.role_regex.toggled.connect(self.set_role_regex) self.type_.textEdited.connect(self.clear_type_error) self.type_.editingFinished.connect(self.set_type) self.type_regex.toggled.connect(self.set_type_regex) self.tclass.selectionModel().selectionChanged.connect(self.set_tclass) self.invert_class.clicked.connect(self.invert_tclass_selection) self.perms.selectionModel().selectionChanged.connect(self.set_perms) self.invert_perms.clicked.connect(self.invert_perms_selection)
def setupUi(self): self.load_ui("rbacrulequery.ui") # set up role autocompletion (source, default) role_completion_list = [str(r) for r in self.policy.roles()] role_completer_model = QStringListModel(self) role_completer_model.setStringList(sorted(role_completion_list)) self.role_completion = QCompleter() self.role_completion.setModel(role_completer_model) self.source.setCompleter(self.role_completion) self.default_role.setCompleter(self.role_completion) # set up role/type autocompletion (target) roletype_completion_list = [str(r) for r in self.policy.roles()] # roletype_completion_list.extend(str(a) for a in self.policy.roleattributes()) roletype_completion_list.extend(str(t) for t in self.policy.types()) roletype_completion_list.extend(str(a) for a in self.policy.typeattributes()) roletype_completer_model = QStringListModel(self) roletype_completer_model.setStringList(sorted(roletype_completion_list)) self.roletype_completion = QCompleter() self.roletype_completion.setModel(roletype_completer_model) self.target.setCompleter(self.roletype_completion) # setup indications of errors on source/target/default self.orig_palette = self.source.palette() self.error_palette = self.source.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_source_error() self.clear_target_error() self.clear_default_error() # populate class list self.class_model = SEToolsListModel(self) self.class_model.item_list = sorted(self.policy.classes()) self.tclass.setModel(self.class_model) # set up results self.table_results_model = RBACRuleListModel(self) self.sort_proxy = QSortFilterProxyModel(self) self.sort_proxy.setSourceModel(self.table_results_model) self.table_results.setModel(self.sort_proxy) # set up processing thread self.thread = QThread() self.worker = ResultsUpdater(self.query, self.table_results_model) self.worker.moveToThread(self.thread) self.worker.raw_line.connect(self.raw_results.appendPlainText) self.worker.finished.connect(self.update_complete) self.worker.finished.connect(self.thread.quit) self.thread.started.connect(self.worker.update) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.canceled.connect(self.thread.requestInterruption) # Ensure settings are consistent with the initial .ui state self.set_source_regex(self.source_regex.isChecked()) self.set_target_regex(self.target_regex.isChecked()) self.set_default_regex(self.default_regex.isChecked()) self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.results_frame.setHidden(not self.results_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) # connect signals self.buttonBox.clicked.connect(self.run) self.clear_ruletypes.clicked.connect(self.clear_all_ruletypes) self.all_ruletypes.clicked.connect(self.set_all_ruletypes) self.source.textEdited.connect(self.clear_source_error) self.source.editingFinished.connect(self.set_source) self.source_regex.toggled.connect(self.set_source_regex) self.target.textEdited.connect(self.clear_target_error) self.target.editingFinished.connect(self.set_target) self.target_regex.toggled.connect(self.set_target_regex) self.tclass.selectionModel().selectionChanged.connect(self.set_tclass) self.invert_class.clicked.connect(self.invert_tclass_selection) self.default_role.textEdited.connect(self.clear_default_error) self.default_role.editingFinished.connect(self.set_default_role) self.default_regex.toggled.connect(self.set_default_regex)
def initUI(self): self.setWindowTitle(self.project["name"]) self.setGeometry(240, 120, WIDTH, HEIGHT) self.setFixedSize(QSize(WIDTH, HEIGHT)) files_group = QGroupBox(self) files_group.setGeometry(20, 10, 590, 300) files_group.setTitle("Files") files_group.setStyleSheet(ll_ss) act_group = QGroupBox(self) act_group.setGeometry(630, 10, 170, 300) act_group.setTitle("Actions") act_group.setStyleSheet(ll_ss) log_group = QGroupBox(self) log_group.setGeometry(20, 320, 430, 190) log_group.setTitle("Log") log_group.setStyleSheet(ll_ss) device_group = QGroupBox(self) device_group.setGeometry(470, 320, 160, 190) device_group.setTitle("Device") device_group.setStyleSheet(ll_ss) status_group = QGroupBox(self) status_group.setGeometry(650, 320, 150, 190) status_group.setTitle("Status") status_group.setStyleSheet(ll_ss) self.wheres = QComboBox(act_group) self.gestures = QComboBox(act_group) self.wheres.setGeometry(10, 30, 150, 25) for w in self.project["sets"]: self.wheres.addItem(w) self.wheres.currentIndexChanged.connect(self.refresh_list) self.gestures.setGeometry(10, 70, 150, 25) for g in self.project["gestures"]: self.gestures.addItem(g) self.gestures.currentIndexChanged.connect(self.refresh_list) lbl = QLabel(act_group) lbl.setText("EMG(Hz):") lbl.move(18, 111) self.emg_freq = QSpinBox(act_group) self.emg_freq.setMinimum(1) self.emg_freq.setMaximum(200) self.emg_freq.setValue(self.project["emg_freq"]) self.emg_freq.move(act_group.width() - 65, 110) lbl = QLabel(act_group) lbl.setText("IMU(Hz):") lbl.move(18, 146) self.imu_freq = QSpinBox(act_group) self.imu_freq.setMinimum(1) self.imu_freq.setMaximum(50) self.imu_freq.setValue(self.project["emg_freq"]) self.imu_freq.setGeometry(act_group.width() - 65, 145, 49, 20) lbl = QLabel(act_group) lbl.setText("Time(ms):") lbl.move(18, 181) self.dur = QSpinBox(act_group) self.dur.setMinimum(1) self.dur.setSingleStep(10) self.dur.setMaximum(5000) self.dur.setValue(self.project["duration"]) self.dur.setGeometry(act_group.width() - 71, 181, 55, 20) self.imu_check = QCheckBox(act_group) self.imu_check.setText("Include IMU") self.imu_check.setChecked(self.project["imu_check"] == 1) self.imu_check.move(16, 215) self.startbtn = QPushButton(act_group) self.startbtn.setText("Start") self.startbtn.setStyleSheet("QPushButton::disabled{background-color: rgb(245, 245, 245);color: rgb(140, 140, 140); border: none; border-radius:5px;} QPushButton::enabled{background-color: rgb(0, 99, 225);color: white; border: none; border-radius:5px;}") self.startbtn.setGeometry(15, 250, 140, 22) self.startbtn.clicked.connect(self.start) self.startbtn.setEnabled(False) self.log_txt = QPlainTextEdit(log_group) self.log_txt.setStyleSheet(ll_ss_txt) self.log_txt.setGeometry(15, 25, log_group.width() - 30, log_group.height() - 40) self.log_txt.textChanged.connect(self.scroll_log_view) self.log_txt.setReadOnly(True) self.add_log("Application Started") self.dev_name = QLabel(device_group) self.dev_name.setText("Name: <unknown>") self.dev_name.setMaximumWidth(device_group.width() - 30) self.dev_name.move(15, 25) self.dev_batt = QLabel(device_group) self.dev_batt.setText("Battery: <unknown>") self.dev_batt.setMaximumWidth(device_group.width() - 30) self.dev_batt.move(15, 55) dev_con = QLabel(device_group) dev_con.setText("Connected: ") dev_con.setMaximumWidth(device_group.width() - 30) dev_con.move(15, 85) self.dev_con_color = QFrame(device_group) self.dev_con_color.setStyleSheet("background-color:red;border-radius:10px;") self.dev_con_color.setGeometry(device_group.width() - 15 - 20, 83, 20, 20) self.conbtn = QPushButton(device_group) self.conbtn.setText("Connect") self.conbtn.setEnabled(True) self.conbtn.setGeometry(10, 110, device_group.width() - 20, 25) self.conbtn.clicked.connect(self.connection) self.discbtn = QPushButton(device_group) self.discbtn.setText("Disconnect") self.discbtn.setGeometry(10, 145, device_group.width() - 20, 25) self.discbtn.setEnabled(False) self.discbtn.clicked.connect(self.disconnection) reclbl = QLabel(status_group) reclbl.setText("Recording: ") reclbl.setMaximumWidth(status_group.width() - 30) reclbl.move(15, 25) self.rec_con_color = QFrame(status_group) self.rec_con_color.setStyleSheet("background-color:red;border-radius:10px;") self.rec_con_color.setGeometry(status_group.width() - 15 - 20, 23, 20, 20) self.rec_proglbl = QLabel(status_group) self.rec_proglbl.setText("Progress: 0%") self.rec_proglbl.setMaximumWidth(status_group.width() - 30) self.rec_proglbl.setGeometry(15, 55, status_group.width() - 30, 25) self.rec_prog = QProgressBar(status_group) self.rec_prog.setMaximum(100) self.rec_prog.setGeometry(15, 90, status_group.width() - 30, 10) self.fileslbl = QLabel(status_group) self.fileslbl.setText("Files: ") self.fileslbl.setMaximumWidth(status_group.width() - 30) self.fileslbl.setGeometry(15, 110, status_group.width() - 30, 25) self.listview = PListView(files_group, ll_ss_txt, self.project) self.listview.setGeometry(15, 25, files_group.width() - 30, files_group.height() - 40) self.listview.setSelectionMode(QAbstractItemView.ExtendedSelection) self.listview.doubleClicked.connect(self.view_data) self.listview.contextMenuShowed.connect(self.view_data) self.listview.contextMenuDifferenced.connect(self.show_diff_data) self.listview.contextMenuAveraged.connect(self.show_ave_data) self.listview.contextMenuShowedFinder.connect(self.show_finder) self.listview.contextMenuMoved.connect(self.move_data) self.listview.contextMenuDeleted.connect(self.delete_data) self.model = QStringListModel() self.listview.setModel(self.model) self.list_data_for_set_and_gesture(self.project["sets"][0], self.project["gestures"][0]) self.add_log("Loading dataset...") total = 0 for set in self.project["sets"]: for gesture in self.project["gestures"]: path = self.project["location"] + "/" + set + "/" + gesture sum = 0 for f in os.listdir(path): if not f.startswith("."): sum = sum + 1 total = total + sum self.add_log("Found " + str(sum) + " files at " + set + "/" + gesture, False) self.add_log("Found " + str(total) + " files")
class WebJumpPrompt(Prompt): label = "url/webjump:" complete_options = {"match": Prompt.SimpleMatch} history = PromptHistory() keymap = WEBJUMP_PROMPT_KEYMAP default_input = "alternate" def completer_model(self): data = [] for name, w in WEBJUMPS.items(): data.append((name, w.doc)) for url, name in self.bookmarks: data.append((name, url)) return PromptTableModel(data) def enable(self, minibuffer): self.bookmarks = app().bookmarks().list() Prompt.enable(self, minibuffer) minibuffer.input().textEdited.connect(self._text_edited) minibuffer.input().installEventFilter(self) self._wc_model = QStringListModel() self._wb_model = minibuffer.input().completer_model() self._active_webjump = None self._completer = None self._popup_sel_model = None input = minibuffer.input() if self.default_input in ("current_url", "alternate"): url = current_buffer().url().toString() input.setText(url) input.setSelection(0, len(url)) if self.default_input == "alternate": input.deselect() elif self.default_input == "default_webjump": wj = WEBJUMPS.get(webjump_default.value) if wj: input.setText(wj.name + ("://" if wj.protocol else " ")) def eventFilter(self, obj, event): # call _text_edited on backspace release, as this is not reported by # the textEdited slot. if event.type() == QEvent.KeyRelease: if event.key() == Qt.Key_Backspace: self._text_edited(self.minibuffer.input().text()) return Prompt.eventFilter(self, obj, event) def _set_active_webjump(self, wj): if self._active_webjump == wj: return if self._active_webjump: if self._completer: self._completer.completed.disconnect(self._got_completions) self._completer.abort() self._completer.deleteLater() self._completer = None m_input = self.minibuffer.input() if wj: self._completer = wj.complete_fn() self._completer.completed.connect(self._got_completions) # set matching strategy m_input.set_match(None) model = self._wc_model else: m_input.set_match(Prompt.SimpleMatch) model = self._wb_model self._active_webjump = wj if m_input.completer_model() != model: m_input.popup().hide() m_input.set_completer_model(model) if self._popup_sel_model: self._popup_sel_model.selectionChanged.disconnect( self._popup_selection_changed) self._popup_sel_model = None if wj: m_input.popup().selectionModel()\ .selectionChanged.connect( self._popup_selection_changed ) def _popup_selection_changed(self, _sel, _desel): # try to abort any completion if the user select something in # the popup if self._completer: self._completer.abort() def _text_edited(self, text): # search for a matching webjump first_word = text.split(" ")[0].split("://")[0] if first_word in [w for w in WEBJUMPS if len(w) < len(text)]: self._set_active_webjump(WEBJUMPS[first_word]) self.start_completion(self._active_webjump) else: # didn't find a webjump, go back to matching # webjump/bookmark/history self._set_active_webjump(None) def start_completion(self, webjump): text = self.minibuffer.input().text() prefix = webjump.name + ("://" if webjump.protocol else " ") self._completer.abort() self._completer.complete(text[len(prefix):]) @Slot(list) def _got_completions(self, data): if self._active_webjump: self._wc_model.setStringList(data) text = self.minibuffer.input().text() prefix = self._active_webjump.name + \ ("://" if self._active_webjump.protocol else " ") self.minibuffer.input().show_completions(text[len(prefix):]) def close(self): Prompt.close(self) self.minibuffer.input().removeEventFilter(self) # not sure if those are required; self._wb_model.deleteLater() self._wc_model.deleteLater() def _on_completion_activated(self, index): super()._on_completion_activated(index) chosen_text = self.minibuffer.input().text() # if there is already an active webjump, if self._active_webjump: # add the selected completion after it if self._active_webjump.protocol: self.minibuffer.input().setText(self._active_webjump.name + "://" + chosen_text) else: self.minibuffer.input().setText(self._active_webjump.name + " " + chosen_text) # if we just chose a webjump # and not WEBJUMPS[chosen_text].protocol: elif chosen_text in WEBJUMPS: # add a space after the selection self.minibuffer.input().setText(chosen_text + ( " " if not WEBJUMPS[chosen_text].protocol else "://")) def value(self): value = super().value() if value is None: return # split webjumps and protocols between command and argument if re.match(r"^\S+://.*", value): args = value.split("://", 1) else: args = value.split(" ", 1) command = args[0] # Look for webjumps webjump = None if command in WEBJUMPS: webjump = WEBJUMPS[command] else: # Look for a incomplete webjump, accepting a candidate # if there is a single option candidates = [wj for wj in WEBJUMPS if wj.startswith(command)] if len(candidates) == 1: webjump = WEBJUMPS[candidates[0]] if webjump: if not webjump.allow_args: # send the url as is return webjump.url elif len(args) < 2: # send the url without a search string return webjump.url.replace("%s", "") else: # format the url as entered if webjump.protocol: return value else: return webjump.url.replace( "%s", str(QUrl.toPercentEncoding(args[1]), "utf-8")) # Look for a bookmark bookmarks = {name: url for url, name in self.bookmarks} if value in bookmarks: return bookmarks[value] # Look for a incomplete bookmarks, accepting a candidate # if there is a single option candidates = [bm for bm in bookmarks if bm.startswith(command)] if len(candidates) == 1: return bookmarks[candidates[0]] # No webjump, no bookmark, look for a url if "://" not in value: url = QUrl.fromUserInput(value) if url.isValid(): # default scheme is https for us if url.scheme() == "http": url.setScheme("https") return url return value
def setupUi(self): self.load_ui("apol/nodeconquery.ui") # set up user autocompletion user_completion_list = [str(u) for u in self.policy.users()] user_completer_model = QStringListModel(self) user_completer_model.setStringList(sorted(user_completion_list)) self.user_completion = QCompleter() self.user_completion.setModel(user_completer_model) self.user.setCompleter(self.user_completion) # set up role autocompletion role_completion_list = [str(r) for r in self.policy.roles()] role_completer_model = QStringListModel(self) role_completer_model.setStringList(sorted(role_completion_list)) self.role_completion = QCompleter() self.role_completion.setModel(role_completer_model) self.role.setCompleter(self.role_completion) # set up type autocompletion type_completion_list = [str(t) for t in self.policy.types()] type_completer_model = QStringListModel(self) type_completer_model.setStringList(sorted(type_completion_list)) self.type_completion = QCompleter() self.type_completion.setModel(type_completer_model) self.type_.setCompleter(self.type_completion) # setup IP version # item 0 is empty string (in the .ui file) self.ip_version.insertItem(1, "IPv4", NodeconIPVersion.ipv4) self.ip_version.insertItem(2, "IPv6", NodeconIPVersion.ipv6) # setup indications of errors on source/target/default self.errors = set() self.orig_palette = self.type_.palette() self.error_palette = self.type_.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_network_error() self.clear_user_error() self.clear_type_error() self.clear_role_error() self.clear_range_error() # set up results self.table_results_model = NodeconTableModel(self) self.sort_proxy = QSortFilterProxyModel(self) self.sort_proxy.setSourceModel(self.table_results_model) self.table_results.setModel(self.sort_proxy) self.table_results.sortByColumn(0, Qt.AscendingOrder) # set up processing thread self.thread = QThread() self.worker = QueryResultsUpdater(self.query, self.table_results_model) self.worker.moveToThread(self.thread) self.worker.raw_line.connect(self.raw_results.appendPlainText) self.worker.finished.connect(self.update_complete) self.worker.finished.connect(self.thread.quit) self.thread.started.connect(self.worker.update) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.canceled.connect(self.thread.requestInterruption) self.busy.reset() # update busy dialog from query INFO logs self.handler = LogHandlerToSignal() self.handler.message.connect(self.busy.setLabelText) logging.getLogger("setools.nodeconquery").addHandler(self.handler) # Ensure settings are consistent with the initial .ui state self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) # Range criteria is available only if policy is MLS if not self.policy.mls: self.range_criteria.setEnabled(False) self.range_criteria.setToolTip("MLS is disabled in this policy.") self.range_.setToolTip("MLS is disabled in this policy.") self.range_exact.setToolTip("MLS is disabled in this policy.") self.range_overlap.setToolTip("MLS is disabled in this policy.") self.range_subset.setToolTip("MLS is disabled in this policy.") self.range_superset.setToolTip("MLS is disabled in this policy.") # connect signals self.buttonBox.clicked.connect(self.run) self.network.textEdited.connect(self.clear_network_error) self.network.editingFinished.connect(self.set_network) self.user.textEdited.connect(self.clear_user_error) self.user.editingFinished.connect(self.set_user) self.user_regex.toggled.connect(self.set_user_regex) self.role.textEdited.connect(self.clear_role_error) self.role.editingFinished.connect(self.set_role) self.role_regex.toggled.connect(self.set_role_regex) self.type_.textEdited.connect(self.clear_type_error) self.type_.editingFinished.connect(self.set_type) self.type_regex.toggled.connect(self.set_type_regex) self.range_.textEdited.connect(self.clear_range_error) self.range_.editingFinished.connect(self.set_range)
def completer_model(self): model = QStringListModel(self) model.setStringList(sorted(variables.VARIABLES)) return model
def searchClick(self): self.ui.spinBox.setValue(1) self.ui.pushButton_2.setEnabled(False) text = self.ui.lineEdit.text() path = 'searchResult' url = 'urlResult' headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0', 'Accept-Language': 'zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Cookie': '__cfduid=d2b34dd3b59a8ec2e1532b15f6cbf328c1581150229; __atuvc=3%7C6%2C5%7C7; _ym_uid=1581150239832564503; _ym_d=1581150239; _ym_isad=2; PHPSESSID=hkncj8heksainod7fjke0r82c5; __atuvs=5e42a0252adbb1cc000; _ym_visorc_54632110=b' } search = urllib.parse.quote(text) searchlist = [] urlist = [] show = [] url = 'https://gimy.tv/vod-search.html?wd=' + search r = requests.get(url, headers=headers) soup = BeautifulSoup(r.text, 'lxml') ul = soup.find('ul', {'class': 'stui-vodlist__media col-pd clearfix'}) title = ul.find_all('h3', {'class': 'title'}) for t in title: a = t.find('a') urlist.append(a['href'] + '\n') searchlist.append(t.string + '\n') show.append(t.string) slm = QStringListModel() slm.setStringList(show) self.ui.listView.setModel(slm) file = open(path, 'w', encoding='utf8') #檔案不存在自動創建覆寫 file.writelines(searchlist) file.close() pt = soup.find('ul', {'class': 'stui-page-text text-center clearfix'}) page = re.search(".(\d*)頁", pt.text) page1 = int(page.group(1)) self.ui.label.setText('共' + str(page1) + '頁') self.ui.spinBox.setMaximum(page1) urllist = [] def BeS(p): url = 'https://gimy.tv/vod-search-pg-' + str( p) + '-wd-' + search + '.html' r = requests.get(url, headers=headers) soup = BeautifulSoup(r.text, 'lxml') ul = soup.find('ul', {'class': 'stui-vodlist__media col-pd clearfix'}) title = ul.find_all('h3', {'class': 'title'}) searchlist = [] for t in title: searchlist.append(t.string + '\n') a = t.find('a') urllist.append(a['href'] + '\n') file = open('searchResult', 'a', encoding='utf8') file.writelines(searchlist) file.close() if (page1 <= 5) and (page1 != 1): for p in range(2, page1 + 1): BeS(p) file = open('url', 'w', encoding='utf8') file.writelines(urlist) file.writelines(urllist) file.close() elif (page1 > 5): for p in range(2, 6): BeS(p) file = open('url', 'w', encoding='utf8') file.writelines(urlist) file.writelines(urllist) file.close() else: self.ui.pushButton_2.setEnabled(False) self.ui.pushButton_4.setEnabled(False) file = open('url', 'w', encoding='utf8') file.writelines(urlist) file.writelines(urllist) file.close()
def __init__(self, fps=30, parent=None): # type: (int, Optional[QWidget]) -> None super().__init__(parent=parent) self.pkg_path = path.dirname(path.dirname(path.abspath(__file__))) self.training_data_dir = path.join(self.pkg_path, 'train') self.models_dir = path.join(self.pkg_path, 'models') self.model_fname = 'fisherfaces.p' try: self.model = data_provider.load_model( path.join(self.models_dir, self.model_fname)) except AssertionError: self.model = None self.existing_labels = QStringListModel(self.get_existing_labels()) self.fps = fps self.video_size = QSize(640, 480) self.gray_image = None self.detected_faces = [] # Setup the UI self.main_layout = QHBoxLayout() self.setLayout(self.main_layout) self.control_layout = QVBoxLayout() self.control_layout.setSpacing(8) self.main_layout.addItem(self.control_layout) # Setup the existing label view self.labels_view = QListView(parent=self) self.labels_view.setModel(self.existing_labels) self.labels_view.setSelectionMode(QListView.SingleSelection) self.labels_view.setItemDelegate(CapitalizeDelegate(self)) self.control_layout.addWidget(self.labels_view) self.new_label_txt = QLineEdit(self) self.new_label_txt.returnPressed.connect(self.add_new_label) self.new_label_txt.returnPressed.connect(self.new_label_txt.clear) self.control_layout.addWidget(self.new_label_txt) self.add_button = QPushButton('Add Label', self) self.add_button.clicked.connect(self.add_new_label) self.control_layout.addWidget(self.add_button) # Setup the training area train_box = QGroupBox('Train', self) train_box_layout = QVBoxLayout() train_box.setLayout(train_box_layout) self.control_layout.addWidget(train_box) self.train_btn = QPushButton('Train', self) self.train_btn.clicked.connect(self.train) train_box_layout.addWidget(self.train_btn) self.control_layout.addStretch(0) # Add take picture shortcut self.take_picture_btn = QPushButton('Take picture', self) self.take_picture_btn.clicked.connect(self.take_picture) self.control_layout.addWidget(self.take_picture_btn) shortcut = QShortcut(QKeySequence('Space'), self, self.take_picture) shortcut.setWhatsThis('Take picture and add to training data.') # Add quit shortcut shortcut = QShortcut(QKeySequence('Esc'), self, self.close) shortcut.setWhatsThis('Quit') # Setup the main camera area self.image_label = QLabel(self) self.image_label.setFixedSize(self.video_size) self.main_layout.addWidget(self.image_label) # Setup the camera self.capture = cv2.VideoCapture(0) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.video_size.width()) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.video_size.height()) self.timer = QTimer() self.timer.timeout.connect(self.display_video_stream) self.timer.start(int(1000 / self.fps))
def __init__(self, args, parent=None): QtGui.QMainWindow.__init__(self, parent) self.srclist = [] # list of source directories self.imageIndex = 0 # index of selected image self.seriesMap = OrderedDict( ) # maps series table row tuples to DicomSeries object it was generated from self.seriesColumns = list(seriesListColumns) # keywords for columns self.selectedRow = -1 # selected series row self.lastDir = '.' # last loaded directory root self.filterRegex = '' # regular expression to filter tags by # create the directory queue and loading thread objects self.srcQueue = Queue() # queue of directories to load self.loadDirThread = threading.Thread(target=self._loadSourceThread) self.loadDirThread.daemon = True # clean shutdown possible with daemon threads self.loadDirThread.start( ) # start the thread now, it will wait until something is put on self.srcQueue # setup ui self.setupUi(self) # create UI elements based on the loaded .ui file self.setWindowTitle('DicomBrowser v%s (FOR RESEARCH ONLY)' % (__version__)) self.setStatus('') # connect signals self.importButton.clicked.connect(self._openDirDialog) self.statusSignal.connect(self.setStatus) self.updateSignal.connect(self._updateSeriesTable) self.filterLine.textChanged.connect(self._setFilterString) self.imageSlider.valueChanged.connect(self.setSeriesImage) self.seriesView.clicked.connect(self._seriesTableClicked) # setup the list and table models self.srcmodel = QStringListModel() self.seriesmodel = SeriesTableModel(self.seriesColumns) self.seriesmodel.layoutChanged.connect(self._seriesTableResize) self.tagmodel = QtGui.QStandardItemModel() # assign models to views self.sourceListView.setModel(self.srcmodel) self.seriesView.setModel(self.seriesmodel) self.tagView.setModel(self.tagmodel) # create the pyqtgraph object for viewing images self.imageview = pg.ImageView() layout = QtGui.QGridLayout(self.view2DGroup) layout.addWidget(self.imageview) # load the empty image placeholder into a ndarray qimg = QtGui.QImage(':/icons/noimage.png') bytedata = qimg.constBits().asstring(qimg.width() * qimg.height()) self.noimg = np.ndarray((qimg.width(), qimg.height()), dtype=np.ubyte, buffer=bytedata) # add the directories passed as arguments to the directory queue to start loading for i in args[1:]: if os.path.exists(i): self.addSource(i) def _setClipboard(): '''Set the clipboard to contain fuller tag data when CTRL+C is applied to a tag line in the tree.''' def printChildren(child, level, out): for r in range(child.rowCount()): print('', file=out) for c in range(child.columnCount()): cc = child.child(r, c) if cc is not None: print(' ' * level, cc.text(), file=out, end='') if cc.hasChildren(): printChildren(cc, level + 1, out) out = StringIO() items = [ self.tagmodel.itemFromIndex(i) for i in self.tagView.selectedIndexes() ] print(' '.join(i.data() or i.text() for i in items if i), end='', file=out) if items[0].hasChildren(): printChildren(items[0], 1, out) QtGui.QApplication.clipboard().setText(out.getvalue()) # override CTRL+C in the tag tree to copy a fuller set of tag data to the clipboard QtGui.QShortcut(QtGui.QKeySequence('Ctrl+c'), self.tagView).activated.connect(_setClipboard)
class Spdom(WizardWidget): drag_label = "Spatial Domain <spdom>" acceptable_tags = ['spdom', 'bounding'] ui_class = UI_spdom.Ui_fgdc_spdom def __init__(self, root_widget=None): self.east = 180 self.west = -180 self.north = 90 self.south = -90 self.valid = True super(self.__class__, self).__init__() self.schema = 'bdp' self.root_widget = root_widget self.after_load = False self.in_xml_load = False self.has_rect = True self.completer = QCompleter() self.ui.fgdc_descgeog.setCompleter(self.completer) self.model = QStringListModel() self.completer.setModel(self.model) self.completer.setCaseSensitivity(0) fname = utils.get_resource_path("spatial/BNDCoords.csv") self.bnds_df = pd.read_csv(fname) self.model.setStringList(self.bnds_df['Name']) self.completer.popup().clicked.connect(self.on_completer_activated) self.completer.popup().selectionModel().selectionChanged.connect( self.on_completer_activated) # self.completer.popup().activated.connect(self.on_completer_activated) def build_ui(self): """ Build and modify this widget's GUI Returns ------- None """ self.ui = self.ui_class() self.ui.setupUi(self) if platform.system() == 'Darwin': map_fname = utils.get_resource_path('leaflet/map_mac.html') else: map_fname = utils.get_resource_path('leaflet/map.html') try: self.view = QWebView() self.view.page().mainFrame().addToJavaScriptWindowObject( "Spdom", self) self.view.setUrl(QUrl.fromLocalFile(map_fname)) self.frame = self.view.page().mainFrame() self.view.load( QUrl.fromLocalFile(QtCore.QDir.current().filePath(map_fname))) except AttributeError: self.view = QWebView() self.view.load( QUrl.fromLocalFile(QtCore.QDir.current().filePath(map_fname))) channel = QWebChannel(self.view.page()) jstr = """ var spdom; new QWebChannel(qt.webChannelTransport, function (channel) { spdom = channel.objects.spdom; });""" self.view.page().setWebChannel(channel) self.evaluate_js(jstr) channel.registerObject("spdom", self) self.ui.verticalLayout_3.addWidget(self.view) # setup drag-drop functionality for this widget and all it's children. self.setup_dragdrop(self) self.add_rect() self.raise_() def connect_events(self): self.ui.fgdc_eastbc.editingFinished.connect(self.coord_updated) self.ui.fgdc_westbc.editingFinished.connect(self.coord_updated) self.ui.fgdc_northbc.editingFinished.connect(self.coord_updated) self.ui.fgdc_southbc.editingFinished.connect(self.coord_updated) def on_completer_activated(self, model_index): try: cur_descgeog = model_index.data() except AttributeError: try: cur_descgeog = model_index.indexes()[0].data() except: return try: if self.bnds_df['Name'].str.contains(cur_descgeog).any(): self.ui.fgdc_eastbc.setText( str( float(self.bnds_df[self.bnds_df['Name'] == cur_descgeog]['east']))) self.ui.fgdc_westbc.setText( str( float(self.bnds_df[self.bnds_df['Name'] == cur_descgeog]['west']))) self.ui.fgdc_northbc.setText( str( float(self.bnds_df[self.bnds_df['Name'] == cur_descgeog]['north']))) self.ui.fgdc_southbc.setText( str( float(self.bnds_df[self.bnds_df['Name'] == cur_descgeog]['south']))) self.add_rect() self.update_map() except: pass # this is a convenience function. # If anything at all happens pass silently def complete_name(self): self.view.page().runJavaScript('addRect();', js_callback) def coord_updated(self): good_coords = self.all_good_coords() try: cur_name = self.sender().objectName() if 'fgdc' not in cur_name: return cur_value = self.sender().text() except AttributeError: cur_name = '' cur_value = '' try: cur_value = float(cur_value) except ValueError: pass msg = '' if type(cur_value) != float and cur_value != '': msg = 'number entered must be numeric only' elif cur_value == '': msg = '' elif cur_name in ['fgdc_westbc', 'fgdc_eastbc'] \ and -180 >= cur_value >= 180: msg = 'East or West coordinate must be within -180 and 180' elif cur_name in ['fgdc_southbc', 'fgdc_northbc'] \ and -90 >= cur_value >= 90: msg = 'North and South coordinates must be within -90 and 90' elif cur_name == 'fgdc_southbc': try: north = float(self.ui.fgdc_northbc.text()) if north <= cur_value: msg = 'North coordinate must be greater than South coordinate' except ValueError: pass elif cur_name == 'fgdc_northbc': try: south = float(self.ui.fgdc_southbc.text()) if south >= cur_value: msg = 'North coordinate must be greater than South coordinate' except ValueError: pass if msg: QMessageBox.warning(self, "Problem bounding coordinates", msg) if good_coords: self.add_rect() else: self.remove_rect() return self.update_map() def update_map(self): jstr = """east = {eastbc}; west = {westbc}; south = {southbc}; north = {northbc}; updateMap(); fitMap(); """.format( **{ 'eastbc': self.ui.fgdc_eastbc.text(), 'westbc': self.ui.fgdc_westbc.text(), 'northbc': self.ui.fgdc_northbc.text(), 'southbc': self.ui.fgdc_southbc.text(), }) self.evaluate_js(jstr) def add_rect(self): jstr = """addRect();""" self.evaluate_js(jstr) def remove_rect(self): if self.has_rect: self.has_rect = False jstr = """removeRect()""" self.evaluate_js(jstr) def evaluate_js(self, jstr): """ :param jstr: :return: """ try: self.frame.evaluateJavaScript(jstr) except: self.view.page().runJavaScript(jstr, js_callback) @pyqtSlot(float, float) def on_ne_move(self, lat, lng): if self.in_xml_load: n, e = lat, lng s = float(self.ui.fgdc_southbc.text()) w = float(self.ui.fgdc_westbc.text()) bounds = spatial_utils.format_bounding((w, e, n, s)) self.ui.fgdc_eastbc.setText(bounds[1]) self.ui.fgdc_northbc.setText(bounds[2]) @pyqtSlot(float, float) def on_nw_move(self, lat, lng): if self.in_xml_load: n, w = lat, lng s = float(self.ui.fgdc_southbc.text()) e = float(self.ui.fgdc_eastbc.text()) bounds = spatial_utils.format_bounding((w, e, n, s)) self.ui.fgdc_westbc.setText(bounds[0]) self.ui.fgdc_northbc.setText(bounds[2]) @pyqtSlot(float, float) def on_se_move(self, lat, lng): if self.in_xml_load: s, e = lat, lng n = float(self.ui.fgdc_northbc.text()) w = float(self.ui.fgdc_westbc.text()) bounds = spatial_utils.format_bounding((w, e, n, s)) self.ui.fgdc_eastbc.setText(bounds[1]) self.ui.fgdc_southbc.setText(bounds[3]) @pyqtSlot(float, float) def on_sw_move(self, lat, lng): if self.in_xml_load: s, w = lat, lng n = float(self.ui.fgdc_northbc.text()) e = float(self.ui.fgdc_eastbc.text()) bounds = spatial_utils.format_bounding((w, e, n, s)) self.ui.fgdc_westbc.setText(bounds[0]) self.ui.fgdc_southbc.setText(bounds[3]) def switch_schema(self, schema): self.schema = schema if schema == 'bdp': self.ui.fgdc_descgeog.show() self.ui.descgeog_label.show() self.ui.descgeog_star.show() else: self.ui.fgdc_descgeog.hide() self.ui.descgeog_label.hide() self.ui.descgeog_star.hide() def all_good_coords(self): try: if -180 > float(self.ui.fgdc_westbc.text()) > 180: return False if -180 > float(self.ui.fgdc_eastbc.text()) > 180: return False if -90 > float(self.ui.fgdc_southbc.text()) > 90: return False if -90 > float(self.ui.fgdc_northbc.text()) > 90: return False if float(self.ui.fgdc_northbc.text()) <= float( self.ui.fgdc_southbc.text()): return False return True except: return False def clear_widget(self): super(self.__class__, self).clear_widget() # self.view.page().mainFrame().addToJavaScriptWindowObject("Spdom", self) # map_fname = utils.get_resource_path('leaflet/map.html') # self.view.setUrl(QUrl.fromLocalFile(map_fname)) def showEvent(self, e): if not self.after_load: self.add_rect() self.update_map() jstr = "sw_marker.openPopup();" self.evaluate_js(jstr) self.after_load = True def to_xml(self): spdom = xml_node('spdom') if self.schema == 'bdp': descgeog = xml_node('descgeog', text=self.ui.fgdc_descgeog.text(), parent_node=spdom) bounding = xml_node('bounding', parent_node=spdom) westbc = xml_node('westbc', text=self.ui.fgdc_westbc.text(), parent_node=bounding) eastbc = xml_node('eastbc', text=self.ui.fgdc_eastbc.text(), parent_node=bounding) northbc = xml_node('northbc', text=self.ui.fgdc_northbc.text(), parent_node=bounding) southbc = xml_node('southbc', text=self.ui.fgdc_southbc.text(), parent_node=bounding) if self.original_xml is not None: boundalt = xml_utils.search_xpath(self.original_xml, 'bounding/boundalt') if boundalt is not None: spdom.append(deepcopy(boundalt)) dsgpoly_list = xml_utils.search_xpath(self.original_xml, 'dsgpoly', only_first=False) for dsgpoly in dsgpoly_list: spdom.append(deepcopy(dsgpoly)) return spdom def from_xml(self, spdom): self.in_xml_load = False self.original_xml = spdom self.clear_widget() utils.populate_widget(self, spdom) contents = xml_utils.node_to_dict(spdom, add_fgdc=False) if 'bounding' in contents: contents = contents['bounding'] try: if self.all_good_coords(): self.add_rect() self.update_map() else: self.remove_rect() except KeyError: self.remove_rect() self.in_xml_load = True
class TriblerWindow(QMainWindow): resize_event = pyqtSignal() escape_pressed = pyqtSignal() received_search_completions = pyqtSignal(object) def on_exception(self, *exc_info): if self.exception_handler_called: # We only show one feedback dialog, even when there are two consecutive exceptions. return self.exception_handler_called = True self.delete_tray_icon() # Stop the download loop self.downloads_page.stop_loading_downloads() # Add info about whether we are stopping Tribler or not os.environ['TRIBLER_SHUTTING_DOWN'] = str( self.core_manager.shutting_down) if not self.core_manager.shutting_down: self.core_manager.stop(stop_app_on_shutdown=False) self.setHidden(True) if self.debug_window: self.debug_window.setHidden(True) exception_text = "".join(traceback.format_exception(*exc_info)) logging.error(exception_text) dialog = FeedbackDialog( self, exception_text, self.core_manager.events_manager.tribler_version, self.start_time) dialog.show() def __init__(self, core_args=None, core_env=None, api_port=None): QMainWindow.__init__(self) QCoreApplication.setOrganizationDomain("nl") QCoreApplication.setOrganizationName("TUDelft") QCoreApplication.setApplicationName("Tribler") QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) self.gui_settings = QSettings() api_port = api_port or int( get_gui_setting(self.gui_settings, "api_port", DEFAULT_API_PORT)) dispatcher.update_worker_settings(port=api_port) self.navigation_stack = [] self.tribler_started = False self.tribler_settings = None self.debug_window = None self.core_manager = CoreManager(api_port) self.pending_requests = {} self.pending_uri_requests = [] self.download_uri = None self.dialog = None self.new_version_dialog = None self.start_download_dialog_active = False self.request_mgr = None self.search_request_mgr = None self.search_suggestion_mgr = None self.selected_torrent_files = [] self.vlc_available = True self.has_search_results = False self.last_search_query = None self.last_search_time = None self.start_time = time.time() self.exception_handler_called = False self.token_refresh_timer = None sys.excepthook = self.on_exception uic.loadUi(get_ui_file_path('mainwindow.ui'), self) TriblerRequestManager.window = self self.tribler_status_bar.hide() # Load dynamic widgets uic.loadUi(get_ui_file_path('torrent_channel_list_container.ui'), self.channel_page_container) self.channel_torrents_list = self.channel_page_container.items_list self.channel_torrents_detail_widget = self.channel_page_container.details_tab_widget self.channel_torrents_detail_widget.initialize_details_widget() self.channel_torrents_list.itemSelectionChanged.connect( self.channel_page.clicked_item) uic.loadUi(get_ui_file_path('torrent_channel_list_container.ui'), self.search_page_container) self.search_results_list = self.search_page_container.items_list self.search_torrents_detail_widget = self.search_page_container.details_tab_widget self.search_torrents_detail_widget.initialize_details_widget() self.search_results_list.itemClicked.connect( self.on_channel_item_click) self.search_results_list.itemSelectionChanged.connect( self.search_results_page.clicked_item) self.token_balance_widget.mouseReleaseEvent = self.on_token_balance_click def on_state_update(new_state): self.loading_text_label.setText(new_state) self.core_manager.core_state_update.connect(on_state_update) self.magnet_handler = MagnetHandler(self.window) QDesktopServices.setUrlHandler("magnet", self.magnet_handler, "on_open_magnet_link") self.debug_pane_shortcut = QShortcut(QKeySequence("Ctrl+d"), self) self.debug_pane_shortcut.activated.connect( self.clicked_menu_button_debug) # Remove the focus rect on OS X for widget in self.findChildren(QLineEdit) + self.findChildren( QListWidget) + self.findChildren(QTreeWidget): widget.setAttribute(Qt.WA_MacShowFocusRect, 0) self.menu_buttons = [ self.left_menu_button_home, self.left_menu_button_search, self.left_menu_button_my_channel, self.left_menu_button_subscriptions, self.left_menu_button_video_player, self.left_menu_button_downloads, self.left_menu_button_discovered ] self.video_player_page.initialize_player() self.search_results_page.initialize_search_results_page() self.settings_page.initialize_settings_page() self.subscribed_channels_page.initialize() self.edit_channel_page.initialize_edit_channel_page() self.downloads_page.initialize_downloads_page() self.home_page.initialize_home_page() self.loading_page.initialize_loading_page() self.discovering_page.initialize_discovering_page() self.discovered_page.initialize_discovered_page() self.trust_page.initialize_trust_page() self.stackedWidget.setCurrentIndex(PAGE_LOADING) # Create the system tray icon if QSystemTrayIcon.isSystemTrayAvailable(): self.tray_icon = QSystemTrayIcon() use_monochrome_icon = get_gui_setting(self.gui_settings, "use_monochrome_icon", False, is_bool=True) self.update_tray_icon(use_monochrome_icon) # Create the tray icon menu menu = self.create_add_torrent_menu() show_downloads_action = QAction('Show downloads', self) show_downloads_action.triggered.connect( self.clicked_menu_button_downloads) token_balance_action = QAction('Show token balance', self) token_balance_action.triggered.connect( lambda: self.on_token_balance_click(None)) quit_action = QAction('Quit Tribler', self) quit_action.triggered.connect(self.close_tribler) menu.addSeparator() menu.addAction(show_downloads_action) menu.addAction(token_balance_action) menu.addSeparator() menu.addAction(quit_action) self.tray_icon.setContextMenu(menu) else: self.tray_icon = None self.hide_left_menu_playlist() self.left_menu_button_debug.setHidden(True) self.top_menu_button.setHidden(True) self.left_menu.setHidden(True) self.token_balance_widget.setHidden(True) self.settings_button.setHidden(True) self.add_torrent_button.setHidden(True) self.top_search_bar.setHidden(True) # Set various icons self.top_menu_button.setIcon(QIcon(get_image_path('menu.png'))) self.search_completion_model = QStringListModel() completer = QCompleter() completer.setModel(self.search_completion_model) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.item_delegate = QStyledItemDelegate() completer.popup().setItemDelegate(self.item_delegate) completer.popup().setStyleSheet(""" QListView { background-color: #404040; } QListView::item { color: #D0D0D0; padding-top: 5px; padding-bottom: 5px; } QListView::item:hover { background-color: #707070; } """) self.top_search_bar.setCompleter(completer) # Toggle debug if developer mode is enabled self.window().left_menu_button_debug.setHidden(not get_gui_setting( self.gui_settings, "debug", False, is_bool=True)) # Start Tribler self.core_manager.start(core_args=core_args, core_env=core_env) self.core_manager.events_manager.received_search_result_channel.connect( self.search_results_page.received_search_result_channel) self.core_manager.events_manager.received_search_result_torrent.connect( self.search_results_page.received_search_result_torrent) self.core_manager.events_manager.torrent_finished.connect( self.on_torrent_finished) self.core_manager.events_manager.new_version_available.connect( self.on_new_version_available) self.core_manager.events_manager.tribler_started.connect( self.on_tribler_started) self.core_manager.events_manager.events_started.connect( self.on_events_started) self.core_manager.events_manager.low_storage_signal.connect( self.on_low_storage) self.core_manager.events_manager.credit_mining_signal.connect( self.on_credit_mining_error) # Install signal handler for ctrl+c events def sigint_handler(*_): self.close_tribler() signal.signal(signal.SIGINT, sigint_handler) self.installEventFilter(self.video_player_page) # Resize the window according to the settings center = QApplication.desktop().availableGeometry(self).center() pos = self.gui_settings.value( "pos", QPoint(center.x() - self.width() * 0.5, center.y() - self.height() * 0.5)) size = self.gui_settings.value("size", self.size()) self.move(pos) self.resize(size) self.show() def update_tray_icon(self, use_monochrome_icon): if not QSystemTrayIcon.isSystemTrayAvailable(): return if use_monochrome_icon: self.tray_icon.setIcon( QIcon(QPixmap(get_image_path('monochrome_tribler.png')))) else: self.tray_icon.setIcon( QIcon(QPixmap(get_image_path('tribler.png')))) self.tray_icon.show() def delete_tray_icon(self): if self.tray_icon: try: self.tray_icon.deleteLater() except RuntimeError: # The tray icon might have already been removed when unloading Qt. # This is due to the C code actually being asynchronous. logging.debug( "Tray icon already removed, no further deletion necessary." ) self.tray_icon = None def on_low_storage(self): """ Dealing with low storage space available. First stop the downloads and the core manager and ask user to user to make free space. :return: """ self.downloads_page.stop_loading_downloads() self.core_manager.stop(False) close_dialog = ConfirmationDialog( self.window(), "<b>CRITICAL ERROR</b>", "You are running low on disk space (<100MB). Please make sure to have " "sufficient free space available and restart Tribler again.", [("Close Tribler", BUTTON_TYPE_NORMAL)]) close_dialog.button_clicked.connect(lambda _: self.close_tribler()) close_dialog.show() def on_torrent_finished(self, torrent_info): self.tray_show_message( "Download finished", "Download of %s has finished." % torrent_info["name"]) def show_loading_screen(self): self.top_menu_button.setHidden(True) self.left_menu.setHidden(True) self.token_balance_widget.setHidden(True) self.settings_button.setHidden(True) self.add_torrent_button.setHidden(True) self.top_search_bar.setHidden(True) self.stackedWidget.setCurrentIndex(PAGE_LOADING) def tray_set_tooltip(self, message): """ Set a tooltip message for the tray icon, if possible. :param message: the message to display on hover """ if self.tray_icon: try: self.tray_icon.setToolTip(message) except RuntimeError as e: logging.error("Failed to set tray tooltip: %s", str(e)) def tray_show_message(self, title, message): """ Show a message at the tray icon, if possible. :param title: the title of the message :param message: the message to display """ if self.tray_icon: try: self.tray_icon.showMessage(title, message) except RuntimeError as e: logging.error("Failed to set tray message: %s", str(e)) def on_tribler_started(self): self.tribler_started = True self.top_menu_button.setHidden(False) self.left_menu.setHidden(False) self.token_balance_widget.setHidden(False) self.settings_button.setHidden(False) self.add_torrent_button.setHidden(False) self.top_search_bar.setHidden(False) # fetch the settings, needed for the video player port self.request_mgr = TriblerRequestManager() self.fetch_settings() self.downloads_page.start_loading_downloads() self.home_page.load_popular_torrents() if not self.gui_settings.value( "first_discover", False) and not self.core_manager.use_existing_core: self.window().gui_settings.setValue("first_discover", True) self.discovering_page.is_discovering = True self.stackedWidget.setCurrentIndex(PAGE_DISCOVERING) else: self.clicked_menu_button_home() self.setAcceptDrops(True) def on_events_started(self, json_dict): self.setWindowTitle("Tribler %s" % json_dict["version"]) def show_status_bar(self, message): self.tribler_status_bar_label.setText(message) self.tribler_status_bar.show() def hide_status_bar(self): self.tribler_status_bar.hide() def process_uri_request(self): """ Process a URI request if we have one in the queue. """ if len(self.pending_uri_requests) == 0: return uri = self.pending_uri_requests.pop() if uri.startswith('file') or uri.startswith('magnet'): self.start_download_from_uri(uri) def perform_start_download_request(self, uri, anon_download, safe_seeding, destination, selected_files, total_files=0, callback=None): # Check if destination directory is writable is_writable, error = is_dir_writable(destination) if not is_writable: gui_error_message = "Insufficient write permissions to <i>%s</i> directory. Please add proper " \ "write permissions on the directory and add the torrent again. %s" \ % (destination, error) ConfirmationDialog.show_message(self.window(), "Download error <i>%s</i>" % uri, gui_error_message, "OK") return selected_files_uri = "" if len(selected_files) != total_files: # Not all files included selected_files_uri = u'&' + u''.join( u"selected_files[]=%s&" % quote_plus_unicode(filename) for filename in selected_files)[:-1] anon_hops = int(self.tribler_settings['download_defaults'] ['number_hops']) if anon_download else 0 safe_seeding = 1 if safe_seeding else 0 post_data = "uri=%s&anon_hops=%d&safe_seeding=%d&destination=%s%s" % ( quote_plus_unicode(uri), anon_hops, safe_seeding, destination, selected_files_uri) post_data = post_data.encode( 'utf-8') # We need to send bytes in the request, not unicode request_mgr = TriblerRequestManager() request_mgr.perform_request( "downloads", callback if callback else self.on_download_added, method='PUT', data=post_data) # Save the download location to the GUI settings current_settings = get_gui_setting(self.gui_settings, "recent_download_locations", "") recent_locations = current_settings.split( ",") if len(current_settings) > 0 else [] if isinstance(destination, unicode): destination = destination.encode('utf-8') encoded_destination = destination.encode('hex') if encoded_destination in recent_locations: recent_locations.remove(encoded_destination) recent_locations.insert(0, encoded_destination) if len(recent_locations) > 5: recent_locations = recent_locations[:5] self.gui_settings.setValue("recent_download_locations", ','.join(recent_locations)) def on_new_version_available(self, version): if version == str(self.gui_settings.value('last_reported_version')): return self.new_version_dialog = ConfirmationDialog( self, "New version available", "Version %s of Tribler is available.Do you want to visit the " "website to download the newest version?" % version, [('IGNORE', BUTTON_TYPE_NORMAL), ('LATER', BUTTON_TYPE_NORMAL), ('OK', BUTTON_TYPE_NORMAL)]) self.new_version_dialog.button_clicked.connect( lambda action: self.on_new_version_dialog_done(version, action)) self.new_version_dialog.show() def on_new_version_dialog_done(self, version, action): if action == 0: # ignore self.gui_settings.setValue("last_reported_version", version) elif action == 2: # ok import webbrowser webbrowser.open("https://tribler.org") self.new_version_dialog.close_dialog() self.new_version_dialog = None def on_search_text_change(self, text): self.search_suggestion_mgr = TriblerRequestManager() self.search_suggestion_mgr.perform_request( "search/completions?q=%s" % text, self.on_received_search_completions) def on_received_search_completions(self, completions): if completions is None: return self.received_search_completions.emit(completions) self.search_completion_model.setStringList(completions["completions"]) def fetch_settings(self): self.request_mgr = TriblerRequestManager() self.request_mgr.perform_request("settings", self.received_settings, capture_errors=False) def received_settings(self, settings): if not settings: return # If we cannot receive the settings, stop Tribler with an option to send the crash report. if 'error' in settings: raise RuntimeError( TriblerRequestManager.get_message_from_error(settings)) self.tribler_settings = settings['settings'] # Set the video server port self.video_player_page.video_player_port = settings["ports"][ "video_server~port"] # Disable various components based on the settings if not self.tribler_settings['search_community']['enabled']: self.window().top_search_bar.setHidden(True) if not self.tribler_settings['video_server']['enabled']: self.left_menu_button_video_player.setHidden(True) self.downloads_creditmining_button.setHidden( not self.tribler_settings["credit_mining"]["enabled"]) self.downloads_all_button.click() # process pending file requests (i.e. someone clicked a torrent file when Tribler was closed) # We do this after receiving the settings so we have the default download location. self.process_uri_request() # Set token balance refresh timer and load the token balance self.token_refresh_timer = QTimer() self.token_refresh_timer.timeout.connect(self.load_token_balance) self.token_refresh_timer.start(60000) self.load_token_balance() def on_top_search_button_click(self): current_ts = time.time() current_search_query = self.top_search_bar.text() if self.last_search_query and self.last_search_time \ and self.last_search_query == self.top_search_bar.text() \ and current_ts - self.last_search_time < 1: logging.info( "Same search query already sent within 500ms so dropping this one" ) return self.left_menu_button_search.setChecked(True) self.has_search_results = True self.clicked_menu_button_search() self.search_results_page.perform_search(current_search_query) self.search_request_mgr = TriblerRequestManager() self.search_request_mgr.perform_request( "search?q=%s" % current_search_query, None) self.last_search_query = current_search_query self.last_search_time = current_ts def on_settings_button_click(self): self.deselect_all_menu_buttons() self.stackedWidget.setCurrentIndex(PAGE_SETTINGS) self.settings_page.load_settings() self.navigation_stack = [] self.hide_left_menu_playlist() def on_token_balance_click(self, _): self.raise_window() self.deselect_all_menu_buttons() self.stackedWidget.setCurrentIndex(PAGE_TRUST) self.trust_page.load_trust_statistics() self.navigation_stack = [] self.hide_left_menu_playlist() def load_token_balance(self): self.request_mgr = TriblerRequestManager() self.request_mgr.perform_request("trustchain/statistics", self.received_token_balance, capture_errors=False) def received_token_balance(self, statistics): if not statistics or "statistics" not in statistics: return statistics = statistics["statistics"] if 'latest_block' in statistics: balance = (statistics["latest_block"]["transaction"]["total_up"] - statistics["latest_block"]["transaction"]["total_down"]) self.set_token_balance(balance) else: self.token_balance_label.setText("0 MB") def set_token_balance(self, balance): if abs(balance) > 1024**4: # Balance is over a TB balance /= 1024.0**4 self.token_balance_label.setText("%.1f TB" % balance) elif abs(balance) > 1024**3: # Balance is over a GB balance /= 1024.0**3 self.token_balance_label.setText("%.1f GB" % balance) else: balance /= 1024.0**2 self.token_balance_label.setText("%d MB" % balance) def raise_window(self): self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) self.raise_() self.activateWindow() def create_add_torrent_menu(self): """ Create a menu to add new torrents. Shows when users click on the tray icon or the big plus button. """ menu = TriblerActionMenu(self) browse_files_action = QAction('Import torrent from file', self) browse_directory_action = QAction('Import torrent(s) from directory', self) add_url_action = QAction('Import torrent from magnet/URL', self) browse_files_action.triggered.connect(self.on_add_torrent_browse_file) browse_directory_action.triggered.connect( self.on_add_torrent_browse_dir) add_url_action.triggered.connect(self.on_add_torrent_from_url) menu.addAction(browse_files_action) menu.addAction(browse_directory_action) menu.addAction(add_url_action) return menu def on_add_torrent_button_click(self, pos): self.create_add_torrent_menu().exec_( self.mapToGlobal(self.add_torrent_button.pos())) def on_add_torrent_browse_file(self): filenames = QFileDialog.getOpenFileNames( self, "Please select the .torrent file", QDir.homePath(), "Torrent files (*.torrent)") if len(filenames[0]) > 0: [ self.pending_uri_requests.append(u"file:%s" % filename) for filename in filenames[0] ] self.process_uri_request() def start_download_from_uri(self, uri): self.download_uri = uri if get_gui_setting(self.gui_settings, "ask_download_settings", True, is_bool=True): # If tribler settings is not available, fetch the settings and inform the user to try again. if not self.tribler_settings: self.fetch_settings() ConfirmationDialog.show_error( self, "Download Error", "Tribler settings is not available yet. " "Fetching it now. Please try again later.") return # Clear any previous dialog if exists if self.dialog: self.dialog.close_dialog() self.dialog = None self.dialog = StartDownloadDialog(self, self.download_uri) self.dialog.button_clicked.connect(self.on_start_download_action) self.dialog.show() self.start_download_dialog_active = True else: # In the unlikely scenario that tribler settings are not available yet, try to fetch settings again and # add the download uri back to self.pending_uri_requests to process again. if not self.tribler_settings: self.fetch_settings() if self.download_uri not in self.pending_uri_requests: self.pending_uri_requests.append(self.download_uri) return self.window().perform_start_download_request( self.download_uri, self.window().tribler_settings['download_defaults'] ['anonymity_enabled'], self.window().tribler_settings['download_defaults'] ['safeseeding_enabled'], self.tribler_settings['download_defaults']['saveas'], [], 0) self.process_uri_request() def on_start_download_action(self, action): if action == 1: if self.dialog and self.dialog.dialog_widget: self.window().perform_start_download_request( self.download_uri, self.dialog.dialog_widget.anon_download_checkbox.isChecked( ), self.dialog.dialog_widget.safe_seed_checkbox.isChecked(), self.dialog.dialog_widget.destination_input.currentText(), self.dialog.get_selected_files(), self.dialog.dialog_widget.files_list_view. topLevelItemCount()) else: ConfirmationDialog.show_error( self, "Tribler UI Error", "Something went wrong. Please try again.") logging.exception( "Error while trying to download. Either dialog or dialog.dialog_widget is None" ) self.dialog.request_mgr.cancel_request( ) # To abort the torrent info request self.dialog.close_dialog() self.dialog = None self.start_download_dialog_active = False if action == 0: # We do this after removing the dialog since process_uri_request is blocking self.process_uri_request() def on_add_torrent_browse_dir(self): chosen_dir = QFileDialog.getExistingDirectory( self, "Please select the directory containing the .torrent files", QDir.homePath(), QFileDialog.ShowDirsOnly) if len(chosen_dir) != 0: self.selected_torrent_files = [ torrent_file for torrent_file in glob.glob(chosen_dir + "/*.torrent") ] self.dialog = ConfirmationDialog( self, "Add torrents from directory", "Are you sure you want to add %d torrents to Tribler?" % len(self.selected_torrent_files), [('ADD', BUTTON_TYPE_NORMAL), ('CANCEL', BUTTON_TYPE_CONFIRM)]) self.dialog.button_clicked.connect( self.on_confirm_add_directory_dialog) self.dialog.show() def on_confirm_add_directory_dialog(self, action): if action == 0: for torrent_file in self.selected_torrent_files: escaped_uri = u"file:%s" % pathname2url(torrent_file) self.perform_start_download_request( escaped_uri, self.window().tribler_settings['download_defaults'] ['anonymity_enabled'], self.window().tribler_settings['download_defaults'] ['safeseeding_enabled'], self.tribler_settings['download_defaults']['saveas'], [], 0) if self.dialog: self.dialog.close_dialog() self.dialog = None def on_add_torrent_from_url(self): # Make sure that the window is visible (this action might be triggered from the tray icon) self.raise_window() if self.video_player_page.isVisible(): # If we're adding a torrent from the video player page, go to the home page. # This is necessary since VLC takes the screen and the popup becomes invisible. self.clicked_menu_button_home() self.dialog = ConfirmationDialog( self, "Add torrent from URL/magnet link", "Please enter the URL/magnet link in the field below:", [('ADD', BUTTON_TYPE_NORMAL), ('CANCEL', BUTTON_TYPE_CONFIRM)], show_input=True) self.dialog.dialog_widget.dialog_input.setPlaceholderText( 'URL/magnet link') self.dialog.dialog_widget.dialog_input.setFocus() self.dialog.button_clicked.connect( self.on_torrent_from_url_dialog_done) self.dialog.show() def on_torrent_from_url_dialog_done(self, action): if self.dialog and self.dialog.dialog_widget: uri = self.dialog.dialog_widget.dialog_input.text() # Remove first dialog self.dialog.close_dialog() self.dialog = None if action == 0: self.start_download_from_uri(uri) def on_download_added(self, result): if not result: return if len(self.pending_uri_requests ) == 0: # Otherwise, we first process the remaining requests. self.window().left_menu_button_downloads.click() else: self.process_uri_request() def on_top_menu_button_click(self): if self.left_menu.isHidden(): self.left_menu.show() else: self.left_menu.hide() def deselect_all_menu_buttons(self, except_select=None): for button in self.menu_buttons: if button == except_select: button.setEnabled(False) continue button.setEnabled(True) if button == self.left_menu_button_search and not self.has_search_results: button.setEnabled(False) button.setChecked(False) def clicked_menu_button_home(self): self.deselect_all_menu_buttons(self.left_menu_button_home) self.stackedWidget.setCurrentIndex(PAGE_HOME) self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_search(self): self.deselect_all_menu_buttons(self.left_menu_button_search) self.stackedWidget.setCurrentIndex(PAGE_SEARCH_RESULTS) self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_discovered(self): self.deselect_all_menu_buttons(self.left_menu_button_discovered) self.stackedWidget.setCurrentIndex(PAGE_DISCOVERED) self.discovered_page.load_discovered_channels() self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_my_channel(self): self.deselect_all_menu_buttons(self.left_menu_button_my_channel) self.stackedWidget.setCurrentIndex(PAGE_EDIT_CHANNEL) self.edit_channel_page.load_my_channel_overview() self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_video_player(self): self.deselect_all_menu_buttons(self.left_menu_button_video_player) self.stackedWidget.setCurrentIndex(PAGE_VIDEO_PLAYER) self.navigation_stack = [] self.show_left_menu_playlist() def clicked_menu_button_downloads(self): self.raise_window() self.left_menu_button_downloads.setChecked(True) self.deselect_all_menu_buttons(self.left_menu_button_downloads) self.stackedWidget.setCurrentIndex(PAGE_DOWNLOADS) self.navigation_stack = [] self.hide_left_menu_playlist() def clicked_menu_button_debug(self): if not self.debug_window: self.debug_window = DebugWindow( self.tribler_settings, self.core_manager.events_manager.tribler_version) self.debug_window.show() def clicked_menu_button_subscriptions(self): self.deselect_all_menu_buttons(self.left_menu_button_subscriptions) self.subscribed_channels_page.load_subscribed_channels() self.stackedWidget.setCurrentIndex(PAGE_SUBSCRIBED_CHANNELS) self.navigation_stack = [] self.hide_left_menu_playlist() def hide_left_menu_playlist(self): self.left_menu_seperator.setHidden(True) self.left_menu_playlist_label.setHidden(True) self.left_menu_playlist.setHidden(True) def show_left_menu_playlist(self): self.left_menu_seperator.setHidden(False) self.left_menu_playlist_label.setHidden(False) self.left_menu_playlist.setHidden(False) def on_channel_item_click(self, channel_list_item): list_widget = channel_list_item.listWidget() from TriblerGUI.widgets.channel_list_item import ChannelListItem if isinstance(list_widget.itemWidget(channel_list_item), ChannelListItem): channel_info = channel_list_item.data(Qt.UserRole) self.channel_page.initialize_with_channel(channel_info) self.navigation_stack.append(self.stackedWidget.currentIndex()) self.stackedWidget.setCurrentIndex(PAGE_CHANNEL_DETAILS) def on_playlist_item_click(self, playlist_list_item): list_widget = playlist_list_item.listWidget() from TriblerGUI.widgets.playlist_list_item import PlaylistListItem if isinstance(list_widget.itemWidget(playlist_list_item), PlaylistListItem): playlist_info = playlist_list_item.data(Qt.UserRole) self.playlist_page.initialize_with_playlist(playlist_info) self.navigation_stack.append(self.stackedWidget.currentIndex()) self.stackedWidget.setCurrentIndex(PAGE_PLAYLIST_DETAILS) def on_page_back_clicked(self): try: prev_page = self.navigation_stack.pop() self.stackedWidget.setCurrentIndex(prev_page) if prev_page == PAGE_SEARCH_RESULTS: self.stackedWidget.widget( prev_page).load_search_results_in_list() if prev_page == PAGE_SUBSCRIBED_CHANNELS: self.stackedWidget.widget(prev_page).load_subscribed_channels() if prev_page == PAGE_DISCOVERED: self.stackedWidget.widget(prev_page).load_discovered_channels() except IndexError: logging.exception("Unknown page found in stack") def on_credit_mining_error(self, error): ConfirmationDialog.show_error(self, "Credit Mining Error", error[u'message']) def on_edit_channel_clicked(self): self.stackedWidget.setCurrentIndex(PAGE_EDIT_CHANNEL) self.navigation_stack = [] self.channel_page.on_edit_channel_clicked() def resizeEvent(self, _): # Resize home page cells cell_width = self.home_page_table_view.width( ) / 3 - 3 # We have some padding to the right cell_height = cell_width / 2 + 60 for i in range(0, 3): self.home_page_table_view.setColumnWidth(i, cell_width) self.home_page_table_view.setRowHeight(i, cell_height) self.resize_event.emit() def exit_full_screen(self): self.top_bar.show() self.left_menu.show() self.video_player_page.is_full_screen = False self.showNormal() def close_tribler(self): if not self.core_manager.shutting_down: def show_force_shutdown(): self.loading_text_label.setText( "Tribler is taking longer than expected to shut down. You can force " "Tribler to shutdown by pressing the button below. This might lead " "to data loss.") self.window().force_shutdown_btn.show() self.delete_tray_icon() self.show_loading_screen() self.hide_status_bar() self.loading_text_label.setText("Shutting down...") self.shutdown_timer = QTimer() self.shutdown_timer.timeout.connect(show_force_shutdown) self.shutdown_timer.start(SHUTDOWN_WAITING_PERIOD) self.gui_settings.setValue("pos", self.pos()) self.gui_settings.setValue("size", self.size()) if self.core_manager.use_existing_core: # Don't close the core that we are using QApplication.quit() self.core_manager.stop() self.core_manager.shutting_down = True self.downloads_page.stop_loading_downloads() request_queue.clear() # Stop the token balance timer if self.token_refresh_timer: self.token_refresh_timer.stop() def closeEvent(self, close_event): self.close_tribler() close_event.ignore() def keyReleaseEvent(self, event): if event.key() == Qt.Key_Escape: self.escape_pressed.emit() if self.isFullScreen(): self.exit_full_screen() def dragEnterEvent(self, e): file_urls = [_qurl_to_path(url) for url in e.mimeData().urls() ] if e.mimeData().hasUrls() else [] if any(os.path.isfile(filename) for filename in file_urls): e.accept() else: e.ignore() def dropEvent(self, e): file_urls = ([(_qurl_to_path(url), url.toString()) for url in e.mimeData().urls()] if e.mimeData().hasUrls() else []) for filename, fileurl in file_urls: if os.path.isfile(filename): self.start_download_from_uri(fileurl) e.accept() def clicked_force_shutdown(self): process_checker = ProcessChecker() if process_checker.already_running: core_pid = process_checker.get_pid_from_lock_file() os.kill(int(core_pid), 9) # Stop the Qt application QApplication.quit()
def __init__(self, core_args=None, core_env=None, api_port=None): QMainWindow.__init__(self) QCoreApplication.setOrganizationDomain("nl") QCoreApplication.setOrganizationName("TUDelft") QCoreApplication.setApplicationName("Tribler") QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) self.gui_settings = QSettings() api_port = api_port or int( get_gui_setting(self.gui_settings, "api_port", DEFAULT_API_PORT)) dispatcher.update_worker_settings(port=api_port) self.navigation_stack = [] self.tribler_started = False self.tribler_settings = None self.debug_window = None self.core_manager = CoreManager(api_port) self.pending_requests = {} self.pending_uri_requests = [] self.download_uri = None self.dialog = None self.new_version_dialog = None self.start_download_dialog_active = False self.request_mgr = None self.search_request_mgr = None self.search_suggestion_mgr = None self.selected_torrent_files = [] self.vlc_available = True self.has_search_results = False self.last_search_query = None self.last_search_time = None self.start_time = time.time() self.exception_handler_called = False self.token_refresh_timer = None sys.excepthook = self.on_exception uic.loadUi(get_ui_file_path('mainwindow.ui'), self) TriblerRequestManager.window = self self.tribler_status_bar.hide() # Load dynamic widgets uic.loadUi(get_ui_file_path('torrent_channel_list_container.ui'), self.channel_page_container) self.channel_torrents_list = self.channel_page_container.items_list self.channel_torrents_detail_widget = self.channel_page_container.details_tab_widget self.channel_torrents_detail_widget.initialize_details_widget() self.channel_torrents_list.itemSelectionChanged.connect( self.channel_page.clicked_item) uic.loadUi(get_ui_file_path('torrent_channel_list_container.ui'), self.search_page_container) self.search_results_list = self.search_page_container.items_list self.search_torrents_detail_widget = self.search_page_container.details_tab_widget self.search_torrents_detail_widget.initialize_details_widget() self.search_results_list.itemClicked.connect( self.on_channel_item_click) self.search_results_list.itemSelectionChanged.connect( self.search_results_page.clicked_item) self.token_balance_widget.mouseReleaseEvent = self.on_token_balance_click def on_state_update(new_state): self.loading_text_label.setText(new_state) self.core_manager.core_state_update.connect(on_state_update) self.magnet_handler = MagnetHandler(self.window) QDesktopServices.setUrlHandler("magnet", self.magnet_handler, "on_open_magnet_link") self.debug_pane_shortcut = QShortcut(QKeySequence("Ctrl+d"), self) self.debug_pane_shortcut.activated.connect( self.clicked_menu_button_debug) # Remove the focus rect on OS X for widget in self.findChildren(QLineEdit) + self.findChildren( QListWidget) + self.findChildren(QTreeWidget): widget.setAttribute(Qt.WA_MacShowFocusRect, 0) self.menu_buttons = [ self.left_menu_button_home, self.left_menu_button_search, self.left_menu_button_my_channel, self.left_menu_button_subscriptions, self.left_menu_button_video_player, self.left_menu_button_downloads, self.left_menu_button_discovered ] self.video_player_page.initialize_player() self.search_results_page.initialize_search_results_page() self.settings_page.initialize_settings_page() self.subscribed_channels_page.initialize() self.edit_channel_page.initialize_edit_channel_page() self.downloads_page.initialize_downloads_page() self.home_page.initialize_home_page() self.loading_page.initialize_loading_page() self.discovering_page.initialize_discovering_page() self.discovered_page.initialize_discovered_page() self.trust_page.initialize_trust_page() self.stackedWidget.setCurrentIndex(PAGE_LOADING) # Create the system tray icon if QSystemTrayIcon.isSystemTrayAvailable(): self.tray_icon = QSystemTrayIcon() use_monochrome_icon = get_gui_setting(self.gui_settings, "use_monochrome_icon", False, is_bool=True) self.update_tray_icon(use_monochrome_icon) # Create the tray icon menu menu = self.create_add_torrent_menu() show_downloads_action = QAction('Show downloads', self) show_downloads_action.triggered.connect( self.clicked_menu_button_downloads) token_balance_action = QAction('Show token balance', self) token_balance_action.triggered.connect( lambda: self.on_token_balance_click(None)) quit_action = QAction('Quit Tribler', self) quit_action.triggered.connect(self.close_tribler) menu.addSeparator() menu.addAction(show_downloads_action) menu.addAction(token_balance_action) menu.addSeparator() menu.addAction(quit_action) self.tray_icon.setContextMenu(menu) else: self.tray_icon = None self.hide_left_menu_playlist() self.left_menu_button_debug.setHidden(True) self.top_menu_button.setHidden(True) self.left_menu.setHidden(True) self.token_balance_widget.setHidden(True) self.settings_button.setHidden(True) self.add_torrent_button.setHidden(True) self.top_search_bar.setHidden(True) # Set various icons self.top_menu_button.setIcon(QIcon(get_image_path('menu.png'))) self.search_completion_model = QStringListModel() completer = QCompleter() completer.setModel(self.search_completion_model) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.item_delegate = QStyledItemDelegate() completer.popup().setItemDelegate(self.item_delegate) completer.popup().setStyleSheet(""" QListView { background-color: #404040; } QListView::item { color: #D0D0D0; padding-top: 5px; padding-bottom: 5px; } QListView::item:hover { background-color: #707070; } """) self.top_search_bar.setCompleter(completer) # Toggle debug if developer mode is enabled self.window().left_menu_button_debug.setHidden(not get_gui_setting( self.gui_settings, "debug", False, is_bool=True)) # Start Tribler self.core_manager.start(core_args=core_args, core_env=core_env) self.core_manager.events_manager.received_search_result_channel.connect( self.search_results_page.received_search_result_channel) self.core_manager.events_manager.received_search_result_torrent.connect( self.search_results_page.received_search_result_torrent) self.core_manager.events_manager.torrent_finished.connect( self.on_torrent_finished) self.core_manager.events_manager.new_version_available.connect( self.on_new_version_available) self.core_manager.events_manager.tribler_started.connect( self.on_tribler_started) self.core_manager.events_manager.events_started.connect( self.on_events_started) self.core_manager.events_manager.low_storage_signal.connect( self.on_low_storage) self.core_manager.events_manager.credit_mining_signal.connect( self.on_credit_mining_error) # Install signal handler for ctrl+c events def sigint_handler(*_): self.close_tribler() signal.signal(signal.SIGINT, sigint_handler) self.installEventFilter(self.video_player_page) # Resize the window according to the settings center = QApplication.desktop().availableGeometry(self).center() pos = self.gui_settings.value( "pos", QPoint(center.x() - self.width() * 0.5, center.y() - self.height() * 0.5)) size = self.gui_settings.value("size", self.size()) self.move(pos) self.resize(size) self.show()
class QmyWidget(QtWidgets.QWidget): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_Widget() self.ui.setupUi(self) self.__provinces = [ "北京", "上海", "天津", "河北", "山东", "四川", "重庆", "广东", "河南" ] self.model = QStringListModel(self) self.model.setStringList(self.__provinces) self.ui.qListView.setModel(self.model) self.ui.qListView.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked) @pyqtSlot() def on_qPushButton1_clicked(self): # 恢复列表 self.model.setStringList(self.__provinces) @pyqtSlot() def on_qPushButton2_clicked(self): # 添加项 lastRow = self.model.rowCount() self.model.insertRow(lastRow) index = self.model.index(lastRow, 0) self.model.setData(index, "new item", Qt.DisplayRole) self.ui.qListView.setCurrentIndex(index) @pyqtSlot() def on_qPushButton3_clicked(self): # 插入项 index = self.ui.qListView.currentIndex() self.model.insertRow(index.row()) self.model.setData(index, "inserted item", Qt.DisplayRole) self.ui.qListView.setCurrentIndex(index) @pyqtSlot() def on_qPushButton4_clicked(self): # 删除当前项 index = self.ui.qListView.currentIndex() self.model.removeRow(index.row()) @pyqtSlot() def on_qPushButton5_clicked(self): # 清空列表 count = self.model.rowCount() self.model.removeRows(0, count) @pyqtSlot() def on_qPushButton6_clicked(self): # 清空文本 self.ui.qPlainTextEdit.clear() @pyqtSlot() def on_qPushButton7_clicked(self): # 显示数据模型的StringList strList = self.model.stringList() self.ui.qPlainTextEdit.clear() for strLine in strList: self.ui.qPlainTextEdit.appendPlainText(strLine) def on_qListView_clicked(self, index): self.ui.qLabel.setText("当前项index:row=%d, column=%d" % (index.row(), index.column()))
def re_map_list(self, ui, type): tuple_lst = self.dao.get_map_list(type) lst = map(lambda t: str(t[0]), tuple_lst) slm = QStringListModel() slm.setStringList(lst) ui.lst_sub_map.setModel(slm)
class DicomBrowser(QtGui.QMainWindow, Ui_DicomBrowserWin): ''' The window class for the app which implements the UI functionality and the directory loading thread. It inherits from the type loaded from the .ui file in the resources. ''' statusSignal = QtCore.pyqtSignal( str, int, int) # signal for updating the status bar asynchronously updateSignal = QtCore.pyqtSignal( ) # signal for updating the source list and series table def __init__(self, args, parent=None): QtGui.QMainWindow.__init__(self, parent) self.srclist = [] # list of source directories self.imageIndex = 0 # index of selected image self.seriesMap = OrderedDict( ) # maps series table row tuples to DicomSeries object it was generated from self.seriesColumns = list(seriesListColumns) # keywords for columns self.selectedRow = -1 # selected series row self.lastDir = '.' # last loaded directory root self.filterRegex = '' # regular expression to filter tags by # create the directory queue and loading thread objects self.srcQueue = Queue() # queue of directories to load self.loadDirThread = threading.Thread(target=self._loadSourceThread) self.loadDirThread.daemon = True # clean shutdown possible with daemon threads self.loadDirThread.start( ) # start the thread now, it will wait until something is put on self.srcQueue # setup ui self.setupUi(self) # create UI elements based on the loaded .ui file self.setWindowTitle('DicomBrowser v%s (FOR RESEARCH ONLY)' % (__version__)) self.setStatus('') # connect signals self.importButton.clicked.connect(self._openDirDialog) self.statusSignal.connect(self.setStatus) self.updateSignal.connect(self._updateSeriesTable) self.filterLine.textChanged.connect(self._setFilterString) self.imageSlider.valueChanged.connect(self.setSeriesImage) self.seriesView.clicked.connect(self._seriesTableClicked) # setup the list and table models self.srcmodel = QStringListModel() self.seriesmodel = SeriesTableModel(self.seriesColumns) self.seriesmodel.layoutChanged.connect(self._seriesTableResize) self.tagmodel = QtGui.QStandardItemModel() # assign models to views self.sourceListView.setModel(self.srcmodel) self.seriesView.setModel(self.seriesmodel) self.tagView.setModel(self.tagmodel) # create the pyqtgraph object for viewing images self.imageview = pg.ImageView() layout = QtGui.QGridLayout(self.view2DGroup) layout.addWidget(self.imageview) # load the empty image placeholder into a ndarray qimg = QtGui.QImage(':/icons/noimage.png') bytedata = qimg.constBits().asstring(qimg.width() * qimg.height()) self.noimg = np.ndarray((qimg.width(), qimg.height()), dtype=np.ubyte, buffer=bytedata) # add the directories passed as arguments to the directory queue to start loading for i in args[1:]: if os.path.exists(i): self.addSource(i) def _setClipboard(): '''Set the clipboard to contain fuller tag data when CTRL+C is applied to a tag line in the tree.''' def printChildren(child, level, out): for r in range(child.rowCount()): print('', file=out) for c in range(child.columnCount()): cc = child.child(r, c) if cc is not None: print(' ' * level, cc.text(), file=out, end='') if cc.hasChildren(): printChildren(cc, level + 1, out) out = StringIO() items = [ self.tagmodel.itemFromIndex(i) for i in self.tagView.selectedIndexes() ] print(' '.join(i.data() or i.text() for i in items if i), end='', file=out) if items[0].hasChildren(): printChildren(items[0], 1, out) QtGui.QApplication.clipboard().setText(out.getvalue()) # override CTRL+C in the tag tree to copy a fuller set of tag data to the clipboard QtGui.QShortcut(QtGui.QKeySequence('Ctrl+c'), self.tagView).activated.connect(_setClipboard) def keyPressEvent(self, e): '''Close the window if escape is pressed, otherwise do as inherited.''' if e.key() == Qt.Key_Escape: self.close() else: QtGui.QMainWindow.keyPressEvent(self, e) def show(self): '''Calls the inherited show() method then sets the splitter positions.''' QtGui.QMainWindow.show(self) self.listSplit.moveSplitter(100, 1) self.seriesSplit.moveSplitter(80, 1) self.viewMetaSplitter.moveSplitter(600, 1) def _loadSourceThread(self): ''' This method is run in a daemon thread and continually checks self.srcQueue for a queued directory or zip file to scan for Dicom files. It calls loadDicomDir() for a given directory or loadDicomZip() for a zip file and adds the results the self.srclist member. ''' while True: try: src = self.srcQueue.get(True, 0.5) loader = loadDicomDir if os.path.isdir(src) else loadDicomZip series = loader(src, self.statusSignal.emit) if series and all(len(s.filenames) > 0 for s in series): for s in series: s.filenames, s.loadtags = zip(*sorted( zip(s.filenames, s.loadtags) )) # sort series contents by filename self.srclist.append((src, series)) self.updateSignal.emit() except Empty: pass def _openDirDialog(self): '''Opens the open file dialog to choose a directory to scan for Dicoms.''' rootdir = str( QtGui.QFileDialog.getExistingDirectory(self, 'Choose Source Directory', self.lastDir)) if rootdir: self.addSource(rootdir) def _updateSeriesTable(self): ''' Updates the self.seriesMap object from self.srclist, and refills the self.srcmodel object. This will refresh the list of source directories and the table of available series. ''' self.seriesMap.clear() for _, series in self.srclist: # add each series in each source into self.seriesMap for s in series: entry = s.getTagValues(self.seriesColumns) self.seriesMap[entry] = s self.srcmodel.setStringList([s[0] for s in self.srclist]) self.seriesmodel.updateSeriesTable(self.seriesMap.keys()) self.seriesmodel.layoutChanged.emit() def _seriesTableClicked(self, item): '''Called when a series is clicked on, set the viewed image to be from the clicked series.''' self.selectedRow = item.row() self.setSeriesImage(self.imageSlider.value(), True) def _seriesTableResize(self): '''Resizes self.seriesView columns to contents, setting the last section to stretch.''' self.seriesView.horizontalHeader().setStretchLastSection(False) self.seriesView.resizeColumnsToContents() self.seriesView.horizontalHeader().setStretchLastSection(True) def _setFilterString(self, regex): '''Set the filtering regex to be `regex'.''' self.filterRegex = regex self._fillTagView() def _fillTagView(self): '''Refill the Dicom tag view, this will rejig the columns and (unfortunately) reset column sorting.''' series = self.getSelectedSeries() vpos = self.tagView.verticalScrollBar().value() self.tagmodel.clear() self.tagmodel.setHorizontalHeaderLabels(tagTreeColumns) fillTagModel(self.tagmodel, series.getTagObject(self.imageIndex), self.filterRegex) self.tagView.expandAll() self.tagView.resizeColumnToContents(0) self.tagView.verticalScrollBar().setValue(vpos) def getSelectedSeries(self): '''Returns the DicomSeries object for the selected series, None if no series is selected.''' if 0 <= self.selectedRow < len(self.seriesMap): return self.seriesMap[self.seriesmodel.getRow(self.selectedRow)] def setSeriesImage(self, i, autoRange=False): ''' Set the view image to be that at index `i' of the selected series. The `autoRange' boolean value sets whether the data value range is reset or not when this is done. The tag table is also set to that of image `i'. ''' series = self.getSelectedSeries() if series: maxindex = len(series.filenames) - 1 self.imageIndex = np.clip(i, 0, maxindex) img = series.getPixelData(self.imageIndex) # image matrix interval = 1 # tick interval on the slider # choose a more sensible tick interval if there's a lot of images if maxindex >= 5000: interval = 100 elif maxindex >= 500: interval = 10 if img is None: # if the image is None use the default "no image" object img = self.noimg #elif len(img.shape)==3: # multi-channel or multi-dimensional image, use average of dimensions # img=np.mean(img,axis=2) self.imageview.setImage( img.T, autoRange=autoRange, autoLevels=self.autoLevelsCheck.isChecked()) self._fillTagView() self.imageSlider.setTickInterval(interval) self.imageSlider.setMaximum(maxindex) self.numLabel.setText(str(self.imageIndex)) self.view2DGroup.setTitle( '2D View - ' + os.path.basename(series.filenames[self.imageIndex])) self.view2DGroup.setToolTip(series.filenames[self.imageIndex]) def setStatus(self, msg, progress=0, progressmax=0): ''' Set the status bar with message `msg' with progress set to `progress' out of `progressmax', or hide the status elements if `msg' is empty or None. ''' if not msg: progress = 0 progressmax = 0 self.statusText.setText(msg) self.statusText.setVisible(bool(msg)) self.importButton.setVisible(not bool(msg)) self.statusProgressBar.setVisible(progressmax > 0) self.statusProgressBar.setRange(0, progressmax) self.statusProgressBar.setValue(progress) def removeSource(self, index): '''Remove the source directory at the given index.''' self.srclist.pop(index) self.updateSignal.emit() def addSource(self, rootdir): '''Add the given directory to the queue of directories to load and set the self.lastDir value to its parent.''' self.srcQueue.put(rootdir) self.lastDir = os.path.dirname(rootdir)
def setupUi(self): self.load_ui("apol/mlsrulequery.ui") # set up source/target autocompletion typeattr_completion_list = [str(t) for t in self.policy.types()] typeattr_completion_list.extend(str(a) for a in self.policy.typeattributes()) typeattr_completer_model = QStringListModel(self) typeattr_completer_model.setStringList(sorted(typeattr_completion_list)) self.typeattr_completion = QCompleter() self.typeattr_completion.setModel(typeattr_completer_model) self.source.setCompleter(self.typeattr_completion) self.target.setCompleter(self.typeattr_completion) # setup indications of errors on source/target/default self.errors = set() self.orig_palette = self.source.palette() self.error_palette = self.source.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_source_error() self.clear_target_error() self.clear_default_error() # populate class list self.class_model = SEToolsListModel(self) self.class_model.item_list = sorted(self.policy.classes()) self.tclass.setModel(self.class_model) # set up results self.table_results_model = MLSRuleTableModel(self) self.sort_proxy = QSortFilterProxyModel(self) self.sort_proxy.setSourceModel(self.table_results_model) self.table_results.setModel(self.sort_proxy) self.table_results.sortByColumn(1, Qt.AscendingOrder) # set up processing thread self.thread = QThread() self.worker = QueryResultsUpdater(self.query, self.table_results_model) self.worker.moveToThread(self.thread) self.worker.raw_line.connect(self.raw_results.appendPlainText) self.worker.finished.connect(self.update_complete) self.worker.finished.connect(self.thread.quit) self.thread.started.connect(self.worker.update) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.canceled.connect(self.thread.requestInterruption) self.busy.reset() # update busy dialog from query INFO logs self.handler = LogHandlerToSignal() self.handler.message.connect(self.busy.setLabelText) logging.getLogger("setools.mlsrulequery").addHandler(self.handler) # Ensure settings are consistent with the initial .ui state self.set_source_regex(self.source_regex.isChecked()) self.set_target_regex(self.target_regex.isChecked()) self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) # connect signals self.buttonBox.clicked.connect(self.run) self.clear_ruletypes.clicked.connect(self.clear_all_ruletypes) self.all_ruletypes.clicked.connect(self.set_all_ruletypes) self.source.textEdited.connect(self.clear_source_error) self.source.editingFinished.connect(self.set_source) self.source_regex.toggled.connect(self.set_source_regex) self.target.textEdited.connect(self.clear_target_error) self.target.editingFinished.connect(self.set_target) self.target_regex.toggled.connect(self.set_target_regex) self.tclass.selectionModel().selectionChanged.connect(self.set_tclass) self.invert_class.clicked.connect(self.invert_tclass_selection) self.default_range.textEdited.connect(self.clear_default_error) self.default_range.editingFinished.connect(self.set_default_range)
def setupUi(self): self.load_ui("initsidquery.ui") # set up user autocompletion user_completion_list = [str(u) for u in self.policy.users()] user_completer_model = QStringListModel(self) user_completer_model.setStringList(sorted(user_completion_list)) self.user_completion = QCompleter() self.user_completion.setModel(user_completer_model) self.user.setCompleter(self.user_completion) # set up role autocompletion role_completion_list = [str(r) for r in self.policy.roles()] role_completer_model = QStringListModel(self) role_completer_model.setStringList(sorted(role_completion_list)) self.role_completion = QCompleter() self.role_completion.setModel(role_completer_model) self.role.setCompleter(self.role_completion) # set up type autocompletion type_completion_list = [str(t) for t in self.policy.types()] type_completer_model = QStringListModel(self) type_completer_model.setStringList(sorted(type_completion_list)) self.type_completion = QCompleter() self.type_completion.setModel(type_completer_model) self.type_.setCompleter(self.type_completion) # setup indications of errors on source/target/default self.orig_palette = self.type_.palette() self.error_palette = self.type_.palette() self.error_palette.setColor(QPalette.Base, Qt.red) self.clear_name_error() self.clear_user_error() self.clear_type_error() self.clear_role_error() self.clear_range_error() # set up results self.table_results_model = InitialSIDTableModel(self) self.sort_proxy = QSortFilterProxyModel(self) self.sort_proxy.setSourceModel(self.table_results_model) self.table_results.setModel(self.sort_proxy) self.table_results.sortByColumn(0, Qt.AscendingOrder) # set up processing thread self.thread = QThread() self.worker = QueryResultsUpdater(self.query, self.table_results_model) self.worker.moveToThread(self.thread) self.worker.raw_line.connect(self.raw_results.appendPlainText) self.worker.finished.connect(self.update_complete) self.worker.finished.connect(self.thread.quit) self.thread.started.connect(self.worker.update) # create a "busy, please wait" dialog self.busy = QProgressDialog(self) self.busy.setModal(True) self.busy.setRange(0, 0) self.busy.setMinimumDuration(0) self.busy.canceled.connect(self.thread.requestInterruption) self.busy.reset() # update busy dialog from query INFO logs self.handler = LogHandlerToSignal() self.handler.message.connect(self.busy.setLabelText) logging.getLogger("setools.initsidquery").addHandler(self.handler) # Ensure settings are consistent with the initial .ui state self.set_name_regex(self.name_regex.isChecked()) self.criteria_frame.setHidden(not self.criteria_expander.isChecked()) self.notes.setHidden(not self.notes_expander.isChecked()) # Range criteria is available only if policy is MLS if not self.policy.mls: self.range_criteria.setEnabled(False) self.range_criteria.setToolTip("MLS is disabled in this policy.") self.range_.setToolTip("MLS is disabled in this policy.") self.range_exact.setToolTip("MLS is disabled in this policy.") self.range_overlap.setToolTip("MLS is disabled in this policy.") self.range_subset.setToolTip("MLS is disabled in this policy.") self.range_superset.setToolTip("MLS is disabled in this policy.") # connect signals self.buttonBox.clicked.connect(self.run) self.name.textEdited.connect(self.clear_name_error) self.name.editingFinished.connect(self.set_name) self.name_regex.toggled.connect(self.set_name_regex) self.user.textEdited.connect(self.clear_user_error) self.user.editingFinished.connect(self.set_user) self.user_regex.toggled.connect(self.set_user_regex) self.role.textEdited.connect(self.clear_role_error) self.role.editingFinished.connect(self.set_role) self.role_regex.toggled.connect(self.set_role_regex) self.type_.textEdited.connect(self.clear_type_error) self.type_.editingFinished.connect(self.set_type) self.type_regex.toggled.connect(self.set_type_regex) self.range_.textEdited.connect(self.clear_range_error) self.range_.editingFinished.connect(self.set_range)
def completer_model(self): model = QStringListModel(self) model.setStringList(sorted(k for k, v in COMMANDS.items() if v.visible)) return model
class AppletNoticeWindow(QWidget): def __init__(self, controller): super(AppletNoticeWindow, self).__init__() self.__controller = controller self.__pkglist = [] # setup widgets self.__vbox_up = QVBoxLayout() self.__critical_label = QLabel() self.__critical_label.setWordWrap(True) self.__list_model = QStringListModel() self.__list_view = QListView() self.__list_view.setModel(self.__list_model) self.__vbox_up.addWidget(self.__critical_label) self.__vbox_up.addWidget(self.__list_view) # bottom buttons self.__vbox = QVBoxLayout() self.__vbox.addLayout(self.__vbox_up) self.__button_hbox = QHBoxLayout() self.__close_button = QPushButton(_("Close")) self.__launch_pm_button = QPushButton(_("Launch Application Browser")) self.__button_hbox.addWidget(self.__launch_pm_button) self.__button_hbox.addWidget(self.__close_button) self.__vbox.addLayout(self.__button_hbox) self.setLayout(self.__vbox) # set window settings self.resize(400, 200) self.setWindowTitle(_("Application updates")) self.__close_button.clicked.connect(self.on_close) self.__launch_pm_button.clicked.connect(self.on_pm) def closeEvent(self, event): """ We don't want to kill the window, since the whole app will close otherwise. """ event.ignore() self.on_close() def on_pm(self): self.__controller.launch_package_manager() def on_close(self): self.__controller.trigger_notice_window() def populate(self, pkg_data, critical_txt): self.__list_model.setStringList(pkg_data) self.__critical_label.setText(critical_txt) self.__list_view.update()