def __init__(self,parent=None,devices=None):
     #print '~'*80
     #print 'In AttributesPanel()'
     PARENT_KLASS.__init__(self,parent)
     self.setSizePolicy(Qt.QSizePolicy(Qt.QSizePolicy.Ignored,Qt.QSizePolicy.Ignored))
     self.worker = SingletonWorker(parent=self,cursor=True,sleep=50.,start=True)
     #self.worker.log.setLogLevel(self.worker.log.Debug)
     self.filters=('','','') #server/device/attribute
     self.devices=devices or []
     self.setValues(None)
     self.models = []
     self.current_item = None
     #self.connect(self, Qt.SIGNAL('customContextMenuRequested(const QPoint&)'), self.onContextMenu)
     self.popMenu = Qt.QMenu(self)
     self.actions = {
         'TestDevice': self.popMenu.addAction(Qt.QIcon(),"Test Device",self.onTestDevice),
         'ShowDeviceInfo': self.popMenu.addAction(Qt.QIcon(),"Show Device Info",self.onShowInfo),
         #'ShowDevicePanel': self.popMenu.addAction(Qt.QIcon(),"Show Info",self.onShowPanel),
         'ShowArchivingInfo': self.popMenu.addAction(Qt.QIcon(),"Show Archiving Info",self.onShowArchivingModes),
         #'Test Device': self.popMenu.addAction(Qt.QIcon(),"Test Device",self.onTestDevice)
         }
     #if hasattr(self,'setFrameStyle'):
         #self.setFrameStyle(self.Box)
     try:
         import PyTangoArchiving
         self.reader = PyTangoArchiving.Reader('*')
         #self.hreader = self.reader.configs['hdb']
         #self.treader = self.reader.configs.get('tdb',self.hreader)
     except:
         traceback.print_exc()
Пример #2
0
    def init_ui(self, parent, mainwindow):

        try:
            PARENT_CLASS.__init__(self, parent)
            self._connected = False
            self._ui = Ui_AlarmList()
            self._ui.setupUi(self)
            if mainwindow:
                mainwindow = self.init_mw(mainwindow)
            self.mainwindow = mainwindow

            url = os.path.dirname(
                panic.__file__) + '/gui/icon/panic-6-banner.png'
            trace('... splash ...')
            px = Qt.QPixmap(url)
            self.splash = Qt.QSplashScreen(px)
            self.splash.showMessage('initializing application...')
            self.splash.show()
            trace('showing splash ... %s' % px.size())

        except:
            print traceback.format_exc()

        if self.mainwindow:

            self.mainwindow.setWindowTitle(
                'PANIC %s (%s[%s]@%s)' %
                (panic.__RELEASE__, self.scope, self.default_regEx,
                 fn.get_tango_host().split(':')[0]))

            icon = '/gui/icon/panic-6-big.png'  #'.svg'
            url = os.path.dirname(panic.__file__) + icon
            px = Qt.QPixmap(url)
            self.mainwindow.setWindowIcon(Qt.QIcon(px))

        self.setExpertView(True)

        self._message = Qt.QMessageBox(self)
        self._message.setWindowTitle("Empty fields")
        self._message.setIcon(Qt.QMessageBox.Critical)
