Пример #1
0
    def __init__(self, app):
        QMainWindow.__init__(self, None)
        self.app = app
        self.client = app  # used by the NewViewDialog

        # this is done in Panel.__init__ for the panel version
        self.settings = CompatSettings()
        self.loadSettings(self.settings)

        BaseHistoryWindow.__init__(self)
        self.splitter.setSizes([20, 80])

        DlgUtils.__init__(self, 'History viewer')

        self.actionAttachElog.setVisible(False)

        self.splitter.restoreState(self.splitterstate)

        self.setCentralWidget(self.splitter)
        self.newValue.connect(self.newvalue_callback)

        for toolbar in self.getToolbars():
            self.addToolBar(toolbar)
        for menu in self.getMenus():
            self.menuBar().addMenu(menu)
        self.actionFitLinear.trigger()
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)
Пример #2
0
 def __init__(self, parent, client, **settings):
     QMainWindow.__init__(self, parent)
     DlgUtils.__init__(self, 'Instrument config')
     loadUi(self, findResource('nicos_mlz/kws1/gui/instrconfig.ui'))
     self.setWindowTitle('Reconfigure Instrument')
     self.client = client
     self.client.connected.connect(self.on_client_connected)
     self.client.disconnected.connect(self.on_client_disconnected)
     self._parts = settings['parts']
     self._widgets = []
     for (i, part) in enumerate(self._parts):
         label = QLabel(part + ':', self)
         bgrp = QButtonGroup(self)
         rbtn = QRadioButton('real', self)
         vbtn = QRadioButton('virtual', self)
         bgrp.addButton(rbtn)
         bgrp.addButton(vbtn)
         self.grid.addWidget(label, i, 0)
         self.grid.addWidget(rbtn, i, 1)
         self.grid.addWidget(vbtn, i, 2)
         self._widgets.append((label, bgrp, rbtn, vbtn))
     self.resize(self.sizeHint())
     if self.client.isconnected:
         self._update()
     else:
         self.frame.setDisabled(True)
Пример #3
0
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        self.resize(800, 500)
        self.setWindowTitle('Debug console')

        self.console = ConsoleBox(parent=self,
                                  startup_message='-' * 80 + '''
NICOS GUI debug console
Objects in the namespace:
  app             Qt application object
  main            Main window instance
  client          Client connection object
Helper functions:
  watch(*events)  Install a handler for daemon events (all if no arguments)
                  that prints them to this console
''' + '-' * 80)
        self.outbox = QPlainTextEdit(self)
        self.outbox.document().setDefaultFont(
            self.console.document().defaultFont())
        self.mainwidget = QSplitter(Qt.Vertical, self)
        self.mainwidget.addWidget(self.console)
        self.mainwidget.addWidget(self.outbox)
        self.setCentralWidget(self.mainwidget)
        self.console.closeConsole.connect(self.close)

        self.console.namespace.update(
            dict(
                app=QCoreApplication.instance(),
                main=parent,
                client=parent.client,
                watch=self.install_handlers,
            ))
Пример #4
0
    def __init__(self, item, window, menuwindow, parent):
        from nicos.clients.gui.panels.utils import createWindowItem
        QMainWindow.__init__(self, parent)
        self.user_color = window.user_color
        self.mainwindow = window.mainwindow
        self.log = NicosLogger('AuxiliarySubWindow')
        self.log.parent = self.mainwindow.log

        self.panels = []

        # we have to nest one step to get consistent layout spacing
        # around the central widget
        central = QWidget(self)
        layout = QVBoxLayout()
        # only keep margin at the top (below the tabs)
        layout.setContentsMargins(0, 6, 0, 0)
        if len(item) == 1:
            (subitem, setupSpec) = item + (None, )
        else:
            (subitem, setupSpec) = item
        it = createWindowItem(subitem, window, menuwindow, self, self.log)
        if it:
            if isinstance(it, (
                    Panel,
                    QSplitter,
            )):
                if isinstance(it, Panel):
                    it.hideTitle()
                # if tab has its own setups overwrite panels setups
                if setupSpec:
                    it.setSetups(setupSpec)
                it.setWidgetVisible.connect(parent.setWidgetVisibleSlot)
            layout.addWidget(it)
            central.setLayout(layout)
            self.setCentralWidget(central)
