def recalculate(self): try: self._simulate() except (ZeroDivisionError, IndexError): QMessageBox.warning(self.parent().parent(), 'Error', 'The current instrument setup is not well ' 'defined for polarisation analysis')
def on_client_connected(self): with waitCursor(): missed_devices = [] for d in ('def1', 'polcol', 'man', 'med'): self.client.eval('%s.pollParam()', None) params = self.client.getDeviceParams(d) for p, v in params.items(): self._update_key('%s/%s' % (d, p), v) for d in ('ra5', 'ra6', 'ra7', 'ta5', 'ta6', 'ta7', 'rd5', 'rd6', 'rd7', 'rg5', 'rg6', 'rg7', 'rd5_cad', 'rd6_cad', 'rd7_cad', 'lsa', 'lsd1', 'lsd2', 'lad', 'lpsd', 'kf', 'def1', 'def2', 'slit2.width'): try: self.log.debug('poll: %s', d) self.client.eval("session.getDevice('%s').poll()" % d) val = self.client.getDeviceValue('%s' % d) self._update_key('%s/value' % d, val) self.log.debug('%s/%s', d, val) except (NicosError, NameError): missed_devices += [d] if not missed_devices: self.recalculate() for w in (self.kf, self.LSA, self.LSD1, self.LSD1, self.gamma1, self.gamma2, self.LAD, self.bA, self.bD, self.bS): w.textChanged.connect(self.recalculate) else: QMessageBox.warning( self.parent().parent(), 'Error', 'The following devices are not available:<br>' "'%s'" % ', '.join(missed_devices)) self.setDisabled(True)
def editParam(self, pname): if not self.paraminfo[pname]['settable'] or self.client.viewonly: return mainunit = self.paramvalues.get('unit', 'main') punit = (self.paraminfo[pname]['unit'] or '').replace('main', mainunit) dlg = dialogFromUi(self, 'panels/devices_param.ui') dlg.target = DeviceParamEdit(self, dev=self.devname, param=pname) dlg.target.setClient(self.client) dlg.paramName.setText('Parameter: %s.%s' % (self.devname, pname)) dlg.paramDesc.setText(self.paraminfo[pname]['description']) dlg.paramValue.setText(str(self.paramvalues[pname]) + ' ' + punit) dlg.targetLayout.addWidget(dlg.target) dlg.resize(dlg.sizeHint()) dlg.target.setFocus() if dlg.exec_() != QDialog.Accepted: return try: new_value = dlg.target.getValue() except ValueError: self.log.exception('invalid value for typed value') # shouldn't happen, but if it does, at least give an indication that # something went wrong QMessageBox.warning( self, 'Error', 'The entered value is invalid ' 'for this parameter.') return if self.devrepr == self.devname: self.device_panel.exec_command('%s.%s = %r' % (self.devname, pname, new_value)) else: self.device_panel.exec_command( 'set(%s, %s, %r)' % (self.devrepr, srepr(pname), new_value))
def on_actionSetLimits_triggered(self): dlg = dialogFromUi(self, 'panels/devices_limits.ui') dlg.descLabel.setText('Adjust user limits of %s:' % self.devname) dlg.limitMin.setText(self.limitMin.text()) dlg.limitMax.setText(self.limitMax.text()) abslimits = self.client.getDeviceParam(self.devname, 'abslimits') offset = self.client.getDeviceParam(self.devname, 'offset') if offset is not None: abslimits = abslimits[0] - offset, abslimits[1] - offset dlg.limitMinAbs.setText(str(abslimits[0])) dlg.limitMaxAbs.setText(str(abslimits[1])) target = DeviceParamEdit(dlg, dev=self.devname, param='userlimits') target.setClient(self.client) btn = dlg.buttonBox.addButton('Reset to maximum range', QDialogButtonBox.ResetRole) def callback(): self.device_panel.exec_command('resetlimits(%s)' % self.devrepr) dlg.reject() btn.clicked.connect(callback) dlg.targetLayout.addWidget(target) res = dlg.exec_() if res != QDialog.Accepted: return newlimits = target.getValue() if newlimits[0] < abslimits[0] or newlimits[1] > abslimits[1]: QMessageBox.warning( self, 'Error', 'The entered limits are not ' 'within the absolute limits for the device.') # retry self.on_actionSetLimits_triggered() return self.device_panel.exec_command('set(%s, "userlimits", %s)' % (self.devrepr, newlimits))
def on_oneShotEval_clicked(self): expr, ok = QInputDialog.getText(self, 'Evaluate an expression', 'Expression to evaluate:') if not ok: return ret = self.client.eval(expr, stringify=True) QMessageBox.information(self, 'Result', ret)
def maybeAccept(self): if not self.frm.nameBox.text(): QMessageBox.warning(self, 'Error', 'Please enter a sample name.') self.frm.nameBox.setFocus() return name = self.frm.nameBox.text() if name in [config['name'] for config in self.configs]: QMessageBox.warning( self, 'Error', 'This sample name is already ' 'used, please use a different ' 'one.') self.frm.nameBox.setFocus() return if float(self.frm.thickBox.text()) == 0: QMessageBox.warning(self, 'Error', 'Thickness cannot be zero.') self.frm.thickBox.setFocus() return for i in range(self.frm.posTbl.rowCount()): dev_name = self.frm.posTbl.item(i, 0).text() dev_pos = self.frm.posTbl.item(i, 1).text() if not dev_name or dev_name.startswith('<'): QMessageBox.warning(self, 'Error', f'{dev_name} is not a valid device name.') return try: dev_pos = float(dev_pos) except ValueError: QMessageBox.warning( self, 'Error', f'{dev_pos} is not a valid ' f'position for device {dev_name}.') return self.accept()
def __init__(self, parent, client, data): self.client = client client.setup.connect(self.on_client_setup) self.data = data add_mode = data[0] == 'added' if add_mode: message = ( '<b>New sample environment detected</b><br/>' 'A new sample environment <b>%s</b> has been detected:<br/>%s' % (data[1], data[2] or '')) else: message = ( '<b>Sample environment removed</b><br/>' 'The sample environment <b>%s</b> has been removed:<br/>%s' % (data[1], data[2] or '')) QMessageBox.__init__(self, QMessageBox.Information, 'NICOS Plug & Play', message, QMessageBox.NoButton, parent) self.setWindowModality(Qt.NonModal) self.b0 = self.addButton('Ignore', QMessageBox.RejectRole) self.b0.setIcon(self.style().standardIcon( QStyle.SP_DialogCancelButton)) if add_mode: self.b1 = self.addButton('Load setup', QMessageBox.YesRole) else: self.b1 = self.addButton('Remove setup', QMessageBox.YesRole) self.b1.setIcon(self.style().standardIcon(QStyle.SP_DialogOkButton)) self.b0.clicked.connect(self.on_ignore_clicked) self.b1.clicked.connect(self.on_execute_clicked) self.b0.setFocus()
def maybeAccept(self): if not self.frm.nameBox.text(): QMessageBox.warning(self, 'Error', 'Please enter a sample name.') self.frm.nameBox.setFocus() return name = self.frm.nameBox.text() if name in [config['name'] for config in self.configs]: QMessageBox.warning(self, 'Error', 'This sample name is already ' 'used, please use a different one.') self.frm.nameBox.setFocus() return for box in [self.frm.offsetBox, self.frm.thickBox, self.frm.factorBox, self.frm.apXBox, self.frm.apYBox, self.frm.apWBox, self.frm.apHBox]: if not box.text(): QMessageBox.warning(self, 'Error', 'Please enter valid values ' 'for all input fields.') return for i in range(self.frm.posTbl.rowCount()): devname = self.frm.posTbl.item(i, 0).text() devpos = self.frm.posTbl.item(i, 1).text() if not devname or devname.startswith('<'): QMessageBox.warning(self, 'Error', '%r is not a valid device ' 'name.' % devname) return try: devpos = float(devpos) except ValueError: QMessageBox.warning(self, 'Error', '%r is not a valid position' ' for device %r.' % (devpos, devname)) return self.accept()
def _readDev(self, name): rv = self.client.eval('%s.format(%s.read())' % (name, name), None) if rv is None: QMessageBox.warning(self, 'Error', 'Could not read device %s!' % name) return '0' return rv
def _update_device(self, devname): try: parlist = self.client.eval('session.getDevice(%r)._dev.' 'ListParams()' % devname) cmdlist = self.client.eval('session.getDevice(%r)._dev.' 'ListCmds()' % devname) except Exception: QMessageBox.warning( self, 'Error', 'Could not retrieve the param/' 'command list from device.') return self.controlBox.setEnabled(True) self._par_values = {} self._changed_pars = {} self.paramTable.clear() self.paramTable.setColumnCount(2) self.paramTable.setRowCount(len(parlist)) for (i, par) in enumerate(parlist): nameitem = QTableWidgetItem(par) nameitem.setFlags(nameitem.flags() & ~Qt.ItemIsEditable) self.paramTable.setItem(i, 0, nameitem) value = self.client.eval('session.getDevice(%r)._dev.' 'GetParam(%r)' % (devname, par), default=None) valuestr = '<error>' if value is None else '%.6g' % value self._par_values[par] = valuestr self.paramTable.setItem(i, 1, QTableWidgetItem(valuestr)) self.paramTable.resizeRowsToContents() self.paramTable.resizeColumnToContents(0) self.cmdList.clear() for cmd in cmdlist: QListWidgetItem(cmd, self.cmdList)
def _getProposalInput(self): prop = self.proposalNum.text() title = self.expTitle.text() try: users = splitUsers(self.users.text()) except ValueError: QMessageBox.warning( self, 'Error', 'Invalid users list, please specify as\n\n' 'First Name <*****@*****.**>; Second Name <*****@*****.**>' ) raise ConfigurationError from None try: local = splitUsers(self.localContacts.text()) except ValueError: QMessageBox.warning( self, 'Error', 'Invalid local contacts, please specify as\n\n' 'First Name <*****@*****.**>; Second Name <*****@*****.**>' ) raise ConfigurationError from None sample = self.sampleName.text() notifEmails = self.notifEmails.toPlainText().strip() notifEmails = notifEmails.split('\n') if notifEmails else [] dataEmails = self.dataEmails.toPlainText().strip() dataEmails = dataEmails.split('\n') if dataEmails else [] errorbehavior = 'abort' if self.errorAbortBox.isChecked() else 'report' return prop, title, users, local, sample, notifEmails, dataEmails, \ errorbehavior
def exec_(self): QMessageBox.exec_(self) btn = self.clickedButton() if btn == self.b0: return QMessageBox.Yes # Append if btn == self.b1: return QMessageBox.Apply # Overwrite return QMessageBox.Cancel # Cancel
def _is_empty(self): for box in self._get_editable_settings(): if not box.text(): QMessageBox.warning(self, 'Error', 'A property cannot be empty.') box.setFocus() return True return False
def addValue(self): dlg = NewValueDialog() if dlg.exec_(): value = dlg.getValue() if not value: QMessageBox.warning(self, 'Error', 'No value entered.') return self.currentItem().addChild(QTreeWidgetItem([value])) self.editedSetup.emit()
def _format_users(self, users): if users: try: return splitUsers(users) except ValueError: QMessageBox.warning(self, 'Error', 'Invalid email address in ' 'users list') raise ConfigurationError from None return []
def read_axes(): ax1, ax2 = dlg._info[2], dlg._info[4] for (ax, box) in [(ax1, dlg.ax1Box), (ax2, dlg.ax2Box)]: if not ax: continue x = self.client.eval('%s.read()' % ax, None) if x is None: QMessageBox.warning(dlg, 'Error', f'Could not read {ax}.') return box.setText(f'x:.1f')
def __init__(self): QMessageBox.__init__( self, QMessageBox.Question, 'Code generation', 'Do you want to append to or overwrite the ' 'current code?', QMessageBox.NoButton) self.b0 = self.addButton('Append', QMessageBox.YesRole) self.b1 = self.addButton('Overwrite', QMessageBox.ApplyRole) self.b2 = self.addButton('Cancel', QMessageBox.RejectRole) self.b2.setIcon(self.style().standardIcon( QStyle.SP_DialogCancelButton))
def _format_local_contacts(self, local_contacts): if local_contacts: try: return splitUsers(local_contacts) except ValueError: QMessageBox.warning( self, 'Error', 'Invalid email address in ' 'local contacts list') raise ConfigurationError from None return []
def on_selDevices_clicked(self): if not self.client.isconnected: QMessageBox.warning(self, 'Error', 'You must be connected to ' 'a daemon to be able to select devices.') return dlg = DevicesDialog(self, self.measdef, self.client) if dlg.exec_() != QDialog.Accepted: return self.measdef.devices = dlg.toDefs() self.updateTable()
def on_actionSave_triggered(self): fn = QFileDialog.getSaveFileName(self, 'Save', '', 'All files (*.*)')[0] if not fn: return try: fn = fn.encode(sys.getfilesystemencoding()) with open(fn, 'w') as f: f.write(self.outView.getOutputString()) except Exception as err: QMessageBox.warning(self, 'Error', 'Writing file failed: %s' % err)
def exec_(self): # According to the docs, exec_() returns an "opaque value" if using # non-standard buttons, so we have to check clickedButton(). Do that # here and return a valid QMessageBox button constant. QMessageBox.exec_(self) btn = self.clickedButton() if btn == self.b2: return QMessageBox.Apply # Execute now elif btn == self.b1: return QMessageBox.Yes # Queue return QMessageBox.Cancel # Cancel
def on_readApBtn_clicked(self): if self.instrument != 'kws3': rv = self.client.eval('ap_sam.read()', None) else: rv = self.client.eval('sam_ap.read()', None) if rv is None: QMessageBox.warning(self, 'Error', 'Could not read aperture!') return self.frm.apXBox.setText('%.2f' % rv[0]) self.frm.apYBox.setText('%.2f' % rv[1]) self.frm.apWBox.setText('%.2f' % rv[2]) self.frm.apHBox.setText('%.2f' % rv[3])
def __init__(self): QMessageBox.__init__( self, QMessageBox.Information, 'Error', 'A script is currently running. What do you want to do?', QMessageBox.NoButton) self.b0 = self.addButton('Cancel', QMessageBox.RejectRole) self.b0.setIcon(self.style().standardIcon( QStyle.SP_DialogCancelButton)) self.b1 = self.addButton('Queue script', QMessageBox.YesRole) self.b1.setIcon(self.style().standardIcon(QStyle.SP_DialogOkButton)) self.b2 = self.addButton('Execute now!', QMessageBox.ApplyRole) self.b2.setIcon(self.style().standardIcon(QStyle.SP_MessageBoxWarning))
def _set_cached_values_to_ui(self): _cached_values = self._get_cached_values_of_instrument_settings() for index, box in enumerate(self._get_editable_settings()): box.setText(f'{_cached_values[index]}') if not self._verify_instrument_settings(): QMessageBox.warning( 'Error', 'Current values of the instrument settings are ' 'different than the values in the cache. Try ' 'to reconnect to the server.') # Setting cached values will trigger `textChanged`. However, we do not # want to re-apply already cached values. self.instSetApply.setEnabled(False)
def _set_ui_values_to_cache(self): _key_values = self._get_current_values_of_instrument_settings() _commands = [ f'session.getDevice("{DEVICES[0]}")' f'._set_parameter("{param}", "{val}")' for param, val in zip(INST_SET_KEYS, _key_values) ] for cmd in _commands: self.client.eval(cmd) if not self._verify_instrument_settings(): QMessageBox.warning( self, 'Error', 'Applied changes in instrument ' 'settings have not been cached.')
def on_countStartButton_clicked(self): if self.opTime.isChecked(): value = float(self.timePresetBox.text()) preset = 't' else: try: value = float(self.monitorPresetBox.text()) preset = 'm' except ValueError: self.log.exception('invalid value for monitor preset') QMessageBox.warning(self, 'Error', 'Invalid monitor preset') return args = '%s=%r' % (preset, int(value)) code = 'count(%s)' % args self.exec_command(code)
def closeEvent(self, event): if self.confirmexit and QMessageBox.question( self, 'Quit', 'Do you really want to quit?', QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: event.ignore() return for panel in self.panels: if not panel.requestClose(): event.ignore() return if self.autosavelayout: self.saveWindowLayout() with self.sgroup as settings: self.saveSettings(settings) for panel in self.panels: with panel.sgroup as settings: panel.saveSettings(settings) for window in list(self.windows.values()): if not window.close(): event.ignore() return if self.helpWindow: self.helpWindow.close() if self.client.isconnected: self.on_actionConnect_triggered(False) event.accept() QApplication.instance().quit()
def dropEvent(self, event): """ To satisfy Qt, a call to TreeWidgetContextMenu.dropEvent is neccessary. Else, the animation would look really gross and suggest the object might actually not have been copied. But after the call, the newly appended child item seems to be completely useless: It carries neither data nor does it emit the treeWidget's itemActivated signal. This may be a bug or my inability to find what's wrong. Because of that, I need to construct my own item, find the old one and replace it with my new one. """ target = self.getSetupOfDropPos(event.pos()) if self.dragItem.device.name in target.setup.devices.keys(): QMessageBox.warning( self, 'Error', 'The target setup already ' 'contains a device with that name!') self.dragItem = None event.ignore() return count = 0 previousItems = [] while count < target.childCount(): previousItems.append(target.child(count)) count += 1 TreeWidgetContextMenu.dropEvent(self, event) count = 0 afterDropItems = [] while count < target.childCount(): afterDropItems.append(target.child(count)) count += 1 newItem = None for child in afterDropItems: if child not in previousItems: newItem = child index = target.indexOfChild(newItem) target.takeChild(index) deviceName = self.dragItem.device.name target.setup.devices[deviceName] = deepcopy(self.dragItem.device) deviceItem = QTreeWidgetItem([deviceName], ItemTypes.Device) deviceItem.setFlags(deviceItem.flags() & ~Qt.ItemIsDropEnabled) deviceItem.device = target.setup.devices[deviceName] deviceItem.setIcon(0, QIcon(path.join(getResDir(), 'device.png'))) target.insertChild(index, deviceItem) self.deviceAdded.emit(target, deviceName) self.itemActivated.emit(deviceItem, 0)
def on_paramTable_itemChanged(self, item): if self._in_reread: return # someone edited the cell name = self.paramTable.item(item.row(), 0).text() try: value = float(item.text()) except ValueError: QMessageBox.warning( self, 'Error', 'Invalid value; should be a ' 'floating point number.') self._in_reread = True item.setText(self._par_values[name]) self._in_reread = False return self._par_values[name] = item.text() self._changed_pars[name] = value
def loadDevice(self, device): self.clear() errors = [] try: self.myClass = self.getClassOfDevice(device) except KeyError as e: errors.append('Failed to load class ' + str(e)) if errors: QMessageBox.warning(self, 'Errors', '\n'.join(errors)) self.pushButtonAdd.setEnabled(False) return classParam = DeviceParam('Class', create(self, str, device.classString)) classParam.pushButtonRemove.setVisible(False) classParam.placeholder.setVisible(True) classParam.valueWidget.setEnabled(False) self.parametersLayout.addWidget(classParam) self.parameters['Class'] = classParam mandatoryParams = [] optionalParams = [] for param in sorted(device.parameters): try: mandatory = self.myClass.parameters[param].mandatory except (AttributeError, KeyError): mandatory = False if mandatory: mandatoryParams.append(param) else: optionalParams.append(param) for param in mandatoryParams: value = device.parameters[param] newParam = self.createParameterWidget(param, value) self.parametersLayout.addWidget(newParam) self.parameters[param] = newParam for param in optionalParams: value = device.parameters[param] newParam = self.createParameterWidget(param, value) self.parametersLayout.addWidget(newParam) self.parameters[param] = newParam self.parametersLayout.addStretch() self.setOptimalWidth()