예제 #1
0
    def _add_log_box(self):
        box = QGroupBox("Application log")
        box.setLayout(QHBoxLayout(box))

        self.log_area = QTextBrowser(box)
        self.log_area.setLineWrapMode(QTextEdit.NoWrap)

        box.layout().addWidget(self.log_area)
        self.layout().addWidget(box)
예제 #2
0
 def _add_log_box(self):
     box = QGroupBox("Application log")
     box.setLayout(QHBoxLayout(box))
     
     self.log_area = QTextBrowser(box)
     self.log_area.setLineWrapMode(QTextEdit.NoWrap)
     
     box.layout().addWidget(self.log_area)
     self.layout().addWidget(box)
    def _initAppletDrawerUic(self):
        super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic()

        from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout
        group = QGroupBox("Export Object Feature Table", self.drawer)
        group.setLayout(QVBoxLayout())
        self.drawer.layout().addWidget(group)

        btn = QPushButton("Configure and export", group)
        btn.clicked.connect(self.show_export_dialog)
        group.layout().addWidget(btn)
    def _initAppletDrawerUic(self):
        super(TrackingBaseDataExportGui, self)._initAppletDrawerUic()

        from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout
        group = QGroupBox("Export Object Feature and Tracking Table", self.drawer)
        group.setLayout(QVBoxLayout())
        self.drawer.layout().addWidget(group)

        btn = QPushButton("Configure and export", group)
        btn.clicked.connect(self.show_export_dialog)
        group.layout().addWidget(btn)
예제 #5
0
 def _add_additional_prefs(self):
     box = QGroupBox("Additional Preferences")
     box.setLayout(QHBoxLayout(box))
             
     log_btn = QPushButton("View Log", box)
     log_btn.clicked.connect(self.open_log_file)
     reset_btn = QPushButton("Reset Settings", box)
     reset_btn.clicked.connect(Settings().reset)
             
     box.layout().addWidget(log_btn)
     box.layout().addWidget(reset_btn)
     
     self.layout().addWidget(box)
예제 #6
0
    def _add_additional_prefs(self):
        box = QGroupBox("Additional Preferences")
        box.setLayout(QHBoxLayout(box))

        log_btn = QPushButton("View Log", box)
        log_btn.clicked.connect(self.open_log_file)
        reset_btn = QPushButton("Reset Settings", box)
        reset_btn.clicked.connect(Settings().reset)

        box.layout().addWidget(log_btn)
        box.layout().addWidget(reset_btn)

        self.layout().addWidget(box)
예제 #7
0
    def _add_dota_box(self):
        box = QGroupBox("Dota Location")
        box.setLayout(QHBoxLayout(box))
        
        self.dota_path = QLineEdit(box)
        self.dota_path.setReadOnly(True)
        self.dota_path.setText(Settings().get("dota_path"))
        
        change_btn = QPushButton("Change...", box)
        change_btn.clicked.connect(self.change_dota_path)

        box.layout().addWidget(self.dota_path)
        box.layout().addWidget(change_btn)
        
        self.layout().addWidget(box)
예제 #8
0
    def _add_dota_box(self):
        box = QGroupBox("Dota Location")
        box.setLayout(QHBoxLayout(box))

        self.dota_path = QLineEdit(box)
        self.dota_path.setReadOnly(True)
        self.dota_path.setText(Settings().get("dota_path"))

        change_btn = QPushButton("Change...", box)
        change_btn.clicked.connect(self.change_dota_path)

        box.layout().addWidget(self.dota_path)
        box.layout().addWidget(change_btn)

        self.layout().addWidget(box)