Пример #5
0
    def __init__(self, parent, wintype, config):
        from nicos.clients.gui.panels.utils import createWindowItem
        QMainWindow.__init__(self, parent)
        loadUi(self, 'auxwindow.ui')
        self.mainwindow = parent
        self.client = parent.client
        self.log = NicosLogger('AuxiliaryWindow')
        self.log.parent = self.mainwindow.log

        self.type = wintype
        self.panels = []
        self.splitters = []

        self.sgroup = SettingGroup(config.name)
        with self.sgroup as settings:
            loadUserStyle(self, settings)

        self.setWindowTitle(config.name)
        widget = createWindowItem(config.contents, self, self, self, self.log)
        if widget:
            self.centralLayout.addWidget(widget)
        self.centralLayout.setContentsMargins(6, 6, 6, 6)

        with self.sgroup as settings:
            loadBasicWindowSettings(self, settings)

        if len(self.splitstate) == len(self.splitters):
            for sp, st in zip(self.splitters, self.splitstate):
                sp.restoreState(st)

        setups = config[1].get('setups', '')
        self.setSetups(setups)
        self.client.register(self, 'session/mastersetup')

        SetupDepWindowMixin.__init__(self, self.client)
Пример #6
0
    def __init__(self, parent, client, **settings):
        QMainWindow.__init__(self, parent)
        self.client = client
        self.setWindowTitle(' ')  # window title is unnecessary
        flags = self.windowFlags()
        flags |= Qt.WindowStaysOnTopHint
        flags ^= Qt.WindowMinimizeButtonHint
        self.setWindowFlags(flags)

        self.sgroup = SettingGroup('EstopTool')
        with self.sgroup as settings:
            self.restoreGeometry(settings.value('geometry', '', QByteArray))

        icon = QIcon(':/estop')
        icon.addFile(':/estopdown', mode=QIcon.Active)
        self.btn = PicButton(icon, self)

        widget = QWidget(self)
        layout = QHBoxLayout()
        layout.addWidget(self.btn)
        layout.setContentsMargins(3, 3, 3, 3)
        widget.setLayout(layout)
        self.setCentralWidget(widget)
        self.btn.clicked.connect(self.dostop)
        self.setFixedSize(self.minimumSize())
        self.show()
Пример #7
0
 def __init__(self, title, parent):
     self.tabIdx = -1
     QMainWindow.__init__(self, parent)
     self.setWindowTitle(title)
     self.setWindowModality(Qt.NonModal)
     self.sgroup = SettingGroup(title)
     with self.sgroup as settings:
         loadBasicWindowSettings(self, settings)
Пример #8
0
 def __init__(self, parent, client):
     QMainWindow.__init__(self, parent)
     loadUi(self, 'dialogs/helpwin.ui')
     self.history = []
     self.webView = QWebView(self)
     self.webView.setPage(HelpPage(client, self.history, self.webView))
     self.frame.layout().addWidget(self.webView)
     self.client = client
     self._next_scrollpos = None
Пример #9
0
 def show(self):
     QMainWindow.show(self)
     if self.autoconnect and not self.client.isconnected:
         self.on_actionConnect_triggered(True)
     if sys.platform == 'darwin':
         # on Mac OS loadBasicWindowSettings seems not to work before show()
         # so we do it here again
         with self.sgroup as settings:
             loadBasicWindowSettings(self, settings)
Пример #10
0
    def __init__(self, parent, _client, **_kwds):
        QMainWindow.__init__(self, parent)
        DlgUtils.__init__(self, 'Hexapod')

        # set during actions that will call signal handlers
        self.recursive = False

        loadUi(self, findResource('nicos_mlz/kws1/gui/tools/hexapod.ui'))

        for but in (self.butStart, self.butSetWorkspace, self.butSetFrame,
                    self.butSaveVel):
            but.setEnabled(False)

        self.axes = {}
        self.axeslist = []

        try:
            self._controller = PyTango.DeviceProxy(TANGO_DEV_BASE +
                                                   'controller')
            # make sure the server is running and create remaining proxies
            try:
                self._controller.State()
            except AttributeError:
                raise Exception('server appears to be not running')
            for axis in AXES:
                self.axes[axis] = PyTango.DeviceProxy(TANGO_DEV_BASE + axis)
                self.axeslist.append(self.axes[axis])
        except Exception as err:
            self.showError('could not connect to tango server: %s' % err)
            self.deleteLater()
            return

        self.on_cbsWorkspace_activated(0)
        self.on_cbsFrame_activated(self.cbsFrame.currentText())

        tx_speed = self.query_attr(self.axes['tx'], 'speed')
        self.inpVelTrans.setValue(tx_speed)
        self.lblVelTrans.setText(self.inpVelTrans.text())
        self.inpVelRot.setValue(self.query_attr(self.axes['rx'], 'speed'))
        self.lblVelRot.setText(self.inpVelRot.text())
        self.inpVelOmega.setValue(self.query_attr(self.axes['omega'], 'speed'))
        self.lblVelOmega.setText(self.inpVelOmega.text())

        # ramp time = speed / acceleration
        self.inpRampUp.setValue(tx_speed /
                                self.query_attr(self.axes['tx'], 'accel'))
        self.lblRampUp.setText(self.inpRampUp.text())
        self.inpRampDown.setValue(tx_speed /
                                  self.query_attr(self.axes['tx'], 'decel'))
        self.lblRampDown.setText(self.inpRampDown.text())

        self.updTimer = QTimer()
        self.updTimer.timeout.connect(self.updateTimer)
        self.updTimer.start(1000)
