Пример #1
0
class BackgroundSelector(QWidget):

    """presents all available backgrounds with previews"""

    def __init__(self, parent):
        super(BackgroundSelector, self).__init__(parent)
        loadUi(self)
        self.kcfg_backgroundName = QLineEdit(self)
        self.kcfg_backgroundName.setVisible(False)
        self.kcfg_backgroundName.setObjectName('kcfg_backgroundName')
        self.setUp()

    def setUp(self):
        """fill the selector"""

        # The lineEdit widget holds our background path, but the user does
        # not manipulate it directly
        self.kcfg_backgroundName.hide()

        self.backgroundNameList.currentRowChanged.connect(
            self.backgroundRowChanged)
        self.kcfg_backgroundName.textChanged.connect(
            self.backgroundNameChanged)
        self.backgroundList = Background.available()
        for aset in self.backgroundList:
            self.backgroundNameList.addItem(aset.name)
        self.kcfg_backgroundName.setText(Internal.Preferences.backgroundName)

    def backgroundNameChanged(self, name):
        """the name changed: update the current row"""
        igrindex = 0
        for idx, aset in enumerate(self.backgroundList):
            if aset.desktopFileName == name:
                igrindex = idx
                break
        self.backgroundNameList.setCurrentRow(igrindex)

    def backgroundRowChanged(self):
        """user selected a new background, update our information about it and paint preview"""
        selBackground = self.backgroundList[
            self.backgroundNameList.currentRow()]
        self.kcfg_backgroundName.setText(selBackground.desktopFileName)
        self.backgroundAuthor.setText(selBackground.author)
        self.backgroundContact.setText(selBackground.authorEmail)
        self.backgroundDescription.setText(selBackground.description)
        selBackground.setPalette(self.backgroundPreview)
        self.backgroundPreview.setAutoFillBackground(True)
Пример #2
0
class EWOEntradaTexto(ElementoWidgetOpciones, QHBox):
    """Es una entrada de texto, con un nombre, que devuelve un valor insertado por el usuario"""
    def __init__(self, parent, nombre, valorpordefecto = ""):
        ElementoWidgetOpciones.__init__(self)
        QHBox.__init__(self, parent, "EntradaTexto")
        self.__etiqueta = QLabel(nombre, self)
        self.__entrada = QLineEdit(self, "Linea")
        self.__entrada.setText(valorpordefecto)
        self.nombre = nombre

    def opciones(self):
        """Devuelve las opciones seleccionadas"""
        if self.__entrada.text():
            return {self.nombre:self.__entrada.text().latin1()}
        else:
            return {}

    def activar(self):
        """Activa el widget"""
        self.__entrada.setEnabled(True)

    def desactivar(self):
        """Desactiva el widget"""
        self.__entrada.setEnabled(False)
Пример #3
0
class TilesetSelector(QWidget):
    """presents all available tiles with previews"""
    def __init__(self, parent):
        super(TilesetSelector, self).__init__(parent)

        loadUi(self)
        self.kcfg_tilesetName = QLineEdit(self)
        self.kcfg_tilesetName.setVisible(False)
        self.kcfg_tilesetName.setObjectName('kcfg_tilesetName')

        self.tileScene = SceneWithFocusRect()
        self.tileView = FittingView()
        self.tileView.setScene(self.tileScene)
        self.tileset = Tileset(Internal.Preferences.tilesetName)
        self.uiTiles = [UITile('w' + s.char.lower()) for s in Wind.all4]
        self.board = Board(2, 2, self.tileset)
        self.board.showShadows = True
        self.tileScene.addItem(self.board)
        self.tileView.setParent(self.tilesetPreview)
        layout = QHBoxLayout(self.tilesetPreview)
        layout.addWidget(self.tileView)
        for idx, offsets in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):
            self.uiTiles[idx].setBoard(self.board, *offsets)
            self.uiTiles[idx].focusable = False
        self.setUp()

    def setUp(self):
        """set-up the selector"""

        # The lineEdit widget holds our tileset path, but the user does
        # not manipulate it directly
        self.kcfg_tilesetName.hide()

        self.tilesetNameList.currentRowChanged.connect(self.tilesetRowChanged)
        self.kcfg_tilesetName.textChanged.connect(self.tilesetNameChanged)

        Tileset.loadAll()
        # list default tileset first
        self.tilesetList = Tileset.available()
        for aset in self.tilesetList:
            self.tilesetNameList.addItem(aset.name)
        self.kcfg_tilesetName.setText(Internal.Preferences.tilesetName)

    def tilesetNameChanged(self, name):
        """the name changed: update the current row"""
        igrindex = 0
        for idx, aset in enumerate(self.tilesetList):
            if aset.desktopFileName == name:
                igrindex = idx
                break
        self.tilesetNameList.setCurrentRow(igrindex)

    def tilesetRowChanged(self):
        """user selected a new tileset, update our information about it and
        paint preview"""
        selTileset = self.tilesetList[self.tilesetNameList.currentRow()]
        self.kcfg_tilesetName.setText(selTileset.desktopFileName)
        self.tilesetAuthor.setText(selTileset.author)
        self.tilesetContact.setText(selTileset.authorEmail)
        self.tilesetDescription.setText(selTileset.description)
        with AnimationSpeed():
            self.board.tileset = selTileset