예제 #9
0
    def __init__(self, parent=None, signalManager=None,
                 title="CSV File Import"):
        OWWidget.__init__(self, parent, signalManager, title,
                          wantMainArea=False, noReport=True)

        self.symbol_DC = ""
        self.symbol_DK = ""

        #: List of recent opened files.
        self.recent_files = []
        #: Current selected file name
        self.selected_file = None
        #: Variable reuse flag
        self.create_new_on = 2
        #: Display advanced var reuse options
        self.show_advanced = False

        self.loadSettings()

        self.recent_files = filter(os.path.exists, self.recent_files)

        self._loader = None
        self._invalidated = False
        self._datareport = None

        layout = QHBoxLayout()
        OWGUI.widgetBox(self.controlArea, "File", orientation=layout)

        icons = standard_icons(self)

        self.recent_combo = QComboBox(
            self, objectName="recent_combo",
            toolTip="Recent files.",
            activated=self.activate_recent
        )
        cb_append_file_list(self.recent_combo, self.recent_files)

        self.recent_combo.insertSeparator(self.recent_combo.count())
        self.recent_combo.addItem(u"Browse documentation data sets…")

        self.browse_button = QPushButton(
            u"…",
            icon=icons.dir_open_icon, toolTip="Browse filesystem",
            clicked=self.browse
        )

        self.reload_button = QPushButton(
            "Reload", icon=icons.reload_icon,
            toolTip="Reload the selected file", clicked=self.reload,
            default=True
        )

        layout.addWidget(self.recent_combo, 2)
        layout.addWidget(self.browse_button)
        layout.addWidget(self.reload_button)

        ###########
        # Info text
        ###########
        box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True)
        self.infoa = OWGUI.widgetLabel(box, "No data loaded.")
        self.infob = OWGUI.widgetLabel(box, " ")
        self.warnings = OWGUI.widgetLabel(box, " ")

        # Set word wrap so long warnings won't expand the widget
        self.warnings.setWordWrap(True)
        self.warnings.setSizePolicy(QSizePolicy.Ignored,
                                    QSizePolicy.MinimumExpanding)

        advanced = QGroupBox(
            "Advanced Settings", checkable=True, checked=self.show_advanced
        )
        advanced.setLayout(QVBoxLayout())

        def set_group_visible(groupbox, state):
            layout = groupbox.layout()
            for i in range(layout.count()):
                item = layout.itemAt(i)
                widget = item.widget()
                if widget is not None:
                    widget.setVisible(state)
            groupbox.setFlat(not state)

        def toogle_advanced(state):
            self.show_advanced = state
            set_group_visible(advanced, state)
            self.layout().activate()
            QApplication.instance().processEvents()
            QTimer.singleShot(0, self.adjustSize)

        advanced.toggled.connect(toogle_advanced)

        self.taboptions = QWidget()
        self.taboptions.setLayout(QVBoxLayout())
        box = QGroupBox("Missing Value Symbols", flat=True)
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        form.addRow(
            "Don't care:",
            OWGUI.lineEdit(None, self, "symbol_DC",
                           tooltip="Default values: '~' or '*'"))
        form.addRow(
            "Don't know:",
            OWGUI.lineEdit(None, self, "symbol_DK",
                           tooltip="Default values: empty fields (space), "
                                   "'?' or 'NA'"))
        box.setLayout(form)
        advanced.layout().addWidget(box)

        rb = OWGUI.radioButtonsInBox(
            advanced, self, "create_new_on",
            box="New Attributes",
            callback=self._invalidate,
            label=u"Create a new attribute when existing attribute(s) …",
            btnLabels=[u"Have mismatching order of values",
                       u"Have no common values with the new (recommended)",
                       u"Miss some values of the new attribute",
                       u"… Always create a new attribute"]
        )
        rb.setFlat(True)
        self.controlArea.layout().addWidget(advanced)

        button_box = QDialogButtonBox(orientation=Qt.Horizontal)
        self.import_options_button = QPushButton(
            u"Import Options…", enabled=False
        )
        self.import_options_button.pressed.connect(self._activate_import_dialog)
        button_box.addButton(
            self.import_options_button, QDialogButtonBox.ActionRole
        )
        button_box.addButton(
            QPushButton("&Report", pressed=self.reportAndFinish),
            QDialogButtonBox.ActionRole
        )
        self.controlArea.layout().addWidget(button_box)

        OWGUI.rubber(self.controlArea)

        set_group_visible(advanced, self.show_advanced)

        if self.recent_files and self.recent_files[0] == self.selected_file:
            QTimer.singleShot(
                0, lambda: self.activate_recent(0)
            )
        else:
            self.selected_file = None
            self.recent_combo.setCurrentIndex(-1)