Пример #11
0
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        DlgUtils.__init__(self, 'Live data')
        self.panel = parent
        layout1 = QVBoxLayout()
        self.plot = QwtPlot(self)
        layout1.addWidget(self.plot)
        self.curve = QwtPlotCurve()
        self.curve.setRenderHint(QwtPlotCurve.RenderAntialiased)
        self.curve.attach(self.plot)
        self.marker = QwtPlotMarker()
        self.marker.attach(self.plot)
        self.markerpen = QPen(Qt.red)
        self.marker.setSymbol(
            QwtSymbol(QwtSymbol.Ellipse, QBrush(), self.markerpen, QSize(7,
                                                                         7)))
        self.zoomer = QwtPlotZoomer(self.plot.canvas())
        self.zoomer.setMousePattern(QwtPlotZoomer.MouseSelect3, Qt.NoButton)
        self.picker = QwtPlotPicker(self.plot.canvas())
        self.picker.setSelectionFlags(QwtPlotPicker.PointSelection
                                      | QwtPlotPicker.ClickSelection)
        self.picker.setMousePattern(QwtPlotPicker.MouseSelect1, Qt.MidButton)
        self.picker.selected.connect(self.pickerSelected)
        layout2 = QHBoxLayout()
        layout2.addWidget(QLabel('Scale:', self))
        self.scale = QComboBox(self)
        self.scale.addItems([
            'Single detectors, sorted by angle',
            'Scattering angle 2theta (deg)', 'Q value (A-1)'
        ])
        self.scale.currentIndexChanged[int].connect(self.scaleChanged)
        layout2.addWidget(self.scale)
        layout2.addStretch()
        self.scaleframe = QFrame(self)
        self.scaleframe.setLayout(layout2)
        self.scaleframe.setVisible(False)
        layout1.addWidget(self.scaleframe)
        mainframe = QFrame(self)
        mainframe.setLayout(layout1)
        self.setCentralWidget(mainframe)
        self.setContentsMargins(6, 6, 6, 6)
        plotfont = scaledFont(self.font(), 0.7)
        self.plot.setAxisFont(QwtPlot.xBottom, plotfont)
        self.plot.setAxisFont(QwtPlot.yLeft, plotfont)
        self.plot.setCanvasBackground(Qt.white)
        self.resize(800, 200)

        self._detinfo = None
        self._anglemap = None
        self._infowindow = None
        self._infolabel = None
        self._xs = self._ys = None
        self._type = None
Пример #12
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        uic.loadUi(
            path.join(path.dirname(path.abspath(__file__)), 'ui',
                      'mainwindow.ui'), self)

        logging.basicConfig()
        self.log = logging.getLogger()

        setupcontroller.init(self.log)
        classparser.init(self.log)

        # dictionary of absolute path to a setup - setupWidget
        self.setupWidgets = {}
        # dictionary of absolute path to setup - dict
        # which is deviceName - deviceWidget
        self.deviceWidgets = {}

        self.labelHeader = QLabel('Select Setup or device...')
        self.labelHeader.setAlignment(Qt.AlignCenter)

        # signal/slot connections
        self.treeWidget.itemActivated.connect(self.loadSelection)
        self.treeWidget.deviceRemoved.connect(self.deviceRemovedSlot)
        self.treeWidget.deviceAdded.connect(self.deviceAddedSlot)
        self.treeWidget.newDeviceAdded.connect(self.newDeviceAddedSlot)

        # setup the menu bar
        self.actionNewFile.triggered.connect(self.treeWidget.newSetup)
        self.actionSave.triggered.connect(self.actionSaveSlot)
        self.actionSaveAs.triggered.connect(self.actionSaveAsSlot)
        self.actionExit.triggered.connect(self.close)
        self.instrumentMenu = self.menuView.addMenu('Instrument')
        self.actionShowAllInstrument = self.menuView.addAction(
            'Show all instruments')
        self.actionShowAllInstrument.triggered.connect(
            self.treeWidget.setAllInstrumentsVisible)
        self.menuView.addAction(self.dockWidget.toggleViewAction())
        self.dockWidget.toggleViewAction().setText('Show Tree')
        self.actionAboutSetupFileTool.triggered.connect(
            self.aboutSetupFileTool)
        self.actionAboutQt.triggered.connect(QApplication.aboutQt)

        self.workarea.addWidget(self.labelHeader)

        self.treeWidget.loadNicosData()
        for directory in sorted(setupcontroller.setup_directories):
            instrumentAction = self.instrumentMenu.addAction(directory)
            instrumentAction.triggered.connect(
                self.treeWidget.setInstrumentMode)
        if config.instrument and config.instrument not in ('jcns', 'demo'):
            self.treeWidget.setSingleInstrument(config.instrument)
