def insertItems(self, idx, lst):
     self.minWidth = 0
     if isinstance(lst, basestring): lst = [
             lst,
     ]
     if not isinstance(lst, list): lst = list(lst)
     QComboBox.insertItems(self, idx, lst)
class GeneralSection(QWidget):

    def __init__(self):
        super(GeneralSection, self).__init__()
        container = QVBoxLayout(self)

        # Inicio
        group_on_start = QGroupBox(self.tr("Al Iniciar:"))
        box = QVBoxLayout(group_on_start)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_splash = QCheckBox(self.tr("Mostrar Splash"))
        self.check_splash.setChecked(
            settings.get_setting('general/show-splash'))
        box.addWidget(self.check_splash)
        self.check_on_start = QCheckBox(self.tr("Mostrar Página de Inicio"))
        show_start_page = settings.get_setting('general/show-start-page')
        self.check_on_start.setChecked(show_start_page)
        box.addWidget(self.check_on_start)
        self.check_load_files = QCheckBox(self.tr("Cargar archivos desde la "
                                          "última sesión"))
        load_files = settings.get_setting('general/load-files')
        self.check_load_files.setChecked(load_files)
        box.addWidget(self.check_load_files)
        container.addWidget(group_on_start)

        # Al salir
        group_on_exit = QGroupBox(self.tr("Al Salir:"))
        box = QVBoxLayout(group_on_exit)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_on_exit = QCheckBox(self.tr("Confirmar Salida"))
        self.check_on_exit.setChecked(
            settings.get_setting('general/confirm-exit'))
        box.addWidget(self.check_on_exit)
        self.check_geometry = QCheckBox(self.tr(
            "Guardar posición y tamaño de la ventana"))
        self.check_geometry.setChecked(
            settings.get_setting('window/store-size'))
        box.addWidget(self.check_geometry)
        container.addWidget(group_on_exit)

        # Notificaciones
        group_notifications = QGroupBox(self.tr("Notificaciones:"))
        box = QVBoxLayout(group_notifications)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_updates = QCheckBox(self.tr("Buscar Actualizaciones"))
        self.check_updates.setChecked(
            settings.get_setting('general/check-updates'))
        box.addWidget(self.check_updates)
        container.addWidget(group_notifications)

        # Sistema
        if settings.IS_LINUX:
            group_terminal = QGroupBox(self.tr("Sistema:"))
            box = QHBoxLayout(group_terminal)
            box.addWidget(QLabel(self.tr("Ejecutar programa con:")))
            self.line_terminal = QLineEdit()
            self.line_terminal.setAlignment(Qt.AlignLeft)
            self.line_terminal.setFixedWidth(300)
            self.line_terminal.setText(settings.get_setting('terminal'))
            box.addWidget(self.line_terminal, 1, Qt.AlignLeft)
            container.addWidget(group_terminal)

        # User Interface
        group_ui = QGroupBox(self.tr("Interfáz de Usuario:"))
        box = QGridLayout(group_ui)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Tema:")), 0, 0)
        self.combo_theme = QComboBox()
        self.combo_theme.setFixedWidth(200)
        self._update_combo()
        index = self.combo_theme.findText(
            settings.get_setting('window/style-sheet'))
        self.combo_theme.setCurrentIndex(index)
        box.addWidget(self.combo_theme, 0, 1)

        self.combo_lang = QComboBox()
        self.combo_lang.setFixedWidth(200)
        box.addWidget(QLabel(self.tr("Idioma:")), 1, 0)
        box.addWidget(self.combo_lang, 1, 1)
        langs = os.listdir(os.path.join(paths.PATH, "extras", "i18n"))
        self.combo_lang.addItems(["Spanish"] + [lang[:-3] for lang in langs])
        lang = settings.get_setting('general/language')
        index = 0 if not lang else self.combo_lang.findText(lang)
        self.combo_lang.setCurrentIndex(index)
        container.addWidget(group_ui)
        box.setAlignment(Qt.AlignLeft)

        # Reestablecer
        group_restart = QGroupBox(self.tr("Reestablecer:"))
        box = QHBoxLayout(group_restart)
        box.setContentsMargins(20, 5, 20, 5)
        btn_restart = QPushButton(self.tr("Reiniciar configuraciones"))
        btn_restart.setObjectName("custom")
        box.addWidget(btn_restart)
        box.addStretch(1)
        container.addWidget(group_restart)

        container.addItem(QSpacerItem(0, 0,
                          QSizePolicy.Expanding, QSizePolicy.Expanding))

        # Conexiones
        btn_restart.clicked.connect(self._restart_configurations)
        self.combo_theme.currentIndexChanged[int].connect(
            self._change_style_sheet)

        # Install
        EnvironmentConfiguration.install_widget(self.tr("General"), self)

    def _update_combo(self):
        self.combo_theme.addItems(['Default', 'Edark'])
        list_dir = os.listdir(paths.EDIS)
        list_styles = [i.split('.')[0]for i
                       in list_dir
                       if os.path.splitext(i)[-1] == '.qss']
        self.combo_theme.insertItems(2, list_styles)

    def _change_style_sheet(self, index):
        style_sheet = None
        path = None
        if index == 1:
            path = os.path.join(paths.PATH, "extras",
                                "theme", "edark.qss")
        elif index != 0:
            style = self.combo_styles.currentText() + '.qss'
            path = os.path.join(paths.EDIS, style)
        if path is not None:
            with open(path, mode='r') as f:
                style_sheet = f.read()
        QApplication.instance().setStyleSheet(style_sheet)

    def _restart_configurations(self):
        flags = QMessageBox.Cancel
        flags |= QMessageBox.Yes

        result = QMessageBox.question(self, self.tr("Advertencia!"),
                                      self.tr("Está seguro que quiere "
                                              "reestablecer las "
                                              "configuraciones?"),
                                      flags)
        if result == QMessageBox.Cancel:
            return
        elif result == QMessageBox.Yes:
            QSettings(paths.CONFIGURACION, QSettings.IniFormat).clear()
            dialog_preferences = Edis.get_component("preferences")
            dialog_preferences.close()

    def save(self):

        settings.set_setting('general/show-splash',
                             self.check_splash.isChecked())
        show_start_page = self.check_on_start.isChecked()
        settings.set_setting('general/show-start-page', show_start_page)
        settings.set_setting('ventana/store-size',
                             self.check_geometry.isChecked())
        settings.set_setting('general/confirm-exit',
                             self.check_on_exit.isChecked())
        settings.set_setting('general/check-updates',
                             self.check_updates.isChecked())
        load_files = self.check_load_files.isChecked()
        settings.set_setting('general/load-files', load_files)
        lang = self.combo_lang.currentText()
        settings.set_setting('general/language', lang)
        if settings.IS_LINUX:
            settings.set_setting('terminal', self.line_terminal.text())