예제 #10
0
    def __init__(self,
                 parent=None,
                 signalManager=None,
                 title="CSV File Import"):
        OWWidget.__init__(self,
                          parent,
                          signalManager,
                          title,
                          wantMainArea=False,
                          noReport=True)

        self.symbol_DC = ""
        self.symbol_DK = ""

        #: List of recent opened files.
        self.recent_files = []
        #: Current selected file name
        self.selected_file = None
        #: Variable reuse flag
        self.create_new_on = 2
        #: Display advanced var reuse options
        self.show_advanced = False

        self.loadSettings()

        self.recent_files = filter(os.path.exists, self.recent_files)

        self._loader = None
        self._invalidated = False
        self._datareport = None

        layout = QHBoxLayout()
        OWGUI.widgetBox(self.controlArea, "File", orientation=layout)

        icons = standard_icons(self)

        self.recent_combo = QComboBox(self,
                                      objectName="recent_combo",
                                      toolTip="Recent files.",
                                      activated=self.activate_recent)
        cb_append_file_list(self.recent_combo, self.recent_files)

        self.recent_combo.insertSeparator(self.recent_combo.count())
        self.recent_combo.addItem(u"Browse documentation data sets…")

        self.browse_button = QPushButton(u"…",
                                         icon=icons.dir_open_icon,
                                         toolTip="Browse filesystem",
                                         clicked=self.browse)

        self.reload_button = QPushButton("Reload",
                                         icon=icons.reload_icon,
                                         toolTip="Reload the selected file",
                                         clicked=self.reload,
                                         default=True)

        layout.addWidget(self.recent_combo, 2)
        layout.addWidget(self.browse_button)
        layout.addWidget(self.reload_button)

        ###########
        # Info text
        ###########
        box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True)
        self.infoa = OWGUI.widgetLabel(box, "No data loaded.")
        self.infob = OWGUI.widgetLabel(box, " ")
        self.warnings = OWGUI.widgetLabel(box, " ")

        # Set word wrap so long warnings won't expand the widget
        self.warnings.setWordWrap(True)
        self.warnings.setSizePolicy(QSizePolicy.Ignored,
                                    QSizePolicy.MinimumExpanding)

        advanced = QGroupBox("Advanced Settings",
                             checkable=True,
                             checked=self.show_advanced)
        advanced.setLayout(QVBoxLayout())

        def set_group_visible(groupbox, state):
            layout = groupbox.layout()
            for i in range(layout.count()):
                item = layout.itemAt(i)
                widget = item.widget()
                if widget is not None:
                    widget.setVisible(state)
            groupbox.setFlat(not state)

        def toogle_advanced(state):
            self.show_advanced = state
            set_group_visible(advanced, state)
            self.layout().activate()
            QApplication.instance().processEvents()
            QTimer.singleShot(0, self.adjustSize)

        advanced.toggled.connect(toogle_advanced)

        self.taboptions = QWidget()
        self.taboptions.setLayout(QVBoxLayout())
        box = QGroupBox("Missing Value Symbols", flat=True)
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        form.addRow(
            "Don't care:",
            OWGUI.lineEdit(None,
                           self,
                           "symbol_DC",
                           tooltip="Default values: '~' or '*'"))
        form.addRow(
            "Don't know:",
            OWGUI.lineEdit(None,
                           self,
                           "symbol_DK",
                           tooltip="Default values: empty fields (space), "
                           "'?' or 'NA'"))
        box.setLayout(form)
        advanced.layout().addWidget(box)

        rb = OWGUI.radioButtonsInBox(
            advanced,
            self,
            "create_new_on",
            box="New Attributes",
            callback=self._invalidate,
            label=u"Create a new attribute when existing attribute(s) …",
            btnLabels=[
                u"Have mismatching order of values",
                u"Have no common values with the new (recommended)",
                u"Miss some values of the new attribute",
                u"… Always create a new attribute"
            ])
        rb.setFlat(True)
        self.controlArea.layout().addWidget(advanced)

        button_box = QDialogButtonBox(orientation=Qt.Horizontal)
        self.import_options_button = QPushButton(u"Import Options…",
                                                 enabled=False)
        self.import_options_button.pressed.connect(
            self._activate_import_dialog)
        button_box.addButton(self.import_options_button,
                             QDialogButtonBox.ActionRole)
        button_box.addButton(
            QPushButton("&Report", pressed=self.reportAndFinish),
            QDialogButtonBox.ActionRole)
        self.controlArea.layout().addWidget(button_box)

        OWGUI.rubber(self.controlArea)

        set_group_visible(advanced, self.show_advanced)

        if self.recent_files and self.recent_files[0] == self.selected_file:
            QTimer.singleShot(0, lambda: self.activate_recent(0))
        else:
            self.selected_file = None
            self.recent_combo.setCurrentIndex(-1)
