Пример #1
0
def radio_filler(group_caption, labels, buttons_per_row=None, tool_tips=None):
    """ create a QGroupBox filled with a QGridLayout of QRadioButtons 
        that are part of a QButtonGroup
        
        group_caption: 
        
        labels:    list of strings that contain text for QRadioButtons
                   order of this list is important as the index is
                   used for QButtonGroup.Id
                   
        buttons_per_row: optional argument. number of QRadioButtons in
                         each row of the output QGridLayout.
                         
                         If None, all QRadioButtons
                         will be placed on one row. 
                         
        tool_tips: list of toolTip strings that will be added to each
                   QRadioButton.
                   
                   If None, no toolTips are added
    """

    group_box = QGroupBox(group_caption)
    grid = QGridLayout()
    bname = re.split("[\'\/ ,.]+", group_caption)
    bname = ' '.join(bname).title().replace(' ', '')
    bname = 'bgrp' + bname
    button_group = QButtonGroup(group_box)
    button_group.setObjectName(bname)
    # ~ button_group = QButtonGroup(group_box)

    for idx, label in enumerate(labels):
        radio_button = QRadioButton(label)
        # re.split seems to be the only way to quickly split on multiple
        # delimiters
        oname = re.split("[\'\/ ,.\n\-]+", label)
        oname = ' '.join(oname).title().replace(' ', '')
        oname = 'opt' + oname

        radio_button.setObjectName(oname)
        if tool_tips is not None:
            if len(tool_tips) == len(labels):
                radio_button.setToolTip(tool_tips[idx])

        if buttons_per_row is None:
            # all QRadioButtons go in row 0
            row = 0
            col = idx
        else:
            row = int(idx / buttons_per_row)
            col = idx % buttons_per_row
        button_group.addButton(radio_button, idx)  # set Id to idx

        grid.addWidget(radio_button, row, col)

    group_box.setLayout(grid)

    return (group_box, button_group)