Пример #13
0
    def __init__(self, cacheclient, parent=None):
        QMainWindow.__init__(self)
        self.client = cacheclient
        self._treeitems = {}
        uic.loadUi(join(path.dirname(path.abspath(__file__)), 'ui',
                        'mainwindow.ui'), self)
        self.watcherWindow = WatcherWindow(self)
        self.setupEvents()
        self.ipAddress = '127.0.0.1'
        self.port = 14869
        self.showTimeStamp = True
        self.showTTL = True

        setBackgroundColor(self.labelDemoTTL, ttlColor)
        setBackgroundColor(self.labelDemoExpired, expiredColor)
Пример #14
0
 def occur(self, what, regex=False):
     content = self.toPlainText().split('\n')
     if regex:
         regexp = QRegExp(what, Qt.CaseInsensitive)
         content = [line for line in content if regexp.indexIn(line) >= 0]
     else:
         what = what.lower()
         content = [line for line in content if what in line.lower()]
     content = '\n'.join(content)
     window = QMainWindow(self)
     window.resize(600, 800)
     window.setWindowTitle('Lines matching %r' % what)
     widget = QTextEdit(window)
     widget.setFont(self.font())
     window.setCentralWidget(widget)
     widget.setText(content)
     window.show()
Пример #15
0
    def __init__(self):
        self._reconfiguring = False
        QMainWindow.__init__(self)
        # set app icon in multiple sizes
        icon = QIcon()
        icon.addFile(':/appicon')
        icon.addFile(':/appicon-16')
        icon.addFile(':/appicon-48')
        self.setWindowIcon(icon)

        self.keyChange.connect(lambda obj, args: obj.on_keyChange(*args))
        self.reconfigure.connect(self.do_reconfigure)

        self.sgroup = SettingGroup('Monitor')
        with self.sgroup as settings:
            # geometry and window appearance
            loadBasicWindowSettings(self, settings)
Пример #16
0
 def event(self, event):
     if self._reconfiguring and event.type() == 76:  # LayoutRequest
         self._reconfiguring = False
         # always resize first; works around layout bugs where the full
         # screen window is actually made larger than the full screen
         self.resize(self.sizeHint())
         if self._wantFullScreen:
             self.setGeometry(QApplication.screens()[0].geometry())
     return QMainWindow.event(self, event)
Пример #17
0
 def on_page_unsupportedContent(self, reply):
     if reply.url().scheme() != 'file':
         return
     filename = reply.url().path()
     if filename.endswith('.dat'):
         content = open(filename, encoding='utf-8', errors='replace').read()
         window = QMainWindow(self)
         window.resize(600, 800)
         window.setWindowTitle(filename)
         widget = QTextEdit(window)
         widget.setFontFamily('monospace')
         window.setCentralWidget(widget)
         widget.setText(content)
         window.show()
     else:
         # try to open the link with host computer default application
         try:
             QDesktopServices.openUrl(reply.url())
         except Exception:
             pass
Пример #18
0
 def _retrieve_detinfo(self):
     if self._detinfo is None:
         info = self.panel.client.eval(
             'det._detinfo_parsed, '
             'det._anglemap', None)
         if not info:
             return self.showError('Cannot retrieve detector info.')
         self._lambda = self.panel.client.eval('chWL()', None)
         if not self._lambda:
             return self.showError('Cannot retrieve wavelength.')
         self._detinfo, self._anglemap = info
         self._inverse_anglemap = 0
         self._infowindow = QMainWindow(self)
         self._infolabel = QLabel(self._infowindow)
         self._infolabel.setTextFormat(Qt.RichText)
         self._infowindow.setCentralWidget(self._infolabel)
         self._infowindow.setContentsMargins(10, 10, 10, 10)
         self._inv_anglemap = [[
             entry for entry in self._detinfo[1:]
             if entry[12] == self._anglemap[detnr] + 1
         ][0] for detnr in range(len(self._xs))]