예제 #11
0
class LeapWindow(QMainWindow):
    #XXX tbd: refactor into model / view / controller
    #and put in its own modules...

    newLogLine = pyqtSignal([str])
    statusChange = pyqtSignal([object])

    def __init__(self, opts):
        super(LeapWindow, self).__init__()
        self.debugmode = getattr(opts, 'debug', False)

        self.vpn_service_started = False

        self.createWindowHeader()
        self.createIconGroupBox()

        self.createActions()
        self.createTrayIcon()
        if self.debugmode:
            self.createLogBrowser()

        # create timer
        self.timer = QTimer()

        # bind signals

        self.trayIcon.activated.connect(self.iconActivated)
        self.newLogLine.connect(self.onLoggerNewLine)
        self.statusChange.connect(self.onStatusChange)
        self.timer.timeout.connect(self.onTimerTick)

        widget = QWidget()
        self.setCentralWidget(widget)

        # add widgets to layout
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.headerBox)
        mainLayout.addWidget(self.statusIconBox)
        if self.debugmode:
            mainLayout.addWidget(self.statusBox)
            mainLayout.addWidget(self.loggerBox)
        widget.setLayout(mainLayout)

        #
        # conductor is in charge of all
        # vpn-related configuration / monitoring.
        # we pass a tuple of signals that will be
        # triggered when status changes.
        #
        config_file = getattr(opts, 'config_file', None)
        self.conductor = EIPConductor(
            watcher_cb=self.newLogLine.emit,
            config_file=config_file,
            status_signals=(self.statusChange.emit, ))

        self.trayIcon.show()

        self.setWindowTitle("Leap")
        self.resize(400, 300)

        self.set_statusbarMessage('ready')

        if self.conductor.autostart:
            self.start_or_stopVPN()

    def closeEvent(self, event):
        """
        redefines close event (persistent window behaviour)
        """
        if self.trayIcon.isVisible() and not self.debugmode:
            QMessageBox.information(self, "Systray",
                                    "The program will keep running "
                                    "in the system tray. To "
                                    "terminate the program, choose "
                                    "<b>Quit</b> in the "
                                    "context menu of the system tray entry.")
            self.hide()
            event.ignore()
        if self.debugmode:
            self.cleanupAndQuit()

    def setIcon(self, name):
        icon = self.Icons.get(name)
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)

    def setToolTip(self):
        """
        get readable status and place it on systray tooltip
        """
        status = self.conductor.status.get_readable_status()
        self.trayIcon.setToolTip(status)

    def iconActivated(self, reason):
        """
        handles left click, left double click
        showing the trayicon menu
        """
        #XXX there's a bug here!
        #menu shows on (0,0) corner first time,
        #until double clicked at least once.
        if reason in (QSystemTrayIcon.Trigger,
                      QSystemTrayIcon.DoubleClick):
            self.trayIconMenu.show()

    def createWindowHeader(self):
        """
        description lines for main window
        """
        #XXX good candidate to refactor out! :)
        self.headerBox = QGroupBox()
        self.headerLabel = QLabel("<font size=40><b>E</b>ncryption \
<b>I</b>nternet <b>P</b>roxy</font>")
        self.headerLabelSub = QLabel("<i>trust your \
technolust</i>")

        pixmap = QPixmap(':/images/leapfrog.jpg')
        frog_lbl = QLabel()
        frog_lbl.setPixmap(pixmap)

        headerLayout = QHBoxLayout()
        headerLayout.addWidget(frog_lbl)
        headerLayout.addWidget(self.headerLabel)
        headerLayout.addWidget(self.headerLabelSub)
        headerLayout.addStretch()
        self.headerBox.setLayout(headerLayout)

    def getIcon(self, icon_name):
        # XXX get from connection dict
        icons = {'disconnected': 0,
                 'connecting': 1,
                 'connected': 2}
        return icons.get(icon_name, None)

    def createIconGroupBox(self):
        """
        dummy icongroupbox
        (to be removed from here -- reference only)
        """
        icons = {
            'disconnected': ':/images/conn_error.png',
            'connecting': ':/images/conn_connecting.png',
            'connected': ':/images/conn_connected.png'
        }
        con_widgets = {
            'disconnected': QLabel(),
            'connecting': QLabel(),
            'connected': QLabel(),
        }
        con_widgets['disconnected'].setPixmap(
            QPixmap(icons['disconnected']))
        con_widgets['connecting'].setPixmap(
            QPixmap(icons['connecting']))
        con_widgets['connected'].setPixmap(
            QPixmap(icons['connected'])),
        self.ConnectionWidgets = con_widgets

        con_icons = {
            'disconnected': QIcon(icons['disconnected']),
            'connecting': QIcon(icons['connecting']),
            'connected': QIcon(icons['connected'])
        }
        self.Icons = con_icons

        self.statusIconBox = QGroupBox("Connection Status")
        statusIconLayout = QHBoxLayout()
        statusIconLayout.addWidget(self.ConnectionWidgets['disconnected'])
        statusIconLayout.addWidget(self.ConnectionWidgets['connecting'])
        statusIconLayout.addWidget(self.ConnectionWidgets['connected'])
        statusIconLayout.itemAt(1).widget().hide()
        statusIconLayout.itemAt(2).widget().hide()
        self.statusIconBox.setLayout(statusIconLayout)

    def createActions(self):
        """
        creates actions to be binded to tray icon
        """
        self.connectVPNAction = QAction("Connect to &VPN", self,
                                        triggered=self.hide)
        # XXX change action name on (dis)connect
        self.dis_connectAction = QAction("&(Dis)connect", self,
                                         triggered=self.start_or_stopVPN)
        self.minimizeAction = QAction("Mi&nimize", self,
                                      triggered=self.hide)
        self.maximizeAction = QAction("Ma&ximize", self,
                                      triggered=self.showMaximized)
        self.restoreAction = QAction("&Restore", self,
                                     triggered=self.showNormal)
        self.quitAction = QAction("&Quit", self,
                                  triggered=self.cleanupAndQuit)

    def createTrayIcon(self):
        """
        creates the tray icon
        """
        self.trayIconMenu = QMenu(self)

        self.trayIconMenu.addAction(self.connectVPNAction)
        self.trayIconMenu.addAction(self.dis_connectAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.minimizeAction)
        self.trayIconMenu.addAction(self.maximizeAction)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.quitAction)

        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)

    def createLogBrowser(self):
        """
        creates Browser widget for displaying logs
        (in debug mode only).
        """
        self.loggerBox = QGroupBox()
        logging_layout = QVBoxLayout()
        self.logbrowser = QTextBrowser()

        startStopButton = QPushButton("&Connect")
        startStopButton.clicked.connect(self.start_or_stopVPN)
        self.startStopButton = startStopButton

        logging_layout.addWidget(self.logbrowser)
        logging_layout.addWidget(self.startStopButton)
        self.loggerBox.setLayout(logging_layout)

        # status box

        self.statusBox = QGroupBox()
        grid = QGridLayout()

        self.updateTS = QLabel('')
        self.status_label = QLabel('Disconnected')
        self.ip_label = QLabel('')
        self.remote_label = QLabel('')

        tun_read_label = QLabel("tun read")
        self.tun_read_bytes = QLabel("0")
        tun_write_label = QLabel("tun write")
        self.tun_write_bytes = QLabel("0")

        grid.addWidget(self.updateTS, 0, 0)
        grid.addWidget(self.status_label, 0, 1)
        grid.addWidget(self.ip_label, 1, 0)
        grid.addWidget(self.remote_label, 1, 1)
        grid.addWidget(tun_read_label, 2, 0)
        grid.addWidget(self.tun_read_bytes, 2, 1)
        grid.addWidget(tun_write_label, 3, 0)
        grid.addWidget(self.tun_write_bytes, 3, 1)

        self.statusBox.setLayout(grid)

    @pyqtSlot(str)
    def onLoggerNewLine(self, line):
        """
        simple slot: writes new line to logger Pane.
        """
        if self.debugmode:
            self.logbrowser.append(line[:-1])

    def set_statusbarMessage(self, msg):
        self.statusBar().showMessage(msg)

    @pyqtSlot(object)
    def onStatusChange(self, status):
        """
        slot for status changes. triggers new signals for
        updating icon, status bar, etc.
        """

        print('STATUS CHANGED! (on Qt-land)')
        print('%s -> %s' % (status.previous, status.current))
        icon_name = self.conductor.get_icon_name()
        self.setIcon(icon_name)
        print 'icon = ', icon_name

        # change connection pixmap widget
        self.setConnWidget(icon_name)

    def setConnWidget(self, icon_name):
        #print 'changing icon to %s' % icon_name
        oldlayout = self.statusIconBox.layout()

        # XXX reuse with icons
        # XXX move states to StateWidget
        states = {"disconnected": 0,
                  "connecting": 1,
                  "connected": 2}

        for i in range(3):
            oldlayout.itemAt(i).widget().hide()
        new = states[icon_name]
        oldlayout.itemAt(new).widget().show()

    @pyqtSlot()
    def start_or_stopVPN(self):
        """
        stub for running child process with vpn
        """
        if self.vpn_service_started is False:
            self.conductor.connect()
            if self.debugmode:
                self.startStopButton.setText('&Disconnect')
            self.vpn_service_started = True

            # XXX what is optimum polling interval?
            # too little is overkill, too much
            # will miss transition states..

            self.timer.start(250.0)
            return
        if self.vpn_service_started is True:
            self.conductor.disconnect()
            # FIXME this should trigger also
            # statuschange event. why isn't working??
            if self.debugmode:
                self.startStopButton.setText('&Connect')
            self.vpn_service_started = False
            self.timer.stop()
            return

    @pyqtSlot()
    def onTimerTick(self):
        self.statusUpdate()

    @pyqtSlot()
    def statusUpdate(self):
        """
        called on timer tick
        polls status and updates ui with real time
        info about transferred bytes / connection state.
        """
        # XXX it's too expensive to poll
        # continously. move to signal events instead.

        if not self.vpn_service_started:
            return

        # XXX remove all access to manager layer
        # from here.
        if self.conductor.manager.with_errors:
            #XXX how to wait on pkexec???
            #something better that this workaround, plz!!
            time.sleep(10)
            print('errors. disconnect.')
            self.start_or_stopVPN()  # is stop

        state = self.conductor.poll_connection_state()
        if not state:
            return

        ts, con_status, ok, ip, remote = state
        self.set_statusbarMessage(con_status)
        self.setToolTip()

        ts = time.strftime("%a %b %d %X", ts)
        if self.debugmode:
            self.updateTS.setText(ts)
            self.status_label.setText(con_status)
            self.ip_label.setText(ip)
            self.remote_label.setText(remote)

        # status i/o

        status = self.conductor.manager.get_status_io()
        if status and self.debugmode:
            #XXX move this to systray menu indicators
            ts, (tun_read, tun_write, tcp_read, tcp_write, auth_read) = status
            ts = time.strftime("%a %b %d %X", ts)
            self.updateTS.setText(ts)
            self.tun_read_bytes.setText(tun_read)
            self.tun_write_bytes.setText(tun_write)

    def cleanupAndQuit(self):
        """
        cleans state before shutting down app.
        """
        # TODO:make sure to shutdown all child process / threads
        # in conductor
        self.conductor.cleanup()
        qApp.quit()