Beispiel #3
0
class PDFWidget(QWidget):
    scaleFactors = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0]
    scalePercents = ["25%", "50%", "75%", "100%", "125%", "150%", "200%"]

    def __init__(self):
        QWidget.__init__(self)
        self.hboxLayout = QVBoxLayout()
        self.setLayout(self.hboxLayout)
        self.setMenu()
        self.setPDFLabelScrollArea()

        self.connect(self.pageLineEdit, SIGNAL("valueChanged(int)"),
                     self.pdfLabel.setPage)
        self.connect(self.pdfLabel, SIGNAL("pageChanged"),
                     self.pageLineEdit.setPageNumberValue)
        self.connect(self.pdfLabel, SIGNAL("pageChanged"), self.scrollToTop)

        self.connect(self.scaleComboBox, SIGNAL("currentIndexChanged(int)"),
                     self.scaleDocument)

        self.connect(self.searchLineEdit, SIGNAL("returnPressed()"),
                     self.searchDocument)
        self.connect(self.findButton, SIGNAL("clicked()"), self.searchDocument)
        self.connect(self.clearButton, SIGNAL("clicked()"),
                     self.pdfLabel.setPage)
        self.connect(self.searchLineEdit, SIGNAL("textChanged(QString)"),
                     self.checkSearchText)
        self.connect(self, SIGNAL("setDocument"), self.setDocument)

    def setMenu(self):
        self.menuLayout = QHBoxLayout()
        self.hboxLayout.addLayout(self.menuLayout)
        self.pageLineEdit = PageLineEdit()
        self.pageLineEdit.setEnabled(False)
        self.menuLayout.addLayout(self.pageLineEdit)

        spacer = QSpacerItem(20, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.menuLayout.addItem(spacer)

        self.searchLayout = QHBoxLayout()
        self.menuLayout.addLayout(self.searchLayout)
        self.searchLabel = QLabel(self.tr("Search:"))
        self.searchLabel.setTextFormat(Qt.AutoText)
        self.searchLayout.addWidget(self.searchLabel)
        self.searchLineEdit = QLineEdit()
        self.searchLineEdit.setEnabled(False)
        self.searchLabel.setBuddy(self.searchLineEdit)
        self.searchLayout.addWidget(self.searchLineEdit)
        self.searchComboBox = QComboBox()
        self.searchComboBox.setEnabled(False)
        self.searchComboBox.insertItems(0, ["Forwards", "Backwards"])
        self.searchLayout.addWidget(self.searchComboBox)
        self.findButton = QPushButton("Find")
        self.findButton.setEnabled(False)
        self.searchLayout.addWidget(self.findButton)
        self.clearButton = QPushButton("Clear")
        self.clearButton.setEnabled(False)
        self.searchLayout.addWidget(self.clearButton)

        spacer = QSpacerItem(20, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.menuLayout.addItem(spacer)

        self.scaleLabel = QLabel("Scale:")
        self.menuLayout.addWidget(self.scaleLabel)
        self.scaleComboBox = QComboBox()
        self.scaleComboBox.setEnabled(False)
        self.scaleComboBox.insertItems(0, self.scalePercents)
        self.scaleComboBox.setCurrentIndex(3)
        self.scaleLabel.setBuddy(self.scaleComboBox)
        self.menuLayout.addWidget(self.scaleComboBox)

    def setPDFLabelScrollArea(self):
        self.pdfLabel = PDFLabel(self)
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setAlignment(Qt.AlignCenter)
        self.scrollArea.setWidget(self.pdfLabel)
        self.hboxLayout.addWidget(self.scrollArea)

    def scrollToTop(self, value):
        self.scrollArea.verticalScrollBar().setValue(0)

    def setDocument(self, data):
        if self.pdfLabel.setDocument(data):
            self.searchLineEdit.setEnabled(True)
            self.searchComboBox.setEnabled(True)
            self.findButton.setEnabled(True)
            self.clearButton.setEnabled(True)
            self.scaleComboBox.setEnabled(True)
            self.pageLineEdit.setEnabled(True)
            self.pageLineEdit.setPageNumberValue(1)
            self.pageLineEdit.setMaximumPageNumber(
                self.pdfLabel.document().numPages())

    def setError(self, errorMessage):
        self.pdfLabel.setError(errorMessage)

    def setMessage(self, message):
        self.pdfLabel.setText(message)

    def checkSearchText(self, text):
        if text == "":
            self.pdfLabel.setPage()

    def scaleDocument(self, index):
        self.pdfLabel.setScale(self.scaleFactors[index])

    def searchDocument(self):
        if self.searchComboBox.currentIndex() == 0:
            location = self.pdfLabel.searchForwards(self.searchLineEdit.text())
        else:
            location = self.pdfLabel.searchBackwards(
                self.searchLineEdit.text())

        target = self.pdfLabel.matrix().mapRect(location).center().toPoint()
        self.scrollArea.ensureVisible(target.x(), target.y())
class ProfileWizard(StandaloneWizardPage):
    """Wizard for the creation of a new database
profile.

.. attribute:: languages
.. attribute:: dialects

A list of languages allowed in the profile selection, an empty list will
allow all languages
    """

    languages = []
    dialects = []

    def __init__(self, profiles, parent=None):
        super(ProfileWizard, self).__init__(parent)

        self._connection_valid = False
        self.network_reply = None
        self.profiles = profiles

        self.setWindowTitle(_('Profile Wizard'))
        self.set_banner_logo_pixmap(art.Icon('tango/22x22/categories/preferences-system.png').getQPixmap())
        self.set_banner_title(_('Create New/Edit Profile'))
        self.set_banner_subtitle(_('Please enter the database settings'))
        self.banner_widget().setStyleSheet('background-color: white;')

        self.manager = QtNetwork.QNetworkAccessManager( self )
        self.manager.finished.connect( self.update_network_status )
        #self.manager.networkAccessibleChanged.connect( self.network_accessible_changed )
        self.manager.proxyAuthenticationRequired.connect( self.proxy_authentication_required )
        
        self.create_labels_and_widgets()
        self.create_buttons()
        self.set_tab_order()
        self.set_widgets_values()
        # note: connections come after labels and widgets are created
        # and have default values
        self.connect_widgets()
        self.connect_buttons()
        
        timer = QtCore.QTimer(self)
        timer.timeout.connect( self.new_network_request )
        timer.setInterval( 3000 )
        timer.start()
        self.new_network_request()

    def create_labels_and_widgets(self):
        assert object_thread( self )
        self.profile_label = QLabel(_('Profile Name:'))
        self.dialect_label = QLabel(_('Driver:'))
        self.host_label = QLabel(_('Server Host:'))
        self.port_label = QLabel(_('Port:'))
        self.database_name_label = QLabel(_('Database Name:'))
        self.username_label = QLabel(_('Username:'******'Password:'******'Media Location:'))
        self.language_label = QLabel(_('Language:'))
        self.proxy_host_label = QLabel(_('Proxy Host:'))
        self.proxy_port_label = QLabel(_('Port:'))
        self.proxy_username_label = QLabel(_('Proxy Username:'******'Proxy Password:'******'Media location path '\
            'is not accessible.'))
        self.not_accessible_media_path_label.setStyleSheet('color: red')
        self.not_writable_media_path_label = QLabel(_('Media location path '\
            'is not writable.'))
        self.not_writable_media_path_label.setStyleSheet('color: red')

        layout = QGridLayout()

        layout.addWidget(self.profile_label, 0, 0, Qt.AlignRight)
        layout.addWidget(self.dialect_label, 1, 0, Qt.AlignRight)
        layout.addWidget(self.host_label, 2, 0, Qt.AlignRight)
        layout.addWidget(self.port_label, 2, 3, Qt.AlignRight)
        layout.addWidget(self.database_name_label, 3, 0, Qt.AlignRight)
        layout.addWidget(self.username_label, 4, 0, Qt.AlignRight)
        layout.addWidget(self.password_label, 5, 0, Qt.AlignRight)
        layout.addWidget(self.media_location_label, 7, 0, Qt.AlignRight)
        layout.addWidget(self.language_label, 8, 0, Qt.AlignRight)
        layout.addWidget(self.proxy_host_label,  10, 0, Qt.AlignRight)
        layout.addWidget(self.proxy_port_label,  10, 3, Qt.AlignRight)
        layout.addWidget(self.proxy_username_label, 11, 0, Qt.AlignRight)
        layout.addWidget(self.proxy_password_label, 12, 0, Qt.AlignRight)

        self.profile_editor = QComboBox(self)
        self.profile_editor.setEditable(True)

        # 32767 is Qt max length for string
        # should be more than enough for folders
        # http://doc.qt.nokia.com/latest/qlineedit.html#maxLength-prop
        self.dialect_editor = ChoicesEditor(parent=self)
        self.host_editor = TextLineEditor(self, length=32767)
        self.host_editor.set_value('')
        self.port_editor = TextLineEditor(self)
        self.port_editor.setFixedWidth(60)
        self.port_editor.set_value('')
        self.database_name_editor = TextLineEditor(self, length=32767)
        self.database_name_editor.set_value('')
        self.username_editor = TextLineEditor(self)
        self.username_editor.set_value('')
        self.password_editor = TextLineEditor(self)
        self.password_editor.setEchoMode(QLineEdit.Password)
        self.password_editor.set_value('')
        self.media_location_editor = TextLineEditor(self, length=32767)
        self.media_location_editor.set_value('')
        self.language_editor = LanguageEditor(languages=self.languages,
                                              parent=self)
        #
        # try to find a default language
        #
        system_language = QtCore.QLocale.system().name()
        if self.languages:
            if system_language in self.languages:
                self.language_editor.set_value( system_language )
            else:
                self.language_editor.set_value( self.languages[0] )
        else:
            self.language_editor.set_value( system_language )

        self.proxy_host_editor = TextLineEditor(self, length=32767)
        self.proxy_host_editor.set_value('')
        self.proxy_port_editor = TextLineEditor(self)
        self.proxy_port_editor.setFixedWidth(60)
        self.proxy_port_editor.set_value('')
        self.proxy_username_editor = TextLineEditor(self)
        self.proxy_username_editor.set_value('')
        self.proxy_password_editor = TextLineEditor(self)
        self.proxy_password_editor.set_value('')
        self.proxy_password_editor.setEchoMode(QLineEdit.Password)

        layout.addWidget(self.profile_editor, 0, 1, 1, 1)
        layout.addWidget(self.dialect_editor, 1, 1, 1, 1)
        layout.addWidget(self.host_editor, 2, 1, 1, 1)
        layout.addWidget(self.port_editor, 2, 4, 1, 1)
        layout.addWidget(self.database_name_editor, 3, 1, 1, 1)
        layout.addWidget(self.username_editor, 4, 1, 1, 1)
        layout.addWidget(self.password_editor, 5, 1, 1, 1)
        layout.addWidget(HSeparator(), 6, 0, 1, 5)
        layout.addWidget(self.media_location_editor, 7, 1, 1, 1)
        layout.addWidget(self.language_editor, 8, 1, 1, 1)
        layout.addWidget(HSeparator(), 9, 0, 1, 5)
        layout.addWidget(self.proxy_host_editor, 10, 1, 1, 1)
        layout.addWidget(self.proxy_port_editor, 10, 4, 1, 1)
        layout.addWidget(self.proxy_username_editor, 11, 1, 1, 1)
        layout.addWidget(self.proxy_password_editor, 12, 1, 1, 1)
        
        layout.addWidget(self.network_status_label, 13, 1, 1, 4)
        
        self.main_widget().setLayout(layout)

    def set_widgets_values(self):
        self.dialect_editor.clear()
        self.profile_editor.clear()
        
        if self.dialects:
            dialects = self.dialects
        else:
            import sqlalchemy.dialects
            dialects = [name for _importer, name, is_package in \
                        pkgutil.iter_modules(sqlalchemy.dialects.__path__) \
                        if is_package]
        self.dialect_editor.set_choices([(dialect, dialect.capitalize()) \
            for dialect in dialects])

        self.profile_editor.insertItems(1, [''] + \
            [item for item in fetch_profiles()])
        self.profile_editor.setFocus()
        self.update_wizard_values()

    def connect_widgets(self):
        self.profile_editor.editTextChanged.connect(self.update_wizard_values)
        # self.dialect_editor.currentIndexChanged.connect(self.update_wizard_values)    
    
    def create_buttons(self):
        self.more_button = QPushButton(_('More'))
        self.more_button.setCheckable(True)
        self.more_button.setAutoDefault(False)
        self.cancel_button = QPushButton(_('Cancel'))
        self.ok_button = QPushButton(_('OK'))

        layout = QHBoxLayout()
        layout.setDirection(QBoxLayout.RightToLeft)

        layout.addWidget(self.cancel_button)
        layout.addWidget(self.ok_button)
        layout.addStretch()
        layout.addWidget(self.more_button)

        self.buttons_widget().setLayout(layout)

        self.browse_button = QPushButton(_('Browse'))
        self.main_widget().layout().addWidget(self.browse_button, 7, 2, 1, 3)

        self.setup_extension()

    def setup_extension(self):
        self.extension = QWidget()

        self.load_button = QPushButton(_('Load profiles'))
        self.save_button = QPushButton(_('Save profiles'))

        extension_buttons_layout = QHBoxLayout()
        extension_buttons_layout.setContentsMargins(0, 0, 0, 0)
        extension_buttons_layout.addWidget(self.load_button)
        extension_buttons_layout.addWidget(self.save_button)
        extension_buttons_layout.addStretch()

        extension_layout = QVBoxLayout()
        extension_layout.setContentsMargins(0, 0, 0, 0)
        extension_layout.addWidget(HSeparator())
        extension_layout.addLayout(extension_buttons_layout)

        self.extension.setLayout(extension_layout)
        self.main_widget().layout().addWidget(self.extension, 15, 0, 1, 5)
        self.extension.hide()

    def set_tab_order(self):
        all_widgets = [self.profile_editor, self.dialect_editor,
            self.host_editor, self.port_editor,  self.database_name_editor,
            self.username_editor, self.password_editor,
            self.media_location_editor, self.browse_button,
            self.language_editor,
            self.proxy_host_editor, self.proxy_port_editor,
            self.proxy_username_editor, self.proxy_password_editor,
            self.ok_button, self.cancel_button]

        i = 1
        while i != len(all_widgets):
            self.setTabOrder(all_widgets[i-1], all_widgets[i])
            i += 1

    def connect_buttons(self):
        self.cancel_button.pressed.connect(self.reject)
        self.ok_button.pressed.connect(self.proceed)
        self.browse_button.pressed.connect(self.fill_media_location)
        self.more_button.toggled.connect(self.extension.setVisible)
        self.save_button.pressed.connect(self.save_profiles_to_file)
        self.load_button.pressed.connect(self.load_profiles_from_file)

    def proceed(self):
        if self.is_connection_valid():
            profilename, info = self.collect_info()
            if profilename in self.profiles:
                self.profiles[profilename].update(info)
            else:
                self.profiles[profilename] = info
            store_profiles(self.profiles)
            use_chosen_profile(profilename)
            self.accept()

    def is_connection_valid(self):
        profilename, info = self.collect_info()
        mt = SignalSlotModelThread(lambda:None)
        mt.start()
        progress = ProgressDialog(_('Verifying database settings'))
        mt.post(lambda:self.test_connection( info ),
            progress.finished, progress.exception)
        progress.exec_()
        return self._connection_valid

    def test_connection(self, profile):
        self._connection_valid = False
        connection_string = connection_string_from_profile( profile )
        engine = create_engine(connection_string, pool_recycle=True)
        try:
            connection = engine.raw_connection()
            cursor = connection.cursor()
            cursor.close()
            connection.close()
            self._connection_valid = True
        except Exception, e:
            self._connection_valid = False
            raise UserException( _('Could not connect to database, please check host and port'),
                                 resolution = _('Verify driver, host and port or contact your system administrator'),
                                 detail = unicode(e) )
Beispiel #5
0
class ProfileWizard(StandaloneWizardPage):
    """Wizard for the creation of a new database
profile.

.. attribute:: languages
.. attribute:: dialects

A list of languages allowed in the profile selection, an empty list will
allow all languages
    """

    languages = []
    dialects = []

    def __init__(self, profiles, parent=None):
        super(ProfileWizard, self).__init__(parent)

        self._connection_valid = False
        self.network_reply = None
        self.profiles = profiles

        self.setWindowTitle(_('Profile Wizard'))
        self.set_banner_logo_pixmap(
            art.Icon(
                'tango/22x22/categories/preferences-system.png').getQPixmap())
        self.set_banner_title(_('Create New/Edit Profile'))
        self.set_banner_subtitle(_('Please enter the database settings'))
        self.banner_widget().setStyleSheet('background-color: white;')

        self.manager = QtNetwork.QNetworkAccessManager(self)
        self.manager.finished.connect(self.update_network_status)
        #self.manager.networkAccessibleChanged.connect( self.network_accessible_changed )
        self.manager.proxyAuthenticationRequired.connect(
            self.proxy_authentication_required)

        self.create_labels_and_widgets()
        self.create_buttons()
        self.set_tab_order()
        self.set_widgets_values()
        # note: connections come after labels and widgets are created
        # and have default values
        self.connect_widgets()
        self.connect_buttons()

        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.new_network_request)
        timer.setInterval(3000)
        timer.start()
        self.new_network_request()

    def create_labels_and_widgets(self):
        assert object_thread(self)
        self.profile_label = QLabel(_('Profile Name:'))
        self.dialect_label = QLabel(_('Driver:'))
        self.host_label = QLabel(_('Server Host:'))
        self.port_label = QLabel(_('Port:'))
        self.database_name_label = QLabel(_('Database Name:'))
        self.username_label = QLabel(_('Username:'******'Password:'******'Media Location:'))
        self.language_label = QLabel(_('Language:'))
        self.proxy_host_label = QLabel(_('Proxy Host:'))
        self.proxy_port_label = QLabel(_('Port:'))
        self.proxy_username_label = QLabel(_('Proxy Username:'******'Proxy Password:'******'Media location path '\
            'is not accessible.'))
        self.not_accessible_media_path_label.setStyleSheet('color: red')
        self.not_writable_media_path_label = QLabel(_('Media location path '\
            'is not writable.'))
        self.not_writable_media_path_label.setStyleSheet('color: red')

        layout = QGridLayout()

        layout.addWidget(self.profile_label, 0, 0, Qt.AlignRight)
        layout.addWidget(self.dialect_label, 1, 0, Qt.AlignRight)
        layout.addWidget(self.host_label, 2, 0, Qt.AlignRight)
        layout.addWidget(self.port_label, 2, 3, Qt.AlignRight)
        layout.addWidget(self.database_name_label, 3, 0, Qt.AlignRight)
        layout.addWidget(self.username_label, 4, 0, Qt.AlignRight)
        layout.addWidget(self.password_label, 5, 0, Qt.AlignRight)
        layout.addWidget(self.media_location_label, 7, 0, Qt.AlignRight)
        layout.addWidget(self.language_label, 8, 0, Qt.AlignRight)
        layout.addWidget(self.proxy_host_label, 10, 0, Qt.AlignRight)
        layout.addWidget(self.proxy_port_label, 10, 3, Qt.AlignRight)
        layout.addWidget(self.proxy_username_label, 11, 0, Qt.AlignRight)
        layout.addWidget(self.proxy_password_label, 12, 0, Qt.AlignRight)

        self.profile_editor = QComboBox(self)
        self.profile_editor.setEditable(True)

        # 32767 is Qt max length for string
        # should be more than enough for folders
        # http://doc.qt.nokia.com/latest/qlineedit.html#maxLength-prop
        self.dialect_editor = ChoicesEditor(parent=self)
        self.host_editor = TextLineEditor(self, length=32767)
        self.host_editor.set_value('')
        self.port_editor = TextLineEditor(self)
        self.port_editor.setFixedWidth(60)
        self.port_editor.set_value('')
        self.database_name_editor = TextLineEditor(self, length=32767)
        self.database_name_editor.set_value('')
        self.username_editor = TextLineEditor(self)
        self.username_editor.set_value('')
        self.password_editor = TextLineEditor(self)
        self.password_editor.setEchoMode(QLineEdit.Password)
        self.password_editor.set_value('')
        self.media_location_editor = TextLineEditor(self, length=32767)
        self.media_location_editor.set_value('')
        self.language_editor = LanguageEditor(languages=self.languages,
                                              parent=self)
        #
        # try to find a default language
        #
        system_language = QtCore.QLocale.system().name()
        if self.languages:
            if system_language in self.languages:
                self.language_editor.set_value(system_language)
            else:
                self.language_editor.set_value(self.languages[0])
        else:
            self.language_editor.set_value(system_language)

        self.proxy_host_editor = TextLineEditor(self, length=32767)
        self.proxy_host_editor.set_value('')
        self.proxy_port_editor = TextLineEditor(self)
        self.proxy_port_editor.setFixedWidth(60)
        self.proxy_port_editor.set_value('')
        self.proxy_username_editor = TextLineEditor(self)
        self.proxy_username_editor.set_value('')
        self.proxy_password_editor = TextLineEditor(self)
        self.proxy_password_editor.set_value('')
        self.proxy_password_editor.setEchoMode(QLineEdit.Password)

        layout.addWidget(self.profile_editor, 0, 1, 1, 1)
        layout.addWidget(self.dialect_editor, 1, 1, 1, 1)
        layout.addWidget(self.host_editor, 2, 1, 1, 1)
        layout.addWidget(self.port_editor, 2, 4, 1, 1)
        layout.addWidget(self.database_name_editor, 3, 1, 1, 1)
        layout.addWidget(self.username_editor, 4, 1, 1, 1)
        layout.addWidget(self.password_editor, 5, 1, 1, 1)
        layout.addWidget(HSeparator(), 6, 0, 1, 5)
        layout.addWidget(self.media_location_editor, 7, 1, 1, 1)
        layout.addWidget(self.language_editor, 8, 1, 1, 1)
        layout.addWidget(HSeparator(), 9, 0, 1, 5)
        layout.addWidget(self.proxy_host_editor, 10, 1, 1, 1)
        layout.addWidget(self.proxy_port_editor, 10, 4, 1, 1)
        layout.addWidget(self.proxy_username_editor, 11, 1, 1, 1)
        layout.addWidget(self.proxy_password_editor, 12, 1, 1, 1)

        layout.addWidget(self.network_status_label, 13, 1, 1, 4)

        self.main_widget().setLayout(layout)

    def set_widgets_values(self):
        self.dialect_editor.clear()
        self.profile_editor.clear()

        if self.dialects:
            dialects = self.dialects
        else:
            import sqlalchemy.dialects
            dialects = [name for _importer, name, is_package in \
                        pkgutil.iter_modules(sqlalchemy.dialects.__path__) \
                        if is_package]
        self.dialect_editor.set_choices([(dialect, dialect.capitalize()) \
            for dialect in dialects])

        self.profile_editor.insertItems(1, [''] + \
            [item for item in fetch_profiles()])
        self.profile_editor.setFocus()
        self.update_wizard_values()

    def connect_widgets(self):
        self.profile_editor.editTextChanged.connect(self.update_wizard_values)
        # self.dialect_editor.currentIndexChanged.connect(self.update_wizard_values)

    def create_buttons(self):
        self.more_button = QPushButton(_('More'))
        self.more_button.setCheckable(True)
        self.more_button.setAutoDefault(False)
        self.cancel_button = QPushButton(_('Cancel'))
        self.ok_button = QPushButton(_('OK'))

        layout = QHBoxLayout()
        layout.setDirection(QBoxLayout.RightToLeft)

        layout.addWidget(self.cancel_button)
        layout.addWidget(self.ok_button)
        layout.addStretch()
        layout.addWidget(self.more_button)

        self.buttons_widget().setLayout(layout)

        self.browse_button = QPushButton(_('Browse'))
        self.main_widget().layout().addWidget(self.browse_button, 7, 2, 1, 3)

        self.setup_extension()

    def setup_extension(self):
        self.extension = QWidget()

        self.load_button = QPushButton(_('Load profiles'))
        self.save_button = QPushButton(_('Save profiles'))

        extension_buttons_layout = QHBoxLayout()
        extension_buttons_layout.setContentsMargins(0, 0, 0, 0)
        extension_buttons_layout.addWidget(self.load_button)
        extension_buttons_layout.addWidget(self.save_button)
        extension_buttons_layout.addStretch()

        extension_layout = QVBoxLayout()
        extension_layout.setContentsMargins(0, 0, 0, 0)
        extension_layout.addWidget(HSeparator())
        extension_layout.addLayout(extension_buttons_layout)

        self.extension.setLayout(extension_layout)
        self.main_widget().layout().addWidget(self.extension, 15, 0, 1, 5)
        self.extension.hide()

    def set_tab_order(self):
        all_widgets = [
            self.profile_editor, self.dialect_editor, self.host_editor,
            self.port_editor, self.database_name_editor, self.username_editor,
            self.password_editor, self.media_location_editor,
            self.browse_button, self.language_editor, self.proxy_host_editor,
            self.proxy_port_editor, self.proxy_username_editor,
            self.proxy_password_editor, self.ok_button, self.cancel_button
        ]

        i = 1
        while i != len(all_widgets):
            self.setTabOrder(all_widgets[i - 1], all_widgets[i])
            i += 1

    def connect_buttons(self):
        self.cancel_button.pressed.connect(self.reject)
        self.ok_button.pressed.connect(self.proceed)
        self.browse_button.pressed.connect(self.fill_media_location)
        self.more_button.toggled.connect(self.extension.setVisible)
        self.save_button.pressed.connect(self.save_profiles_to_file)
        self.load_button.pressed.connect(self.load_profiles_from_file)

    def proceed(self):
        if self.is_connection_valid():
            profilename, info = self.collect_info()
            if profilename in self.profiles:
                self.profiles[profilename].update(info)
            else:
                self.profiles[profilename] = info
            store_profiles(self.profiles)
            use_chosen_profile(profilename)
            self.accept()

    def is_connection_valid(self):
        profilename, info = self.collect_info()
        mt = SignalSlotModelThread(lambda: None)
        mt.start()
        progress = ProgressDialog(_('Verifying database settings'))
        mt.post(lambda: self.test_connection(info), progress.finished,
                progress.exception)
        progress.exec_()
        return self._connection_valid

    def test_connection(self, profile):
        self._connection_valid = False
        connection_string = connection_string_from_profile(profile)
        engine = create_engine(connection_string, pool_recycle=True)
        try:
            connection = engine.raw_connection()
            cursor = connection.cursor()
            cursor.close()
            connection.close()
            self._connection_valid = True
        except Exception, e:
            self._connection_valid = False
            raise UserException(
                _('Could not connect to database, please check host and port'),
                resolution=
                _('Verify driver, host and port or contact your system administrator'
                  ),
                detail=unicode(e))
 def insertItems(self, idx, lst):
     self.minWidth = 0
     if isinstance(lst, basestring): lst = [lst,]
     if not isinstance(lst, list): lst = list(lst)
     QComboBox.insertItems(self, idx, lst)
Beispiel #7
0
class GeneralSection(QWidget):
    def __init__(self):
        super(GeneralSection, self).__init__()
        container = QVBoxLayout(self)

        # Inicio
        group_on_start = QGroupBox(self.tr("Al Iniciar:"))
        box = QVBoxLayout(group_on_start)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_splash = QCheckBox(self.tr("Mostrar Splash"))
        self.check_splash.setChecked(
            settings.get_setting('general/show-splash'))
        box.addWidget(self.check_splash)
        self.check_on_start = QCheckBox(self.tr("Mostrar Página de Inicio"))
        show_start_page = settings.get_setting('general/show-start-page')
        self.check_on_start.setChecked(show_start_page)
        box.addWidget(self.check_on_start)
        self.check_load_files = QCheckBox(
            self.tr("Cargar archivos desde la "
                    "última sesión"))
        load_files = settings.get_setting('general/load-files')
        self.check_load_files.setChecked(load_files)
        box.addWidget(self.check_load_files)
        container.addWidget(group_on_start)

        # Al salir
        group_on_exit = QGroupBox(self.tr("Al Salir:"))
        box = QVBoxLayout(group_on_exit)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_on_exit = QCheckBox(self.tr("Confirmar Salida"))
        self.check_on_exit.setChecked(
            settings.get_setting('general/confirm-exit'))
        box.addWidget(self.check_on_exit)
        self.check_geometry = QCheckBox(
            self.tr("Guardar posición y tamaño de la ventana"))
        self.check_geometry.setChecked(
            settings.get_setting('window/store-size'))
        box.addWidget(self.check_geometry)
        container.addWidget(group_on_exit)

        # Notificaciones
        group_notifications = QGroupBox(self.tr("Notificaciones:"))
        box = QVBoxLayout(group_notifications)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_updates = QCheckBox(self.tr("Buscar Actualizaciones"))
        self.check_updates.setChecked(
            settings.get_setting('general/check-updates'))
        box.addWidget(self.check_updates)
        container.addWidget(group_notifications)

        # Sistema
        if settings.IS_LINUX:
            group_terminal = QGroupBox(self.tr("Sistema:"))
            box = QHBoxLayout(group_terminal)
            box.addWidget(QLabel(self.tr("Ejecutar programa con:")))
            self.line_terminal = QLineEdit()
            self.line_terminal.setAlignment(Qt.AlignLeft)
            self.line_terminal.setFixedWidth(300)
            self.line_terminal.setText(settings.get_setting('terminal'))
            box.addWidget(self.line_terminal, 1, Qt.AlignLeft)
            container.addWidget(group_terminal)

        # User Interface
        group_ui = QGroupBox(self.tr("Interfáz de Usuario:"))
        box = QGridLayout(group_ui)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Tema:")), 0, 0)
        self.combo_theme = QComboBox()
        self.combo_theme.setFixedWidth(200)
        self._update_combo()
        index = self.combo_theme.findText(
            settings.get_setting('window/style-sheet'))
        self.combo_theme.setCurrentIndex(index)
        box.addWidget(self.combo_theme, 0, 1)

        self.combo_lang = QComboBox()
        self.combo_lang.setFixedWidth(200)
        box.addWidget(QLabel(self.tr("Idioma:")), 1, 0)
        box.addWidget(self.combo_lang, 1, 1)
        langs = os.listdir(os.path.join(paths.PATH, "extras", "i18n"))
        self.combo_lang.addItems(["Spanish"] + [lang[:-3] for lang in langs])
        lang = settings.get_setting('general/language')
        index = 0 if not lang else self.combo_lang.findText(lang)
        self.combo_lang.setCurrentIndex(index)
        container.addWidget(group_ui)
        box.setAlignment(Qt.AlignLeft)

        # Reestablecer
        group_restart = QGroupBox(self.tr("Reestablecer:"))
        box = QHBoxLayout(group_restart)
        box.setContentsMargins(20, 5, 20, 5)
        btn_restart = QPushButton(self.tr("Reiniciar configuraciones"))
        btn_restart.setObjectName("custom")
        box.addWidget(btn_restart)
        box.addStretch(1)
        container.addWidget(group_restart)

        container.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding))

        # Conexiones
        btn_restart.clicked.connect(self._restart_configurations)
        self.combo_theme.currentIndexChanged[int].connect(
            self._change_style_sheet)

        # Install
        EnvironmentConfiguration.install_widget(self.tr("General"), self)

    def _update_combo(self):
        self.combo_theme.addItems(['Default', 'Edark'])
        list_dir = os.listdir(paths.EDIS)
        list_styles = [
            i.split('.')[0] for i in list_dir
            if os.path.splitext(i)[-1] == '.qss'
        ]
        self.combo_theme.insertItems(2, list_styles)

    def _change_style_sheet(self, index):
        style_sheet = None
        path = None
        if index == 1:
            path = os.path.join(paths.PATH, "extras", "theme", "edark.qss")
        elif index != 0:
            style = self.combo_styles.currentText() + '.qss'
            path = os.path.join(paths.EDIS, style)
        if path is not None:
            with open(path, mode='r') as f:
                style_sheet = f.read()
        QApplication.instance().setStyleSheet(style_sheet)

    def _restart_configurations(self):
        flags = QMessageBox.Cancel
        flags |= QMessageBox.Yes

        result = QMessageBox.question(
            self, self.tr("Advertencia!"),
            self.tr("Está seguro que quiere "
                    "reestablecer las "
                    "configuraciones?"), flags)
        if result == QMessageBox.Cancel:
            return
        elif result == QMessageBox.Yes:
            QSettings(paths.CONFIGURACION, QSettings.IniFormat).clear()
            dialog_preferences = Edis.get_component("preferences")
            dialog_preferences.close()

    def save(self):

        settings.set_setting('general/show-splash',
                             self.check_splash.isChecked())
        show_start_page = self.check_on_start.isChecked()
        settings.set_setting('general/show-start-page', show_start_page)
        settings.set_setting('ventana/store-size',
                             self.check_geometry.isChecked())
        settings.set_setting('general/confirm-exit',
                             self.check_on_exit.isChecked())
        settings.set_setting('general/check-updates',
                             self.check_updates.isChecked())
        load_files = self.check_load_files.isChecked()
        settings.set_setting('general/load-files', load_files)
        lang = self.combo_lang.currentText()
        settings.set_setting('general/language', lang)
        if settings.IS_LINUX:
            settings.set_setting('terminal', self.line_terminal.text())