Пример #4
0
class AddUserDialog(KDialog):
    """add a user account on a server: This dialog asks for the needed attributes"""

    # pylint: disable=too-many-instance-attributes

    def __init__(self, url, username, password):
        KDialog.__init__(self)
        decorateWindow(self, i18n('Create User Account'))
        self.setButtons(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))
        vbox = QVBoxLayout()
        grid = QFormLayout()
        self.lbServer = QLabel()
        self.lbServer.setText(url)
        grid.addRow(i18n('Game server:'), self.lbServer)
        self.lbUser = QLabel()
        grid.addRow(i18n('Username:'******'Password:'******'Repeat password:'), self.edPassword2)
        vbox.addLayout(grid)
        widget = QWidget(self)
        widget.setLayout(vbox)
        self.setMainWidget(widget)
        pol = QSizePolicy()
        pol.setHorizontalPolicy(QSizePolicy.Expanding)
        self.lbUser.setSizePolicy(pol)

        self.edPassword.textChanged.connect(self.passwordChanged)
        self.edPassword2.textChanged.connect(self.passwordChanged)
        StateSaver(self)
        self.username = username
        self.password = password
        self.passwordChanged()
        self.edPassword2.setFocus()

    def passwordChanged(self, dummyText=None):
        """password changed"""
        self.validate()

    def validate(self):
        """does the dialog hold valid data?"""
        equal = self.edPassword.size() and self.edPassword.text(
        ) == self.edPassword2.text()
        self.button(KDialog.Ok).setEnabled(equal)

    @property
    def username(self):
        """abstracts the username of the dialog"""
        return self.lbUser.text()

    @username.setter
    def username(self, username):
        """abstracts the username of the dialog"""
        self.lbUser.setText(username)

    @property
    def password(self):
        """abstracts the password of the dialog"""
        return self.edPassword.text()

    @password.setter
    def password(self, password):
        """abstracts the password of the dialog"""
        self.edPassword.setText(password)