예제 #12
0
파일: snmpd.py 프로젝트: maximerobin/Ufwi
class SnmpdWidget(QFrame):
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.parent = parent

        form = QVBoxLayout(self)
        title = QLabel("<H1>%s</H1>" % self.tr('SNMP Server Configuration'))
        form.addWidget(title)

        # Enable:
        self.enable_line = QWidget()
        self.enable_line.setLayout(QFormLayout())
        self.enable_server = QCheckBox()
        self.connect(self.enable_server, SIGNAL('stateChanged(int)'),
                     parent.setEnabled)
        self.enable_line.layout().addRow(self.tr("Enable SNMP server"),
                                         self.enable_server)
        form.addWidget(self.enable_line)
        parent.main_window.writeAccessNeeded(self.enable_server)

        # V2c list (source network, community):
        self.v2c_list_groupbox = QGroupBox()
        self.v2c_list_groupbox.setTitle(self.tr("SNMPv2c access list"))
        self.v2c_list_groupbox.setLayout(QVBoxLayout())
        self.v2c_list_edit = ListEdit()
        self.v2c_list_edit.headers = self.getColumnLabelsV2c()
        self.v2c_list_edit.readOnly = self.parent.main_window.readonly
        self.v2c_list_edit.editInPopup = True
        self.v2c_list_edit.displayUpDown = False
        self.v2c_list_edit.setColDelegate(self.createDelegateForColumnV2c)
        self.connect(self.v2c_list_edit, SIGNAL('itemDeleted'),
                     self.setModified)
        self.connect(self.v2c_list_edit, SIGNAL('itemAdded'),
                     self.setModified)
        self.connect(self.v2c_list_edit, SIGNAL('itemModified'),
                     self.setModified)
        self.v2c_list_groupbox.layout().addWidget(self.v2c_list_edit)
        parent.main_window.writeAccessNeeded(self.v2c_list_edit)
        form.addWidget(self.v2c_list_groupbox)

        # V3 list (username, auth passphrase, auth proto, privacy key, algo):
        self.v3_list_groupbox = QGroupBox()
        self.v3_list_groupbox.setTitle(self.tr("SNMPv3 access list"))
        self.v3_list_groupbox.setLayout(QVBoxLayout())
        self.v3_list_edit = ListEdit()
        self.v3_list_edit.readOnly = self.parent.main_window.readonly
        self.v3_list_edit.headers = self.getColumnLabelsV3()
        self.v3_list_edit.displayUpDown = False
        self.v3_list_edit.editInPopup = True
        self.v3_list_edit.setColDelegate(self.createDelegateForColumnV3)
        self.connect(self.v3_list_edit, SIGNAL('itemDeleted'),
                     self.setModified)
        self.connect(self.v3_list_edit, SIGNAL('itemAdded'),
                     self.setModified)
        self.connect(self.v3_list_edit, SIGNAL('itemModified'),
                     self.setModified)
        self.v3_list_groupbox.layout().addWidget(self.v3_list_edit)
        parent.main_window.writeAccessNeeded(self.v3_list_edit)
        form.addWidget(self.v3_list_groupbox)

    def createDelegateForColumnV2c(self, column):
        if column == INDEX_V2C_SOURCE:
            return EditColumnDelegate(NetworkEdit)
        return EditColumnDelegate(CommunityEdit)

    def createDelegateForColumnV3(self, column):
        if column == INDEX_V3_USERNAME:
            return EditColumnDelegate(UsernameEdit)
        elif column == INDEX_V3_AUTHENTICATION_PASS:
            return PasswordColumnDelegate(PassEdit)
        elif column == INDEX_V3_AUTHENTICATION_PROTO:
            return ComboBoxColumnDelegate(("SHA", "MD5"))
        elif column == INDEX_V3_ENCRYPTION_PASS:
            return PasswordColumnDelegate(PassEdit)
        elif column == INDEX_V3_ENCRYPTION_ALGO:
            return ComboBoxColumnDelegate(("AES", "DES"))
        return EditColumnDelegate(PassEdit)

    def getColumnLabelsV2c(self):
        return [self.tr("Source host or network"), self.tr("Community")]

    def getColumnLabelsV3(self):
        return [self.tr("Username"), self.tr("Passphrase"),
                self.tr("Protocol"), self.tr("Privacy key"),
                self.tr("Encrypting algorithm")]

    def setModified(self, *unused):
        self.parent.setModified()