Пример #3
0
    def init_mw(self, tmw=None):
        """ 
        Method to initialize main window (menus and frames) 
        """
        t0 = time.time()
        alarmApp = self
        tmw = tmw if isinstance(tmw, Qt.QMainWindow) else CleanMainWindow()
        tmw.setWindowTitle('PANIC')
        tmw.menuBar = Qt.QMenuBar(tmw)
        tmw.toolsMenu = Qt.QMenu('Tools', tmw.menuBar)
        tmw.fileMenu = Qt.QMenu('File', tmw.menuBar)
        tmw.viewMenu = Qt.QMenu('View', tmw.menuBar)
        tmw.helpMenu = Qt.QMenu('Help', tmw.menuBar)

        tmw.setMenuBar(tmw.menuBar)
        [
            tmw.menuBar.addAction(a.menuAction())
            for a in (tmw.fileMenu, tmw.toolsMenu, tmw.helpMenu, tmw.viewMenu)
        ]
        toolbar = Qt.QToolBar(tmw)
        toolbar.setIconSize(Qt.QSize(20, 20))

        tmw.helpMenu.addAction(getThemeIcon("applications-system"), "Webpage",
                               lambda: os.system('konqueror %s &' % PANIC_URL))
        tmw.toolsMenu.addAction(getThemeIcon("applications-system"), "Jive",
                                lambda: os.system('jive &'))
        tmw.toolsMenu.addAction(getThemeIcon("applications-system"), "Astor",
                                lambda: os.system('astor &'))
        tmw.fileMenu.addAction(getThemeIcon(":/designer/back.png"),
                               "Export to CSV file", alarmApp.saveToFile)
        tmw.fileMenu.addAction(getThemeIcon(":/designer/forward.png"),
                               "Import from CSV file", alarmApp.loadFromFile)
        tmw.fileMenu.addAction(getThemeIcon(":/designer/filereader.png"),
                               "Use external editor", alarmApp.editFile)
        tmw.fileMenu.addAction(getThemeIcon("applications-system"), "Exit",
                               tmw.close)
        tmw.viewMenu.connect(tmw.viewMenu, Qt.SIGNAL('aboutToShow()'),
                             alarmApp.setViewMenu)

        from phonebook import PhoneBook
        alarmApp.tools['bookApp'] = WindowManager.addWindow(
            PhoneBook(container=tmw))
        tmw.toolsMenu.addAction(getThemeIcon("x-office-address-book"),
                                "PhoneBook", alarmApp.tools['bookApp'].show)
        toolbar.addAction(getThemeIcon("x-office-address-book"), "PhoneBook",
                          alarmApp.tools['bookApp'].show)

        trend_action = (getThemeIcon(":/designer/qwtplot.png"), 'Trend',
                        lambda: WindowManager.addWindow(
                            widgets.get_archive_trend(show=True)))
        tmw.toolsMenu.addAction(*trend_action)
        toolbar.addAction(*trend_action)

        alarmApp.tools['config'] = WindowManager.addWindow(
            dacWidget(container=tmw))
        tmw.toolsMenu.addAction(getThemeIcon("applications-system"),
                                "Advanced Configuration",
                                alarmApp.tools['config'].show)
        toolbar.addAction(getThemeIcon("applications-system"),
                          "Advanced Configuration",
                          alarmApp.tools['config'].show)

        toolbar.setMovable(False)
        toolbar.setFloatable(False)
        tmw.addToolBar(toolbar)

        if SNAP_ALLOWED:
            alarmApp.tools['history'] = WindowManager.addWindow(
                ahWidget(container=tmw))
            tmw.toolsMenu.addAction(getThemeIcon("office-calendar"),
                                    "Alarm History Viewer",
                                    alarmApp.tools['history'].show)
            toolbar.addAction(getThemeIcon("office-calendar"),
                              "Alarm History Viewer",
                              alarmApp.tools['history'].show)
        else:
            trace("Unable to load SNAP", 'History Viewer Disabled!')

        alarm_preview_action = (getThemeIcon("accessories-calculator"),
                                "Alarm Calculator",
                                lambda g=alarmApp: WindowManager.addWindow(
                                    AlarmPreview.showEmptyAlarmPreview(g)))
        [o.addAction(*alarm_preview_action) for o in (tmw.toolsMenu, toolbar)]

        try:
            import PyTangoArchiving.widget.ArchivingBrowser
            MSW = PyTangoArchiving.widget.ArchivingBrowser.ModelSearchWidget
            alarmApp.tools['finder'] = WindowManager.addWindow(MSW())
            tmw.toolsMenu.addAction(getThemeIcon("system-search"),
                                    "Attribute Finder",
                                    alarmApp.tools['finder'].show)
            toolbar.addAction(getThemeIcon("system-search"),
                              "Attribute Finder",
                              alarmApp.tools['finder'].show)
        except:
            print('PyTangoArchiving not available')
            #traceback.print_exc()

        import panic.gui.panel

        def showNewAlarmPanel(s=self, a=alarmApp):
            i = len([
                w for w in WindowManager.getWindowsNames()
                if w.startswith('panel')
            ])
            name = 'panel%d' % i
            a.tools[name] = WindowManager.addWindow(
                panic.gui.panel.QAlarmPanel())
            a.tools[name].setModel(s.view)
            a.tools[name].show()

        url = os.path.dirname(panic.__file__) + '/gui/icon/panel-view.png'
        panel_icon = Qt.QIcon(Qt.QPixmap(url))
        alarm_panel_action = (panel_icon, "Alarm Panel", showNewAlarmPanel)
        [o.addAction(*alarm_panel_action) for o in (tmw.toolsMenu, toolbar)]

        import panic.gui.views
        alarmApp.tools['rawview'] = WindowManager.addWindow(
            panic.gui.views.ViewRawBrowser())
        #url = os.path.dirname(panic.__file__)+'/gui/icon/panel-view.png'
        #panel_icon = Qt.QIcon(Qt.QPixmap(url))
        alarm_panel_action = (
            getThemeIcon('actions:leftjust.svg'), "RawView",
            lambda s=self: alarmApp.tools['rawview'].setModel(self))
        [o.addAction(*alarm_panel_action) for o in (tmw.toolsMenu, )]

        print('Toolbars created after %s seconds' % (time.time() - t0))
        tmw.setCentralWidget(alarmApp)
        tmw.show()
        return tmw
