Пример #1
0
class CISession(SingleDeviceSession):
    """Session for the cache inspector: makes log messages appear in the
    status bar of the main window.
    """

    _qthandler = None

    def createRootLogger(self, prefix='nicos', console=True, logfile=True):
        self.log = NicosLogger('nicos')
        self.log.setLevel(INFO)
        self.log.parent = None
        self.log.addHandler(ColoredConsoleHandler())
        self._qthandler = StatusBarHandler()
        self.log.addHandler(self._qthandler)
Пример #2
0
class TestSession(Session):
    autocreate_devices = False
    cache_class = TestCacheClient

    def __init__(self, appname, daemonized=False):
        old_setup_info = getattr(self, '_setup_info', {})
        Session.__init__(self, appname, daemonized)
        self._setup_info = old_setup_info
        self._setup_paths = (path.join(module_root, 'test', 'setups'), )
        self._user_level = system_user.level

    def readSetupInfo(self):
        # since we know the setups don't change, only read them once
        if not self._setup_info:
            return Session.readSetupInfo(self)
        return self._setup_info

    def createRootLogger(self, prefix='nicos', console=True, logfile=True):
        self.log = NicosLogger('nicos')
        self.log.parent = None
        self.log.setLevel(DEBUG)
        self.testhandler = TestLogHandler()
        self.log.addHandler(self.testhandler)
        self._master_handler = None

    def runsource(self, source, filename='<input>', symbol='single'):
        code = self.commandHandler(source,
                                   lambda src: compile(src, filename, symbol))
        if code is None:
            return
        exec_(code, self.namespace)

    def delay(self, _secs):
        # TODO: this sleep shouldn't be necessary
        sleep(0.0001)

    def _string_to_level(self, level):
        if isinstance(level, string_types):
            for k, v in ACCESS_LEVELS.items():
                if v == level:
                    return k
            raise ValueError('invalid access level name: %r' % level)
        return level

    @contextlib.contextmanager
    def withUserLevel(self, level):
        old_level = self._user_level
        self._user_level = self._string_to_level(level)
        yield
        self._user_level = old_level

    def checkAccess(self, required):
        if 'level' in required:
            rlevel = self._string_to_level(required['level'])
            if rlevel > self._user_level:
                raise AccessError('%s access is not sufficient, %s access '
                                  'is required' %
                                  (ACCESS_LEVELS.get(self._user_level,
                                                     str(self._user_level)),
                                   ACCESS_LEVELS.get(rlevel, str(rlevel))))
        return Session.checkAccess(self, required)
Пример #3
0
def main(argv):
    global log  # pylint: disable=global-statement

    userpath = path.join(path.expanduser('~'), '.config', 'nicos')

    # Set up logging for the GUI instance.
    initLoggers()
    log = NicosLogger('gui')
    log.parent = None
    log.setLevel(logging.INFO)
    log.addHandler(ColoredConsoleHandler())
    log.addHandler(
        NicosLogfileHandler(path.join(userpath, 'log'),
                            'gui',
                            use_subdir=False))

    # set up logging for unhandled exceptions in Qt callbacks
    def log_unhandled(*exc_info):
        traceback.print_exception(*exc_info)
        log.exception('unhandled exception in QT callback', exc_info=exc_info)

    sys.excepthook = log_unhandled

    app = QApplication(argv, organizationName='nicos', applicationName='gui')

    opts = parseargs()

    if opts.configfile is None:
        try:
            config.apply()
        except RuntimeError:
            pass
        # If "demo" is detected automatically, let the user choose their
        # instrument configuration.
        need_dialog = config.instrument is None or \
                      (config.setup_package == 'nicos_demo' and
                       config.instrument == 'demo' and
                       'INSTRUMENT' not in os.environ)
        if need_dialog:
            opts.configfile = InstrSelectDialog.select(
                'Your instrument could not be automatically detected.')
            if opts.configfile is None:
                return
        else:
            opts.configfile = path.join(config.setup_package_path,
                                        config.instrument, 'guiconfig.py')

    with open(opts.configfile, 'rb') as fp:
        configcode = fp.read()
    gui_conf = processGuiConfig(configcode)
    gui_conf.stylefile = ''

    if gui_conf.options.get('facility') in ['ess', 'sinq']:
        gui_conf.stylefile = f"{config.nicos_root}" \
                             f"/nicos/clients/flowui/guiconfig.qss"

    stylefiles = [
        path.join(userpath, 'style-%s.qss' % sys.platform),
        path.join(userpath, 'style.qss'),
        path.splitext(opts.configfile)[0] + '-%s.qss' % sys.platform,
        path.splitext(opts.configfile)[0] + '.qss',
    ]

    for stylefile in [gui_conf.stylefile] or stylefiles:
        if path.isfile(stylefile):
            try:
                with open(stylefile, 'r', encoding='utf-8') as fd:
                    app.setStyleSheet(fd.read())
                gui_conf.stylefile = stylefile
                break
            except Exception:
                log.warning('Error setting user style sheet from %s',
                            stylefile,
                            exc=1)

    mainwindow_cls = _mainwindow_cls.get(
        gui_conf.options.get('facility', 'default'))
    mainwindow = mainwindow_cls(log, gui_conf, opts.viewonly, opts.tunnel)
    log.addHandler(DebugHandler(mainwindow))

    if opts.connect:
        parsed = parseConnectionString(opts.connect, DEFAULT_PORT)
        if parsed:
            cdata = ConnectionData(**parsed)
            cdata.viewonly = opts.viewonly
            mainwindow.setConnData(cdata)
            if cdata.password is not None:
                # we have a password, connect right away
                mainwindow.client.connect(mainwindow.conndata)
            else:
                # we need to ask for password, override last preset (uses given
                # connection data) and force showing connect window
                mainwindow.lastpreset = ''
                mainwindow.autoconnect = True
    mainwindow.startup()

    return app.exec_()