Пример #2
0
class AddAccountDialog(base_class, ui_class):
    __metaclass__ = QSingleton

    implements(IObserver)

    def __init__(self, parent=None):
        super(AddAccountDialog, self).__init__(parent)
        with Resources.directory:
            self.setupUi(self)
        self.background_frame.setStyleSheet("")
        self.button_group = QButtonGroup(self)
        self.button_group.setObjectName("button_group")
        self.button_group.addButton(
            self.add_account_button,
            self.panel_view.indexOf(self.add_account_panel))
        self.button_group.addButton(
            self.create_account_button,
            self.panel_view.indexOf(self.create_account_panel))
        font = self.title_label.font()
        font.setPointSizeF(self.info_label.fontInfo().pointSizeF() + 3)
        font.setFamily("Sans Serif")
        self.title_label.setFont(font)
        font_metrics = self.create_status_label.fontMetrics()
        self.create_status_label.setMinimumHeight(
            font_metrics.height() + 2 *
            (font_metrics.height() + font_metrics.leading())
        )  # reserve space for 3 lines
        font_metrics = self.email_note_label.fontMetrics()
        self.email_note_label.setMinimumWidth(
            font_metrics.width(
                u'The E-mail address is used when sending voicemail')
        )  # hack to make text justification look nice everywhere
        self.add_account_button.setChecked(True)
        self.panel_view.setCurrentWidget(self.add_account_panel)
        self.new_password_editor.textChanged.connect(
            self._SH_PasswordTextChanged)
        self.button_group.buttonClicked[int].connect(
            self._SH_PanelChangeRequest)
        self.accept_button.clicked.connect(self._SH_AcceptButtonClicked)
        self.display_name_editor.statusChanged.connect(
            self._SH_ValidityStatusChanged)
        self.name_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.username_editor.statusChanged.connect(
            self._SH_ValidityStatusChanged)
        self.sip_address_editor.statusChanged.connect(
            self._SH_ValidityStatusChanged)
        self.password_editor.statusChanged.connect(
            self._SH_ValidityStatusChanged)
        self.new_password_editor.statusChanged.connect(
            self._SH_ValidityStatusChanged)
        self.verify_password_editor.statusChanged.connect(
            self._SH_ValidityStatusChanged)
        self.email_address_editor.statusChanged.connect(
            self._SH_ValidityStatusChanged)
        self.display_name_editor.regexp = re.compile('^.*$')
        self.name_editor.regexp = re.compile('^.+$')
        self.username_editor.regexp = re.compile(
            '^\w(?<=[^0_])[\w.-]{4,31}(?<=[^_.-])$', re.IGNORECASE
        )  # in order to enable unicode characters add re.UNICODE to flags
        self.sip_address_editor.regexp = re.compile('^[^@\s]+@[^@\s]+$')
        self.password_editor.regexp = re.compile('^.*$')
        self.new_password_editor.regexp = re.compile('^.{8,}$')
        self.verify_password_editor.regexp = re.compile('^$')
        self.email_address_editor.regexp = re.compile('^[^@\s]+@[^@\s]+$')

        account_manager = AccountManager()
        notification_center = NotificationCenter()
        notification_center.add_observer(self, sender=account_manager)

    def _get_display_name(self):
        if self.panel_view.currentWidget() is self.add_account_panel:
            return self.display_name_editor.text()
        else:
            return self.name_editor.text()

    def _set_display_name(self, value):
        self.display_name_editor.setText(value)
        self.name_editor.setText(value)

    def _get_username(self):
        return self.username_editor.text()

    def _set_username(self, value):
        self.username_editor.setText(value)

    def _get_sip_address(self):
        return self.sip_address_editor.text()

    def _set_sip_address(self, value):
        self.sip_address_editor.setText(value)

    def _get_password(self):
        if self.panel_view.currentWidget() is self.add_account_panel:
            return self.password_editor.text()
        else:
            return self.new_password_editor.text()

    def _set_password(self, value):
        self.password_editor.setText(value)
        self.new_password_editor.setText(value)

    def _get_verify_password(self):
        return self.verify_password_editor.text()

    def _set_verify_password(self, value):
        self.verify_password_editor.setText(value)

    def _get_email_address(self):
        return self.email_address_editor.text()

    def _set_email_address(self, value):
        self.email_address_editor.setText(value)

    display_name = property(_get_display_name, _set_display_name)
    username = property(_get_username, _set_username)
    sip_address = property(_get_sip_address, _set_sip_address)
    password = property(_get_password, _set_password)
    verify_password = property(_get_verify_password, _set_verify_password)
    email_address = property(_get_email_address, _set_email_address)

    del _get_display_name, _set_display_name, _get_username, _set_username
    del _get_sip_address, _set_sip_address, _get_email_address, _set_email_address
    del _get_password, _set_password, _get_verify_password, _set_verify_password

    def _SH_AcceptButtonClicked(self):
        if self.panel_view.currentWidget() is self.add_account_panel:
            account = Account(self.sip_address)
            account.enabled = True
            account.display_name = self.display_name or None
            account.auth.password = self.password
            account.save()
            account_manager = AccountManager()
            account_manager.default_account = account
            self.accept()
        else:
            self.setEnabled(False)
            self.create_status_label.value = Status(
                'Creating account on server...')
            self._create_sip_account(self.username, self.password,
                                     self.email_address, self.display_name)

    def _SH_PanelChangeRequest(self, index):
        self.panel_view.setCurrentIndex(index)
        if self.panel_view.currentWidget() is self.add_account_panel:
            inputs = [
                self.display_name_editor, self.sip_address_editor,
                self.password_editor
            ]
        else:
            inputs = [
                self.name_editor, self.username_editor,
                self.new_password_editor, self.verify_password_editor,
                self.email_address_editor
            ]
        self.accept_button.setEnabled(all(input.text_valid
                                          for input in inputs))

    def _SH_PasswordTextChanged(self, text):
        self.verify_password_editor.regexp = re.compile(u'^%s$' %
                                                        re.escape(text))

    def _SH_ValidityStatusChanged(self):
        red = '#cc0000'
        # validate the add panel
        if not self.display_name_editor.text_valid:
            self.add_status_label.value = Status(
                "Display name cannot be empty", color=red)
        elif not self.sip_address_editor.text_correct:
            self.add_status_label.value = Status(
                "SIP address should be specified as user@domain", color=red)
        elif not self.sip_address_editor.text_allowed:
            self.add_status_label.value = Status(
                "An account with this SIP address was already added",
                color=red)
        elif not self.password_editor.text_valid:
            self.add_status_label.value = Status("Password cannot be empty",
                                                 color=red)
        else:
            self.add_status_label.value = None
        # validate the create panel
        if not self.name_editor.text_valid:
            self.create_status_label.value = Status("Name cannot be empty",
                                                    color=red)
        elif not self.username_editor.text_correct:
            self.create_status_label.value = Status(
                "Username should have 5 to 32 characters, start with a letter or non-zero digit, contain only letters, digits or .-_ and end with a letter or digit",
                color=red)
        elif not self.username_editor.text_allowed:
            self.create_status_label.value = Status(
                "The username you requested is already taken. Please choose another one and try again.",
                color=red)
        elif not self.new_password_editor.text_valid:
            self.create_status_label.value = Status(
                "Password should contain at least 8 characters", color=red)
        elif not self.verify_password_editor.text_valid:
            self.create_status_label.value = Status("Passwords do not match",
                                                    color=red)
        elif not self.email_address_editor.text_valid:
            self.create_status_label.value = Status(
                "E-mail address should be specified as user@domain", color=red)
        else:
            self.create_status_label.value = None
        # enable the accept button if everything is valid in the current panel
        if self.panel_view.currentWidget() is self.add_account_panel:
            inputs = [
                self.display_name_editor, self.sip_address_editor,
                self.password_editor
            ]
        else:
            inputs = [
                self.name_editor, self.username_editor,
                self.new_password_editor, self.verify_password_editor,
                self.email_address_editor
            ]
        self.accept_button.setEnabled(all(input.text_valid
                                          for input in inputs))

    def _initialize(self):
        self.display_name = user_info.fullname
        self.username = user_info.username.lower().replace(u' ', u'.')
        self.sip_address = u''
        self.password = u''
        self.verify_password = u''
        self.email_address = u''

    @run_in_thread('network-io')
    def _create_sip_account(self,
                            username,
                            password,
                            email_address,
                            display_name,
                            timezone=None):
        red = '#cc0000'
        if timezone is None and sys.platform != 'win32':
            try:
                timezone = open('/etc/timezone').read().strip()
            except (OSError, IOError):
                try:
                    timezone = '/'.join(
                        os.readlink('/etc/localtime').split('/')[-2:])
                except (OSError, IOError):
                    pass
        enrollment_data = dict(username=username.lower().encode('utf-8'),
                               password=password.encode('utf-8'),
                               email=email_address.encode('utf-8'),
                               display_name=display_name.encode('utf-8'),
                               tzinfo=timezone)
        try:
            settings = SIPSimpleSettings()
            response = urllib2.urlopen(settings.server.enrollment_url,
                                       urllib.urlencode(dict(enrollment_data)))
            response_data = cjson.decode(response.read().replace(r'\/', '/'))
            response_data = defaultdict(lambda: None, response_data)
            if response_data['success']:
                try:
                    passport = response_data['passport']
                    if passport is not None:
                        certificate_path = self._save_certificates(
                            response_data['sip_address'], passport['crt'],
                            passport['key'], passport['ca'])
                    else:
                        certificate_path = None
                except (GNUTLSError, IOError, OSError):
                    certificate_path = None
                account_manager = AccountManager()
                try:
                    account = Account(response_data['sip_address'])
                except DuplicateIDError:
                    account = account_manager.get_account(
                        response_data['sip_address'])
                account.enabled = True
                account.display_name = display_name or None
                account.auth.password = password
                account.sip.outbound_proxy = response_data['outbound_proxy']
                account.nat_traversal.msrp_relay = response_data['msrp_relay']
                account.xcap.xcap_root = response_data['xcap_root']
                account.tls.certificate = certificate_path
                account.server.conference_server = response_data[
                    'conference_server']
                account.server.settings_url = response_data['settings_url']
                account.save()
                account_manager.default_account = account
                call_in_gui_thread(self.accept)
            elif response_data['error'] == 'user_exists':
                call_in_gui_thread(self.username_editor.addException, username)
            else:
                call_in_gui_thread(
                    setattr, self.create_status_label, 'value',
                    Status(response_data['error_message'], color=red))
        except (cjson.DecodeError, KeyError):
            call_in_gui_thread(setattr, self.create_status_label, 'value',
                               Status('Illegal server response', color=red))
        except urllib2.URLError, e:
            call_in_gui_thread(
                setattr, self.create_status_label, 'value',
                Status('Failed to contact server: %s' % e.reason, color=red))
        finally:
Пример #3
0
class app(QMainWindow):
    def __init__(self):
        super().__init__()

        self.init_variables()
        self.init_ui()

    def init_ui(self):
        """inits ui"""
        self.setWindowTitle("example window")
        # self.setGeometry(100,100,700,700)
        # self.move(100, 100)
        self.center()

        self.setFixedSize(700, 700)

        self.labels()
        self.buttons()
        self.line_edits()
        self.checkboxes()
        self.radiobuttons()
        self.text_edits()
        self.menu_bar()

        self.show()

    def init_variables(self):
        """inits class variables"""
        self.button_counter = 0
        self.img1_path = "07-pyqt5/images/img.png"
        self.file_dialog_path = ""

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def labels(self):
        """adds labels"""
        self.l1 = QLabel(self)
        self.l1.setText("label 1")
        # self.l1.move(120, 230)
        self.l1.setGeometry(120, 230, 100, 10)

        # add image
        self.l2 = QLabel(self)
        self.l2.setPixmap(QtGui.QPixmap(self.img1_path))
        self.l2.setGeometry(0, 0, 700, 200)

    def buttons(self):
        """adds buttons"""
        self.b1 = QPushButton(self)
        self.b1.setText("counter")
        self.b1.move(10, 220)
        self.b1.clicked.connect(self.on_click)

        self.b2 = QPushButton(self)
        self.b2.setText("clear")
        self.b2.move(10, 270)
        self.b2.clicked.connect(self.on_click)

        self.b3 = QPushButton(self)
        self.b3.setText("open file dialog")
        self.b3.move(10, 420)
        self.b3.clicked.connect(self.on_click)

    def line_edits(self):
        """adds line edits"""
        self.line1 = QLineEdit(self)
        self.line1.setText("")
        self.line1.move(120, 270)

    def checkboxes(self):
        """adds checkboxes"""
        self.checkbox1 = QCheckBox(self)
        self.checkbox1.setText("checkbox example")
        self.checkbox1.move(10, 320)
        self.checkbox1.setObjectName("checkbox1")
        # self.checkbox1.setDisabled(True)

        self.checkbox1.clicked.connect(self.on_click)

    def radiobuttons(self):
        """adds radiobuttons"""
        self.radiobutton1 = QRadioButton(self)
        self.radiobutton1.setText("radiobutton 1")
        self.radiobutton1.move(10, 370)
        self.radiobutton1.setObjectName("radiobutton1")
        self.radiobutton1.clicked.connect(self.on_click)

        self.radiobutton2 = QRadioButton(self)
        self.radiobutton2.setText("radiobutton 2")
        self.radiobutton2.move(120, 370)
        self.radiobutton2.setObjectName("radiobutton2")
        self.radiobutton2.clicked.connect(self.on_click)

        self.radiobutton3 = QRadioButton(self)
        self.radiobutton3.setText("radiobutton 3")
        self.radiobutton3.move(230, 370)
        self.radiobutton3.setObjectName("radiobutton3")
        self.radiobutton3.clicked.connect(self.on_click)

        # button groups
        self.button_group1 = QButtonGroup()
        self.button_group1.addButton(self.radiobutton1)
        self.button_group1.addButton(self.radiobutton2)
        self.button_group1.setObjectName("button_group1")

        # this can listen all buttons in the group but it has no attribute calles .text()
        # so you cant use single listener function with it or use objectname()
        # self.button_group1.buttonClicked.connect(self.on_click)

        self.button_group2 = QButtonGroup()
        self.button_group2.addButton(self.radiobutton3)
        self.button_group2.setObjectName("button_group2")

    def text_edits(self):
        """adds text edits"""
        self.te1 = QTextEdit(self)
        self.te1.setGeometry(350, 220, 300, 200)
        self.te1.setText("this is a biiiiiig text field")

    def menu_bar(self):
        """adds menu bar and actions under it"""
        # menu items
        self.bar = self.menuBar()

        self.file_menu = self.bar.addMenu("file")
        self.file_menu.triggered.connect(self.on_menu_click)

        self.edit_menu = self.bar.addMenu("edit")

        self.sub_menu = self.edit_menu.addMenu("sub menu")

        # actions
        self.open_file_function = QAction("open file", self)
        self.open_file_function.setShortcut("Ctrl+O")
        self.open_file_function.setObjectName("open_file_function")
        self.open_file_function.triggered.connect(self.on_click)
        self.file_menu.addAction(self.open_file_function)

        self.test_trigger = QAction("test trigger", self)
        self.test_trigger.setObjectName("test_trigger")
        self.file_menu.addAction(self.test_trigger)

        self.exit_function = QAction("exit", self)
        self.exit_function.setShortcut("Ctrl+Q")
        self.exit_function.setObjectName("exit")
        self.exit_function.triggered.connect(self.on_click)
        self.sub_menu.addAction(self.exit_function)

    def open_file(self):
        """opens file dialog"""
        file_name = QFileDialog.getOpenFileName(self, "file dialog example",
                                                self.file_dialog_path)
        print(file_name)

        if (os.path.exists(file_name[0])):
            return file_name[0]
        else:
            return None

    def on_menu_click(self, action):
        """triggers on menu clicks"""
        if (action.text() == "open file"):
            print("open file used")
        if (action.text() == "test trigger"):
            print("test trigger used")

    def on_click(self):
        """button click function for listeners"""
        sender = self.sender()

        # buttons
        if (sender.text() == "counter"):
            self.button_counter += 1
            self.l1.setText("counter is:{}".format(self.button_counter))
        elif (sender.text() == "clear"):
            self.line1.setText("")
        elif (sender.text() == "open file dialog"):
            self.open_file()

        # checkboxes
        elif (sender.objectName() == "checkbox1"):
            if (self.checkbox1.isChecked()):
                self.checkbox1.setText("checked")
            else:
                self.checkbox1.setText("not checked")

        # radiobuttons
        elif (sender.objectName() == "radiobutton1"):
            self.radiobutton1.setText("hi there")
        elif (sender.objectName() == "radiobutton2"):
            self.radiobutton2.setText("hi there")
        elif (sender.objectName() == "radiobutton3"):
            self.radiobutton3.setText("hi there")

        # menu items
        elif (sender.objectName() == "exit"):
            sys.exit()
        elif (sender.objectName() == "open_file_function"):
            self.open_file()

        print(sender.objectName())