Пример #5
0
class LoginDlg(QDialog):
    """login dialog for server"""
    def __init__(self):
        """self.servers is a list of tuples containing server and last playername"""
        QDialog.__init__(self, None)
        decorateWindow(self, i18nc('kajongg', 'Login'))
        self.setupUi()

        localName = i18nc('kajongg name for local game server',
                          Query.localServerName)
        self.servers = Query(
            'select url,lastname from server order by lasttime desc').records
        servers = list(x[0] for x in self.servers
                       if x[0] != Query.localServerName)
        # the first server combobox item should be default: either the last used server
        # or localName for autoPlay
        if localName not in servers:
            servers.append(localName)
        if 'kajongg.org' not in servers:
            servers.append('kajongg.org')
        if Internal.autoPlay:
            demoHost = Options.host or localName
            if demoHost in servers:
                servers.remove(
                    demoHost
                )  # we want a unique list, it will be re-used for all following games
            servers.insert(0, demoHost)
            # in this process but they will not be autoPlay
        self.cbServer.addItems(servers)
        self.passwords = Query(
            'select url, p.name, passwords.password from passwords, player p '
            'where passwords.player=p.id').records
        Players.load()
        self.cbServer.editTextChanged.connect(self.serverChanged)
        self.cbUser.editTextChanged.connect(self.userChanged)
        self.serverChanged()
        StateSaver(self)

    def returns(self, dummyButton=None):
        """login data returned by this dialog"""
        return (Url(self.url), self.username, self.password,
                self.__defineRuleset())

    def setupUi(self):
        """create all Ui elements but do not fill them"""
        self.buttonBox = KDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        # Ubuntu 11.10 unity is a bit strange - without this, it sets focus on
        # the cancel button (which it shows on the left). I found no obvious
        # way to use setDefault and setAutoDefault for fixing this.
        self.buttonBox.button(QDialogButtonBox.Ok).setFocus(True)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        vbox = QVBoxLayout(self)
        self.grid = QFormLayout()
        self.cbServer = QComboBox()
        self.cbServer.setEditable(True)
        self.grid.addRow(i18n('Game server:'), self.cbServer)
        self.cbUser = QComboBox()
        self.cbUser.setEditable(True)
        self.grid.addRow(i18n('Username:'******'Password:'******'kajongg', 'Ruleset:'), self.cbRuleset)
        vbox.addLayout(self.grid)
        vbox.addWidget(self.buttonBox)
        pol = QSizePolicy()
        pol.setHorizontalPolicy(QSizePolicy.Expanding)
        self.cbUser.setSizePolicy(pol)
        self.__port = None

    def serverChanged(self, dummyText=None):
        """the user selected a different server"""
        records = Query(
            'select player.name from player, passwords '
            'where passwords.url=? and passwords.player = player.id',
            (self.url, )).records
        players = list(x[0] for x in records)
        preferPlayer = Options.player
        if preferPlayer:
            if preferPlayer in players:
                players.remove(preferPlayer)
            players.insert(0, preferPlayer)
        self.cbUser.clear()
        self.cbUser.addItems(players)
        if not self.cbUser.count():
            user = KUser() if os.name == 'nt' else KUser(os.geteuid())
            self.cbUser.addItem(user.fullName() or user.loginName())
        if not preferPlayer:
            userNames = [x[1] for x in self.servers if x[0] == self.url]
            if userNames:
                userIdx = self.cbUser.findText(userNames[0])
                if userIdx >= 0:
                    self.cbUser.setCurrentIndex(userIdx)
        showPW = bool(self.url) and not Url(self.url).isLocalHost
        self.grid.labelForField(self.edPassword).setVisible(showPW)
        self.edPassword.setVisible(showPW)
        self.grid.labelForField(self.cbRuleset).setVisible(
            not showPW and not Options.ruleset)
        self.cbRuleset.setVisible(not showPW and not Options.ruleset)
        if not showPW:
            self.cbRuleset.clear()
            if Options.ruleset:
                self.cbRuleset.items = [Options.ruleset]
            else:
                self.cbRuleset.items = Ruleset.selectableRulesets(self.url)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(bool(self.url))

    def __defineRuleset(self):
        """find out what ruleset to use"""
        if Options.ruleset:
            return Options.ruleset
        elif Internal.autoPlay or bool(Options.host):
            return Ruleset.selectableRulesets()[0]
        else:
            return self.cbRuleset.current

    def userChanged(self, text):
        """the username has been changed, lookup password"""
        if text == '':
            self.edPassword.clear()
            return
        passw = None
        for entry in self.passwords:
            if entry[0] == self.url and entry[1] == text:
                passw = entry[2]
        if passw:
            self.edPassword.setText(passw)
        else:
            self.edPassword.clear()

    @property
    def url(self):
        """abstracts the url of the dialog"""
        return english(self.cbServer.currentText())

    @property
    def username(self):
        """abstracts the username of the dialog"""
        return self.cbUser.currentText()

    @property
    def password(self):
        """abstracts the password of the dialog"""
        return self.edPassword.text()

    @password.setter
    def password(self, password):
        """abstracts the password of the dialog"""
        self.edPassword.setText(password)