Пример #4
0
    def __init__(self,
                 parent=None,
                 filters='',
                 options=None,
                 mainwindow=None,
                 api=None):

        options = options or {}
        if not fn.isDictionary(options):
            options = dict(
                (o.replace('-', '').split('=')[0], o.split('=', 1)[-1])
                for o in options)

        trace('In AlarmGUI(%s): %s' % (filters, options))

        self.last_reload = 0
        self.AlarmRows = {}
        self.timeSortingEnabled = None
        self.changed = True
        self.severities = []  #List to keep severities currently visible

        self.expert = False
        self.tools = {}  #Widgets dictionary

        self.scope = options.get('scope', '*')  #filters or '*'
        self.default_regEx = options.get('default', filters or '*')
        self.regEx = self.default_regEx
        self.init_ui(parent, mainwindow)  #init_mw is called here
        self.NO_ICON = Qt.QIcon()

        refresh = int(options.get('refresh', self.REFRESH_TIME))
        self.REFRESH_TIME = refresh
        #AlarmRow.REFRESH_TIME = refresh

        #if self.regEx not in ('','*'):
        #print 'Setting RegExp filter: %s'%self.regEx
        #self._ui.regExLine.setText(str(self.regEx))

        self.api = api or panic.AlarmAPI(self.scope)
        trace('AlarmGUI(%s): api done' % self.scope)

        # @TODO: api-based views are not multi-host
        self.view = panic.view.AlarmView(api=self.api,
                                         scope=self.scope,
                                         refresh=self.REFRESH_TIME / 1e3,
                                         events=False,
                                         verbose=1)
        trace('AlarmGUI(): view done')

        self.snapi = None
        self.ctx_names = []

        if not self.api.keys(): trace('NO ALARMS FOUND IN DATABASE!?!?')
        #AlarmRow.TAG_SIZE = 1+max([len(k) for k in self.api] or [40])

        N = len(self.getAlarms())
        trace('AlarmGUI(): %d alarms' % N)
        if 1:  #N<150:
            #self._ui.sevDebugCheckBox.setChecked(True)
            self._ui.activeCheckBox.setChecked(False)
        #else:
        #self._ui.sevDebugCheckBox.setChecked(False)
        #self._ui.activeCheckBox.setChecked(True)

        if N <= self.MAX_ALARMS: self.USE_EVENT_REFRESH = True

        self.init_timers()
        self.init_filters()

        trace('AlarmGUI(): signals done')
        ## connection of ui signals is delayed until first onRefresh()

        self.updateStatusLabel()

        trace('AlarmGUI(): done')