Пример #19
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        uic.loadUi(
            path.join(path.dirname(path.abspath(__file__)), 'ui',
                      'mainwindow.ui'), self)

        self.className = ''  # name of the devices class in auth tuple
        self.group = ''  # name of the group defined in the setup file
        self.description = ''  # name of the description in the setup file
        self.authDict = {}  # dictionary containing info in auth tuple
        self.users = {}  # dict to store users while working

        self.actionLoad.triggered.connect(self.loadFile)
        self.actionSave.triggered.connect(self.save)
        self.actionPrintUsers.triggered.connect(self.debugUsers)
        self.actionShowDebug.triggered.connect(self.toggleDebug)

        self.menuBar.clear()
        self.menuBar.addMenu(self.menuFile)
        self.menuBar.addMenu(self.menuEdit)

        self.userList.currentItemChanged.connect(self.changeUser)
        self.pushButtonAddUser.clicked.connect(self.addUser)
        self.pushButtonDeleteUser.clicked.connect(self.deleteUser)
        self.pushButtonSaveConfig.clicked.connect(self.setConfig)
        self.pushButtonSaveUser.clicked.connect(self.setUserData)

        self.comboBoxHashing.activated.connect(self.changedConfig)
        self.lineEditUserName.textEdited.connect(self.changedUser)
        self.lineEditPassword.textEdited.connect(self.changedUser)
        self.comboBoxUserLevel.activated.connect(self.changedUser)

        # Initialize a logger required by setups.readSetup()
        self.log = logging.getLogger()
        self.setuppath = path.join(path.abspath('.'), 'nicos_mlz',
                                   config.instrument, 'setups', 'special',
                                   'daemon.py')
        self.setup = None
        self.readSetupFile(self.setuppath)
Пример #20
0
 def keyPressEvent(self, event):
     if event.text() == 'q':
         self.close()
     elif event.text() == 'f':
         self._wantFullScreen = not self._wantFullScreen
         if self._wantFullScreen:
             self.showFullScreen()
         else:
             self.showNormal()
     elif event.text() == 'r':
         # resize/refresh/redraw
         self.resize(self.sizeHint())
     return QMainWindow.keyPressEvent(self, event)
Пример #21
0
 def moveEvent(self, event):
     QMainWindow.moveEvent(self, event)
     self.saveSettings()
Пример #22
0
 def resizeEvent(self, event):
     QMainWindow.resizeEvent(self, event)
     self.saveSettings()
Пример #23
0
 def __init__(self, parent=None):
     QMainWindow.__init__(self, parent)
     uic.loadUi(path.join(path.dirname(path.abspath(__file__)), 'ui',
                          'watcher.ui'), self)
     self.buttonClear.clicked.connect(self.clear)
Пример #24
0
    def __init__(self, log, gui_conf, viewonly=False, tunnel=''):
        QMainWindow.__init__(self)
        DlgUtils.__init__(self, 'NICOS')
        loadUi(self, self.ui)

        # set app icon in multiple sizes
        icon = QIcon()
        icon.addFile(':/appicon')
        icon.addFile(':/appicon-16')
        icon.addFile(':/appicon-48')
        self.setWindowIcon(icon)

        if tunnel and SSHTunnelForwarder is None:
            self.showError('You want to establish a connection to NICOS via '
                           "a SSH tunnel, but the 'sshtunnel' module is not "
                           'installed. The tunneling feature will disabled.')
        self.tunnel = tunnel if SSHTunnelForwarder is not None else ''
        self.tunnelServer = None

        # hide admin label until we are connected as admin
        self.adminLabel.hide()

        # our logger instance
        self.log = log

        # window for displaying errors
        self.errorWindow = None

        # window for "prompt" event confirmation
        self.promptWindow = None

        # debug console window, if opened
        self.debugConsole = None

        # log messages sent by the server
        self.messages = []

        # are we in expert mode?  (always false on startup)
        self.expertmode = False

        # no wrapping at startup
        self.allowoutputlinewrap = False

        # set-up the initial connection data
        self.conndata = ConnectionData(host='localhost',
                                       port=1301,
                                       user='******',
                                       password=None,
                                       viewonly=viewonly)

        # state members
        self.current_status = None

        # connect the client's events
        self.client = NicosGuiClient(self, self.log)
        self.client.error.connect(self.on_client_error)
        self.client.broken.connect(self.on_client_broken)
        self.client.failed.connect(self.on_client_failed)
        self.client.connected.connect(self.on_client_connected)
        self.client.disconnected.connect(self.on_client_disconnected)
        self.client.status.connect(self.on_client_status)
        self.client.showhelp.connect(self.on_client_showhelp)
        self.client.clientexec.connect(self.on_client_clientexec)
        self.client.plugplay.connect(self.on_client_plugplay)
        self.client.watchdog.connect(self.on_client_watchdog)
        self.client.prompt.connect(self.on_client_prompt)

        # data handling setup
        self.data = DataHandler(self.client)

        # panel configuration
        self.gui_conf = gui_conf
        self.initDataReaders()
        self.mainwindow = self

        # determine if there is an editor window type, because we would like to
        # have a way to open files from a console panel later
        self.editor_wintype = self.gui_conf.find_panel(
            ('editor.EditorPanel',
             'nicos.clients.gui.panels.editor.EditorPanel'))
        self.history_wintype = self.gui_conf.find_panel(
            ('history.HistoryPanel',
             'nicos.clients.gui.panels.history.HistoryPanel'))

        # additional panels
        self.panels = []
        self.splitters = []
        self.windowtypes = []
        self.windows = {}

        # setting presets
        self.instrument = self.gui_conf.name

        self.createWindowContent()

        # timer for reconnecting
        self.reconnectTimer = QTimer(singleShot=True, timeout=self._reconnect)
        self._reconnect_count = 0
        self._reconnect_time = 0

        # timer for session keepalive, every 12 hours
        self.keepaliveTimer = QTimer(singleShot=False, timeout=self._keepalive)
        self.keepaliveTimer.start(self.keepaliveInterval)

        # setup tray icon
        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.activated.connect(self.on_trayIcon_activated)
        self.trayMenu = QMenu(self)
        nameAction = self.trayMenu.addAction(self.instrument)
        nameAction.setEnabled(False)
        self.trayMenu.addSeparator()
        toggleAction = self.trayMenu.addAction('Hide main window')
        toggleAction.setCheckable(True)
        toggleAction.triggered[bool].connect(
            lambda hide: self.setVisible(not hide))
        self.trayIcon.setContextMenu(self.trayMenu)

        # help window
        self.helpWindow = None
        # watchdog window
        self.watchdogWindow = None
        # plug-n-play notification windows
        self.pnpWindows = {}

        # create initial state
        self._init_toolbar()