Пример #6
0
class ImportPage(QWidget):

    update_command_lst_low_level = Signal(list)

    """
    This stacked widget basically helps the user to browse the input images
    path, there is no auto-generated GUI form Phil parameters in use withing
    this widget.
    """

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

        main_v_box = QVBoxLayout()

        label_font = QFont()
        sys_font_point_size = label_font.pointSize()
        label_font.setPointSize(sys_font_point_size + 2)
        step_label = QLabel(str("Import"))
        step_label.setFont(label_font)

        self.simple_lin = QLineEdit(self)
        self.simple_lin.textChanged.connect(self.update_command)

        self.x_spn_bx = QSpinBox()
        self.x_spn_bx.setMaximum(99999)
        self.x_spn_bx.setSpecialValueText(" ")
        self.y_spn_bx = QSpinBox()
        self.y_spn_bx.setMaximum(99999)
        self.y_spn_bx.setSpecialValueText(" ")

        self.x_spn_bx.valueChanged.connect(self.x_beam_changed)
        self.y_spn_bx.valueChanged.connect(self.y_beam_changed)

        self.chk_invert = QCheckBox("Invert rotation axis")
        self.chk_invert.stateChanged.connect(self.inv_rota_changed)

        self.opn_fil_btn = QPushButton(" \n Select file(s) \n ")

        main_path = get_main_path()

        self.opn_fil_btn.setIcon(QIcon(main_path + "/resources/import.png"))
        self.opn_fil_btn.setIconSize(QSize(80, 48))

        main_v_box.addWidget(step_label)
        main_v_box.addWidget(self.opn_fil_btn)
        main_v_box.addWidget(self.simple_lin)
        self.b_cetre_label = QLabel("\n\n Beam centre")
        main_v_box.addWidget(self.b_cetre_label)
        cent_hbox = QHBoxLayout()
        self.x_label = QLabel("    X: ")
        cent_hbox.addWidget(self.x_label)
        cent_hbox.addWidget(self.x_spn_bx)
        self.y_label = QLabel("    Y: ")
        cent_hbox.addWidget(self.y_label)
        cent_hbox.addWidget(self.y_spn_bx)
        #    cent_hbox.addWidget(QLabel(" \n "))
        cent_hbox.addStretch()
        main_v_box.addLayout(cent_hbox)
        main_v_box.addWidget(self.chk_invert)
        main_v_box.addStretch()

        self.opn_fil_btn.clicked.connect(self.open_files)

        self.defa_dir = str(os.getcwd())
        self.setLayout(main_v_box)
        # self.show()
        self.reset_par()

    def reset_par(self):
        logger.info("reset_par(ImportPage)")
        self.cmd_list = []
        self.simple_lin.setText(" ? ")
        self.x_spn_bx.setValue(0.0)
        self.y_spn_bx.setValue(0.0)
        self.chk_invert.setChecked(False)

        self.x_beam, self.y_beam = 0.0, 0.0
        self.path_file_str = ""
        self.second_half = ""
        self.third_half = ""

    def update_param_w_lst(self, lst_in):
        self.reset_par()
        logger.info("update_param_w_lst(ImportPage) \n lst: \n", lst_in)
        for singl_com in lst_in:
            if singl_com[0:1] == "/":
                self.path_file_str = str(singl_com)
                self.put_str_lin()

            if singl_com[0:12] == "image_range=":
                self.path_file_str += " "
                self.path_file_str += str(singl_com)
                self.put_str_lin()

            if singl_com == "invert_rotation_axis=True":
                self.chk_invert.setChecked(True)

            if singl_com[0:22] == "slow_fast_beam_centre=":
                yb_xb_str = singl_com[22:]
                yb_str, xb_str = yb_xb_str.split(",")
                yb = float(yb_str)
                xb = float(xb_str)
                self.y_spn_bx.setValue(yb)
                self.x_spn_bx.setValue(xb)

    def inv_rota_changed(self):
        if self.chk_invert.checkState():
            self.third_half = "invert_rotation_axis=True"

        else:
            self.third_half = ""

        self.put_str_lin()

    def x_beam_changed(self, value):
        self.x_beam = value
        self.build_second_half()

    def y_beam_changed(self, value):
        self.y_beam = value
        self.build_second_half()

    def build_second_half(self):
        if self.x_beam != 0.0 and self.y_beam != 0.0:
            self.second_half = (
                "slow_fast_beam_centre=" + str(self.y_beam) + "," + str(self.x_beam)
            )

        else:
            self.second_half = ""

        self.put_str_lin()

    def open_files(self):

        lst_file_path = QFileDialog.getOpenFileNames(
            self, "Open File(s)", self.defa_dir, "All Files (*.*)"
        )

        if len(lst_file_path) > 0:
            new_dir, new_command = get_import_run_string(lst_file_path)
            # logger.info("\n new_dir=", new_dir, ">>")
            # logger.info("\n new_command =", new_command, ">>")
            self.path_file_str = new_command
            self.defa_dir = new_dir
            self.put_str_lin()

    def put_str_lin(self):
        # logger.info("self.path_file_str =", self.path_file_str, ">>")
        self.cmd_list = [
            self.path_file_str,
            self.second_half.lstrip(),
            self.third_half.lstrip(),
        ]
        txt_lin = " ".join(self.cmd_list).rstrip()
        while "  " in txt_lin:
            txt_lin = txt_lin.replace("  ", " ")

        self.simple_lin.setText(txt_lin)

    def set_arg_obj(self, sys_arg_in):
        """Pass the system argument object to handle launch arguments."""
        if sys_arg_in.template is not None:
            str_arg = str(sys_arg_in.template)
            self.simple_lin.setText(str_arg)

    def update_command(self):
        self.command_lst = [["import"]]
        param_com = str(self.simple_lin.text())

        cmd_lst = param_com.split(" ")

        for single_com in cmd_lst:
            self.command_lst[0].append(single_com)

        self.update_command_lst_low_level.emit(self.command_lst[0])

    def gray_me_out(self):
        self.simple_lin.setEnabled(False)
        self.opn_fil_btn.setEnabled(False)
        self.x_spn_bx.setEnabled(False)
        self.y_spn_bx.setEnabled(False)
        self.x_label.setEnabled(False)
        self.y_label.setEnabled(False)
        self.b_cetre_label.setEnabled(False)
        self.chk_invert.setEnabled(False)

    def activate_me(self, cur_nod=None):
        self.simple_lin.setEnabled(True)
        self.opn_fil_btn.setEnabled(True)
        self.y_spn_bx.setEnabled(True)
        self.x_spn_bx.setEnabled(True)
        self.x_label.setEnabled(True)
        self.y_label.setEnabled(True)
        self.b_cetre_label.setEnabled(True)
        self.chk_invert.setEnabled(True)