Пример #4
0
class AddAccountDialog(base_class, ui_class):
    __metaclass__ = QSingleton

    implements(IObserver)

    def __init__(self, parent=None):
        super(AddAccountDialog, self).__init__(parent)
        with Resources.directory:
            self.setupUi(self)
        self.background_frame.setStyleSheet("")
        self.button_group = QButtonGroup(self)
        self.button_group.setObjectName("button_group")
        self.button_group.addButton(self.add_account_button, self.panel_view.indexOf(self.add_account_panel))
        self.button_group.addButton(self.create_account_button, self.panel_view.indexOf(self.create_account_panel))
        default_font_size = self.info_label.fontInfo().pointSizeF()
        title_font_size = limit(default_font_size + 3, max=14)
        font = self.title_label.font()
        font.setPointSizeF(title_font_size)
        self.title_label.setFont(font)
        font_metrics = self.create_status_label.fontMetrics()
        self.create_status_label.setMinimumHeight(font_metrics.height() + 2*(font_metrics.height() + font_metrics.leading()))   # reserve space for 3 lines
        font_metrics = self.email_note_label.fontMetrics()
        self.email_note_label.setMinimumWidth(font_metrics.width(u'The E-mail address is used when sending voicemail'))  # hack to make text justification look nice everywhere
        self.add_account_button.setChecked(True)
        self.panel_view.setCurrentWidget(self.add_account_panel)
        self.new_password_editor.textChanged.connect(self._SH_PasswordTextChanged)
        self.button_group.buttonClicked[int].connect(self._SH_PanelChangeRequest)
        self.accept_button.clicked.connect(self._SH_AcceptButtonClicked)
        self.display_name_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.name_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.username_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.sip_address_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.password_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.new_password_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.verify_password_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.email_address_editor.statusChanged.connect(self._SH_ValidityStatusChanged)
        self.display_name_editor.regexp = re.compile('^.*$')
        self.name_editor.regexp = re.compile('^.+$')
        self.username_editor.regexp = re.compile('^\w(?<=[^0_])[\w.-]{4,31}(?<=[^_.-])$', re.IGNORECASE)  # in order to enable unicode characters add re.UNICODE to flags
        self.sip_address_editor.regexp = re.compile('^[^@\s]+@[^@\s]+$')
        self.password_editor.regexp = re.compile('^.*$')
        self.new_password_editor.regexp = re.compile('^.{8,}$')
        self.verify_password_editor.regexp = re.compile('^$')
        self.email_address_editor.regexp = re.compile('^[^@\s]+@[^@\s]+$')

        account_manager = AccountManager()
        notification_center = NotificationCenter()
        notification_center.add_observer(self, sender=account_manager)

    def _get_display_name(self):
        if self.panel_view.currentWidget() is self.add_account_panel:
            return self.display_name_editor.text()
        else:
            return self.name_editor.text()

    def _set_display_name(self, value):
        self.display_name_editor.setText(value)
        self.name_editor.setText(value)

    def _get_username(self):
        return self.username_editor.text()

    def _set_username(self, value):
        self.username_editor.setText(value)

    def _get_sip_address(self):
        return self.sip_address_editor.text()

    def _set_sip_address(self, value):
        self.sip_address_editor.setText(value)

    def _get_password(self):
        if self.panel_view.currentWidget() is self.add_account_panel:
            return self.password_editor.text()
        else:
            return self.new_password_editor.text()

    def _set_password(self, value):
        self.password_editor.setText(value)
        self.new_password_editor.setText(value)

    def _get_verify_password(self):
        return self.verify_password_editor.text()

    def _set_verify_password(self, value):
        self.verify_password_editor.setText(value)

    def _get_email_address(self):
        return self.email_address_editor.text()

    def _set_email_address(self, value):
        self.email_address_editor.setText(value)

    display_name    = property(_get_display_name, _set_display_name)
    username        = property(_get_username, _set_username)
    sip_address     = property(_get_sip_address, _set_sip_address)
    password        = property(_get_password, _set_password)
    verify_password = property(_get_verify_password, _set_verify_password)
    email_address   = property(_get_email_address, _set_email_address)

    del _get_display_name, _set_display_name, _get_username, _set_username
    del _get_sip_address, _set_sip_address, _get_email_address, _set_email_address
    del _get_password, _set_password, _get_verify_password, _set_verify_password

    def _SH_AcceptButtonClicked(self):
        if self.panel_view.currentWidget() is self.add_account_panel:
            account = Account(self.sip_address)
            account.enabled = True
            account.display_name = self.display_name or None
            account.auth.password = self.password
            account.save()
            account_manager = AccountManager()
            account_manager.default_account = account
            self.accept()
        else:
            self.setEnabled(False)
            self.create_status_label.value = Status('Creating account on server...')
            self._create_sip_account(self.username, self.password, self.email_address, self.display_name)

    def _SH_PanelChangeRequest(self, index):
        self.panel_view.setCurrentIndex(index)
        if self.panel_view.currentWidget() is self.add_account_panel:
            inputs = [self.display_name_editor, self.sip_address_editor, self.password_editor]
        else:
            inputs = [self.name_editor, self.username_editor, self.new_password_editor, self.verify_password_editor, self.email_address_editor]
        self.accept_button.setEnabled(all(input.text_valid for input in inputs))

    def _SH_PasswordTextChanged(self, text):
        self.verify_password_editor.regexp = re.compile(u'^%s$' % re.escape(text))

    def _SH_ValidityStatusChanged(self):
        red = '#cc0000'
        # validate the add panel
        if not self.display_name_editor.text_valid:
            self.add_status_label.value = Status("Display name cannot be empty", color=red)
        elif not self.sip_address_editor.text_correct:
            self.add_status_label.value = Status("SIP address should be specified as user@domain", color=red)
        elif not self.sip_address_editor.text_allowed:
            self.add_status_label.value = Status("An account with this SIP address was already added", color=red)
        elif not self.password_editor.text_valid:
            self.add_status_label.value = Status("Password cannot be empty", color=red)
        else:
            self.add_status_label.value = None
        # validate the create panel
        if not self.name_editor.text_valid:
            self.create_status_label.value = Status("Name cannot be empty", color=red)
        elif not self.username_editor.text_correct:
            self.create_status_label.value = Status("Username should have 5 to 32 characters, start with a letter or non-zero digit, contain only letters, digits or .-_ and end with a letter or digit", color=red)
        elif not self.username_editor.text_allowed:
            self.create_status_label.value = Status("The username you requested is already taken. Please choose another one and try again.", color=red)
        elif not self.new_password_editor.text_valid:
            self.create_status_label.value = Status("Password should contain at least 8 characters", color=red)
        elif not self.verify_password_editor.text_valid:
            self.create_status_label.value = Status("Passwords do not match", color=red)
        elif not self.email_address_editor.text_valid:
            self.create_status_label.value = Status("E-mail address should be specified as user@domain", color=red)
        else:
            self.create_status_label.value = None
        # enable the accept button if everything is valid in the current panel
        if self.panel_view.currentWidget() is self.add_account_panel:
            inputs = [self.display_name_editor, self.sip_address_editor, self.password_editor]
        else:
            inputs = [self.name_editor, self.username_editor, self.new_password_editor, self.verify_password_editor, self.email_address_editor]
        self.accept_button.setEnabled(all(input.text_valid for input in inputs))

    def _initialize(self):
        self.display_name = user_info.fullname
        self.username = user_info.username.lower().replace(u' ', u'.')
        self.sip_address = u''
        self.password = u''
        self.verify_password = u''
        self.email_address = u''

    @run_in_thread('network-io')
    def _create_sip_account(self, username, password, email_address, display_name, timezone=None):
        red = '#cc0000'
        if timezone is None and sys.platform != 'win32':
            try:
                timezone = open('/etc/timezone').read().strip()
            except (OSError, IOError):
                try:
                    timezone = '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
                except (OSError, IOError):
                    pass
        enrollment_data = dict(username=username.lower().encode('utf-8'),
                               password=password.encode('utf-8'),
                               email=email_address.encode('utf-8'),
                               display_name=display_name.encode('utf-8'),
                               tzinfo=timezone)
        try:
            settings = SIPSimpleSettings()
            response = urllib2.urlopen(settings.server.enrollment_url, urllib.urlencode(dict(enrollment_data)))
            response_data = cjson.decode(response.read().replace(r'\/', '/'))
            response_data = defaultdict(lambda: None, response_data)
            if response_data['success']:
                try:
                    passport = response_data['passport']
                    if passport is not None:
                        certificate_path = self._save_certificates(response_data['sip_address'], passport['crt'], passport['key'], passport['ca'])
                    else:
                        certificate_path = None
                except (GNUTLSError, IOError, OSError):
                    certificate_path = None
                account_manager = AccountManager()
                try:
                    account = Account(response_data['sip_address'])
                except DuplicateIDError:
                    account = account_manager.get_account(response_data['sip_address'])
                account.enabled = True
                account.display_name = display_name or None
                account.auth.password = password
                account.sip.outbound_proxy = response_data['outbound_proxy']
                account.nat_traversal.msrp_relay = response_data['msrp_relay']
                account.xcap.xcap_root = response_data['xcap_root']
                account.tls.certificate = certificate_path
                account.server.conference_server = response_data['conference_server']
                account.server.settings_url = response_data['settings_url']
                account.save()
                account_manager.default_account = account
                call_in_gui_thread(self.accept)
            elif response_data['error'] == 'user_exists':
                call_in_gui_thread(self.username_editor.addException, username)
            else:
                call_in_gui_thread(setattr, self.create_status_label, 'value', Status(response_data['error_message'], color=red))
        except (cjson.DecodeError, KeyError):
            call_in_gui_thread(setattr, self.create_status_label, 'value', Status('Illegal server response', color=red))
        except urllib2.URLError, e:
            call_in_gui_thread(setattr, self.create_status_label, 'value', Status('Failed to contact server: %s' % e.reason, color=red))
        finally:
Пример #5
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1920, 1080)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_3.setObjectName("gridLayout_3")

        self.Tab1 = QtWidgets.QTabWidget(self.centralwidget)
        self.Tab1.setLocale(
            QtCore.QLocale(QtCore.QLocale.Russian, QtCore.QLocale.Russia))
        self.Tab1.setObjectName("Tab1")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout = QtWidgets.QGridLayout(self.tab)
        self.gridLayout.setObjectName("gridLayout")

        self.groupBoxButtons = QGroupBox(self.tab)
        self.groupBoxButtons.setObjectName(u"groupBoxButtons")
        self.groupBoxButtons.setMaximumSize(QSize(100, 16777215))
        self.formLayout = QFormLayout(self.groupBoxButtons)
        self.gridLayout.addWidget(self.groupBoxButtons, 0, 1, 6, 1)

        self.ButtonAddLeg = QtWidgets.QPushButton(self.groupBoxButtons)
        self.ButtonAddLeg.setObjectName("ButtonAddLeg")
        self.formLayout.setWidget(2, QFormLayout.LabelRole, self.ButtonAddLeg)

        self.pushButtonDelLeg = QtWidgets.QPushButton(self.groupBoxButtons)
        self.pushButtonDelLeg.setObjectName(u"pushButtonDelLeg")
        self.pushButtonDelLeg.setText(u"Del Leg")
        self.formLayout.setWidget(3, QFormLayout.LabelRole,
                                  self.pushButtonDelLeg)

        self.calendarWidget = QtWidgets.QCalendarWidget(self.tab)
        self.calendarWidget.setObjectName("calendarWidget")
        self.gridLayout.addWidget(self.calendarWidget, 0, 0, 6, 1,
                                  QtCore.Qt.AlignLeft)
        self.calendarWidget.setGridVisible(True)

        self.ButtonAddAC = QtWidgets.QPushButton(self.groupBoxButtons)
        self.ButtonAddAC.setObjectName("ButtonAddAC")
        self.formLayout.setWidget(0, QFormLayout.LabelRole, self.ButtonAddAC)

        self.pushButtonDelAC = QtWidgets.QPushButton(self.groupBoxButtons)
        self.pushButtonDelAC.setObjectName("pushButtonDelAC")
        self.pushButtonDelAC.setText(u"Del A/C")
        self.formLayout.setWidget(1, QFormLayout.LabelRole,
                                  self.pushButtonDelAC)

        self.tableViewAcft = QtWidgets.QTableView(self.tab)
        self.tableViewAcft.setObjectName(u"tableViewAcft")
        self.gridLayout.addWidget(self.tableViewAcft, 0, 2, 6, 1,
                                  QtCore.Qt.AlignLeft)
        self.tableViewAcft.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)
        self.tableViewAcft.horizontalHeader().setStretchLastSection(False)
        self.tableViewAcft.setMaximumSize(QSize(140, 16777215))

        self.model = QtGui.QStandardItemModel(self.tab)

        self.tableLog = QtWidgets.QTableView(self.tab)
        self.tableLog.setModel(self.model)
        self.tableLog.setObjectName("tableLog")
        self.gridLayout.addWidget(self.tableLog, 6, 0, 1, 6)
        self.tableLog.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)
        self.tableLog.horizontalHeader().setStretchLastSection(False)
        self.tableLog.setSortingEnabled(True)
        self.tableLog.setAlternatingRowColors(True)

        self.Tab1.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.Tab1.addTab(self.tab_2, "")
        self.gridLayout_3.addWidget(self.Tab1, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1920, 30))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.lcdNumber = QtWidgets.QLCDNumber(self.tab)
        self.lcdNumber.setObjectName(u"lcdNumber")
        self.lcdNumber.setMinimumSize(QtCore.QSize(300, 0))
        self.lcdNumber.setDigitCount(8)
        self.gridLayout.addWidget(self.lcdNumber, 2, 5, 2, 1,
                                  QtCore.Qt.AlignLeft)

        self.lcdNumberBLK = QtWidgets.QLCDNumber(self.tab)
        self.lcdNumberBLK.setObjectName(u"lcdNumberBLK")
        self.lcdNumberBLK.setMinimumSize(QtCore.QSize(300, 0))
        self.lcdNumberBLK.setDigitCount(8)
        self.gridLayout.addWidget(self.lcdNumberBLK, 0, 5, 2, 1,
                                  QtCore.Qt.AlignLeft)

        self.lcdNumberNight = QtWidgets.QLCDNumber(self.tab)
        self.lcdNumberNight.setObjectName(u"lcdNumberNight")
        self.lcdNumberNight.setMinimumSize(QtCore.QSize(300, 0))
        self.lcdNumberNight.setDigitCount(8)
        self.gridLayout.addWidget(self.lcdNumberNight, 4, 5, 2, 1,
                                  QtCore.Qt.AlignLeft)

        self.label_3 = QtWidgets.QLabel(self.tab)
        self.label_3.setObjectName(u"label_3")
        self.label_3.setEnabled(True)
        font = QtGui.QFont()
        font.setPointSize(30)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setText(
            u"<html><head/><body><p>Night Time	</p></body></html>")
        self.label_3.setAlignment(QtCore.Qt.AlignRight
                                  | QtCore.Qt.AlignTrailing
                                  | QtCore.Qt.AlignVCenter)
        self.gridLayout.addWidget(self.label_3, 4, 4, 2, 1,
                                  QtCore.Qt.AlignLeft)

        self.label_2 = QtWidgets.QLabel(self.tab)
        self.label_2.setObjectName(u"label_2")
        self.label_2.setFont(font)
        self.label_2.setText(
            u"<html><head/><body><p>Flight Time	</p></body></html>")
        self.label_2.setAlignment(QtCore.Qt.AlignRight
                                  | QtCore.Qt.AlignTrailing
                                  | QtCore.Qt.AlignVCenter)
        self.gridLayout.addWidget(self.label_2, 2, 4, 2, 1,
                                  QtCore.Qt.AlignLeft)

        self.label = QtWidgets.QLabel(self.tab)
        self.label.setObjectName(u"label")
        self.label.setFont(font)
        self.label.setText(
            u"<html><head/><body><p>Block Time	</p></body></html>")
        self.label.setTextFormat(QtCore.Qt.AutoText)
        self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing
                                | QtCore.Qt.AlignVCenter)
        self.gridLayout.addWidget(self.label, 0, 4, 2, 1, QtCore.Qt.AlignLeft)

        self.groupBoxFilters = QGroupBox(self.tab)
        self.groupBoxFilters.setObjectName(u"groupBoxFilters")

        self.groupBoxFilters.setToolTip(u"")
        self.groupBoxFilters.setStatusTip(u"")
        self.groupBoxFilters.setWhatsThis(u"")
        self.groupBoxFilters.setAccessibleName(u"")
        self.groupBoxFilters.setAccessibleDescription(u"")
        self.groupBoxFilters.setTitle(u"Filters")
        self.gridLayout_2 = QGridLayout(self.groupBoxFilters)
        self.gridLayout_2.setObjectName(u"gridLayout_2")
        self.gridLayout.addWidget(self.groupBoxFilters, 0, 3, 6, 1,
                                  QtCore.Qt.AlignLeft)

        self.radioButton12Month = QRadioButton(self.groupBoxFilters)
        self.buttonGroupFilter = QButtonGroup(MainWindow)
        self.buttonGroupFilter.setObjectName(u"buttonGroupFilter")
        self.buttonGroupFilter.addButton(self.radioButton12Month)
        self.radioButton12Month.setObjectName(u"radioButton12Month")
        self.radioButton12Month.setToolTip(u"")
        self.radioButton12Month.setStatusTip(u"")
        self.radioButton12Month.setWhatsThis(u"")
        self.radioButton12Month.setAccessibleName(u"")
        self.radioButton12Month.setAccessibleDescription(u"")
        self.radioButton12Month.setText(u"Last 12 Month")

        self.gridLayout_2.addWidget(self.radioButton12Month, 2, 1, 1, 1)

        self.radioButtonDateToDate = QRadioButton(self.groupBoxFilters)
        self.buttonGroupFilter.addButton(self.radioButtonDateToDate)
        self.radioButtonDateToDate.setObjectName(u"radioButtonDateToDate")
        self.radioButtonDateToDate.setToolTip(u"")
        self.radioButtonDateToDate.setStatusTip(u"")
        self.radioButtonDateToDate.setWhatsThis(u"")
        self.radioButtonDateToDate.setAccessibleName(u"")
        self.radioButtonDateToDate.setAccessibleDescription(u"")
        self.radioButtonDateToDate.setText(u"From Date To Date")

        self.gridLayout_2.addWidget(self.radioButtonDateToDate, 4, 1, 1, 1)

        self.radioButtonPrDay = QRadioButton(self.groupBoxFilters)
        self.buttonGroupFilter.addButton(self.radioButtonPrDay)
        self.radioButtonPrDay.setObjectName(u"radioButtonPrDay")
        self.radioButtonPrDay.setToolTip(u"")
        self.radioButtonPrDay.setStatusTip(u"")
        self.radioButtonPrDay.setWhatsThis(u"")
        self.radioButtonPrDay.setAccessibleName(u"")
        self.radioButtonPrDay.setAccessibleDescription(u"")
        self.radioButtonPrDay.setText(u"Previous Day")

        self.gridLayout_2.addWidget(self.radioButtonPrDay, 0, 0, 1, 1)

        self.radioButton30days = QRadioButton(self.groupBoxFilters)
        self.buttonGroupFilter.addButton(self.radioButton30days)
        self.radioButton30days.setObjectName(u"radioButton30days")
        self.radioButton30days.setToolTip(u"")
        self.radioButton30days.setStatusTip(u"")
        self.radioButton30days.setWhatsThis(u"")
        self.radioButton30days.setAccessibleName(u"")
        self.radioButton30days.setAccessibleDescription(u"")
        self.radioButton30days.setText(u"Last 30 Days")

        self.gridLayout_2.addWidget(self.radioButton30days, 0, 1, 1, 1)

        self.radioButtonPrYear = QRadioButton(self.groupBoxFilters)
        self.buttonGroupFilter.addButton(self.radioButtonPrYear)
        self.radioButtonPrYear.setObjectName(u"radioButtonPrYear")
        self.radioButtonPrYear.setToolTip(u"")
        self.radioButtonPrYear.setStatusTip(u"")
        self.radioButtonPrYear.setWhatsThis(u"")
        self.radioButtonPrYear.setAccessibleName(u"")
        self.radioButtonPrYear.setAccessibleDescription(u"")
        self.radioButtonPrYear.setText(u"Previous Year")

        self.gridLayout_2.addWidget(self.radioButtonPrYear, 4, 0, 1, 1)

        self.radioButtonPrMonth = QRadioButton(self.groupBoxFilters)
        self.buttonGroupFilter.addButton(self.radioButtonPrMonth)
        self.radioButtonPrMonth.setObjectName(u"radioButtonPrMonth")
        self.radioButtonPrMonth.setToolTip(u"")
        self.radioButtonPrMonth.setStatusTip(u"")
        self.radioButtonPrMonth.setWhatsThis(u"")
        self.radioButtonPrMonth.setAccessibleName(u"")
        self.radioButtonPrMonth.setAccessibleDescription(u"")
        self.radioButtonPrMonth.setText(u"Previous Month")

        self.gridLayout_2.addWidget(self.radioButtonPrMonth, 2, 0, 1, 1)

        self.dateEditFilterFrom = QDateEdit(self.groupBoxFilters)
        self.dateEditFilterFrom.setObjectName(u"dateEditFilterFrom")
        self.dateEditFilterFrom.setToolTip(u"")
        self.dateEditFilterFrom.setStatusTip(u"")
        self.dateEditFilterFrom.setWhatsThis(u"")
        self.dateEditFilterFrom.setAccessibleName(u"")
        self.dateEditFilterFrom.setAccessibleDescription(u"")
        self.dateEditFilterFrom.setSpecialValueText(u"")
        self.dateEditFilterFrom.setDisplayFormat(u"dd.MM.yyyy")
        self.dateEditFilterFrom.setCalendarPopup(True)
        self.dateEditFilterFrom.setTimeSpec(Qt.UTC)

        self.gridLayout_2.addWidget(self.dateEditFilterFrom, 5, 0, 1, 1)

        self.dateEditFilterTo = QDateEdit(self.groupBoxFilters)
        self.dateEditFilterTo.setObjectName(u"dateEditFilterTo")
        self.dateEditFilterTo.setToolTip(u"")
        self.dateEditFilterTo.setStatusTip(u"")
        self.dateEditFilterTo.setWhatsThis(u"")
        self.dateEditFilterTo.setAccessibleName(u"")
        self.dateEditFilterTo.setAccessibleDescription(u"")
        self.dateEditFilterTo.setSpecialValueText(u"")
        self.dateEditFilterTo.setDisplayFormat(u"dd.MM.yyyy")
        self.dateEditFilterTo.setCalendarPopup(True)
        self.dateEditFilterTo.setTimeSpec(Qt.UTC)

        self.gridLayout_2.addWidget(self.dateEditFilterTo, 5, 1, 1, 1)

        self.pushButtonAppFilter = QPushButton(self.groupBoxFilters)
        self.pushButtonAppFilter.setObjectName(u"pushButtonAppFilter")
        self.pushButtonAppFilter.setToolTip(u"")
        self.pushButtonAppFilter.setStatusTip(u"")
        self.pushButtonAppFilter.setWhatsThis(u"")
        self.pushButtonAppFilter.setAccessibleName(u"")
        self.pushButtonAppFilter.setAccessibleDescription(u"")
        self.pushButtonAppFilter.setText(u"Apply Filter")

        self.gridLayout_2.addWidget(self.pushButtonAppFilter, 7, 0, 1, 1)

        self.pushButtonResetFilter = QPushButton(self.groupBoxFilters)
        self.pushButtonResetFilter.setObjectName(u"pushButtonResetFilter")
        self.pushButtonResetFilter.setToolTip(u"")
        self.pushButtonResetFilter.setStatusTip(u"")
        self.pushButtonResetFilter.setWhatsThis(u"")
        self.pushButtonResetFilter.setAccessibleName(u"")
        self.pushButtonResetFilter.setAccessibleDescription(u"")
        self.pushButtonResetFilter.setText(u"Reset Filter")

        self.gridLayout_2.addWidget(self.pushButtonResetFilter, 7, 1, 1, 1)

        self.retranslateUi(MainWindow)
        self.Tab1.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(
            _translate("Yet Another Log Book", "Yet Another Log Book"))
        self.ButtonAddLeg.setText(_translate("MainWindow", "Add Leg"))
        self.ButtonAddAC.setText(_translate("MainWindow", "Add A/C"))
        self.Tab1.setTabText(self.Tab1.indexOf(self.tab),
                             _translate("MainWindow", "Log Book"))
        self.Tab1.setTabText(self.Tab1.indexOf(self.tab_2),
                             _translate("MainWindow", "Tab 2"))