Пример #25
0
class ToftofProfileWindow(DlgUtils, QMainWindow):
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        DlgUtils.__init__(self, 'Live data')
        self.panel = parent
        layout1 = QVBoxLayout()
        self.plot = QwtPlot(self)
        layout1.addWidget(self.plot)
        self.curve = QwtPlotCurve()
        self.curve.setRenderHint(QwtPlotCurve.RenderAntialiased)
        self.curve.attach(self.plot)
        self.marker = QwtPlotMarker()
        self.marker.attach(self.plot)
        self.markerpen = QPen(Qt.red)
        self.marker.setSymbol(
            QwtSymbol(QwtSymbol.Ellipse, QBrush(), self.markerpen, QSize(7,
                                                                         7)))
        self.zoomer = QwtPlotZoomer(self.plot.canvas())
        self.zoomer.setMousePattern(QwtPlotZoomer.MouseSelect3, Qt.NoButton)
        self.picker = QwtPlotPicker(self.plot.canvas())
        self.picker.setSelectionFlags(QwtPlotPicker.PointSelection
                                      | QwtPlotPicker.ClickSelection)
        self.picker.setMousePattern(QwtPlotPicker.MouseSelect1, Qt.MidButton)
        self.picker.selected.connect(self.pickerSelected)
        layout2 = QHBoxLayout()
        layout2.addWidget(QLabel('Scale:', self))
        self.scale = QComboBox(self)
        self.scale.addItems([
            'Single detectors, sorted by angle',
            'Scattering angle 2theta (deg)', 'Q value (A-1)'
        ])
        self.scale.currentIndexChanged[int].connect(self.scaleChanged)
        layout2.addWidget(self.scale)
        layout2.addStretch()
        self.scaleframe = QFrame(self)
        self.scaleframe.setLayout(layout2)
        self.scaleframe.setVisible(False)
        layout1.addWidget(self.scaleframe)
        mainframe = QFrame(self)
        mainframe.setLayout(layout1)
        self.setCentralWidget(mainframe)
        self.setContentsMargins(6, 6, 6, 6)
        plotfont = scaledFont(self.font(), 0.7)
        self.plot.setAxisFont(QwtPlot.xBottom, plotfont)
        self.plot.setAxisFont(QwtPlot.yLeft, plotfont)
        self.plot.setCanvasBackground(Qt.white)
        self.resize(800, 200)

        self._detinfo = None
        self._anglemap = None
        self._infowindow = None
        self._infolabel = None
        self._xs = self._ys = None
        self._type = None

    def _retrieve_detinfo(self):
        if self._detinfo is None:
            info = self.panel.client.eval(
                'det._detinfo_parsed, '
                'det._anglemap', None)
            if not info:
                return self.showError('Cannot retrieve detector info.')
            self._lambda = self.panel.client.eval('chWL()', None)
            if not self._lambda:
                return self.showError('Cannot retrieve wavelength.')
            self._detinfo, self._anglemap = info
            self._inverse_anglemap = 0
            self._infowindow = QMainWindow(self)
            self._infolabel = QLabel(self._infowindow)
            self._infolabel.setTextFormat(Qt.RichText)
            self._infowindow.setCentralWidget(self._infolabel)
            self._infowindow.setContentsMargins(10, 10, 10, 10)
            self._inv_anglemap = [[
                entry for entry in self._detinfo[1:]
                if entry[12] == self._anglemap[detnr] + 1
            ][0] for detnr in range(len(self._xs))]

    def scaleChanged(self, scale):
        self.update(self._type, self._orig_nbins, self._orig_x, self._orig_y)

    def update(self, proftype, nbins, x, y):
        self._orig_x = x
        self._orig_y = y
        self._orig_nbins = nbins
        x.setsize(8 * nbins)
        y.setsize(8 * nbins)
        xs = struct.unpack('d' * nbins, x)
        ys = struct.unpack('d' * nbins, y)
        if proftype == 0:
            if self.scale.currentIndex() == 0:
                xs = xs
            elif self.scale.currentIndex() == 1:
                self._retrieve_detinfo()
                xs = [self._inv_anglemap[int(xi)][5] for xi in xs]
            else:
                self._retrieve_detinfo()
                if self._lambda is None:
                    self.showError('Could not determine wavelength.')
                    self.scale.setCurrentIndex(1)
                    return
                xs = [
                    4 * pi / self._lambda *
                    sin(radians(self._inv_anglemap[int(xi)][5] / 2.))
                    for xi in xs
                ]
        self._xs = xs
        self._ys = ys
        self.curve.setData(xs, ys)
        self.plot.setAxisAutoScale(QwtPlot.xBottom)
        self.plot.setAxisAutoScale(QwtPlot.yLeft)
        self.marker.setVisible(False)
        self.zoomer.setZoomBase(True)
        self._type = proftype
        if proftype == 0:
            self.setWindowTitle(
                'Single detector view (time-channel integrated)')
            self.scaleframe.setVisible(True)
        elif proftype == 1:
            self.setWindowTitle('Time channel view (detector integrated)')
            self.scaleframe.setVisible(False)
        else:
            self.scaleframe.setVisible(False)

    def pickerSelected(self, point):
        if self._type != 0:
            return
        self._retrieve_detinfo()
        index = self.curve.closestPoint(self.picker.transform(point))[0]
        detentry = self._inv_anglemap[index][:]
        detentry.append(self._xs[index])
        detentry.append(self._ys[index])
        self.marker.setXValue(self._xs[index])
        self.marker.setYValue(self._ys[index])
        self.marker.setVisible(True)
        self.plot.replot()
        self._infowindow.show()
        entrynames = [
            'EntryNr', 'Rack', 'Plate', 'Pos', 'RPos', '2Theta', 'CableNr',
            'CableType', 'CableLen', 'CableEmpty', 'Card', 'Chan', 'Total',
            'DetName', 'BoxNr', 'BoxChan', 'XValue', 'Counts'
        ]
        formats = [
            '%s', '%d', '%d', '%d', '%d', '%.3f', '%d', '%d', '%.2f', '%d',
            '%d', '%d', '%d', '%r', '%d', '%d', '%s', '%d'
        ]
        empties = [1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]
        self._infolabel.setText('Detector info:<br><table>' + ''.join(
            '<tr><td>%s</td><td></td><td>%s</td></tr>%s' %
            (name, format % value, '<tr></tr>' if empty else '')
            for (name, format, empty,
                 value) in zip(entrynames, formats, empties, detentry)) +
                                '</table>')

    def closeEvent(self, event):
        if self._infowindow:
            self._infowindow.close()
