def load_clicked(self): """'Load' button. Loads a variable using the current loader. """ varname = self._varname_edit.text() varname = str(varname) if not self._validator.format(varname): self._varname_edit.setFocus() return False if not self._validator.unique(varname): varname = unique_varname(varname, self._vistraildata) self._varname_edit.setText(varname) self._varname_edit.setFocus() return False loader = self._tabs[self._tab_widget.currentIndex()] try: variable = loader.load() # The Loader may provide a provenance node (i.e. to record the # specific parameters it used), else we'll just store that it came # from this loader if variable is not None and variable.provenance is None: variable.provenance = data_provenance.Loader(loader=loader) except Exception, e: _ = translate(LoadVariableDialog) QtGui.QMessageBox.critical( self, _("Error"), "%s\n%s: %s" % (_("Got an exception from the VisTrails package:"), e.__class__.__name__, str(e))) return False
def load_clicked(self): """'Load' button. Loads a variable using the current loader. """ varname = self._varname_edit.text() varname = str(varname) if not self._validator.format(varname): self._varname_edit.setFocus() return False if not self._validator.unique(varname): varname = unique_varname(varname, self._vistraildata) self._varname_edit.setText(varname) self._varname_edit.setFocus() return False loader = self._tabs[self._tab_widget.currentIndex()] try: variable = loader.load() # The Loader may provide a provenance node (i.e. to record the # specific parameters it used), else we'll just store that it came # from this loader if variable is not None and variable.provenance is None: variable.provenance = data_provenance.Loader(loader=loader) except Exception, e: _ = translate(LoadVariableDialog) QtGui.QMessageBox.critical( self, _("Error"), "%s\n%s: %s" % ( _("Got an exception from the VisTrails package:"), e.__class__.__name__, str(e))) return False
def __init__(self, overlay, port_name, pos, variable, typecast=None, append=False): QtGui.QPushButton.__init__(self) self.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.setProperty('assigned', variable is not None and 'yes' or 'no') self._variable = variable if variable is not None: if typecast is not None: self.setText("(%s) %s" % (typecast, variable.name)) else: self.setText(variable.name) self.connect(self, QtCore.SIGNAL('clicked()'), lambda: overlay.remove_parameter(port_name, pos)) elif append: self.setText('+') else: _ = translate(DataParameter) self.setText(_("(not set)"))
def select_file(self, filename): """Change the currently selected file. The list of available loaders will be updated accordingly. """ _ = translate(LoadVariableDialog) # Update self._file_edit self._file_edit.setText(filename) # Update self._loader_list self._loader_list.clear() while self._loader_stack.count() > 0: self._loader_stack.removeWidget(self._loader_stack.widget(0)) if filename != '': for loader in self._file_loaders: if loader.can_load(filename): widget = loader(filename) widget.default_variable_name_observer = ( self.default_variable_name_changed) # The order of these lines is important, because adding an # item to the list emits a signal self._loader_stack.addWidget(widget) self._loader_list.addItem(loader.name, widget) if self._loader_stack.count() == 0: self._loader_stack.addWidget( QtGui.QLabel(_("No loader accepts this file"))) else: self._loader_stack.addWidget(QtGui.QLabel(_("No file selected"))) # Update the widget stack self.update_widget()
def showVariable(self, variable): _ = translate(DataProvenancePanel) if self._viewer is not None: self._viewer.deleteLater() self._viewer = self._scene = None if variable is not None: self._scene = QtGui.QGraphicsScene() self._viewer = ZoomPanGraphicsView(self._scene) self.connect( self._viewer, QtCore.SIGNAL('itemClicked(QGraphicsItem*)'), self._item_clicked) # Create the scene recursively, starting at the bottom layout = ProvenanceSceneLayout(variable._controller) layout.populate(variable.provenance) layout.addToScene(self._scene, sink=variable) else: self._viewer = QtGui.QLabel(_("Select a variable to display its " "provenance")) self._viewer.setWordWrap(True) self._viewer.setAlignment(QtCore.Qt.AlignCenter) self._viewer_container.layout().addWidget(self._viewer) # Reset the table self._item_clicked(None)
def showVariable(self, variable): _ = translate(DataProvenancePanel) if self._viewer is not None: self._viewer.deleteLater() self._viewer = self._scene = None if variable is not None: self._scene = QtGui.QGraphicsScene() self._viewer = ZoomPanGraphicsView(self._scene) self.connect(self._viewer, QtCore.SIGNAL('itemClicked(QGraphicsItem*)'), self._item_clicked) # Create the scene recursively, starting at the bottom layout = ProvenanceSceneLayout(variable._controller) layout.populate(variable.provenance) layout.addToScene(self._scene, sink=variable) else: self._viewer = QtGui.QLabel( _("Select a variable to display its " "provenance")) self._viewer.setWordWrap(True) self._viewer.setAlignment(QtCore.Qt.AlignCenter) self._viewer_container.layout().addWidget(self._viewer) # Reset the table self._item_clicked(None)
def choose_operation(typecasts, source_descriptor, expected_descriptor, parent=None): _ = translate('typecast_dialog') dialog = QtGui.QDialog(parent) dialog.setWindowTitle(_("Type casting")) layout = QtGui.QVBoxLayout() label = QtGui.QLabel( _("A {actual} variable was put in a {expected} port. These are not " "compatible, but the following operations can do the " "conversion:").format( actual="%s (%s)" % (source_descriptor.module.__name__, source_descriptor.identifier), expected="%s (%s)" % (expected_descriptor.module.__name__, expected_descriptor.identifier))) label.setWordWrap(True) layout.addWidget(label) list_widget = CategorizedListWidget() list_widget.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) pm = get_package_manager() for operation in typecasts: package = pm.get_package(operation.package_identifier) item = OperationItem(operation, package.name) list_widget.addItem(item, item.category) layout.addWidget(list_widget) buttons = QtGui.QHBoxLayout() ok = QtGui.QPushButton(_("Typecast", "Accept typecast dialog button")) QtCore.QObject.connect(ok, QtCore.SIGNAL('clicked()'), dialog, QtCore.SLOT('accept()')) buttons.addWidget(ok) cancel = QtGui.QPushButton(_("Cancel", "Reject typecast dialog button")) QtCore.QObject.connect(cancel, QtCore.SIGNAL('clicked()'), dialog, QtCore.SLOT('reject()')) buttons.addWidget(cancel) layout.addLayout(buttons) def check_selection(): selection = list_widget.selectedItems() if selection: item = selection[0] if isinstance(item, OperationItem): ok.setEnabled(True) return ok.setEnabled(False) QtCore.QObject.connect(list_widget, QtCore.SIGNAL('itemSelectionChanged()'), check_selection) check_selection() dialog.setLayout(layout) if dialog.exec_() == QtGui.QDialog.Accepted: return list_widget.selectedItems()[0].operation else: raise CancelExecution
def __init__(self, pairs=None): QtGui.QTableWidget.__init__(self, 0, 2) _ = translate(KeyValuePanel) self.setHorizontalHeaderLabels([_("Key"), _("Value")]) self.horizontalHeader().setResizeMode(QtGui.QHeaderView.Fixed) self.set_pairs(pairs)
def pick_file(self): _ = translate(LoadVariableDialog) # Pick a file picked = QtGui.QFileDialog.getOpenFileName(self, _("Choose a file")) if not picked: return self.select_file(str(picked))
def choose_operation(typecasts, source_descriptor, expected_descriptor, parent=None): _ = translate('typecast_dialog') dialog = QtGui.QDialog(parent) dialog.setWindowTitle(_("Type casting")) layout = QtGui.QVBoxLayout() label = QtGui.QLabel(_( "A {actual} variable was put in a {expected} port. These are not " "compatible, but the following operations can do the " "conversion:").format( actual="%s (%s)" % (source_descriptor.module.__name__, source_descriptor.identifier), expected="%s (%s)" % (expected_descriptor.module.__name__, expected_descriptor.identifier))) label.setWordWrap(True) layout.addWidget(label) list_widget = CategorizedListWidget() list_widget.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) pm = get_package_manager() for operation in typecasts: package = pm.get_package(operation.package_identifier) item = OperationItem(operation, package.name) list_widget.addItem(item, item.category) layout.addWidget(list_widget) buttons = QtGui.QHBoxLayout() ok = QtGui.QPushButton(_("Typecast", "Accept typecast dialog button")) QtCore.QObject.connect(ok, QtCore.SIGNAL('clicked()'), dialog, QtCore.SLOT('accept()')) buttons.addWidget(ok) cancel = QtGui.QPushButton(_("Cancel", "Reject typecast dialog button")) QtCore.QObject.connect(cancel, QtCore.SIGNAL('clicked()'), dialog, QtCore.SLOT('reject()')) buttons.addWidget(cancel) layout.addLayout(buttons) def check_selection(): selection = list_widget.selectedItems() if selection: item = selection[0] if isinstance(item, OperationItem): ok.setEnabled(True) return ok.setEnabled(False) QtCore.QObject.connect( list_widget, QtCore.SIGNAL('itemSelectionChanged()'), check_selection) check_selection() dialog.setLayout(layout) if dialog.exec_() == QtGui.QDialog.Accepted: return list_widget.selectedItems()[0].operation else: raise CancelExecution
def pick_file(self): _ = translate(LoadVariableDialog) # Pick a file picked = QtGui.QFileDialog.getOpenFileName( self, _("Choose a file")) if not picked: return self.select_file(str(picked))
def draw(self, qp): Overlay.draw(self, qp) _ = translate(PlotPromptOverlay) qp.setPen(Overlay.text) qp.setBrush(QtCore.Qt.NoBrush) qp.drawText( 10, 10, self.width() - 20, self.height() - 20, QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap, _("Drag a plot in this cell"))
def populate(self, provenance, row=0): if row == 0: self.root = provenance try: node = self.nodes[provenance] except KeyError: pass else: if node.row <= row: node.row = row + 1 return node.item item = None links = set() if isinstance(provenance, data_provenance.Operation): item = OperationProvenanceItem(provenance['name'], provenance) for arg in provenance['args'].itervalues(): self.populate(arg, row + 1) links.add(arg) elif isinstance(provenance, data_provenance.Variable): varname = self._controller.vistrail.get_tag(provenance['version']) vistraildata = VistrailManager(self._controller) prev = vistraildata.variable_provenance(provenance['version']) if prev is None: # We are missing data! Someone tampered with the vistrail? if varname is not None and varname[:8] == 'dat-var': varname = varname[:8] else: varname = translate(ProvenanceSceneLayout)( '(deleted)') warnings.warn( "A variable (version %r) referenced from provenance " "is missing!" % provenance['version']) item = VariableProvenanceItem(varname, provenance) elif varname is not None and varname[:8] == 'dat-var-': self.populate(prev, row + 1) varname = varname[8:] item = VariableProvenanceItem(varname, provenance) links.add(prev) else: # If that variable has been deleted, we just skip it, like an # intermediate result self.populate(prev, row) elif isinstance(provenance, data_provenance.Loader): item = LoaderProvenanceItem(provenance['name'], provenance) elif isinstance(provenance, data_provenance.Constant): item = ConstantProvenanceItem(provenance['constant'], provenance) else: raise TypeError("populate() got %r" % (provenance,)) if item is not None: self.nodes[provenance] = self.TmpNode(item, row, links)
def __init__(self, operation, category, wizard=False): if is_operator(operation.name): _ = translate(OperationItem) name = _("operator {op}").format(op=operation.name) else: name = operation.name QtGui.QTreeWidgetItem.__init__(self, [name]) if wizard: font = self.font(0) font.setItalic(True) self.setFont(0, font) self.operation = operation self.category = category
def test_translate(self): """Tests the translate() mechanism. Doesn't actually checks that anything gets translated. """ from PyQt4 import QtCore old_translate = QtCore.QCoreApplication.translate try: QtCore.QCoreApplication.translate = cr = CallRecorder( old_translate) from dat.gui import translate tr = translate(Test_gui) self.assertIsNotNone(tr) msg = u"Don't translate " msg += u"me (unittest)" # there is no way xgettext can find this self.assertEqual(tr(msg), msg) call1 = ( [ 'dat.tests.test_gui.Test_gui', msg, None, QtCore.QCoreApplication.UnicodeUTF8], dict()) self.assertEqual(cr.calls, [call1]) tr = translate('this test') self.assertEqual(tr(msg, "disambiguation"), msg) call2 = ( [ 'this test', msg, "disambiguation", QtCore.QCoreApplication.UnicodeUTF8], dict()) self.assertEqual(cr.calls, [call1, call2]) finally: QtCore.QCoreApplication.translate = old_translate
def populate(self, provenance, row=0): if row == 0: self.root = provenance try: node = self.nodes[provenance] except KeyError: pass else: node.row = max(node.row, row) return node.item item = None links = set() if isinstance(provenance, data_provenance.Operation): item = OperationProvenanceItem(provenance['name'], provenance) for arg in provenance['args'].itervalues(): self.populate(arg, row + 1) links.add(arg) elif isinstance(provenance, data_provenance.Variable): varname = self._controller.vistrail.get_tag(provenance['version']) vistraildata = VistrailManager(self._controller) prev = vistraildata.variable_provenance(provenance['version']) if prev is None: # We are missing data! Someone tampered with the vistrail? if varname is not None and varname[:8] == 'dat-var': varname = varname[:8] else: varname = translate(ProvenanceSceneLayout)('(deleted)') warnings.warn( "A variable (version %r) referenced from provenance " "is missing!" % provenance['version']) item = VariableProvenanceItem(varname, provenance) elif varname is not None and varname[:8] == 'dat-var-': self.populate(prev, row + 1) varname = varname[8:] item = VariableProvenanceItem(varname, provenance) links.add(prev) else: # If that variable has been deleted, we just skip it, like an # intermediate result self.populate(prev, row) elif isinstance(provenance, data_provenance.Loader): item = LoaderProvenanceItem(provenance['name'], provenance) elif isinstance(provenance, data_provenance.Constant): item = ConstantProvenanceItem(provenance['constant'], provenance) else: raise TypeError("populate() got %r" % (provenance, )) if item is not None: self.nodes[provenance] = self.TmpNode(item, row, links)
def _get_custom_version_panels(controller, version): _ = translate("recipe_version_panel") if not VistrailManager.initialized: return [] vistraildata = VistrailManager(controller) if vistraildata is None: return [] pipelineInfo = vistraildata.get_pipeline(version) if pipelineInfo is None: return [] monospace = QtGui.QFont('Monospace') monospace.setStyleHint(QtGui.QFont.TypeWriter) recipe = pipelineInfo.recipe recipe_widget = QtGui.QGroupBox(_("DAT recipe")) recipe_widget.setSizePolicy( recipe_widget.sizePolicy().horizontalPolicy(), QtGui.QSizePolicy.Fixed) layout = QtGui.QVBoxLayout() line = QtGui.QHBoxLayout() line.addWidget(QtGui.QLabel(_("Plot:"))) plot_label = QtGui.QLabel("%s" % recipe.plot.name) plot_label.setFont(monospace) line.addWidget(plot_label) layout.addLayout(line) layout.addWidget(QtGui.QLabel(_("Variables:"))) variable_list = QtGui.QTextEdit() color = variable_list.textColor() variable_list.setEnabled(False) variable_list.setTextColor(color) variable_list.setFont(monospace) variable_list.setLineWrapMode(QtGui.QTextEdit.NoWrap) variable_list.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) text = [] for p_values in recipe.parameters.itervalues(): for value in p_values: if value.type == RecipeParameterValue.VARIABLE: text.append(value.variable.name) text = '\n'.join(text) variable_list.setPlainText(text) variable_list.setFixedHeight( variable_list.document().size().height()) layout.addWidget(variable_list) recipe_widget.setLayout(layout) return [(-1, recipe_widget)]
def start(args=[], optionsDict={}): """Starts the DAT. Creates an application and a window and enters Qt's main loop. """ try: app = Application(args, optionsDict) except vistrails.core.requirements.MissingRequirement, e: _ = translate('dat.application') QtGui.QMessageBox.critical( None, _("Missing requirement"), _("VisTrails reports that a requirement is missing.\n" "This application can't continue without {required}.").format( required=e.requirement)) return 1
def _get_custom_version_panels(controller, version): _ = translate("recipe_version_panel") if not VistrailManager.initialized: return [] vistraildata = VistrailManager(controller) if vistraildata is None: return [] pipelineInfo = vistraildata.get_pipeline(version) if pipelineInfo is None: return [] monospace = QtGui.QFont('Monospace') monospace.setStyleHint(QtGui.QFont.TypeWriter) recipe = pipelineInfo.recipe recipe_widget = QtGui.QGroupBox(_("DAT recipe")) recipe_widget.setSizePolicy(recipe_widget.sizePolicy().horizontalPolicy(), QtGui.QSizePolicy.Fixed) layout = QtGui.QVBoxLayout() line = QtGui.QHBoxLayout() line.addWidget(QtGui.QLabel(_("Plot:"))) plot_label = QtGui.QLabel("%s" % recipe.plot.name) plot_label.setFont(monospace) line.addWidget(plot_label) layout.addLayout(line) layout.addWidget(QtGui.QLabel(_("Variables:"))) variable_list = QtGui.QTextEdit() color = variable_list.textColor() variable_list.setEnabled(False) variable_list.setTextColor(color) variable_list.setFont(monospace) variable_list.setLineWrapMode(QtGui.QTextEdit.NoWrap) variable_list.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) text = [] for p_values in recipe.parameters.itervalues(): for value in p_values: if value.type == RecipeParameterValue.VARIABLE: text.append(value.variable.name) text = '\n'.join(text) variable_list.setPlainText(text) variable_list.setFixedHeight(variable_list.document().size().height()) layout.addWidget(variable_list) recipe_widget.setLayout(layout) return [(-1, recipe_widget)]
def draw(self, qp): _ = translate(VariableDropEmptyCell) Overlay.draw(self, qp) qp.setPen(Overlay.no_pen) qp.setBrush(Overlay.no_fill) qp.drawRect( 10, 10, self.width() - 20, self.height() - 20) qp.drawText( 10, 10, self.width() - 20, self.height() - 20, QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap, _("You need to drag a plot first"))
def start(args=[], optionsDict={}): """Starts the DAT. Creates an application and a window and enters Qt's main loop. """ try: app = Application(args, optionsDict) except vistrails.core.requirements.MissingRequirement, e: _ = translate('dat.application') QtGui.QMessageBox.critical( None, _("Missing requirement"), _("VisTrails reports that a requirement is missing.\n" "This application can't continue without {required}.") .format(required=e.requirement)) return 1
def advanced_input_dialog(parent, title, label, init_text, default=None, validate=None, flags=AdvancedLineEdit.DEFAULTS): """Similar to QInputDialog#getText() but uses an AdvancedLineEdit. parent: parent widget or None, passed to QWidget's constructor. title: the string displayed in the title bar of the dialog label: the string displayed inside the dialog. init_text: initial value of the field. default: default value of the field, or None. validate: validation function for the field, or None. flags: flags passed to AdvancedLineEdit. Returns either (result: str, True) or (None, False). """ _ = translate('advanced_input_dialog') dialog = QtGui.QDialog(parent) dialog.setWindowTitle(title) layout = QtGui.QVBoxLayout() layout.addWidget(QtGui.QLabel(label)) lineedit = AdvancedLineEdit(init_text, None, default, validate, flags) layout.addWidget(lineedit) buttons = QtGui.QHBoxLayout() ok = QtGui.QPushButton(_("Ok", "Accept dialog button")) ok.setDefault(True) QtCore.QObject.connect(ok, QtCore.SIGNAL('clicked()'), dialog, QtCore.SLOT('accept()')) buttons.addWidget(ok) cancel = QtGui.QPushButton(_("Cancel", "Reject dialog button")) QtCore.QObject.connect(cancel, QtCore.SIGNAL('clicked()'), dialog, QtCore.SLOT('reject()')) buttons.addWidget(cancel) layout.addLayout(buttons) dialog.setLayout(layout) if dialog.exec_() == QtGui.QDialog.Accepted: return str(lineedit.text()), True else: return None, False
def __init__(self, cellcontainer, **kwargs): _ = translate(PlotDroppingOverlay) Overlay.__init__(self, cellcontainer, **kwargs) plotname = str(kwargs['mimeData'].data(MIMETYPE_DAT_PLOT)) plotname = plotname.split(',') if len(plotname) != 2: self._text = "???" return plotname = plotname[1] if cellcontainer._plot is None: text = _("Drop here to add a {plotname} to this cell") else: text = _("Drop here to replace this plot with a new {plotname}") self._text = text.format(plotname=plotname)
def execute_pipeline(controller, pipeline, reason, locator, version, **kwargs): """Execute the pipeline while showing a progress dialog. """ _ = translate('execute_pipeline') totalProgress = len(pipeline.modules) progress = QtGui.QProgressDialog(_("Executing..."), None, 0, totalProgress) progress.setWindowTitle(_("Pipeline Execution")) progress.setWindowModality(QtCore.Qt.WindowModal) progress.show() def moduleExecuted(objId): progress.setValue(progress.value() + 1) QtCore.QCoreApplication.processEvents() if 'module_executed_hook' in kwargs: kwargs['module_executed_hook'].append(moduleExecuted) else: kwargs['module_executed_hook'] = [moduleExecuted] results, changed = controller.execute_workflow_list([( locator, # locator version, # version pipeline, # pipeline DummyView(), # view None, # custom_aliases None, # custom_params reason, # reason None, # sinks kwargs)]) # extra_info get_vistrails_application().send_notification('execution_updated') progress.setValue(totalProgress) progress.hide() progress.deleteLater() if not results[0].errors: return None else: module_id, error = next(results[0].errors.iteritems()) return str(error)
def __init__(self): QtGui.QWidget.__init__(self) _ = translate(OperationPanel) self.setAcceptDrops(True) self._operations = dict() # VariableOperation -> OperationItem layout = QtGui.QVBoxLayout() self._console = ConsoleWidget() layout.addWidget(self._console) layout.addWidget(QtGui.QLabel(_("Enter a command and press return"))) self._input_line = MarkerHighlighterLineEdit() self.connect(self._input_line, QtCore.SIGNAL('returnPressed()'), self.execute_line) layout.addWidget(self._input_line) layout.addWidget(QtGui.QLabel(_("Available operations:"))) self._list = CategorizedListWidget() self._list.setSelectionMode(QtGui.QAbstractItemView.NoSelection) self._list.header().setResizeMode(QtGui.QHeaderView.Stretch) self.connect( self._list, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.operation_clicked) layout.addWidget(self._list) self.setLayout(layout) app = get_vistrails_application() app.register_notification('dat_new_operation', self.operation_added) app.register_notification('dat_removed_operation', self.operation_removed) for operation in GlobalManager.variable_operations: self.operation_added(operation)
def __init__(self): QtGui.QWidget.__init__(self) _ = translate(OperationPanel) self.setAcceptDrops(True) self._operations = dict() # VariableOperation -> OperationItem layout = QtGui.QVBoxLayout() self._console = ConsoleWidget() layout.addWidget(self._console) layout.addWidget(QtGui.QLabel(_("Enter a command and press return"))) self._input_line = MarkerHighlighterLineEdit() self.connect(self._input_line, QtCore.SIGNAL('returnPressed()'), self.execute_line) layout.addWidget(self._input_line) layout.addWidget(QtGui.QLabel(_("Available operations:"))) self._list = CategorizedListWidget() self._list.setSelectionMode(QtGui.QAbstractItemView.NoSelection) self._list.header().setResizeMode(QtGui.QHeaderView.Stretch) self.connect(self._list, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.operation_clicked) layout.addWidget(self._list) self.setLayout(layout) app = get_vistrails_application() app.register_notification('dat_new_operation', self.operation_added) app.register_notification('dat_removed_operation', self.operation_removed) for operation in GlobalManager.variable_operations: self.operation_added(operation)
def __init__(self): QtGui.QWidget.__init__(self) _ = translate(LoadVariableDialog) self._file_loaders = set() self.default_variable_name_observer = None main_layout = QtGui.QVBoxLayout() header_layout = QtGui.QFormLayout() file_edit = QtGui.QHBoxLayout() self._file_edit = QtGui.QLineEdit() self._file_edit.setEnabled(False) file_edit.addWidget(self._file_edit) file_button = QtGui.QPushButton(_("Browse...")) self.connect(file_button, QtCore.SIGNAL('clicked()'), self.pick_file) file_edit.addWidget(file_button) header_layout.addRow(_("File:"), file_edit) self._loader_list = QtGui.QComboBox() self.connect(self._loader_list, QtCore.SIGNAL('currentIndexChanged(int)'), self.update_widget) header_layout.addRow(_("Loader:"), self._loader_list) main_layout.addLayout(header_layout) self._loader_stack = QtGui.QStackedWidget() loader_groupbox = QtGui.QGroupBox(_("Loader parameters")) groupbox_layout = QtGui.QVBoxLayout() groupbox_layout.addWidget(self._loader_stack) loader_groupbox.setLayout(groupbox_layout) main_layout.addWidget(loader_groupbox) self.setLayout(main_layout) self.select_file('')
def __init__(self, overlay, port_name, pos, variable, typecast=None, append=False): QtGui.QPushButton.__init__(self) self.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.setProperty('assigned', variable is not None and 'yes' or 'no') self._variable = variable if variable is not None: if typecast is not None: self.setText("(%s) %s" % (typecast, variable.name)) else: self.setText(variable.name) self.connect( self, QtCore.SIGNAL('clicked()'), lambda: overlay.remove_parameter(port_name, pos)) elif append: self.setText('+') else: _ = translate(DataParameter) self.setText(_("(not set)"))
def __init__(self, filename=None): super(SimpleVariableLoaderMixin, self).__init__() if isinstance(self, CustomVariableLoader) and filename is not None: raise TypeError elif isinstance(self, FileVariableLoader): if filename is None: raise TypeError self.__filename = filename self.__parameters = dict() if not self._simple_parameters: _ = translate(SimpleVariableLoaderMixin) layout = QtGui.QVBoxLayout() layout.addWidget(QtGui.QLabel(_("This loader has no parameters."))) self.setLayout(layout) return layout = QtGui.QFormLayout() for name, opts in self._simple_parameters: # Unpack options if not isinstance(opts, (tuple, list)): ptype, pdef, pdesc = opts, None, None else: ptype, pdef, pdesc = opts + (None,) * (3 - len(opts)) # Widgets if issubclass(ptype, basestring): widget = QtGui.QLineEdit() if pdef is not None: widget.setText(pdef) resetter = lambda: widget.setText(pdef) else: resetter = lambda: widget.setText('') getter = lambda: widget.text() elif ptype is int: widget = QtGui.QSpinBox() if pdef is None: resetter = lambda: widget.setValue(0) elif isinstance(pdef, (tuple, list)): if len(pdef) != 3: raise ValueError widget.setRange(pdef[1], pdef[2]) widget.setValue(pdef[0]) resetter = lambda: widget.setValue(pdef[0]) else: widget.setValue(pdef) resetter = lambda: widget.setValue(pdef) getter = lambda: widget.value() elif ptype is bool: widget = QtGui.QCheckBox() if pdef: widget.setChecked(True) resetter = lambda: widget.setChecked(True) else: resetter = lambda: widget.setChecked(False) getter = lambda: widget.isChecked() else: raise ValueError("No simple widget type for parameter " "type %r" % (ptype,)) # Store widget in layout and (widget, getter) in a dict if pdesc is not None: layout.addRow(pdesc, widget) else: layout.addRow(name, widget) self.__parameters[name] = (getter, resetter) self.setLayout(layout)
def __init__(self, controller, parent=None): QtGui.QDialog.__init__(self, parent, QtCore.Qt.Dialog) self._vistraildata = VistrailManager(controller) self._validator = VariableNameValidator(self._vistraildata) _ = translate(LoadVariableDialog) self.setWindowTitle(_("Load variable")) self._tabs = [] main_layout = QtGui.QVBoxLayout() self._tab_widget = QtGui.QTabWidget() self.connect(self._tab_widget, QtCore.SIGNAL('currentChanged(int)'), self.update_varname) main_layout.addWidget(self._tab_widget) varname_layout = QtGui.QHBoxLayout() varname_layout.addWidget(QtGui.QLabel(_("Variable name:"))) self._varname_edit = AdvancedLineEdit( DEFAULT_VARIABLE_NAME, default=DEFAULT_VARIABLE_NAME, validate=self._validator, flags=(AdvancedLineEdit.COLOR_VALIDITY | AdvancedLineEdit.COLOR_DEFAULTVALUE | AdvancedLineEdit.FOLLOW_DEFAULT_UPDATE)) varname_layout.addWidget(self._varname_edit) main_layout.addLayout(varname_layout) buttons_layout = QtGui.QHBoxLayout() load_cont_button = QtGui.QPushButton(_("Load and close")) self.connect(load_cont_button, QtCore.SIGNAL('clicked()'), self.loadclose_clicked) buttons_layout.addWidget(load_cont_button) load_button = QtGui.QPushButton(_("Load")) self.connect(load_button, QtCore.SIGNAL('clicked()'), self.load_clicked) buttons_layout.addWidget(load_button) cancel_button = QtGui.QPushButton(_("Cancel")) self.connect(cancel_button, QtCore.SIGNAL('clicked()'), self.cancel) buttons_layout.addWidget(cancel_button) main_layout.addLayout(buttons_layout) self.setLayout(main_layout) self._file_loader = FileLoaderPanel() self._file_loader.default_variable_name_observer = ( self.default_variable_name_changed) self._add_tab(self._file_loader, _("File")) app = get_vistrails_application() app.register_notification('dat_new_loader', self.loader_added) app.register_notification('dat_removed_loader', self.loader_removed) for loader in GlobalManager.variable_loaders: self.loader_added(loader) idx = self._tab_widget.currentIndex() if idx >= 0: loader = self._tabs[idx] self._varname_edit.setDefault(loader.get_default_variable_name()) else: self._varname_edit.setDefault(DEFAULT_VARIABLE_NAME) self._varname_edit.reset()
def setupUi(self, overlayed): _ = translate(VariableDroppingOverlay) main_layout = QtGui.QVBoxLayout() name_layout = QtGui.QHBoxLayout() name_label = QtGui.QLabel(self._cell._plot.name + " (") name_label.setObjectName('plot_name') name_layout.addWidget(name_label) name_layout.addStretch() if not overlayed: show_adv_config = QtGui.QPushButton("config") self.connect(show_adv_config, QtCore.SIGNAL('clicked()'), self.show_advanced_config) name_layout.addWidget(show_adv_config) main_layout.addLayout(name_layout) spacing_layout = QtGui.QHBoxLayout() spacing_layout.addSpacing(20) ports_layout = QtGui.QFormLayout() ports_layout.setFieldGrowthPolicy( QtGui.QFormLayout.AllNonFixedFieldsGrow) self._parameters = [] # [[widget]] self._constant_widgets = dict() # widget -> port self._unset_constant_labels = dict() # widget -> QtGui.QLabel for i, port in enumerate(self._cell._plot.ports): widgets = [] if isinstance(port, DataPort): param_panel = QtGui.QWidget() param_panel.setLayout(QtGui.QVBoxLayout()) # Style changes according to the compatibility of the port with # the variable being dragged if self._compatible_ports is not None: compatible = self._compatible_ports[i] else: compatible = '' pos = 0 for pos, variable in enumerate( self._cell._parameters.get(port.name, [])): param = DataParameter(self, port.name, pos, variable=variable.variable, typecast=variable.typecast) param.setProperty('compatible', compatible) param.setProperty('optional', port.optional) param.setProperty('targeted', 'no') widgets.append(param) param_panel.layout().addWidget(param) if ((port.multiple_values and compatible == 'yes') or not self._cell._parameters.get(port.name)): param = DataParameter(self, port.name, pos, variable=None, append=compatible == 'yes') param.setProperty('compatible', compatible) param.setProperty('optional', port.optional) param.setProperty('targeted', 'no') widgets.append(param) param_panel.layout().addWidget(param) else: # isinstance(port, ConstantPort): gp = GuiParameter(port.type) gp.port_spec_item = PortSpecItem(id=-1, pos=0, module=port.type.name, package=port.type.package, default=port.default_value, entry_type=port.entry_type, values=port.enum_values) try: gp.strValue = self._cell._parameters[port.name][0].constant isset = True except KeyError: isset = False param = port.widget_class(gp) self._constant_widgets[param] = port.name param.contentsChanged.connect(self.constant_changed) param_panel = QtGui.QWidget() param_panel.setLayout(QtGui.QHBoxLayout()) param_panel.layout().addWidget(param) if not isset: label = QtGui.QLabel(_("(not set)")) if not port.optional: label.setStyleSheet('QLabel { color: red; }') else: label.setStyleSheet('QLabel { color: grey; }') param_panel.layout().addWidget(label) self._unset_constant_labels[param] = label label = QtGui.QLabel(port.name) label.setBuddy(param_panel) self._parameters.append(widgets) ports_layout.addRow(label, param_panel) # Closing parenthesis paren_label = QtGui.QLabel(")") paren_label.setObjectName('closing_paren') ports_layout.addRow(paren_label) spacing_layout.addLayout(ports_layout) main_layout.addLayout(spacing_layout) main_layout.addStretch(1) if (not overlayed and self._cell.widget() is not None and self._constant_widgets): self._execute_button = QtGui.QPushButton(_("Execute")) self.connect(self._execute_button, QtCore.SIGNAL('clicked()'), lambda: self._cell._set_overlay(None)) self._execute_button.setEnabled(False) self._cancel_button = QtGui.QPushButton(_("Cancel changes")) def cancel_pending(): self._cell._cancel_pending() self._execute_button.setEnabled(False) self._cancel_button.setEnabled(False) self.connect(self._cancel_button, QtCore.SIGNAL('clicked()'), cancel_pending) self._cancel_button.setEnabled(False) buttons = QtGui.QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._execute_button) buttons.addWidget(self._cancel_button) main_layout.addLayout(buttons) else: self._execute_button = None self._cancel_button = None self.setLayout(main_layout)
def __init__(self, parent, variables=VAR_HIDE): """Setups the widget. If variables is not VAR_HIDE, a list of the variables will be displayed on the right. You can override variable_filter to choose which variables are to be displayed. If VAR_SELECT is used, variable_selected(variable) will be called when the selection changes. """ _ = translate(OperationWizard) QtGui.QDialog.__init__(self, parent, QtCore.Qt.Dialog) self._vistraildata = VistrailManager() self._selected_varname = None self._has_error = False var_right_layout = QtGui.QHBoxLayout() vlayout = QtGui.QVBoxLayout() self._validator = VariableNameValidator(VistrailManager()) varname_layout = QtGui.QHBoxLayout() varname_layout.addWidget(QtGui.QLabel(_("Variable name:"))) self._varname_edit = AdvancedLineEdit( DEFAULT_VARIABLE_NAME, default=DEFAULT_VARIABLE_NAME, validate=self._validator, flags=(AdvancedLineEdit.COLOR_VALIDITY | AdvancedLineEdit.COLOR_DEFAULTVALUE | AdvancedLineEdit.FOLLOW_DEFAULT_UPDATE)) varname_layout.addWidget(self._varname_edit) vlayout.addStretch() vlayout.addLayout(varname_layout) # Create this wizard's specific layout app_layout = self.create_ui() assert app_layout is not None vlayout.insertLayout(0, app_layout) var_right_layout.addLayout(vlayout) # Optionally, put a list of variables on the right if variables != self.VAR_HIDE: self._variable_list = DraggableListWidget( mimetype=MIMETYPE_DAT_VARIABLE) self._variable_list.setSizePolicy( QtGui.QSizePolicy.Minimum, self._variable_list.sizePolicy().horizontalPolicy()) for varname in self._vistraildata.variables: if not self.variable_filter( self._vistraildata.get_variable(varname)): continue pos = bisect( self._variable_list.count(), lambda i: str(self._variable_list.item(i).text()), varname) self._variable_list.insertItem(pos, varname) var_right_layout.addWidget(self._variable_list) if variables == self.VAR_SELECT: self._variable_list.setDragEnabled(False) self._variable_list.setSelectionMode( QtGui.QAbstractItemView.SingleSelection) self.connect( self._variable_list, QtCore.SIGNAL('itemSelectionChanged()'), self._selection_changed) main_layout = QtGui.QVBoxLayout() main_layout.addLayout(var_right_layout) self._error_label = QtGui.QLabel() font = self._error_label.font() font.setBold(True) self._error_label.setFont(font) self._error_label.setStyleSheet('color: red;') main_layout.addWidget(self._error_label) buttons = QtGui.QDialogButtonBox( QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel, QtCore.Qt.Horizontal) self.connect(buttons, QtCore.SIGNAL('accepted()'), self._accept) self.connect(buttons, QtCore.SIGNAL('rejected()'), self, QtCore.SLOT('reject()')) main_layout.addWidget(buttons) self.setLayout(main_layout)
def __init__(self, filename=None): super(SimpleVariableLoaderMixin, self).__init__() if isinstance(self, CustomVariableLoader) and filename is not None: raise TypeError elif isinstance(self, FileVariableLoader): if filename is None: raise TypeError self.__filename = filename self.__parameters = dict() if not self._simple_parameters: _ = translate(SimpleVariableLoaderMixin) layout = QtGui.QVBoxLayout() layout.addWidget(QtGui.QLabel(_("This loader has no parameters."))) self.setLayout(layout) return layout = QtGui.QFormLayout() for name, opts in self._simple_parameters: # Unpack options if not isinstance(opts, (tuple, list)): ptype, pdef, pdesc = opts, None, None else: ptype, pdef, pdesc = opts + (None, ) * (3 - len(opts)) # Widgets if issubclass(ptype, basestring): widget = QtGui.QLineEdit() if pdef is not None: widget.setText(pdef) resetter = lambda: widget.setText(pdef) else: resetter = lambda: widget.setText('') getter = lambda: widget.text() elif ptype is int: widget = QtGui.QSpinBox() if pdef is None: resetter = lambda: widget.setValue(0) elif isinstance(pdef, (tuple, list)): if len(pdef) != 3: raise ValueError widget.setRange(pdef[1], pdef[2]) widget.setValue(pdef[0]) resetter = lambda: widget.setValue(pdef[0]) else: widget.setValue(pdef) resetter = lambda: widget.setValue(pdef) getter = lambda: widget.value() elif ptype is bool: widget = QtGui.QCheckBox() if pdef: widget.setChecked(True) resetter = lambda: widget.setChecked(True) else: resetter = lambda: widget.setChecked(False) getter = lambda: widget.isChecked() else: raise ValueError("No simple widget type for parameter " "type %r" % (ptype, )) # Store widget in layout and (widget, getter) in a dict if pdesc is not None: layout.addRow(pdesc, widget) else: layout.addRow(name, widget) self.__parameters[name] = (getter, resetter) self.setLayout(layout)