Пример #5
0
    def setFontsAndColors(item, alarm):

        state, severity = alarm.get_state(), alarm.severity
        severity = severity or panic.DEFAULT_SEVERITY
        color = Qt.QColor("black")
        background = Qt.QColor("white")
        bold = False
        icon = ""

        if state in ('OOSRV', ):
            color = Qt.QColor("grey").light()
            background = Qt.QColor("white")

        elif state in ('ERROR', ):
            color = Qt.QColor("red")
            background = Qt.QColor("white")

        elif state in ACTIVE_STATES:

            if severity in ('ERROR', ):
                color = Qt.QColor("white")
                background = Qt.QColor("red").lighter()

            elif severity in ('ALARM', ):
                background = Qt.QColor("red").lighter()

            elif severity == 'WARNING':
                background = Qt.QColor("orange").lighter()

            elif severity in ('INFO', 'DEBUG'):
                background = Qt.QColor("yellow").lighter()

        elif state in ('DSUPR', 'SHLVD'):
            color = Qt.QColor("grey").light()
            background = Qt.QColor("white")

        elif state == 'NORM':
            color = Qt.QColor("green").lighter()
            background = Qt.QColor("white")

        else:
            raise Exception('UnknownState:%s' % state)

        icon = getIconForAlarm(alarm)

        if (fandango.now() - alarm.get_time()) < 60:
            bold = True

        alarmicon = getThemeIcon(icon) if icon else None
        #tracer('setFontsAndColors(%s,%s,%s,%s,%s)'
        #%(alarm.tag,state,icon,background,bold))
        item.setIcon(alarmicon or Qt.QIcon())
        item.setTextColor(color)
        item.setBackgroundColor(background)
        f = item.font()
        f.setFixedPitch(True)
        f.setBold(bold)
        item.setFont(f)

        status = [
            'Severity: ' + alarm.severity,
            'Formula: ' + alarm.formula,
            'Description: %s' % alarm.description,
            'Alarm Device: %s' % alarm.device,
            'Archived: %s' % ('Yes' if 'SNAP' in alarm.receivers else 'No'),
        ]
        for t in ('last_error', 'acknowledged', 'disabled', 'sortkey'):
            v = getattr(alarm, t, None)
            if v:
                status.append('%s%s: %s' % (t[0].upper(), t[1:], shortstr(v)))

        item.setToolTip('\n'.join(status))

        try:
            forms = []
            for f in WindowManager.WINDOWS:
                if isinstance(f, AlarmForm):
                    tag = f.getCurrentAlarm().tag
                    if tag == alarm.tag:
                        forms.append(f)
            if forms:
                #@TODO: these checks will be not needed after full update
                tracer("\tupdating %d %s forms" % (len(forms), alarm))
                [f.valueChanged(forced=True) for f in forms]
            else:
                pass  #tracer("no forms open?")
        except:
            tracer(traceback.format_exc())

        return item
Пример #6
0
    def setModel(self,
                 model=None,
                 rows=0,
                 cols=0,
                 side=0,
                 fontsize=0,
                 **kwargs):
        print('QAlarmPanel.setModel(%s)' % model)
        import panic, math

        if isinstance(model, AlarmView):
            self.view = model
            self.api = self.view.api
        else:  #if fd.isString(model):
            self.api = panic.AlarmAPI(model, extended=True)
            self.view = AlarmView(api=self.api, verbose=False)

        self.tags = self.view.sort(sortkey=('priority', 'tag'), keep=False)
        self.alarms = self.view.alarms
        self.old_devs = set()
        self.actives = []
        self.panels = []
        self.setCurrentAlarm(None)

        self.fontsize = fontsize

        if rows and not cols:
            self.rows = int(rows)
            self.cols = int(math.ceil((1 + len(self.tags)) / self.rows))
        elif cols and not rows:
            self.rows = int(math.ceil((1 + len(self.tags)) / cols))
            self.cols = int(cols)
        else:
            self.cols = int(cols or math.ceil(math.sqrt(1 + len(self.tags))))
            self.rows = int(
                rows or ((self.cols - 1) if self.cols *
                         (self.cols - 1) >= 1 + len(self.tags) else self.cols))

        self.setLayout(Qt.QGridLayout())
        self.labels = []
        for i in range(self.rows):
            self.labels.append([])
            for j in range(self.cols):
                self.labels[i].append(QAlarmPanelLabel(self))
                self.layout().addWidget(self.labels[i][j], i, j, 1, 1)
        self.logo = self.labels[-1][-1]
        self.logo.setClickHook(self.showGUI)

        self._title = 'PANIC Alarm Panel (%s)' % str(model
                                                     or fd.get_tango_host())
        self.setWindowTitle(self._title)
        url = os.path.dirname(panic.__file__) + '/gui/icon/panic-6-big.png'
        px = Qt.QPixmap(url)
        self.setWindowIcon(Qt.QIcon(px))
        #self.labels[self.rows-1][self.cols-1].resize(50,50)

        print('QAlarmPanel(%s): %d alarms , %d cols, %d rows: %s' %
              (model, len(self.tags), self.cols, self.rows,
               fd.log.shortstr(self.tags)) + '\n' + '#' * 80)

        self.refreshTimer = Qt.QTimer()
        Qt.QObject.connect(self.refreshTimer, Qt.SIGNAL("timeout()"),
                           self.updateAlarms)

        self.refreshTimer.start(self.REFRESH_TIME)
        side = side or (min((self.rows, self.cols)) == 1 and 50) or 50  #70#120
        if all((cols, rows, side)):
            width, height = side * cols, side * rows
            self.logo.setPixmap(px.scaled(side, side))
        else:
            width, height = min((800, side * self.cols)), min(
                (800, side * self.rows))
            self.logo.setPixmap(px.scaled(side, side))  #70,70))
            #px.scaled(height/self.rows,height/self.rows))
        #if (width/self.rows)>=50:
        self.resize(width, height)
        self.show()