Пример #26
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        # scroll area Widget contents - layout
        self.scrollLayout = QFormLayout()
        self.scrollLayout.setContentsMargins(0, 0, 0, 0)

        # scroll area Widget contents
        self.scrollWidget = QWidget()
        self.scrollWidget.setLayout(self.scrollLayout)

        # scroll area
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(self.scrollWidget)

        # main layout
        self.mainLayout = QVBoxLayout()
        self.mainLayout.setSpacing(0)

        # add all main to the main vLayout
        self.mainLayout.addWidget(self.scrollArea)

        # central Widget
        self.centralWidget = QWidget()
        self.centralWidget.setLayout(self.mainLayout)

        # set central Widget
        self.setCentralWidget(self.centralWidget)

        try:
            self._bus = ModbusTcpClient('drum.panda.frm2')
            self._bus.connect()
            self._sync()
            print("Modbus synced!")
            print(self.ReadWord(0x20), self.ReadWord(0x21))
        except Exception as err:
            print("Modbus failed: %r, using demo mode!" % err)
            self._bus = None

        self._sync()

        widgets = []

        widgets.append(
            BaseDev(self, 'mtt motor inputs', 0, has_status=True, addr=34))

        widgets.append(
            BaseDev(self, 'spare inputs', 1, has_status=True, addr=44))
        widgets.append(
            BaseDev(self,
                    'spare outputs',
                    2,
                    has_status=True,
                    target='0x%04x' % self.ReadWord(60),
                    addr=59))
        widgets.append(
            BaseDev(self,
                    'enable_word',
                    3,
                    target='0x%04x' % self.ReadWord(73),
                    addr=73))
        widgets.append(BaseDev(self, 'cycle_counter', 4, addr=74))
        widgets.append(
            BaseDev(self,
                    'handle_cw',
                    5,
                    has_status=True,
                    target='%d' % self.ReadWord(51),
                    addr=50))
        widgets.append(
            BaseDev(self,
                    'handle_ccw',
                    6,
                    has_status=True,
                    target='%d' % self.ReadWord(54),
                    addr=53))
        widgets.append(BaseDev(self, 'enc1', 7, has_status=True, addr=46))
        widgets.append(BaseDev(self, 'enc2', 8, has_status=True, addr=48))
        widgets.append(
            BaseDev(self,
                    'arm_switch',
                    9,
                    has_status=True,
                    target='%d' % self.ReadWord(63),
                    addr=62))
        widgets.append(BaseDev(self, 'encoder1', 10, has_status=False,
                               addr=65))
        widgets.append(
            BaseDev(self,
                    'arm',
                    11,
                    has_status=True,
                    target='%f' % self.ReadFloat(70),
                    value_offset=2,
                    addr=68))
        widgets.append(
            BaseDev(self,
                    'magnet',
                    12,
                    has_status=True,
                    target='%d' % self.ReadWord(57),
                    addr=56))
        widgets.append(
            BaseDev(self,
                    'air',
                    13,
                    has_status=True,
                    target='%d' % self.ReadWord(60),
                    addr=59))

        for w in widgets:
            self.addWidget(w)

        widgets.sort(key=lambda w: w.index)
        self.widgets = widgets

        self.startTimer(225)  # in ms !