예제 #13
0
    def __init__(self, mainwin):
        KDialog.__init__(self, mainwin)
        self.jobs = []
        self.mainwin = mainwin
        self.setButtons(KDialog.ButtonCode(
            KDialog.Try | KDialog.Help |
            KDialog.Details | KDialog.Reset |
            KDialog.Ok | KDialog.Cancel))
        self.setButtonIcon(KDialog.Try, KIcon("run-lilypond"))
        self.setCaption(i18n("Create blank staff paper"))
        self.setHelp("blankpaper")
        self.setDefaultButton(KDialog.Ok)

        layout = QGridLayout(self.mainWidget())
        self.typeChooser = QComboBox()
        self.stack = QStackedWidget()
        StackFader(self.stack)
        paperSettings = QWidget(self)
        paperSettings.setLayout(QHBoxLayout())
        self.actionChooser = QComboBox(self)
        layout.addWidget(self.typeChooser, 0, 1)
        layout.addWidget(self.stack, 1, 0, 1, 3)
        layout.addWidget(self.actionChooser, 2, 1)
        l = QLabel(i18n("Type:"))
        l.setBuddy(self.typeChooser)
        layout.addWidget(l, 0, 0, Qt.AlignRight)
        l = QLabel(i18n("Action:"))
        l.setBuddy(self.actionChooser)
        layout.addWidget(l, 2, 0, Qt.AlignRight)
        
        # tool tips
        self.typeChooser.setToolTip(i18n(
            "Choose what kind of empty staves you want to create."))
        self.actionChooser.setToolTip(i18n(
            "Choose which action happens when clicking \"Ok\"."))
        self.setButtonToolTip(KDialog.Try, i18n(
            "Preview the empty staff paper."))
        self.setButtonToolTip(KDialog.Details, i18n(
            "Click to see more settings."))
        
        # paper stuff
        paper = QGroupBox(i18n("Paper"))
        paperSettings.layout().addWidget(paper)
        settings = QGroupBox(i18n("Settings"))
        paperSettings.layout().addWidget(settings)
        
        paper.setLayout(QGridLayout())
        
        self.paperSize = QComboBox()
        l = QLabel(i18n("Paper size:"))
        l.setBuddy(self.paperSize)
        paper.layout().addWidget(l, 0, 0, Qt.AlignRight)
        paper.layout().addWidget(self.paperSize, 0, 1)
        self.paperSize.addItem(i18n("Default"))
        self.paperSize.addItems(ly.paperSizes)

        self.staffSize = QSpinBox()
        l = QLabel(i18n("Staff Size:"))
        l.setBuddy(self.staffSize)
        paper.layout().addWidget(l, 1, 0, Qt.AlignRight)
        paper.layout().addWidget(self.staffSize, 1, 1)
        self.staffSize.setRange(8, 40)
        
        self.pageCount = QSpinBox()
        l = QLabel(i18n("Page count:"))
        l.setBuddy(self.pageCount)
        paper.layout().addWidget(l, 2, 0, Qt.AlignRight)
        paper.layout().addWidget(self.pageCount, 2, 1)
        self.pageCount.setRange(1, 1000)
        
        self.removeTagline = QCheckBox(i18n("Remove default tagline"))
        paper.layout().addWidget(self.removeTagline, 3, 0, 1, 2)
        
        settings.setLayout(QGridLayout())
        
        self.barLines = QCheckBox(i18n("Print Bar Lines"))
        self.barsPerLine = QSpinBox()
        l = QLabel(i18n("Bars per line:"))
        l.setBuddy(self.barsPerLine)
        settings.layout().addWidget(self.barLines, 0, 0, 1, 2)
        settings.layout().addWidget(l, 1, 0, Qt.AlignRight)
        settings.layout().addWidget(self.barsPerLine, 1, 1)
        self.barsPerLine.setRange(1, 20)
        
        self.pageNumbers = QCheckBox(i18n("Print Page Numbers"))
        self.pageNumStart = QSpinBox()
        l = QLabel(i18n("Start with:"))
        l.setBuddy(self.pageNumStart)
        settings.layout().addWidget(self.pageNumbers, 2, 0, 1, 2)
        settings.layout().addWidget(l, 3, 0, Qt.AlignRight)
        settings.layout().addWidget(self.pageNumStart, 3, 1)
        self.barLines.toggled.connect(self.barsPerLine.setEnabled)
        self.pageNumbers.toggled.connect(self.pageNumStart.setEnabled)
        
        # types
        self.typeWidgets = [
            SingleStaff(self),
            PianoStaff(self),
            OrganStaff(self),
            ChoirStaff(self),
            CustomStaff(self),
            ]
        for widget in self.typeWidgets:
            self.stack.addWidget(widget)
            self.typeChooser.addItem(widget.name())
        self.typeChooser.currentIndexChanged.connect(lambda index:
            self.stack.setCurrentWidget(self.typeWidgets[index]))

        self.actors = [
            PrintPDF,
            SavePDF,
            OpenPDF,
            CopyToEditor,
            ]
        for actor in self.actors:
            self.actionChooser.addItem(actor.name())
        
        self.setDetailsWidget(paperSettings)
        # cleanup on exit
        mainwin.aboutToClose.connect(self.cleanup)
        # buttons
        self.resetClicked.connect(self.default)
        self.tryClicked.connect(self.showPreview)
        self.setInitialSize(QSize(400, 240))
        self.default()
        self.loadSettings()