Пример #7
0
class ExportPage(QWidget):

    update_command_lst_low_level = Signal(list)

    """
    This stacked widget basically helps the user to export by
    generating an MTZ file, there is no auto-generated GUI
    form Phil parameters in use withing this widget.
    """

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

        main_v_box = QVBoxLayout()

        label_font = QFont()
        sys_font_point_size = label_font.pointSize()
        label_font.setPointSize(sys_font_point_size + 2)
        step_label = QLabel(str("Export"))
        step_label.setFont(label_font)

        out_file_label = QLabel(str("mtz output name:"))

        self.simple_lin = QLineEdit(self)
        self.simple_lin.textChanged.connect(self.update_command)

        self.check_scale = QCheckBox("Output Scaled Intensities")
        self.check_scale.setChecked(False)
        self.check_scale.stateChanged.connect(self.update_command)

        self.warning_label = QLabel(str(" "))
        self.warning_label.setWordWrap(True)

        main_v_box.addWidget(step_label)
        main_v_box.addWidget(out_file_label)
        main_v_box.addWidget(self.simple_lin)
        main_v_box.addWidget(self.check_scale)
        main_v_box.addStretch()
        main_v_box.addWidget(self.warning_label)
        main_v_box.addStretch()
        self.setLayout(main_v_box)
        self.fist_time = False
        # self.show()

        self.simple_lin.setText("integrated.mtz")

    def update_command(self):
        self.command_lst = [["export"]]

        param1_com = str(self.simple_lin.text())
        self.command_lst[0].append("mtz.hklout=" + param1_com)

        if self.check_scale.checkState():
            param2_com = "intensity=scale"
            self.command_lst[0].append(param2_com)

        self.update_command_lst_low_level.emit(self.command_lst[0])
        self.check_repeated_file()

    def check_repeated_file(self):
        param1_com = str(self.simple_lin.text())
        cwd_path = os.path.join(sys_arg.directory, "dui_files")
        mtz_file_path = os.path.join(cwd_path, param1_com)
        if os.path.isfile(mtz_file_path):
            txt_warning = "Warning, file: " + param1_com + " already exists"
            self.warning_label.setText(txt_warning)
            self.warning_label.setStyleSheet("color: rgba(255, 55, 55, 255)")
            """
            self.warning_label.setStyleSheet(
                        "color: rgba(255, 55, 55, 255);" "background-color: yellow;"
                    )
            """
        else:
            self.warning_label.setText(" ")
            self.warning_label.setStyleSheet("color: rgba(0, 155, 255, 255)")

    def gray_me_out(self):
        self.simple_lin.setEnabled(False)
        self.check_scale.setEnabled(False)

        self.fist_time = False

    def activate_me(self, cur_nod=None):
        self.simple_lin.setEnabled(True)
        self.check_scale.setEnabled(True)
        if self.fist_time is False:
            self.fist_time = True
            self.simple_lin.setText("integrated.mtz")
            self.check_scale.setChecked(False)
            my_node = cur_nod
            found_scale = False
            for iters in range(5):
                try:
                    if my_node.ll_command_lst[0][0] == "scale":
                        found_scale = True
                        break

                except AttributeError as at_err:
                    logger.info("found ", at_err, " in for loop, not to worry")

                my_node = my_node.prev_step

            if found_scale is True:
                self.simple_lin.setText("scaled.mtz")
                self.check_scale.setChecked(True)

        self.check_repeated_file()

    def reset_par(self):
        logger.info("command_lst(ExportPage.reset_par) = ", self.command_lst)
        logger.info(" Not supposed to reset export page")