Пример #27
0
    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)

        # scroll area Widget contents - layout
        self.scrollLayout = QFormLayout()
        self.scrollLayout.setContentsMargins(0, 0, 0, 0)

        # scroll area Widget contents
        self.scrollWidget = QWidget()
        self.scrollWidget.setLayout(self.scrollLayout)

        # scroll area
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(self.scrollWidget)

        # main layout
        self.mainLayout = QVBoxLayout()
        self.mainLayout.setSpacing(0)

        # add all main to the main vLayout
        self.mainLayout.addWidget(self.scrollArea)

        # central Widget
        self.centralWidget = QWidget()
        self.centralWidget.setLayout(self.mainLayout)

        # set central Widget
        self.setCentralWidget(self.centralWidget)

        try:
            self._bus = ModbusTcpClient('wechsler.panda.frm2')
            self._bus.connect()
            self._sync()
            print("PLC conforms to spec %.4f" % self.ReadFloat(0))
        except Exception:
            print("Modbus failed, using demo mode!")
            self._bus = None

        self._sync()

        widgets = []
        widgets.append(WriteWord(self, 'last_liftpos', addr=58/2))
        widgets.append(ReadWord(self, 'analog1', addr=92/2))
        widgets.append(ReadWord(self, 'analog2', addr=96/2))
        widgets.append(AnalogInput(self, 'liftpos_analog', addr=146/2))
        widgets.append(DiscreteInput(self, 'lift_sw', addr=68/2))
        widgets.append(LIFT(self, 'lift', 104/2))

        widgets.append(WriteWord(self, 'last_magpos', addr=60/2))
        widgets.append(DiscreteInput(self, 'magazin_sw', addr=72/2))
        widgets.append(MAGAZIN(self, 'magazin', addr=110/2))

        widgets.append(DiscreteInput(self, 'magazin_occ_sw', addr=84/2))
        widgets.append(DiscreteInput(self, 'magazin_occ', addr=88/2))

        widgets.append(DiscreteInput(self, 'liftclamp_sw', addr=76/2))
        widgets.append(CLAMP(self, 'liftclamp', addr=116/2))

        widgets.append(DiscreteInput(self, 'magazinclamp_sw', addr=80/2))
        widgets.append(CLAMP(self, 'magazinclamp', addr=122/2))

        widgets.append(CLAMP(self, 'tableclamp', addr=128/2))

        widgets.append(CLAMP(self, 'inhibit_relay', addr=134/2))

        widgets.append(WriteWord(self, 'enable_word', addr=150/2))

        widgets.append(DiscreteInput(self, 'spare inputs', addr=100/2))
        widgets.append(DiscreteOutput(self, 'spare outputs', addr=140/2))

        widgets.append(ReadWord(self, 'cycle_counter', addr=152/2))

        for w in widgets:
            self.addWidget(w)

        self.widgets = widgets

        self.startTimer(225)  # in ms !
Пример #28
0
 def closeEvent(self, event):
     self.saveSettings(self.settings)
     return QMainWindow.closeEvent(self, event)
Пример #29
0
 def show(self):
     QMainWindow.show(self)
     if self.autoconnect and not self.client.isconnected:
         self.on_actionConnect_triggered(True)