예제 #14
0
파일: authent.py 프로젝트: maximerobin/Ufwi
class AuthenticationFrontend(ScrollArea):
    COMPONENT = 'auth_cert'
    LABEL = tr('Authentication server')
    REQUIREMENTS = ('auth_cert',)
    ICON = ':/icons/auth_protocol.png'

    def __init__(self, client, parent):
        self.__loading = True
        ScrollArea.__init__(self)
        self.mainwindow = parent
        self.client = client
        self.modified = False

        self.qauthcertobject = QAuthCertObject.getInstance()

        frame = QFrame(self)

        layout = QVBoxLayout(frame)

        layout.addWidget(QLabel('<H1>%s</H1>' % tr('Authentication server') ))

        head_box = QGroupBox(tr("How the authentication server handles certificates"))
        head = QFormLayout(head_box)
        self.strictCheckBox = QCheckBox()
        head.addRow(QLabel(tr("Strict mode (check the client's certificate against the installed CA)")), self.strictCheckBox)
        self.connect(self.strictCheckBox, SIGNAL('toggled(bool)'),
                     self.setStrict)

        self.cl_auth_box = QGroupBox(tr("Client authentication with a certificate is"))
        cl_auth = QVBoxLayout(self.cl_auth_box)
        self.auth_by_cert = QButtonGroup()
        self.auth_by_cert.setExclusive(True)

        self.mainwindow.writeAccessNeeded(self.strictCheckBox)

        labels = [tr('forbidden'), tr('allowed'), tr('mandatory')]
        for index, label_button in enumerate(labels):
            button = QRadioButton(label_button)
            self.auth_by_cert.addButton(button, index)
            cl_auth.addWidget(button)
            self.mainwindow.writeAccessNeeded(button)
        self.auth_by_cert.button(0).setChecked(Qt.Checked)
        self.connect(self.auth_by_cert, SIGNAL('buttonClicked(int)'),
                     self.auth_by_cert_modified)


        # Captive portal
        # --------------
        self.portal_groupbox = QGroupBox(tr("Captive portal"))
        self.portal_groupbox.setLayout(QVBoxLayout())

        # Enabled checkbox:
        self.portal_checkbox = QCheckBox(tr("Enable captive portal"))
        self.connect(self.portal_checkbox, SIGNAL('toggled(bool)'),
                     self.setPortalEnabled)

        # List of networks redirected to the captive portal:
        self.portal_nets_groupbox = QGroupBox(
            tr("Networks handled by the captive portal"))
        self.portal_nets_groupbox.setLayout(QVBoxLayout())
        self.portal_nets_edit = NetworkListEdit()
        self.connect(self.portal_nets_edit, SIGNAL('textChanged()'), self.setPortalNets)
        self.portal_nets_groupbox.layout().addWidget(self.portal_nets_edit)

        # Pack the widgets:
        for widget in (self.portal_checkbox, self.portal_nets_groupbox):
            self.portal_groupbox.layout().addWidget(widget)
        self.mainwindow.writeAccessNeeded(self.portal_checkbox)
        self.mainwindow.writeAccessNeeded(self.portal_nets_edit)

        if not EDENWALL:
            self.portal_groupbox.setVisible(False)


        # authentication server
        self.pki_widget = PkiEmbedWidget(self.client, self, 'auth_cert', PkiEmbedWidget.SHOW_ALL|PkiEmbedWidget.CRL_OPTIONAL, self.setModified)
        self.mainwindow.writeAccessNeeded(self.pki_widget)

        layout.addWidget(head_box)
        layout.addWidget(self.cl_auth_box)
        layout.addWidget(self.portal_groupbox)
        layout.addWidget(self.pki_widget)
        layout.addStretch()
        self.setWidget(frame)
        self.setWidgetResizable(True)

        self.resetConf()
        self.__loading = False

    def setModified(self, isModified=True, message=""):
        if self.__loading:
            return
        if isModified:
            self.modified = True
            self.mainwindow.setModified(self, True)
            if message:
                self.mainwindow.addToInfoArea(message)
        else:
            self.modified = False

    def setModifiedCallback(self, *unused):
        self.setModified()

    def isModified(self):
        return self.modified

    def saveConf(self, message):
        self.qauthcertobject.auth_cert.auth_by_cert = self.auth_by_cert.checkedId()

        conf = self.pki_widget.getConfig()
        self.qauthcertobject.auth_cert.setSSLDict(conf)

        serialized = self.qauthcertobject.auth_cert.serialize(downgrade=True)
        self.client.call('auth_cert', 'setAuthCertConfig', serialized, message)

    def resetConf(self):
        auth_cert_loaded = self._reset_helper(
            'auth_cert',
            'getAuthCertConfig',
            self.qauthcertobject,
            tr("Authentication interface enabled"),
            tr("Authentication disabled: backend not loaded")
        )
        self.setModified(False)

        remote = self.qauthcertobject.auth_cert.getReceivedSerialVersion()
        if remote < 3:
            self.mainwindow.addWarningMessage(tr('Captive portal configuration disabled: this frontend and your appliance software versions are not compatible.'))
        enable_portal = (
            auth_cert_loaded
            and EDENWALL
            and remote >= 3
            )
        self.portal_groupbox.setVisible(enable_portal)

        if not auth_cert_loaded:
            return


        self.strictCheckBox.setChecked(self.qauthcertobject.auth_cert.strict)
        if not self.qauthcertobject.auth_cert.auth_by_cert:
            self.qauthcertobject.auth_cert.auth_by_cert = 0
        self.auth_by_cert.button(
            self.qauthcertobject.auth_cert.auth_by_cert).setChecked(True)

        # Captive portal:
        self.portal_checkbox.setChecked(
            self.qauthcertobject.auth_cert.portal_enabled)
        self.portal_nets_edit.setIpAddrs(
            self.qauthcertobject.auth_cert.portal_nets)

        # Certificate (PKI):
        pki_conf = self.qauthcertobject.auth_cert.getSSLDict()
        self.pki_widget.setConfig(pki_conf)

    def error(self, message):
        self.mainwindow.addToInfoArea(message, category=COLOR_ERROR)

    def auth_by_cert_modified(self, idbox):
        button_name = self.auth_by_cert.button(idbox).text()
        info = tr("Certificates - Authentication with client certificate : '%s'") % button_name
        self.setModified(message=info)

    def setPortalEnabled(self, value):
        if value != self.qauthcertobject.auth_cert.portal_enabled:
            self.qauthcertobject.auth_cert.setPortalEnabled(value)
            self.setModified()

    def setPortalNets(self):
        if self.portal_nets_edit.isValid():
            self.qauthcertobject.auth_cert.setPortalNets(
                self.portal_nets_edit.value())
            self.setModified()

    def setStrict(self, value):
        if value != self.qauthcertobject.auth_cert.strict:
            self.qauthcertobject.auth_cert.setStrict(value)
            self.setModified()
        self.cl_auth_box.setEnabled(value)

    def isValid(self):
        cert_validity = self.pki_widget.validate()
        if cert_validity is not None:
            self.error_message = '<br/>' + cert_validity + '<br/>'
            self.mainwindow.addToInfoArea(cert_validity, category=COLOR_ERROR)
            return False
        return True

    def onApplyFinished(self):
        self.pki_widget.feed()