コード例 #1
0
ファイル: TaskerManager.py プロジェクト: vaj25/pychess
    def __init__(self):
        #GObject.GObject.__init__(self,0,0,0,0)
        GObject.GObject.__init__(self)
        self.widgets = widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        combo = ToggleComboBox()
        combo.addItem(_("White"), get_pixbuf("glade/white.png"))
        combo.addItem(_("Black"), get_pixbuf("glade/black.png"))
        combo.addItem(_("Random"), get_pixbuf("glade/random.png"))
        combo.setMarkup("<b>", "</b>")
        widgets["colorDock"].add(combo)
        uistuff.keep(combo, "newgametasker_colorcombo")
        widgets['yourColorLabel'].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = ToggleComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
            widgets["skillImage"].set_from_pixbuf(pix)

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #2
0
ファイル: TaskerManager.py プロジェクト: ZeepXanflorp/pychess
    def __init__(self):
        #GObject.GObject.__init__(self,0,0,0,0)
        GObject.GObject.__init__(self)
        self.widgets = widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        combo = ToggleComboBox()
        combo.addItem(_("White"), get_pixbuf("glade/white.png"))
        combo.addItem(_("Black"), get_pixbuf("glade/black.png"))
        combo.addItem(_("Random"), get_pixbuf("glade/random.png"))
        combo.setMarkup("<b>", "</b>")
        widgets["colorDock"].add(combo)
        uistuff.keep(combo, "newgametasker_colorcombo")
        widgets['yourColorLabel'].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = ToggleComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
            widgets["skillImage"].set_from_pixbuf(pix)

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #3
0
ファイル: ChatWindow.py プロジェクト: bboutkov/pychess
    def __init__(self, widgets, connection):
        self.connection = connection

        self.viewspanel = ViewsPanel(self.connection)
        self.channelspanel = ChannelsPanel(self.connection)
        self.adj = self.channelspanel.get_vadjustment()
        self.infopanel = InfoPanel(self.connection)
        self.chatbox = Gtk.Paned()
        self.chatbox.add1(self.channelspanel)

        notebook = Gtk.Notebook()
        notebook.append_page(self.viewspanel, Gtk.Label(_("Chat")))
        notebook.append_page(self.infopanel, Gtk.Label(_("Info")))
        self.chatbox.add2(notebook)

        self.panels = [self.viewspanel, self.channelspanel, self.infopanel]
        self.viewspanel.connect('channel_content_Changed',
                                self.channelspanel.channel_Highlight, id)

        self.channelspanel.connect('conversationAdded',
                                   self.onConversationAdded)
        self.channelspanel.connect('conversationRemoved',
                                   self.onConversationRemoved)
        self.channelspanel.connect('conversationSelected',
                                   self.onConversationSelected)
        self.channelspanel.connect('focus_in_event', self.focus_in, self.adj)

        for panel in self.panels:
            panel.show_all()
            panel.start()

        uistuff.keep(self.chatbox, "chat_paned_position", first_value=100)
コード例 #4
0
    def __init__(self, widgets):

        conf.set("firstName", conf.get("firstName", conf.username))
        conf.set("secondName", conf.get("secondName", _("Guest")))

        # Give to uistuff.keeper

        for key in (
            "firstName",
            "secondName",
            "showEmt",
            "showEval",
            "hideTabs",
            "faceToFace",
            "showCords",
            "showCaptured",
            "figuresInNotation",
            "fullAnimation",
            "moveAnimation",
            "noAnimation",
        ):
            uistuff.keep(widgets[key], key)

        # Options on by default
        for key in ("autoRotate", "fullAnimation", "showBlunder"):
            uistuff.keep(widgets[key], key, first_value=True)
コード例 #5
0
ファイル: TaskerManager.py プロジェクト: torstehu/pychess
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)

        if ICLogon.dialog is None:
            ICLogon.dialog = ICLogon.ICLogon()

        liststore = Gtk.ListStore(str)
        liststore.append(["FICS"])
        liststore.append(["ICC"])
        self.ics_combo = self.widgets["ics_combo"]
        self.ics_combo.set_model(liststore)
        renderer_text = Gtk.CellRendererText()
        self.ics_combo.pack_start(renderer_text, True)
        self.ics_combo.add_attribute(renderer_text, "text", 0)
        self.ics_combo.connect("changed", ICLogon.dialog.on_ics_combo_changed)
        self.ics_combo.set_active(conf.get("ics_combo", 0))

        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        self.widgets["startIcon"].set_from_pixbuf(big_start)

        uistuff.keep(self.widgets["ics_combo"], "icsCombo")
        uistuff.keep(self.widgets["autoLogin"], "autoLogin")
コード例 #6
0
ファイル: ChatWindow.py プロジェクト: torstehu/pychess
    def __init__(self, widgets, connection):
        self.connection = connection

        self.viewspanel = ViewsPanel(self.connection)
        self.channelspanel = ChannelsPanel(self.connection)
        self.adj = self.channelspanel.get_vadjustment()
        self.infopanel = InfoPanel(self.connection)
        self.chatbox = Gtk.Paned()
        self.chatbox.add1(self.channelspanel)

        notebook = Gtk.Notebook()
        notebook.append_page(self.viewspanel, Gtk.Label(_("Chat")))
        notebook.append_page(self.infopanel, Gtk.Label(_("Info")))
        self.chatbox.add2(notebook)

        self.panels = [self.viewspanel, self.channelspanel, self.infopanel]
        self.viewspanel.connect('channel_content_Changed',
                                self.channelspanel.channel_Highlight, id)

        self.channelspanel.connect('conversationAdded',
                                   self.onConversationAdded)
        self.channelspanel.connect('conversationRemoved',
                                   self.onConversationRemoved)
        self.channelspanel.connect('conversationSelected',
                                   self.onConversationSelected)
        self.channelspanel.connect('focus_in_event', self.focus_in, self.adj)

        for panel in self.panels:
            panel.show_all()
            panel.start()

        uistuff.keep(self.chatbox, "chat_paned_position", first_value=100)
コード例 #7
0
ファイル: TaskerManager.py プロジェクト: leogregianin/pychess
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = tasker_widgets
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)

        if ICLogon.dialog is None:
            ICLogon.dialog = ICLogon.ICLogon()

        liststore = Gtk.ListStore(str)
        liststore.append(["FICS"])
        liststore.append(["ICC"])
        self.ics_combo = self.widgets["ics_combo"]
        self.ics_combo.set_model(liststore)
        renderer_text = Gtk.CellRendererText()
        self.ics_combo.pack_start(renderer_text, True)
        self.ics_combo.add_attribute(renderer_text, "text", 0)
        self.ics_combo.connect("changed", ICLogon.dialog.on_ics_combo_changed)
        self.ics_combo.set_active(conf.get("ics_combo"))

        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        self.widgets["startIcon"].set_from_pixbuf(big_start)

        uistuff.keep(self.widgets["ics_combo"], "ics_combo")
        uistuff.keep(self.widgets["autoLogin"], "autoLogin")
コード例 #8
0
    def __init__ (self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack (*args):
            checkbox = widgets["autoSave"]
            widgets["autosave_grid"].set_property("sensitive", checkbox.get_active())
        conf.notify_add("autoSave", checkCallBack)
        widgets["autoSave"].set_active(False)
        uistuff.keep(widgets["autoSave"], "autoSave")
        checkCallBack()

        default_path = os.path.expanduser("~")
        autoSavePath = conf.get("autoSavePath", default_path)
        conf.set("autoSavePath", autoSavePath)

        auto_save_chooser_dialog = Gtk.FileChooserDialog(_("Select auto save path"), None, Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
        auto_save_chooser_button = Gtk.FileChooserButton.new_with_dialog(auto_save_chooser_dialog)
        auto_save_chooser_button.set_current_folder(autoSavePath)

        widgets["savePathChooserDock"].add(auto_save_chooser_button)
        auto_save_chooser_button.show()

        def select_auto_save(button):
            new_directory = auto_save_chooser_dialog.get_filename()
            if new_directory != autoSavePath:
                conf.set("autoSavePath", new_directory)

        auto_save_chooser_button.connect("current-folder-changed", select_auto_save)

        conf.set("autoSaveFormat", conf.get("autoSaveFormat", "pychess"))
        uistuff.keep(widgets["autoSaveFormat"], "autoSaveFormat")

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames")
コード例 #9
0
ファイル: ICLogon.py プロジェクト: vgupta2507/pychess
    def __init__(self):
        self.connection = None
        self.lounge = None
        self.canceled = False
        self.cids = defaultdict(list)
        self.widgets = uistuff.GladeWidgets("fics_logon.glade")
        uistuff.keepWindowSize("fics_logon",
                               self.widgets["fics_logon"],
                               defaultPosition=uistuff.POSITION_GOLDEN)
        self.widgets["fics_logon"].connect(
            'key-press-event',
            lambda w, e: e.keyval == Gdk.KEY_Escape and w.hide())

        def on_logOnAsGuest_toggled(check):
            names = get_user_names()
            self.widgets["nameEntry"].set_text(
                names[1] if check.get_active() else names[0])
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passEntry"].set_sensitive(not check.get_active())

        self.widgets["logOnAsGuest"].connect("toggled",
                                             on_logOnAsGuest_toggled)
        uistuff.keep(self.widgets["logOnAsGuest"], "asGuestCheck")

        as_guest = self.widgets["logOnAsGuest"]

        def user_name_get_value(entry):
            names = get_user_names()
            if as_guest.get_active():
                text = "%s|%s" % (names[0], entry.get_text())
            else:
                text = "%s|%s" % (entry.get_text(), names[1])
            return text

        def user_name_set_value(entry, value):
            names = get_user_names(value=value)
            if as_guest.get_active():
                entry.set_text(names[1])
            else:
                entry.set_text(names[0])

        uistuff.keep(self.widgets["nameEntry"], "usernameEntry", \
                    user_name_get_value, user_name_set_value)
        uistuff.keep(self.widgets["passEntry"], "passwordEntry")
        uistuff.keep(self.widgets["hostEntry"], "hostEntry")
        uistuff.keep(self.widgets["autoLogin"], "autoLogin")
        self.infobar = Gtk.InfoBar()
        self.infobar.set_message_type(Gtk.MessageType.WARNING)
        #self.widgets["messagePanelHBox"].pack_start(self.infobar,
        #    expand=False, fill=False)
        self.widgets["messagePanelHBox"].pack_start(self.infobar, False, False,
                                                    0)
        self.widgets["cancelButton"].connect("clicked", self.onCancel, True)
        self.widgets["stopButton"].connect("clicked", self.onCancel, False)
        self.widgets["createNewButton"].connect("clicked", self.onCreateNew)
        self.widgets["connectButton"].connect("clicked", self.onConnectClicked)

        self.widgets["progressbar"].set_show_text(True)
コード例 #10
0
ファイル: ICLogon.py プロジェクト: CarbonFixer/pychess
    def __init__(self):
        self.connection = None
        self.lounge = None
        self.canceled = False
        self.cids = defaultdict(list)
        self.widgets = uistuff.GladeWidgets("fics_logon.glade")
        uistuff.keepWindowSize("fics_logon",
                               self.widgets["fics_logon"],
                               defaultPosition=uistuff.POSITION_GOLDEN)
        self.widgets["fics_logon"].connect(
            'key-press-event',
            lambda w, e: e.keyval == Gdk.KEY_Escape and w.hide())

        def on_logOnAsGuest_toggled(check):
            names = get_user_names()
            self.widgets["nameEntry"].set_text(names[1] if check.get_active()
                                               else names[0])
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passEntry"].set_sensitive(not check.get_active())

        self.widgets["logOnAsGuest"].connect("toggled",
                                             on_logOnAsGuest_toggled)
        uistuff.keep(self.widgets["logOnAsGuest"], "asGuestCheck")

        as_guest = self.widgets["logOnAsGuest"]

        def user_name_get_value(entry):
            names = get_user_names()
            if as_guest.get_active():
                text = "%s|%s" % (names[0], entry.get_text())
            else:
                text = "%s|%s" % (entry.get_text(), names[1])
            return text

        def user_name_set_value(entry, value):
            names = get_user_names(value=value)
            if as_guest.get_active():
                entry.set_text(names[1])
            else:
                entry.set_text(names[0])

        uistuff.keep(self.widgets["nameEntry"], "usernameEntry",
                     user_name_get_value, user_name_set_value)
        uistuff.keep(self.widgets["passEntry"], "passwordEntry")
        uistuff.keep(self.widgets["hostEntry"], "hostEntry")
        uistuff.keep(self.widgets["autoLogin"], "autoLogin")
        self.infobar = Gtk.InfoBar()
        self.infobar.set_message_type(Gtk.MessageType.WARNING)
        # self.widgets["messagePanelHBox"].pack_start(self.infobar,
        #    expand=False, fill=False)
        self.widgets["messagePanelHBox"].pack_start(self.infobar, False, False,
                                                    0)
        self.widgets["cancelButton"].connect("clicked", self.onCancel, True)
        self.widgets["stopButton"].connect("clicked", self.onCancel, False)
        self.widgets["createNewButton"].connect("clicked", self.onCreateNew)
        self.widgets["connectButton"].connect("clicked", self.onConnectClicked)

        self.widgets["progressbar"].set_show_text(True)
コード例 #11
0
    def __init__(self, widgets):
        self.themes = self.discover_themes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = GdkPixbuf.Pixbuf.new_from_file(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run create_theme_preview.sh !"
                )
                break

        iconView = widgets["pieceTheme"]
        iconView.set_model(store)
        iconView.set_pixbuf_column(0)
        iconView.set_text_column(1)

        #############################################
        # Hack to fix spacing problem in iconview
        # http://stackoverflow.com/questions/14090094/what-causes-the-different-display-behaviour-for-a-gtkiconview-between-different
        def keep_size(crt, *args):
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt, crp = iconView.get_cells()
        crt_notify = crt.connect('notify', keep_size)

        #############################################

        def _get_active(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Pychess")

            indices = selected[0].get_indices()
            if indices:
                i = indices[0]
                theme = model[i][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _set_active(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _get_active,
                     _set_active, "Pychess")
コード例 #12
0
ファイル: newGameDialog.py プロジェクト: jcoffee/pychess
    def __initTimeRadio(cls, name, id, radiobutton, configImage, defmin,
                        defgain):
        #minSpin = Gtk.SpinButton(Gtk.Adjustment(1,1,240,1))
        minSpin = Gtk.SpinButton()
        minSpin.set_adjustment(Gtk.Adjustment(1, 0, 240, 1))
        #gainSpin = Gtk.SpinButton(Gtk.Adjustment(0,-60,60,1))
        gainSpin = Gtk.SpinButton()
        gainSpin.set_adjustment(Gtk.Adjustment(0, -60, 60, 1))
        setattr(cls, "%s_min" % id, minSpin)
        setattr(cls, "%s_gain" % id, gainSpin)
        uistuff.keep(minSpin, "%s min" % id, first_value=defmin)
        uistuff.keep(gainSpin, "%s gain" % id, first_value=defgain)

        table = Gtk.Table(2, 2)
        table.props.row_spacing = 3
        table.props.column_spacing = 12
        label = Gtk.Label(label=_("Minutes:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 0, 1)
        table.attach(minSpin, 1, 2, 0, 1)
        label = Gtk.Label(label=_("Gain:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 1, 2)
        table.attach(gainSpin, 1, 2, 1, 2)
        alignment = Gtk.Alignment.new(1, 1, 1, 1)
        alignment.set_padding(6, 6, 12, 12)
        alignment.add(table)
        ImageMenu.switchWithImage(configImage, alignment)

        def updateString(spin):
            minutes = minSpin.get_value_as_int()
            gain = gainSpin.get_value_as_int()
            if gain > 0:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min + %(gain)d sec/move") % {
                        'name': name,
                        'minutes': minutes,
                        'gain': gain
                    })
            elif gain < 0:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min %(gain)d sec/move") % {
                        'name': name,
                        'minutes': minutes,
                        'gain': gain
                    })
            else:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min") % {
                        'name': name,
                        'minutes': minutes
                    })

        minSpin.connect("value-changed", updateString)
        gainSpin.connect("value-changed", updateString)
        updateString(None)
コード例 #13
0
ファイル: newGameDialog.py プロジェクト: TPNguyen/pychess
    def __initTimeRadio(cls, name, id, radiobutton, configImage, defmin,
                        defgain):
        # minSpin = Gtk.SpinButton(Gtk.Adjustment(1,1,240,1))
        minSpin = Gtk.SpinButton()
        minSpin.set_adjustment(Gtk.Adjustment(1, 0, 240, 1))
        # gainSpin = Gtk.SpinButton(Gtk.Adjustment(0,-60,60,1))
        gainSpin = Gtk.SpinButton()
        gainSpin.set_adjustment(Gtk.Adjustment(0, -60, 60, 1))
        setattr(cls, "%s_min" % id, minSpin)
        setattr(cls, "%s_gain" % id, gainSpin)
        uistuff.keep(minSpin, "%s min" % id, first_value=defmin)
        uistuff.keep(gainSpin, "%s gain" % id, first_value=defgain)

        table = Gtk.Table(2, 2)
        table.props.row_spacing = 3
        table.props.column_spacing = 12
        label = Gtk.Label(label=_("Minutes:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 0, 1)
        table.attach(minSpin, 1, 2, 0, 1)
        label = Gtk.Label(label=_("Gain:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 1, 2)
        table.attach(gainSpin, 1, 2, 1, 2)
        alignment = Gtk.Alignment.new(1, 1, 1, 1)
        alignment.set_padding(6, 6, 12, 12)
        alignment.add(table)
        ImageMenu.switchWithImage(configImage, alignment)

        def updateString(spin):
            minutes = minSpin.get_value_as_int()
            gain = gainSpin.get_value_as_int()
            if gain > 0:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min + %(gain)d sec/move") % {
                        'name': name,
                        'minutes': minutes,
                        'gain': gain
                    })
            elif gain < 0:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min %(gain)d sec/move") % {
                        'name': name,
                        'minutes': minutes,
                        'gain': gain
                    })
            else:
                radiobutton.set_label(_("%(name)s %(minutes)d min") % {
                    'name': name,
                    'minutes': minutes
                })

        minSpin.connect("value-changed", updateString)
        gainSpin.connect("value-changed", updateString)
        updateString(None)
コード例 #14
0
    def __init__ (self, widgets):

        conf.set("firstName", conf.get("firstName", conf.username))
        conf.set("secondName", conf.get("secondName", _("Guest")))
        
        # Give to uistuff.keeper
        
        for key in ("firstName", "secondName",
                    "hideTabs", "autoRotate", "faceToFace", "showCords", "figuresInNotation", "autoCallFlag",
                    "fullAnimation", "moveAnimation", "noAnimation"):
            uistuff.keep(widgets[key], key)
コード例 #15
0
    def __init__ (self, widgets):
        self.themes = self.discover_themes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)
        
        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)
        
            if isfile(pngfile):
                pixbuf = GdkPixbuf.Pixbuf.new_from_file(pngfile)
                store.append((pixbuf, theme))
            else:
                print("WARNING: No piece theme preview icons found. Please run create_theme_preview.sh !")
                break

        iconView = widgets["pieceTheme"]
        iconView.set_model(store)
        iconView.set_pixbuf_column(0)
        iconView.set_text_column(1)
        
        #############################################
        # Hack to fix spacing problem in iconview
        # http://stackoverflow.com/questions/14090094/what-causes-the-different-display-behaviour-for-a-gtkiconview-between-different
        def keep_size(crt, *args):
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt, crp = iconView.get_cells()
        crt_notify = crt.connect('notify', keep_size)
        #############################################

        def _get_active(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()
            
            if len(selected) == 0:
                return conf.get("pieceTheme", "Pychess")
            
            indices = selected[0].get_indices()
            if indices:
                i = indices[0]
                theme = model[i][1]
                Pieces.set_piece_theme(theme)
                return theme
        
        def _set_active(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index,))
                
        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _get_active,
                     _set_active, "Pychess")
コード例 #16
0
    def __init__(self, widgets):

        conf.set("firstName", conf.get("firstName", conf.username))
        conf.set("secondName", conf.get("secondName", _("Guest")))

        # Give to uistuff.keeper

        for key in ("firstName", "secondName", "hideTabs", "autoRotate",
                    "faceToFace", "showCords", "figuresInNotation",
                    "autoCallFlag", "fullAnimation", "moveAnimation",
                    "noAnimation"):
            uistuff.keep(widgets[key], key)
コード例 #17
0
    def __init__(self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack(_):
            """ :Description: Sets the various option based on user interaction with the
                checkboxes in the gui
            """

            checkbox = widgets["autoSave"]
            widgets["autosave_grid"].set_property("sensitive",
                                                  checkbox.get_active())

        conf.notify_add("autoSave", checkCallBack)
        widgets["autoSave"].set_active(False)
        uistuff.keep(widgets["autoSave"], "autoSave")
        checkCallBack(_)

        default_path = os.path.expanduser("~")
        self.auto_save_path = conf.get("autoSavePath", default_path)
        conf.set("autoSavePath", self.auto_save_path)

        auto_save_chooser_dialog = Gtk.FileChooserDialog(
            _("Select auto save path"), mainwindow(),
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        auto_save_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            auto_save_chooser_dialog)
        auto_save_chooser_button.set_current_folder(self.auto_save_path)

        widgets["savePathChooserDock"].add(auto_save_chooser_button)
        auto_save_chooser_button.show()

        def selectAutoSave(_):
            """ :Description: Sets the auto save path for stored games if it
                has changed since last time

                :signal: Activated on receiving the 'current-folder-changed' signal
            """
            new_directory = auto_save_chooser_dialog.get_filename()
            if new_directory != self.auto_save_path:
                conf.set("autoSavePath", new_directory)

        auto_save_chooser_button.connect("current-folder-changed",
                                         selectAutoSave)

        conf.set("autoSaveFormat", conf.get("autoSaveFormat", "pychess"))
        uistuff.keep(widgets["autoSaveFormat"], "autoSaveFormat")

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames")
コード例 #18
0
    def __init__(self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack(_):
            """ :Description: Sets the various option based on user interaction with the
                checkboxes in the gui
            """

            checkbox = widgets["autoSave"]
            widgets["autosave_grid"].set_property("sensitive",
                                                  checkbox.get_active())

        conf.notify_add("autoSave", checkCallBack)
        widgets["autoSave"].set_active(False)
        uistuff.keep(widgets["autoSave"], "autoSave")
        checkCallBack(_)

        default_path = os.path.expanduser("~")
        self.auto_save_path = conf.get("autoSavePath", default_path)
        conf.set("autoSavePath", self.auto_save_path)

        auto_save_chooser_dialog = Gtk.FileChooserDialog(
            _("Select auto save path"), None,
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        auto_save_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            auto_save_chooser_dialog)
        auto_save_chooser_button.set_current_folder(self.auto_save_path)

        widgets["savePathChooserDock"].add(auto_save_chooser_button)
        auto_save_chooser_button.show()

        def selectAutoSave(_):
            """ :Description: Sets the auto save path for stored games if it
                has changed since last time

                :signal: Activated on receiving the 'current-folder-changed' signal
            """
            new_directory = auto_save_chooser_dialog.get_filename()
            if new_directory != self.auto_save_path:
                conf.set("autoSavePath", new_directory)

        auto_save_chooser_button.connect("current-folder-changed", selectAutoSave)

        conf.set("autoSaveFormat", conf.get("autoSaveFormat", "pychess"))
        uistuff.keep(widgets["autoSaveFormat"], "autoSaveFormat")

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames")
コード例 #19
0
    def __init__(self, widgets):

        # Give to uistuff.keeper
        for key in conf.DEFAULTS["General"]:
            # widgets having special getter/setter
            if key in ("ana_combobox", "inv_ana_combobox", "pieceTheme", "board_style", "board_frame"):
                continue

            try:
                if widgets[key] is not None:
                    uistuff.keep(widgets[key], key)
            except AttributeError:
                print("GeneralTab AttributeError", key, conf.DEFAULTS["General"][key])
            except TypeError:
                print("GeneralTab TypeError", key, conf.DEFAULTS["General"][key])
コード例 #20
0
ファイル: TaskerManager.py プロジェクト: leogregianin/pychess
    def __initPlayerCombo(self, discoverer, widgets):
        combo = self.playerCombo
        uistuff.createCombo(combo, newGameDialog.playerItems[0])
        if combo.get_active() < 0:
            combo.set_active(1)
            uistuff.keep(self.playerCombo, "newgametasker_playercombo")

            def on_playerCombobox_changed(widget):
                widgets["skillSlider"].props.visible = widget.get_active() > 0

            combo.connect("changed", on_playerCombobox_changed)

            uistuff.keep(widgets["skillSlider"], "taskerSkillSlider")
            widgets["skillSlider"].set_no_show_all(True)
            on_playerCombobox_changed(self.playerCombo)
コード例 #21
0
ファイル: TaskerManager.py プロジェクト: vishnugonela/pychess
    def __initPlayerCombo(self, discoverer, widgets):
        combo = self.playerCombo
        uistuff.createCombo(combo, newGameDialog.playerItems[0])
        if combo.get_active() < 0:
            combo.set_active(1)
            uistuff.keep(self.playerCombo, "newgametasker_playercombo")

            def on_playerCombobox_changed(widget):
                widgets["skillSlider"].props.visible = widget.get_active() > 0

            combo.connect("changed", on_playerCombobox_changed)

            uistuff.keep(widgets["skillSlider"], "taskerSkillSlider")
            widgets["skillSlider"].set_no_show_all(True)
            on_playerCombobox_changed(self.playerCombo)
コード例 #22
0
ファイル: preferencesDialog.py プロジェクト: ypeng22/pychess
    def __init__(self, widgets):

        # Give to uistuff.keeper
        for key in conf.DEFAULTS["General"]:
            # widgets having special getter/setter
            if key in ("ana_combobox", "inv_ana_combobox", "pieceTheme", "board_style", "board_frame"):
                continue

            try:
                if widgets[key] is not None:
                    uistuff.keep(widgets[key], key)
            except AttributeError:
                print("GeneralTab AttributeError", key, conf.DEFAULTS["General"][key])
            except TypeError:
                print("GeneralTab TypeError", key, conf.DEFAULTS["General"][key])
コード例 #23
0
 def __initPlayerCombo (self, discoverer, widgets):
     combo = self.playerCombo
     for image, name in newGameDialog.smallPlayerItems[0]:
         combo.addItem(name, image)
     combo.label.set_ellipsize(pango.ELLIPSIZE_MIDDLE)
     combo.setMarkup("<b>", "</b>")
     combo.active = 1
     uistuff.keep(self.playerCombo, "newgametasker_playercombo")
     
     def on_playerCombobox_changed (widget, event):
         widgets["skillSlider"].props.visible = widget.active > 0
     combo.connect("changed", on_playerCombobox_changed)
     uistuff.keep(widgets["skillSlider"], "taskerSkillSlider")
     widgets["skillSlider"].set_no_show_all(True)
     on_playerCombobox_changed(self.playerCombo, None)
コード例 #24
0
    def __initPlayerCombo (self, discoverer, widgets):       
        combo = self.playerCombo
        combo.update(newGameDialog.smallPlayerItems[0])
        if combo.active < 0:
            combo.label.set_ellipsize(Pango.EllipsizeMode.MIDDLE)
            combo.setMarkup("<b>", "</b>")
            combo.active = 1
            uistuff.keep(self.playerCombo, "newgametasker_playercombo")

            def on_playerCombobox_changed (widget, event):              
                widgets["skillSlider"].props.visible = widget.active > 0
            combo.connect("changed", on_playerCombobox_changed)
        
            uistuff.keep(widgets["skillSlider"], "taskerSkillSlider")
            widgets["skillSlider"].set_no_show_all(True)
            on_playerCombobox_changed(self.playerCombo, None)
コード例 #25
0
    def __init__(self, widgets):

        conf.set("firstName", conf.get("firstName", conf.username))
        conf.set("secondName", conf.get("secondName", _("Guest")))

        # Give to uistuff.keeper

        for key in ("firstName", "secondName", "showEmt", "showEval",
                    "hideTabs", "faceToFace", "showCords", "showCaptured",
                    "figuresInNotation", "fullAnimation", "moveAnimation",
                    "noAnimation"):
            uistuff.keep(widgets[key], key)

        # Options on by default
        for key in ("autoRotate", "fullAnimation", "showBlunder"):
            uistuff.keep(widgets[key], key, first_value=True)
コード例 #26
0
    def __initPlayerCombo(self, discoverer, widgets):
        combo = self.playerCombo
        combo.update(newGameDialog.smallPlayerItems[0])
        if combo.active < 0:
            combo.label.set_ellipsize(Pango.EllipsizeMode.MIDDLE)
            combo.setMarkup("<b>", "</b>")
            combo.active = 1
            uistuff.keep(self.playerCombo, "newgametasker_playercombo")

            def on_playerCombobox_changed(widget, event):
                widgets["skillSlider"].props.visible = widget.active > 0

            combo.connect("changed", on_playerCombobox_changed)

            uistuff.keep(widgets["skillSlider"], "taskerSkillSlider")
            widgets["skillSlider"].set_no_show_all(True)
            on_playerCombobox_changed(self.playerCombo, None)
コード例 #27
0
ファイル: preferencesDialog.py プロジェクト: btrent/knave
    def __init__ (self, widgets):
        
        conf.set("pieceTheme", conf.get("pieceTheme", "pychess"))

        self.themes = self.discover_themes()
        
        store = gtk.ListStore(gtk.gdk.Pixbuf, str)
        
        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)
        
            if isfile(pngfile):
                pixbuf = gtk.gdk.pixbuf_new_from_file(pngfile)
                store.append((pixbuf, theme))
            else:
                print "WARNING: No piece theme preview icons find. Run create_theme_preview.sh !"
                break

        iconView = widgets["pieceTheme"]
        
        iconView.set_model(store)
        iconView.set_pixbuf_column(0)
        iconView.set_text_column(1)
        
        def _get_active(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()
            
            if len(selected) == 0:
                return conf.get("pieceTheme", "pychess")
            
            i = selected[0][0]
            theme = model[i][1]
            Pieces.set_piece_theme(theme)
            return theme
        
        def _set_active(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path((index,))
                
        uistuff.keep (widgets["pieceTheme"], "pieceTheme", _get_active, _set_active)
コード例 #28
0
    def load(self, widgets, connection, lounge):
        self.connection = connection

        # deferred imports to not slow down PyChess starting up
        from pychess.widgets.ViewsPanel import ViewsPanel
        from pychess.widgets.InfoPanel import InfoPanel
        from pychess.widgets.ChannelsPanel import ChannelsPanel

        self.viewspanel = ViewsPanel(self.connection)
        self.channelspanel = ChannelsPanel(self.connection)
        self.adj = self.channelspanel.get_vadjustment()
        self.infopanel = InfoPanel(self.connection)

        self.chatbox = Gtk.Paned()
        __widget__ = self.chatbox

        self.chatbox.add1(self.channelspanel)

        notebook = Gtk.Notebook()
        notebook.append_page(self.viewspanel, Gtk.Label(_("Chat")))
        notebook.append_page(self.infopanel, Gtk.Label(_("Info")))
        self.chatbox.add2(notebook)

        self.panels = [self.viewspanel, self.channelspanel, self.infopanel]
        self.viewspanel.connect("channel_content_Changed",
                                self.channelspanel.channel_Highlight, id)

        self.channelspanel.connect("conversationAdded",
                                   self.onConversationAdded)
        self.channelspanel.connect("conversationRemoved",
                                   self.onConversationRemoved)
        self.channelspanel.connect("conversationSelected",
                                   self.onConversationSelected)
        self.channelspanel.connect("focus_in_event", self.focus_in, self.adj)

        for panel in self.panels:
            panel.show_all()
            panel.start()
        self.chatbox.show_all()

        uistuff.keep(self.chatbox, "chat_paned_position")

        return __widget__
コード例 #29
0
ファイル: ChatPanel.py プロジェクト: leogregianin/pychess
    def load(self, widgets, connection, lounge):
        self.connection = connection

        # deferred imports to not slow down PyChess starting up
        from pychess.widgets.ViewsPanel import ViewsPanel
        from pychess.widgets.InfoPanel import InfoPanel
        from pychess.widgets.ChannelsPanel import ChannelsPanel

        self.viewspanel = ViewsPanel(self.connection)
        self.channelspanel = ChannelsPanel(self.connection)
        self.adj = self.channelspanel.get_vadjustment()
        self.infopanel = InfoPanel(self.connection)

        self.chatbox = Gtk.Paned()
        __widget__ = self.chatbox

        self.chatbox.add1(self.channelspanel)

        notebook = Gtk.Notebook()
        notebook.append_page(self.viewspanel, Gtk.Label(_("Chat")))
        notebook.append_page(self.infopanel, Gtk.Label(_("Info")))
        self.chatbox.add2(notebook)

        self.panels = [self.viewspanel, self.channelspanel, self.infopanel]
        self.viewspanel.connect('channel_content_Changed',
                                self.channelspanel.channel_Highlight, id)

        self.channelspanel.connect('conversationAdded',
                                   self.onConversationAdded)
        self.channelspanel.connect('conversationRemoved',
                                   self.onConversationRemoved)
        self.channelspanel.connect('conversationSelected',
                                   self.onConversationSelected)
        self.channelspanel.connect('focus_in_event', self.focus_in, self.adj)

        for panel in self.panels:
            panel.show_all()
            panel.start()
        self.chatbox.show_all()

        uistuff.keep(self.chatbox, "chat_paned_position")

        return __widget__
コード例 #30
0
    def __init__(self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack(*args):
            checkbox = widgets["autoSave"]
            widgets["autosave_grid"].set_property("sensitive",
                                                  checkbox.get_active())

        conf.notify_add("autoSave", checkCallBack)
        widgets["autoSave"].set_active(False)
        uistuff.keep(widgets["autoSave"], "autoSave")
        checkCallBack()

        default_path = os.path.expanduser("~")
        autoSavePath = conf.get("autoSavePath", default_path)
        conf.set("autoSavePath", autoSavePath)

        auto_save_chooser_dialog = Gtk.FileChooserDialog(
            _("Select auto save path"), None,
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        auto_save_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            auto_save_chooser_dialog)
        auto_save_chooser_button.set_current_folder(autoSavePath)

        widgets["savePathChooserDock"].add(auto_save_chooser_button)
        auto_save_chooser_button.show()

        def select_auto_save(button):
            new_directory = auto_save_chooser_dialog.get_filename()
            if new_directory != autoSavePath:
                conf.set("autoSavePath", new_directory)

        auto_save_chooser_button.connect("current-folder-changed",
                                         select_auto_save)

        conf.set("autoSaveFormat", conf.get("autoSaveFormat", "pychess"))
        uistuff.keep(widgets["autoSaveFormat"], "autoSaveFormat")

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames")
コード例 #31
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        startButton = self.widgets["startButton"]
        startButton.set_name("startButton")
        combo = Gtk.ComboBox()
        uistuff.createCombo(combo,
                            [(get_pixbuf("glade/white.png"), _("White")),
                             (get_pixbuf("glade/black.png"), _("Black")),
                             (get_pixbuf("glade/random.png"), _("Random"))])
        widgets["colorDock"].add(combo)
        if combo.get_active() < 0:
            combo.set_active(0)
        uistuff.keep(combo, "newgametasker_colorcombo")
        widgets['yourColorLabel'].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = Gtk.ComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            # Just to make sphinx happy...
            try:
                pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
                widgets["skillImage"].set_from_pixbuf(pix)
            except TypeError:
                pass

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #32
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        startButton = self.widgets["startButton"]
        startButton.set_name("startButton")
        combo = Gtk.ComboBox()
        uistuff.createCombo(combo, [
            (get_pixbuf("glade/white.png"), _("White")),
            (get_pixbuf("glade/black.png"), _("Black")),
            (get_pixbuf("glade/random.png"), _("Random"))])
        widgets["colorDock"].add(combo)
        if combo.get_active() < 0:
            combo.set_active(0)
        uistuff.keep(combo, "newgametasker_colorcombo")
        widgets['yourColorLabel'].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = Gtk.ComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            # Just to make sphinx happy...
            try:
                pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
                widgets["skillImage"].set_from_pixbuf(pix)
            except TypeError:
                pass

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #33
0
ファイル: ICLogon.py プロジェクト: metiscus/pychess
    def __init__(self):
        self.connection = None
        self.lounge = None
        self.canceled = False
        self.cids = defaultdict(list)
        self.widgets = uistuff.GladeWidgets("fics_logon.glade")
        uistuff.keepWindowSize("fics_logon",
                               self.widgets["fics_logon"],
                               defaultPosition=uistuff.POSITION_GOLDEN)
        self.widgets["fics_logon"].connect(
            'key-press-event',
            lambda w, e: e.keyval == Gdk.KEY_Escape and w.hide())

        def on_logOnAsGuest_toggled(check):
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passEntry"].set_sensitive(not check.get_active())

        self.widgets["logOnAsGuest"].connect("toggled",
                                             on_logOnAsGuest_toggled)
        uistuff.keep(self.widgets["logOnAsGuest"], "logOnAsGuest")
        uistuff.keep(self.widgets["nameEntry"], "usernameEntry")
        uistuff.keep(self.widgets["passEntry"], "passwordEntry")
        self.infobar = Gtk.InfoBar()
        self.infobar.set_message_type(Gtk.MessageType.WARNING)
        #self.widgets["messagePanelHBox"].pack_start(self.infobar,
        #    expand=False, fill=False)
        self.widgets["messagePanelHBox"].pack_start(self.infobar, False, False,
                                                    0)
        self.widgets["cancelButton"].connect("clicked", self.onCancel, True)
        self.widgets["stopButton"].connect("clicked", self.onCancel, False)
        self.widgets["createNewButton"].connect("clicked", self.onCreateNew)
        self.widgets["connectButton"].connect("clicked", self.onConnectClicked)

        self.widgets["progressbar"].set_show_text(True)
コード例 #34
0
    def __init__(self):
        self.widgets = uistuff.GladeWidgets("fics_logon.glade")
        uistuff.keepWindowSize("fics_logon",
                               self.widgets["fics_logon"],
                               defaultPosition=uistuff.POSITION_GOLDEN)

        self.widgets["fics_logon"].connect(
            'key-press-event',
            lambda w, e: e.keyval == gtk.keysyms.Escape and w.hide())

        def on_logOnAsGuest_toggled(check):
            self.widgets["nameLabel"].set_sensitive(not check.get_active())
            self.widgets["nameEntry"].set_sensitive(not check.get_active())
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passEntry"].set_sensitive(not check.get_active())

        self.widgets["logOnAsGuest"].connect("toggled",
                                             on_logOnAsGuest_toggled)
        uistuff.keep(self.widgets["logOnAsGuest"], "logOnAsGuest")
        uistuff.keep(self.widgets["nameEntry"], "usernameEntry")
        uistuff.keep(self.widgets["passEntry"], "passwordEntry")
        uistuff.makeYellow(self.widgets["messagePanel"])

        self.widgets["cancelButton"].connect("clicked", self.onCancel, True)
        self.widgets["stopButton"].connect("clicked", self.onCancel, False)
        self.widgets["fics_logon"].connect("delete-event", self.onClose)

        self.widgets["createNewButton"].connect("clicked", self.onCreateNew)
        self.widgets["connectButton"].connect("clicked", self.onConnectClicked)

        self.connection = None
        self.lounge = None
コード例 #35
0
ファイル: ICLogon.py プロジェクト: oldstylejoe/pychess-timed
    def __init__ (self):
        self.connection = None
        self.lounge = None
        self.canceled = False
        self.cids = defaultdict(list)
        self.widgets = uistuff.GladeWidgets("fics_logon.glade")
        uistuff.keepWindowSize("fics_logon", self.widgets["fics_logon"],
                               defaultPosition=uistuff.POSITION_GOLDEN)
        self.widgets["fics_logon"].connect('key-press-event',
                lambda w, e: e.keyval == Gdk.KEY_Escape and w.hide())        
        def on_logOnAsGuest_toggled (check):
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passEntry"].set_sensitive(not check.get_active())
        self.widgets["logOnAsGuest"].connect("toggled", on_logOnAsGuest_toggled)
        uistuff.keep(self.widgets["logOnAsGuest"], "logOnAsGuest")
        uistuff.keep(self.widgets["nameEntry"], "usernameEntry")
        uistuff.keep(self.widgets["passEntry"], "passwordEntry")
        self.infobar = Gtk.InfoBar()
        self.infobar.set_message_type(Gtk.MessageType.WARNING)
        #self.widgets["messagePanelHBox"].pack_start(self.infobar, 
        #    expand=False, fill=False)
        self.widgets["messagePanelHBox"].pack_start(self.infobar, 
            False, False, 0)        
        self.widgets["cancelButton"].connect("clicked", self.onCancel, True)
        self.widgets["stopButton"].connect("clicked", self.onCancel, False)
        self.widgets["createNewButton"].connect("clicked", self.onCreateNew)
        self.widgets["connectButton"].connect("clicked", self.onConnectClicked)

        self.widgets["progressbar"].set_show_text(True)
コード例 #36
0
 def __init__ (self):
     self.widgets = uistuff.GladeWidgets("fics_logon.glade")
     uistuff.keepWindowSize("fics_logon", self.widgets["fics_logon"],
                            defaultPosition=uistuff.POSITION_GOLDEN)
     
     self.widgets["fics_logon"].connect('key-press-event',
             lambda w, e: e.keyval == gtk.keysyms.Escape and w.hide())
     
     
     def on_logOnAsGuest_toggled (check):
         self.widgets["nameLabel"].set_sensitive(not check.get_active())
         self.widgets["nameEntry"].set_sensitive(not check.get_active())
         self.widgets["passwordLabel"].set_sensitive(not check.get_active())
         self.widgets["passEntry"].set_sensitive(not check.get_active())
     self.widgets["logOnAsGuest"].connect("toggled", on_logOnAsGuest_toggled)
     uistuff.keep(self.widgets["logOnAsGuest"], "logOnAsGuest")
     uistuff.keep(self.widgets["nameEntry"], "usernameEntry")
     uistuff.keep(self.widgets["passEntry"], "passwordEntry")
     uistuff.makeYellow(self.widgets["messagePanel"])
     
     self.widgets["cancelButton"].connect("clicked", self.onCancel, True)
     self.widgets["stopButton"].connect("clicked", self.onCancel, False)
     self.widgets["fics_logon"].connect("delete-event", self.onClose)
     
     self.widgets["createNewButton"].connect("clicked", self.onCreateNew)
     self.widgets["connectButton"].connect("clicked", self.onConnectClicked)
     
     self.connection = None
     self.lounge = None
コード例 #37
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)

        def asGuestCallback(check):
            names = ICLogon.get_user_names()
            self.widgets["usernameEntry"].set_text(
                names[1] if check.get_active() else names[0])
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passwordEntry"].set_sensitive(not check.get_active())

        self.widgets["asGuestCheck"].connect("toggled", asGuestCallback)

        uistuff.keep(self.widgets["asGuestCheck"], "asGuestCheck")

        as_guest = self.widgets["asGuestCheck"]

        def user_name_get_value(entry):
            names = ICLogon.get_user_names()
            if as_guest.get_active():
                text = "%s|%s" % (names[0], entry.get_text())
            else:
                text = "%s|%s" % (entry.get_text(), names[1])
            return text

        def user_name_set_value(entry, value):
            names = ICLogon.get_user_names(value=value)
            if as_guest.get_active():
                entry.set_text(names[1])
            else:
                entry.set_text(names[0])

        uistuff.keep(self.widgets["usernameEntry"], "usernameEntry",
                     user_name_get_value, user_name_set_value)

        # workaround to FICS Password input doesnt handle strings starting with a number
        # https://github.com/pychess/pychess/issues/1375
        def password_set_value(entry, value):
            entry.set_text(str(value))

        uistuff.keep(self.widgets["passwordEntry"],
                     "passwordEntry",
                     set_value_=password_set_value)

        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        self.widgets["startIcon"].set_from_pixbuf(big_start)
コード例 #38
0
ファイル: TaskerManager.py プロジェクト: vaj25/pychess
    def __init__(self):
        #GObject.GObject.__init__(self,0,0,0,0)
        GObject.GObject.__init__(self)
        self.widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)

        def asGuestCallback(check):
            names = ICLogon.get_user_names()
            self.widgets["usernameEntry"].set_text(names[1] \
                                                   if check.get_active() else names[0])
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passwordEntry"].set_sensitive(not check.get_active())

        self.widgets["asGuestCheck"].connect("toggled", asGuestCallback)

        uistuff.keep(self.widgets["asGuestCheck"], "asGuestCheck")

        as_guest = self.widgets["asGuestCheck"]

        def user_name_get_value(entry):
            names = ICLogon.get_user_names()
            if as_guest.get_active():
                text = "%s|%s" % (names[0], entry.get_text())
            else:
                text = "%s|%s" % (entry.get_text(), names[1])
            return text

        def user_name_set_value(entry, value):
            names = ICLogon.get_user_names(value=value)
            if as_guest.get_active():
                entry.set_text(names[1])
            else:
                entry.set_text(names[0])

        uistuff.keep(self.widgets["usernameEntry"], "usernameEntry", \
                    user_name_get_value, user_name_set_value)
        uistuff.keep(self.widgets["passwordEntry"], "passwordEntry")

        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        self.widgets["startIcon"].set_from_pixbuf(big_start)
コード例 #39
0
ファイル: TaskerManager.py プロジェクト: vgupta2507/pychess
    def __init__(self):
        #GObject.GObject.__init__(self,0,0,0,0)
        GObject.GObject.__init__(self)
        self.widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)

        def asGuestCallback(check):
            names = ICLogon.get_user_names()
            self.widgets["usernameEntry"].set_text(
                names[1] if check.get_active() else names[0])
            self.widgets["passwordLabel"].set_sensitive(not check.get_active())
            self.widgets["passwordEntry"].set_sensitive(not check.get_active())

        self.widgets["asGuestCheck"].connect("toggled", asGuestCallback)

        uistuff.keep(self.widgets["asGuestCheck"], "asGuestCheck")

        as_guest = self.widgets["asGuestCheck"]

        def user_name_get_value(entry):
            names = ICLogon.get_user_names()
            if as_guest.get_active():
                text = "%s|%s" % (names[0], entry.get_text())
            else:
                text = "%s|%s" % (entry.get_text(), names[1])
            return text

        def user_name_set_value(entry, value):
            names = ICLogon.get_user_names(value=value)
            if as_guest.get_active():
                entry.set_text(names[1])
            else:
                entry.set_text(names[0])

        uistuff.keep(self.widgets["usernameEntry"], "usernameEntry", \
                    user_name_get_value, user_name_set_value)
        uistuff.keep(self.widgets["passwordEntry"], "passwordEntry")

        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        self.widgets["startIcon"].set_from_pixbuf(big_start)
コード例 #40
0
    def __init__ (self):
        gtk.Alignment.__init__(self,0,0,0,0)
        self.widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)
        
        def asGuestCallback (checkbutton):
            for widget in (self.widgets["usernameLabel"], self.widgets["usernameEntry"],
                           self.widgets["passwordLabel"], self.widgets["passwordEntry"]):
                widget.set_sensitive(not checkbutton.get_active())
        self.widgets["asGuestCheck"].connect("toggled", asGuestCallback)
        
        uistuff.keep(self.widgets["asGuestCheck"], "asGuestCheck")
        uistuff.keep(self.widgets["usernameEntry"], "usernameEntry")
        uistuff.keep(self.widgets["passwordEntry"], "passwordEntry")
        
        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        self.widgets["startIcon"].set_from_pixbuf(big_start)
コード例 #41
0
    def __init__ (self):
        #GObject.GObject.__init__(self,0,0,0,0)
        GObject.GObject.__init__(self)
        self.widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)
        
        def asGuestCallback (checkbutton):
            for widget in (self.widgets["passwordLabel"], self.widgets["passwordEntry"]):
                widget.set_sensitive(not checkbutton.get_active())
        self.widgets["asGuestCheck"].connect("toggled", asGuestCallback)
        
        uistuff.keep(self.widgets["asGuestCheck"], "asGuestCheck")
        uistuff.keep(self.widgets["usernameEntry"], "usernameEntry")
        uistuff.keep(self.widgets["passwordEntry"], "passwordEntry")
        
        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        self.widgets["startIcon"].set_from_pixbuf(big_start)
コード例 #42
0
ファイル: newGameDialog.py プロジェクト: jcoffee/pychess
    def _init (cls):
        cls.widgets = uistuff.GladeWidgets ("newInOut.glade")

        uistuff.createCombo(cls.widgets["whitePlayerCombobox"], name="whitePlayerCombobox")
        uistuff.createCombo(cls.widgets["blackPlayerCombobox"], name="blackPlayerCombobox")

        cls.widgets["playersIcon"].set_from_pixbuf(big_people)
        cls.widgets["timeIcon"].set_from_pixbuf(big_time)


        def on_playerCombobox_changed (widget, skillHbox):
            skillHbox.props.visible = widget.get_active() > 0
        cls.widgets["whitePlayerCombobox"].connect(
                "changed", on_playerCombobox_changed, cls.widgets["skillHbox1"])
        cls.widgets["blackPlayerCombobox"].connect(
                "changed", on_playerCombobox_changed, cls.widgets["skillHbox2"])
        cls.widgets["whitePlayerCombobox"].set_active(0)
        cls.widgets["blackPlayerCombobox"].set_active(1)


        def on_skill_changed (scale, image):
            image.set_from_pixbuf(skillToIcon[int(scale.get_value())])
        cls.widgets["skillSlider1"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon1"])
        cls.widgets["skillSlider2"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon2"])
        cls.widgets["skillSlider1"].set_value(3)
        cls.widgets["skillSlider2"].set_value(3)


        cls.__initTimeRadio(_("Blitz"), "ngblitz", cls.widgets["blitzRadio"],
                            cls.widgets["configImageBlitz"], 5, 0)
        cls.__initTimeRadio(_("Rapid"), "ngrapid", cls.widgets["rapidRadio"],
                            cls.widgets["configImageRapid"], 15, 5)
        cls.__initTimeRadio(_("Normal"), "ngnormal", cls.widgets["normalRadio"],
                            cls.widgets["configImageNormal"], 40, 15)

        cls.__initVariantRadio("ngvariant1", cls.widgets["playVariant1Radio"],
                               cls.widgets["configImageVariant1"],
                               FISCHERRANDOMCHESS)
        cls.__initVariantRadio("ngvariant2", cls.widgets["playVariant2Radio"],
                               cls.widgets["configImageVariant2"], LOSERSCHESS)

        #@idle_add
        def updateCombos(*args):
            if cls.widgets["playNormalRadio"].get_active():
                variant = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            else:
                variant = conf.get("ngvariant2", LOSERSCHESS)
            variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)
            variant2 = conf.get("ngvariant2", LOSERSCHESS)
            cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)
            data = [(item[0], item[1]) for item in playerItems[variant]]
            uistuff.updateCombo(cls.widgets["blackPlayerCombobox"], data)
            uistuff.updateCombo(cls.widgets["whitePlayerCombobox"], data)

        discoverer.connect_after("all_engines_discovered", updateCombos)
        updateCombos(discoverer)

        conf.notify_add("ngvariant1", updateCombos)
        conf.notify_add("ngvariant2", updateCombos)
        cls.widgets["playNormalRadio"].connect("toggled", updateCombos)
        cls.widgets["playNormalRadio"].set_tooltip_text(variants[NORMALCHESS].__desc__)
        cls.widgets["playVariant1Radio"].connect("toggled", updateCombos)
        variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
        cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)
        cls.widgets["playVariant2Radio"].connect("toggled", updateCombos)
        variant2 = conf.get("ngvariant2", LOSERSCHESS)
        cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)

        # The "variant" has to come before players, because the engine positions
        # in the user comboboxes can be different in different variants
        for key in ("whitePlayerCombobox", "blackPlayerCombobox",
                    "skillSlider1", "skillSlider2",
                    "notimeRadio", "blitzRadio", "rapidRadio", "normalRadio",
                    "playNormalRadio", "playVariant1Radio", "playVariant2Radio"):
            uistuff.keep(cls.widgets[key], key)

        # We don't want the dialog to deallocate when closed. Rather we hide
        # it on respond
        cls.widgets["newgamedialog"].connect("delete_event", lambda *a: True)
コード例 #43
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Background image
        path = conf.get("welcome_image", addDataPrefix("glade/clear.png"))
        conf.set("welcome_image", path)

        image_chooser_dialog = Gtk.FileChooserDialog(
            _("Select background image file"), mainwindow(),
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        image_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            image_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Images"))
        filter.add_pattern("*.bmp")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.png")
        filter.add_pattern("*.svg")
        image_chooser_dialog.add_filter(filter)
        image_chooser_button.set_filename(path)

        self.widgets["imageChooserDock"].add(image_chooser_button)
        image_chooser_button.show()

        def select_new_image(button):
            new_image = image_chooser_dialog.get_filename()
            if new_image:
                conf.set("welcome_image", new_image)
                from pychess.widgets.TaskerManager import tasker
                newTheme(tasker, background=new_image)
                tasker.queue_draw()
            else:
                # restore the original
                image_chooser_dialog.set_filename(path)

        image_chooser_button.connect("file-set", select_new_image)

        # Board Colours

        style_ctxt = widgets["main_window"].get_style_context()
        LIGHT = hexcol(style_ctxt.lookup_color("p_light_color")[1])
        DARK = hexcol(style_ctxt.lookup_color("p_dark_color")[1])

        def onColourSetLight(_):
            """ :Description: Sets the light squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('lightcolour',
                     widgets['light_cbtn'].get_color().to_string())

        widgets["light_cbtn"].connect_after("color-set", onColourSetLight)

        def onColourSetDark(_):
            """ :Description: Sets the dark squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('darkcolour',
                     widgets['dark_cbtn'].get_color().to_string())

        widgets["dark_cbtn"].connect_after("color-set", onColourSetDark)

        def onResetColourClicked(_):
            """ :Description: Resets the chess board squares to factory default
            """
            conf.set("lightcolour", LIGHT)
            conf.set("darkcolour", DARK)

        widgets["reset_btn"].connect("clicked", onResetColourClicked)

        # Get the current board colours if set, if not set, set them to default
        conf.set("lightcolour", conf.get("lightcolour", LIGHT))
        conf.set("darkcolour", conf.get("darkcolour", DARK))

        # Next 2 lines take a #hex str converts them to a color then to a RGBA representation
        self.lightcolour = Gdk.RGBA()
        self.lightcolour.parse(conf.get("lightcolour", LIGHT))
        self.darkcolour = Gdk.RGBA()
        self.darkcolour.parse(conf.get("darkcolour", DARK))

        # Set the color swatches in preference to stored values
        widgets['light_cbtn'].set_rgba(self.lightcolour)
        widgets['dark_cbtn'].set_rgba(self.darkcolour)

        # Chess Sets

        self.themes = self.discoverThemes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run \
                    create_theme_preview.sh !")
                break

        self.icon_view = widgets["pieceTheme"]
        self.icon_view.set_model(store)
        self.icon_view.set_pixbuf_column(0)
        self.icon_view.set_text_column(1)

        def keepSize(crt, _):
            """ :Description: Hack to fix spacing problem in iconview
                http://stackoverflow.com/questions/14090094/what-causes-the-different-\
                    display-behaviour-for-a-gtkiconview-between-different
            """
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt = self.icon_view.get_cells()[0]
        crt_notify = crt.connect('notify', keepSize)

        def _getActive(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                idx = indices[0]
                theme = model[idx][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _setActive(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _getActive,
                     _setActive, "Chessicons")
コード例 #44
0
    def __init__(self, widgets):

        # Init open dialog

        opendialog = Gtk.FileChooserDialog(
            _("Open Sound File"), mainwindow(), Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.ACCEPT))

        for dir in self.SOUND_DIRS:
            if os.path.isdir(dir):
                opendialog.set_current_folder(dir)
                break

        soundfilter = Gtk.FileFilter()
        soundfilter.set_name(_("Sound files"))
        soundfilter.add_mime_type("audio/%s" % EXT)
        soundfilter.add_pattern("*.%s" % EXT)
        opendialog.add_filter(soundfilter)

        # Get combo icons

        icons = ((_("No sound"), "audio-volume-muted", "audio-volume-muted"),
                 (_("Beep"), "stock_bell", "audio-x-generic"),
                 (_("Select sound file..."), "gtk-open", "document-open"))

        items = []
        for level, stock, altstock in icons:
            image = load_icon(16, stock, altstock)
            items += [(image, level)]

        audioIco = load_icon(16, "audio-x-generic")

        # Set-up combos

        def callback(combobox, index):
            if combobox.get_active() == SOUND_SELECT:
                if opendialog.run() == Gtk.ResponseType.ACCEPT:
                    uri = opendialog.get_uri()
                    model = combobox.get_model()
                    conf.set("sounduri%d" % index, uri)
                    label = unquote(os.path.split(uri)[1])
                    if len(model) == 3:
                        model.append([audioIco, label])
                    else:
                        model.set(model.get_iter((3, )), 1, label)
                    combobox.set_active(3)
                else:
                    combobox.set_active(
                        conf.get("soundcombo%d" % index, SOUND_MUTE))
                opendialog.hide()

        for i in range(self.COUNT_OF_SOUNDS):
            combo = widgets["sound%dcombo" % i]
            uistuff.createCombo(combo, items, name="soundcombo%d" % i)
            # combo.set_active(0)
            combo.connect("changed", callback, i)

            label = widgets["soundlabel%d" % i]
            label.props.mnemonic_widget = combo

            uri = conf.get("sounduri%d" % i, "")
            if os.path.isfile(url2pathname(uri[5:])):
                model = combo.get_model()
                model.append([audioIco, unquote(os.path.split(uri)[1])])
                # combo.set_active(3)

        for i in range(self.COUNT_OF_SOUNDS):
            if conf.get("soundcombo%d" % i, SOUND_MUTE) == SOUND_URI and \
                    not os.path.isfile(url2pathname(conf.get("sounduri%d" % i, "")[5:])):
                conf.set("soundcombo%d" % i, SOUND_MUTE)
            uistuff.keep(widgets["sound%dcombo" % i], "soundcombo%d" % i)

        # Init play button

        def playCallback(button, index):
            SoundTab.playAction(index)

        for i in range(self.COUNT_OF_SOUNDS):
            button = widgets["sound%dbutton" % i]
            button.connect("clicked", playCallback, i)

        # Init 'use sound" checkbutton

        def checkCallBack(*args):
            checkbox = widgets["useSounds"]
            widgets["sounds_frame"].set_property("sensitive",
                                                 checkbox.get_active())

        conf.notify_add("useSounds", checkCallBack)
        widgets["useSounds"].set_active(True)
        uistuff.keep(widgets["useSounds"], "useSounds")
        checkCallBack()

        if not self.getPlayer().ready:
            widgets["useSounds"].set_sensitive(False)
            widgets["useSounds"].set_active(False)

        uistuff.keep(widgets["alarm_spin"], "alarm_spin", first_value=15)
コード例 #45
0
ファイル: newGameDialog.py プロジェクト: zennsocial/pychess
    def __initTimeRadio(cls, id, radiobutton, configImage, defmin, defgain,
                        defmoves):
        minSpin = Gtk.SpinButton()
        minSpin.set_adjustment(Gtk.Adjustment(1, 0, 240, 1))
        setattr(cls, "%s_min" % id, minSpin)
        uistuff.keep(minSpin, "%s min" % id)
        movesSpin = Gtk.SpinButton()
        movesSpin.set_adjustment(Gtk.Adjustment(0, 0, 60, 20))
        setattr(cls, "%s_moves" % id, movesSpin)
        uistuff.keep(movesSpin, "%s moves" % id)
        gainSpin = Gtk.SpinButton()
        gainSpin.set_adjustment(Gtk.Adjustment(0, -60, 60, 1))
        setattr(cls, "%s_gain" % id, gainSpin)
        uistuff.keep(gainSpin, "%s gain" % id)

        table = Gtk.Table(2, 2)
        table.props.row_spacing = 3
        table.props.column_spacing = 12
        label = Gtk.Label(label=_("Minutes:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 0, 1)
        table.attach(minSpin, 1, 2, 0, 1)
        label = Gtk.Label(label=_("Moves:") if defmoves > 0 else _("Gain:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 1, 2)
        if defmoves > 0:
            table.attach(movesSpin, 1, 2, 1, 2)
        else:
            table.attach(gainSpin, 1, 2, 1, 2)
        alignment = Gtk.Alignment.new(1, 1, 1, 1)
        alignment.set_padding(6, 6, 12, 12)
        alignment.add(table)
        ImageMenu.switchWithImage(configImage, alignment)

        def updateString(spin):
            # Elements of the clock
            minutes = minSpin.get_value_as_int()
            gain = gainSpin.get_value_as_int()
            moves = movesSpin.get_value_as_int()

            # Duration of the game
            def calculate_duration(ref_moves):
                if moves > 0:
                    return int(2 * minutes * ref_moves / moves)
                else:
                    return max(0, int(2 * minutes + ref_moves * gain / 30))

            duration_20 = calculate_duration(20)
            duration_40 = calculate_duration(40)
            duration_60 = calculate_duration(60)

            # Determination of the caption
            def get_game_name():
                """ https://www.fide.com/fide/handbook.html?id=171&view=article """
                if defmoves > 0:
                    return _("Classical")
                if duration_60 <= 20:  # 10 minutes per player
                    return _("Blitz")
                if duration_60 < 120:  # 60 minutes per player
                    return _("Rapid")
                return _("Normal")

            if moves > 0:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min / %(moves)d moves %(duration)s"
                      ) % {
                          'name':
                          get_game_name(),
                          'minutes':
                          minutes,
                          'moves':
                          moves,
                          'duration':
                          ("(%d')" % duration_40) if duration_40 > 0 else ""
                      })
            elif gain != 0:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min %(sign)s %(gain)d sec/move %(duration)s"
                      ) % {
                          'name':
                          get_game_name(),
                          'minutes':
                          minutes,
                          'sign':
                          "+" if gain > 0 else "–",
                          'gain':
                          abs(gain),
                          'duration':
                          ("(%d')" % duration_40) if duration_40 > 0 else ""
                      })
            else:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min %(duration)s") % {
                        'name':
                        get_game_name(),
                        'minutes':
                        minutes,
                        'duration':
                        ("(%d')" % duration_40) if duration_40 > 0 else ""
                    })

            # Determination of the tooltip
            if duration_20 > 0 and duration_60 > 0 and duration_20 != duration_60:
                radiobutton.set_tooltip_text(
                    _("Estimated duration : %(min)d - %(max)d minutes") %
                    ({
                        "min": min(duration_20, duration_60),
                        "max": max(duration_20, duration_60)
                    }))
            else:
                radiobutton.set_tooltip_text("")

        minSpin.connect("value-changed", updateString)
        movesSpin.connect("value-changed", updateString)
        gainSpin.connect("value-changed", updateString)
        updateString(None)
コード例 #46
0
ファイル: newGameDialog.py プロジェクト: leogregianin/pychess
    def __initTimeRadio(cls, id, radiobutton, configImage, defmin, defgain, defmoves):
        minSpin = Gtk.SpinButton()
        minSpin.set_adjustment(Gtk.Adjustment(1, 0, 240, 1))
        setattr(cls, "%s_min" % id, minSpin)
        uistuff.keep(minSpin, "%s min" % id)
        movesSpin = Gtk.SpinButton()
        movesSpin.set_adjustment(Gtk.Adjustment(0, 0, 60, 20))
        setattr(cls, "%s_moves" % id, movesSpin)
        uistuff.keep(movesSpin, "%s moves" % id)
        gainSpin = Gtk.SpinButton()
        gainSpin.set_adjustment(Gtk.Adjustment(0, -60, 60, 1))
        setattr(cls, "%s_gain" % id, gainSpin)
        uistuff.keep(gainSpin, "%s gain" % id)

        table = Gtk.Table(2, 2)
        table.props.row_spacing = 3
        table.props.column_spacing = 12
        label = Gtk.Label(label=_("Minutes:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 0, 1)
        table.attach(minSpin, 1, 2, 0, 1)
        label = Gtk.Label(label=_("Moves:") if defmoves > 0 else _("Gain:"))
        label.props.xalign = 0
        table.attach(label, 0, 1, 1, 2)
        if defmoves > 0:
            table.attach(movesSpin, 1, 2, 1, 2)
        else:
            table.attach(gainSpin, 1, 2, 1, 2)
        alignment = Gtk.Alignment.new(1, 1, 1, 1)
        alignment.set_padding(6, 6, 12, 12)
        alignment.add(table)
        ImageMenu.switchWithImage(configImage, alignment)

        def updateString(spin):
            # Elements of the clock
            minutes = minSpin.get_value_as_int()
            gain = gainSpin.get_value_as_int()
            moves = movesSpin.get_value_as_int()

            # Duration of the game
            def calculate_duration(ref_moves):
                if moves > 0:
                    return int(2 * minutes * ref_moves / moves)
                else:
                    return max(0, int(2 * minutes + ref_moves * gain / 30))

            duration_20 = calculate_duration(20)
            duration_40 = calculate_duration(40)
            duration_60 = calculate_duration(60)

            # Determination of the caption
            def get_game_name():
                """ https://www.fide.com/fide/handbook.html?id=171&view=article """
                if defmoves > 0:
                    return _("Classical")
                if duration_60 <= 20:  # 10 minutes per player
                    return _("Blitz")
                if duration_60 < 120:  # 60 minutes per player
                    return _("Rapid")
                return _("Normal")

            if moves > 0:
                radiobutton.set_label(_("%(name)s %(minutes)d min / %(moves)d moves %(duration)s") % {
                    'name': get_game_name(),
                    'minutes': minutes,
                    'moves': moves,
                    'duration': ("(%d')" % duration_40) if duration_40 > 0 else ""
                })
            elif gain != 0:
                radiobutton.set_label(
                    _("%(name)s %(minutes)d min %(sign)s %(gain)d sec/move %(duration)s") % {
                        'name': get_game_name(),
                        'minutes': minutes,
                        'sign': "+" if gain > 0 else "–",
                        'gain': abs(gain),
                        'duration': ("(%d')" % duration_40) if duration_40 > 0 else ""
                    })
            else:
                radiobutton.set_label(_("%(name)s %(minutes)d min %(duration)s") % {
                    'name': get_game_name(),
                    'minutes': minutes,
                    'duration': ("(%d')" % duration_40) if duration_40 > 0 else ""
                })

            # Determination of the tooltip
            if duration_20 > 0 and duration_60 > 0 and duration_20 != duration_60:
                radiobutton.set_tooltip_text(_("Estimated duration : %(min)d - %(max)d minutes") % ({
                    "min": min(duration_20, duration_60),
                    "max": max(duration_20, duration_60)}
                ))
            else:
                radiobutton.set_tooltip_text("")

        minSpin.connect("value-changed", updateString)
        movesSpin.connect("value-changed", updateString)
        gainSpin.connect("value-changed", updateString)
        updateString(None)
コード例 #47
0
    def initGlade(self, log_viewer):
        # Init glade and the 'GladeHandlers'
        self.widgets = widgets = uistuff.GladeWidgets("PyChess.glade")
        self.glade_handlers = GladeHandlers(self)
        widgets.getGlade().connect_signals(self.glade_handlers)
        self.window = widgets["main_window"]

        # new_game_tasker, internet_game_tasker = NewGameTasker(
        # ), InternetGameTasker()
        # tasker.packTaskers(new_game_tasker, internet_game_tasker)
        # widgets["Background"].add(tasker)

        # Redirect widgets
        gamewidget.setWidgets(widgets)

        # The only menuitems that need special initing
        for widget in ("hint_mode", "spy_mode"):
            widgets[widget].set_sensitive(False)

        uistuff.keep(widgets["hint_mode"], "hint_mode")
        uistuff.keep(widgets["spy_mode"], "spy_mode")
        uistuff.keep(widgets["show_sidepanels"], "show_sidepanels")
        uistuff.keep(widgets["auto_call_flag"], "autoCallFlag")

        # Show main window and init d'n'd
        widgets["main_window"].set_title('%s - PyChess' % _('Welcome'))
        widgets["main_window"].connect("delete-event",
                                       self.glade_handlers.on_quit1_activate)
        widgets["main_window"].connect("key-press-event",
                                       self.glade_handlers.on_window_key_press)

        uistuff.keepWindowSize("main", widgets["main_window"], None,
                               uistuff.POSITION_GOLDEN)

        # To get drag in the whole window, we add it to the menu and the
        # background. If it can be gotten to work, the drag_dest_set_proxy
        # method is very interesting.
        widgets["menubar1"].drag_dest_set(Gtk.DestDefaults.ALL, DND_LIST,
                                          DRAG_ACTION)
        widgets["box2"].drag_dest_set(Gtk.DestDefaults.ALL, DND_LIST,
                                      DRAG_ACTION)
        widgets["perspectives_notebook"].drag_dest_set(Gtk.DestDefaults.ALL,
                                                       DND_LIST, DRAG_ACTION)

        # Init 'minor' dialogs

        # Log dialog
        if log_viewer:
            from pychess.widgets import LogDialog
            LogDialog.add_destroy_notify(
                lambda: widgets["log_viewer1"].set_active(0))
        else:
            widgets["log_viewer1"].set_property('sensitive', False)

        # About dialog
        self.aboutdialog = widgets["aboutdialog1"]
        self.aboutdialog.set_program_name(NAME)
        self.aboutdialog.set_copyright("Copyright © 2006-2020")
        self.aboutdialog.set_version(VERSION_NAME + " " + VERSION)
        if isgit():
            try:
                self.git_rev = subprocess.check_output(
                    ["git", "describe", "--tags"]).decode().strip()
                self.aboutdialog.set_version('%s Git %s' %
                                             (VERSION_NAME, self.git_rev))
            except subprocess.CalledProcessError:
                pass
        self.aboutdialog.set_comments(self.aboutdialog.get_comments())

        with open(prefix.addDataPrefix("ARTISTS"), encoding="utf-8") as f:
            self.aboutdialog.set_artists(f.read().splitlines())
        with open(prefix.addDataPrefix("AUTHORS"), encoding="utf-8") as f:
            self.aboutdialog.set_authors(f.read().splitlines())
        with open(prefix.addDataPrefix("DOCUMENTERS"), encoding="utf-8") as f:
            self.aboutdialog.set_documenters(f.read().splitlines())
        with open(prefix.addDataPrefix("TRANSLATORS"), encoding="utf-8") as f:
            self.aboutdialog.set_translator_credits(f.read())
        with open(prefix.addDataPrefix("LICENSE"), encoding="utf-8") as f:
            self.aboutdialog.set_license(f.read())

        widgets["load_recent_game1"].set_submenu(recent_menu)

        if conf.get("autoLogin"):
            internet_game_tasker.connectClicked(None)
コード例 #48
0
ファイル: preferencesDialog.py プロジェクト: bboutkov/pychess
    def __init__(self, widgets):
        self.widgets = widgets

        # Background image
        path = conf.get("welcome_image", addDataPrefix("glade/clear.png"))
        conf.set("welcome_image", path)

        image_chooser_dialog = Gtk.FileChooserDialog(
            _("Select background image file"), None, Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        image_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            image_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Images"))
        filter.add_pattern("*.bmp")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.png")
        filter.add_pattern("*.svg")
        image_chooser_dialog.add_filter(filter)
        image_chooser_button.set_filename(path)

        self.widgets["imageChooserDock"].add(image_chooser_button)
        image_chooser_button.show()

        def select_new_image(button):
            new_image = image_chooser_dialog.get_filename()
            if new_image:
                conf.set("welcome_image", new_image)
                from pychess.widgets.TaskerManager import tasker
                newTheme(tasker, background=new_image)
                tasker.queue_draw()
            else:
                # restore the original
                image_chooser_dialog.set_filename(path)

        image_chooser_button.connect("file-set", select_new_image)

        # Board Colours

        style_ctxt = widgets["main_window"].get_style_context()
        LIGHT = hexcol(style_ctxt.lookup_color("p_light_color")[1])
        DARK = hexcol(style_ctxt.lookup_color("p_dark_color")[1])

        def onColourSetLight(_):
            """ :Description: Sets the light squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('lightcolour',
                     widgets['light_cbtn'].get_color().to_string())

        widgets["light_cbtn"].connect_after("color-set", onColourSetLight)

        def onColourSetDark(_):
            """ :Description: Sets the dark squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('darkcolour',
                     widgets['dark_cbtn'].get_color().to_string())

        widgets["dark_cbtn"].connect_after("color-set", onColourSetDark)

        def onResetColourClicked(_):
            """ :Description: Resets the chess board squares to factory default
            """
            conf.set("lightcolour", LIGHT)
            conf.set("darkcolour", DARK)

        widgets["reset_btn"].connect("clicked", onResetColourClicked)

        # Get the current board colours if set, if not set, set them to default
        conf.set("lightcolour", conf.get("lightcolour", LIGHT))
        conf.set("darkcolour", conf.get("darkcolour", DARK))

        # Next 2 lines take a #hex str converts them to a color then to a RGBA representation
        self.lightcolour = Gdk.RGBA()
        self.lightcolour.parse(conf.get("lightcolour", LIGHT))
        self.darkcolour = Gdk.RGBA()
        self.darkcolour.parse(conf.get("darkcolour", DARK))

        # Set the color swatches in preference to stored values
        widgets['light_cbtn'].set_rgba(self.lightcolour)
        widgets['dark_cbtn'].set_rgba(self.darkcolour)

        # Chess Sets

        self.themes = self.discoverThemes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run \
                    create_theme_preview.sh !")
                break

        self.icon_view = widgets["pieceTheme"]
        self.icon_view.set_model(store)
        self.icon_view.set_pixbuf_column(0)
        self.icon_view.set_text_column(1)

        def keepSize(crt, _):
            """ :Description: Hack to fix spacing problem in iconview
                http://stackoverflow.com/questions/14090094/what-causes-the-different-\
                    display-behaviour-for-a-gtkiconview-between-different
            """
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt = self.icon_view.get_cells()[0]
        crt_notify = crt.connect('notify', keepSize)

        def _getActive(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                idx = indices[0]
                theme = model[idx][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _setActive(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _getActive,
                     _setActive, "Chessicons")
コード例 #49
0
    def _init (cls):
        cls.widgets = uistuff.GladeWidgets ("newInOut.glade")

        uistuff.createCombo(cls.widgets["whitePlayerCombobox"],
                            (i[:2] for i in playerItems[0]))
        uistuff.createCombo(cls.widgets["blackPlayerCombobox"],
                            (i[:2] for i in playerItems[0]))

        cls.widgets["playersIcon"].set_from_pixbuf(big_people)
        cls.widgets["timeIcon"].set_from_pixbuf(big_time)


        def on_playerCombobox_changed (widget, skillHbox):
            skillHbox.props.visible = widget.get_active() > 0
        cls.widgets["whitePlayerCombobox"].connect(
                "changed", on_playerCombobox_changed, cls.widgets["skillHbox1"])
        cls.widgets["blackPlayerCombobox"].connect(
                "changed", on_playerCombobox_changed, cls.widgets["skillHbox2"])
        cls.widgets["whitePlayerCombobox"].set_active(0)
        cls.widgets["blackPlayerCombobox"].set_active(1)


        def on_skill_changed (scale, image):
            image.set_from_pixbuf(skillToIcon[int(scale.get_value())])
        cls.widgets["skillSlider1"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon1"])
        cls.widgets["skillSlider2"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon2"])
        cls.widgets["skillSlider1"].set_value(3)
        cls.widgets["skillSlider2"].set_value(3)


        cls.__initTimeRadio(_("Blitz"), "ngblitz", cls.widgets["blitzRadio"],
                            cls.widgets["configImageBlitz"], 5, 0)
        cls.__initTimeRadio(_("Rapid"), "ngrapid", cls.widgets["rapidRadio"],
                            cls.widgets["configImageRapid"], 15, 5)
        cls.__initTimeRadio(_("Normal"), "ngnormal", cls.widgets["normalRadio"],
                            cls.widgets["configImageNormal"], 40, 15)

        cls.__initVariantRadio("ngvariant1", cls.widgets["playVariant1Radio"],
                               cls.widgets["configImageVariant1"],
                               FISCHERRANDOMCHESS)
        cls.__initVariantRadio("ngvariant2", cls.widgets["playVariant2Radio"],
                               cls.widgets["configImageVariant2"], LOSERSCHESS)

        def updateCombos(*args):
            if cls.widgets["playNormalRadio"].get_active():
                variant = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            else:
                variant = conf.get("ngvariant2", LOSERSCHESS)
            variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)            
            variant2 = conf.get("ngvariant2", LOSERSCHESS)
            cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)
            uistuff.updateCombo(cls.widgets["blackPlayerCombobox"], playerItems[variant])
            uistuff.updateCombo(cls.widgets["whitePlayerCombobox"], playerItems[variant])
        conf.notify_add("ngvariant1", updateCombos)
        conf.notify_add("ngvariant2", updateCombos)
        cls.widgets["playNormalRadio"].connect("toggled", updateCombos)
        cls.widgets["playNormalRadio"].set_tooltip_text(variants[NORMALCHESS].__desc__)
        cls.widgets["playVariant1Radio"].connect("toggled", updateCombos)
        variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
        cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)
        cls.widgets["playVariant2Radio"].connect("toggled", updateCombos)
        variant2 = conf.get("ngvariant2", LOSERSCHESS)
        cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)

        # The "variant" has to come before players, because the engine positions
        # in the user comboboxes can be different in different variants
        for key in ("whitePlayerCombobox", "blackPlayerCombobox",
                    "skillSlider1", "skillSlider2",
                    "notimeRadio", "blitzRadio", "rapidRadio", "normalRadio",
                    "playNormalRadio", "playVariant1Radio", "playVariant2Radio"):
            uistuff.keep(cls.widgets[key], key)

        # We don't want the dialog to deallocate when closed. Rather we hide
        # it on respond
        cls.widgets["newgamedialog"].connect("delete_event", lambda *a: True)
コード例 #50
0
 def __init__ (self, widgets):
     
     # Put engines in trees and combos
     
     engines = discoverer.getEngines()
     allstore = gtk.ListStore(gtk.gdk.Pixbuf, str)
     for engine in engines.values():
         c = discoverer.getCountry(engine)
         if c:
             flag = addDataPrefix("flags/%s.png" % c)
         if not c or not os.path.isfile(flag):
             flag = addDataPrefix("flags/unknown.png")
         flag_icon = gtk.gdk.pixbuf_new_from_file(flag)
         allstore.append((flag_icon, discoverer.getName(engine)))
     
     tv = widgets["engines_treeview"]
     tv.set_model(allstore)
     tv.append_column(gtk.TreeViewColumn(
             _("Flag"), gtk.CellRendererPixbuf(), pixbuf=0))
     tv.append_column(gtk.TreeViewColumn(
             _("Name"), gtk.CellRendererText(), text=1))
     
     analyzers = list(discoverer.getAnalyzers())
     ana_data = []
     invana_data = []
     for engine in analyzers:
         name = discoverer.getName(engine)
         c = discoverer.getCountry(engine)
         if c:
             flag = addDataPrefix("flags/%s.png" % c)
         if not c or not os.path.isfile(flag):
             flag = addDataPrefix("flags/unknown.png")
         flag_icon = gtk.gdk.pixbuf_new_from_file(flag)
         ana_data.append((flag_icon, name))
         invana_data.append((flag_icon, name))
     
     uistuff.createCombo(widgets["ana_combobox"], ana_data)
     uistuff.createCombo(widgets["inv_ana_combobox"], invana_data)
     
     # Save, load and make analyze combos active
     
     conf.set("ana_combobox", conf.get("ana_combobox", 0))
     conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", 0))
     
     def on_analyzer_check_toggled (check):
         widgets["analyzers_vbox"].set_sensitive(check.get_active())
         widgets["hint_mode"].set_active(check.get_active())
         from pychess.Main import gameDic
         if gameDic:
             widgets["hint_mode"].set_sensitive(check.get_active())
     widgets["analyzer_check"].connect("toggled", on_analyzer_check_toggled)
     uistuff.keep(widgets["analyzer_check"], "analyzer_check")
     
     def on_invanalyzer_check_toggled (check):
         widgets["inv_analyzers_vbox"].set_sensitive(check.get_active())
         widgets["spy_mode"].set_active(check.get_active())
         from pychess.Main import gameDic
         if gameDic:
             widgets["spy_mode"].set_sensitive(check.get_active())
     widgets["inv_analyzer_check"].connect("toggled", on_invanalyzer_check_toggled)
     uistuff.keep(widgets["inv_analyzer_check"], "inv_analyzer_check")
     
     # Put options in trees in add/edit dialog
     
     #=======================================================================
     # tv = widgets["optionview"]
     # tv.append_column(gtk.TreeViewColumn(
     #    "Option", gtk.CellRendererText(), text=0))
     # tv.append_column(gtk.TreeViewColumn(
     #    "Value", gtk.CellRendererText(), text=1))
     # 
     # def edit (button):
     #    
     #    iter = widgets["engines_treeview"].get_selection().get_selected()[1]
     #    if iter: row = allstore.get_path(iter)[0]
     #    else: return
     #    
     #    engine = discoverer.getEngineN(row)
     #    optionstags = engine.getElementsByTagName("options")
     #    if not optionstags:
     #        widgets["engine_options_expander"].hide()
     #    else:
     #        widgets["engine_options_expander"].show()
     #        widgets["engine_options_expander"].set_expanded(False)
     #        
     #        optionsstore = gtk.ListStore(str, str)
     #        tv = widgets["optionview"]
     #        tv.set_model(optionsstore)
     #        
     #        for option in optionstags[0].childNodes:
     #            if option.nodeType != option.ELEMENT_NODE: continue
     #            optionsstore.append( [option.getAttribute("name"),
     #                                  option.getAttribute("default")] )
     #        
     #    widgets["engine_path_chooser"].set_title(_("Locate Engine"))
     #    widgets["engine_path_chooser"].set_uri("file:///usr/bin/gnuchess")
     #    
     #    dialog = widgets["addconfig_engine"]
     #    answer = dialog.run()
     #    dialog.hide()
     # widgets["edit_engine_button"].connect("clicked", edit)
     #=======================================================================
     #widgets["remove_engine_button"].connect("clicked", remove)
     #widgets["add_engine_button"].connect("clicked", add)
     
     # Give widgets to kepper
     
     for combo in ("ana_combobox", "inv_ana_combobox"):
         
         def get_value (combobox):
             engine = list(discoverer.getAnalyzers())[combobox.get_active()]
             if engine.find('md5') != None:
                 return engine.find('md5').text.strip()
         
         def set_value (combobox, value):
             engine = discoverer.getEngineByMd5(value)
             if not engine:
                 combobox.set_active(0)
             else:
                 try:
                     index = list(discoverer.getAnalyzers()).index(engine)
                 except ValueError:
                     index = 0
                 combobox.set_active(index)
         
         uistuff.keep (widgets[combo], combo, get_value, set_value)
     
     # Init info box
     
     uistuff.makeYellow(widgets["analyzer_pref_infobox"])
     widgets["analyzer_pref_infobox"].hide()
     def updatePrefInfobox (widget, *args):
         widgets["analyzer_pref_infobox"].show()
     widgets["ana_combobox"].connect("changed", updatePrefInfobox)
     widgets["analyzer_check"].connect("toggled", updatePrefInfobox)
     widgets["inv_ana_combobox"].connect("changed", updatePrefInfobox)
     widgets["inv_analyzer_check"].connect("toggled", updatePrefInfobox)
     widgets["preferences"].connect("hide", lambda *a: widgets["analyzer_pref_infobox"].hide())
コード例 #51
0
ファイル: newGameDialog.py プロジェクト: judoaseeta/pychess
    def _init(cls):
        cls.white = get_pixbuf("glade/white.png")
        cls.black = get_pixbuf("glade/black.png")

        cls.widgets = uistuff.GladeWidgets("newInOut.glade")
        cls.widgets["newgamedialog"].set_transient_for(mainwindow())

        def on_exchange_players(widget, button_event):
            white = cls.widgets["whitePlayerCombobox"].get_active()
            black = cls.widgets["blackPlayerCombobox"].get_active()
            whiteLevel = cls.widgets["skillSlider1"].get_value()
            blackLevel = cls.widgets["skillSlider2"].get_value()
            cls.widgets["whitePlayerCombobox"].set_active(black)
            cls.widgets["blackPlayerCombobox"].set_active(white)
            cls.widgets["skillSlider1"].set_value(blackLevel)
            cls.widgets["skillSlider2"].set_value(whiteLevel)

        cls.widgets["whitePlayerButton"].set_image(
            Gtk.Image.new_from_pixbuf(cls.white))
        cls.widgets["whitePlayerButton"].connect("button-press-event",
                                                 on_exchange_players)
        cls.widgets["blackPlayerButton"].set_image(
            Gtk.Image.new_from_pixbuf(cls.black))
        cls.widgets["blackPlayerButton"].connect("button-press-event",
                                                 on_exchange_players)

        uistuff.createCombo(cls.widgets["whitePlayerCombobox"],
                            name="whitePlayerCombobox")
        uistuff.createCombo(cls.widgets["blackPlayerCombobox"],
                            name="blackPlayerCombobox")

        cls.widgets["playersIcon"].set_from_pixbuf(big_people)
        cls.widgets["timeIcon"].set_from_pixbuf(big_time)

        def on_playerCombobox_changed(widget, skill_hbox):
            skill_hbox.props.visible = widget.get_active() > 0

        cls.widgets["whitePlayerCombobox"].connect("changed",
                                                   on_playerCombobox_changed,
                                                   cls.widgets["skillHbox1"])
        cls.widgets["blackPlayerCombobox"].connect("changed",
                                                   on_playerCombobox_changed,
                                                   cls.widgets["skillHbox2"])
        cls.widgets["whitePlayerCombobox"].set_active(0)
        cls.widgets["blackPlayerCombobox"].set_active(1)

        def on_skill_changed(scale, image):
            image.set_from_pixbuf(skillToIcon[int(scale.get_value())])

        cls.widgets["skillSlider1"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon1"])
        cls.widgets["skillSlider2"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon2"])
        cls.widgets["skillSlider1"].set_value(3)
        cls.widgets["skillSlider2"].set_value(3)

        cls.__initTimeRadio(_("Blitz"), "ngblitz", cls.widgets["blitzRadio"],
                            cls.widgets["configImageBlitz"], 5, 0, 0)
        cls.__initTimeRadio(_("Rapid"), "ngrapid", cls.widgets["rapidRadio"],
                            cls.widgets["configImageRapid"], 15, 5, 0)
        cls.__initTimeRadio(_("Normal"), "ngnormal",
                            cls.widgets["normalRadio"],
                            cls.widgets["configImageNormal"], 40, 15, 0)
        cls.__initTimeRadio(_("Classical"), "ngclassical",
                            cls.widgets["classicalRadio"],
                            cls.widgets["configImageClassical"], 3, 0, 40)

        cls.__initVariantRadio("ngvariant1", cls.widgets["playVariant1Radio"],
                               cls.widgets["configImageVariant1"],
                               FISCHERRANDOMCHESS)
        cls.__initVariantRadio("ngvariant2", cls.widgets["playVariant2Radio"],
                               cls.widgets["configImageVariant2"], LOSERSCHESS)

        def updateCombos(*args):
            if cls.widgets["playNormalRadio"].get_active():
                variant = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            else:
                variant = conf.get("ngvariant2", LOSERSCHESS)
            variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            cls.widgets["playVariant1Radio"].set_tooltip_text(
                variants[variant1].__desc__)
            variant2 = conf.get("ngvariant2", LOSERSCHESS)
            cls.widgets["playVariant2Radio"].set_tooltip_text(
                variants[variant2].__desc__)
            data = [(item[0], item[1]) for item in playerItems[variant]]
            uistuff.updateCombo(cls.widgets["blackPlayerCombobox"], data)
            uistuff.updateCombo(cls.widgets["whitePlayerCombobox"], data)

        discoverer.connect_after("all_engines_discovered", updateCombos)
        updateCombos(discoverer)

        conf.notify_add("ngvariant1", updateCombos)
        conf.notify_add("ngvariant2", updateCombos)
        cls.widgets["playNormalRadio"].connect("toggled", updateCombos)
        cls.widgets["playNormalRadio"].set_tooltip_text(
            variants[NORMALCHESS].__desc__)
        cls.widgets["playVariant1Radio"].connect("toggled", updateCombos)
        variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
        cls.widgets["playVariant1Radio"].set_tooltip_text(
            variants[variant1].__desc__)
        cls.widgets["playVariant2Radio"].connect("toggled", updateCombos)
        variant2 = conf.get("ngvariant2", LOSERSCHESS)
        cls.widgets["playVariant2Radio"].set_tooltip_text(
            variants[variant2].__desc__)

        # The "variant" has to come before players, because the engine positions
        # in the user comboboxes can be different in different variants
        for key in ("whitePlayerCombobox", "blackPlayerCombobox",
                    "skillSlider1", "skillSlider2", "notimeRadio",
                    "blitzRadio", "rapidRadio", "normalRadio",
                    "classicalRadio", "playNormalRadio", "playVariant1Radio",
                    "playVariant2Radio"):
            uistuff.keep(cls.widgets[key], key)

        # We don't want the dialog to deallocate when closed. Rather we hide
        # it on respond
        cls.widgets["newgamedialog"].connect("delete_event", lambda *a: True)
コード例 #52
0
ファイル: analyzegameDialog.py プロジェクト: metiscus/pychess
def initialize(gameDic):
    
    uistuff.keep(widgets["fromCurrent"], "fromCurrent", first_value=True)
    uistuff.keep(widgets["threatPV"], "threatPV")
    uistuff.keep(widgets["showEval"], "showEval")
    uistuff.keep(widgets["showBlunder"], "showBlunder", first_value=True)
    uistuff.keep(widgets["max_analysis_spin"], "max_analysis_spin", first_value=3)
    uistuff.keep(widgets["variation_thresold_spin"], "variation_thresold_spin", first_value=50)

    # Analyzing engines
    uistuff.createCombo(widgets["ana_combobox"])

    from pychess.widgets import newGameDialog
    @idle_add
    def update_analyzers_store(discoverer):
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.updateCombo(widgets["ana_combobox"], data)
    discoverer.connect_after("all_engines_discovered", update_analyzers_store)
    update_analyzers_store(discoverer)

    uistuff.keep(widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
        lambda combobox, value: anal_combo_set_value(combobox, value, "hint_mode",
                                              "analyzer_check", HINT))
 
    def hide_window(button, *args):
        widgets["analyze_game"].hide()
        return True
    
    def abort ():
        stop_event.set()
        widgets["analyze_game"].hide()
        
    def run_analyze(button, *args):
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]

        old_check_value = conf.get("analyzer_check", True)
        conf.set("analyzer_check", True)
        analyzer = gamemodel.spectators[HINT]
        gmwidg.menuitems["hint_mode"].active = True
        threat_PV = conf.get("ThreatPV", False)
        if threat_PV:
            old_inv_check_value = conf.get("inv_analyzer_check", True)
            conf.set("inv_analyzer_check", True)
            inv_analyzer = gamemodel.spectators[SPY]
            gmwidg.menuitems["spy_mode"].active = True

        title = _("Game analyzing in progress...")
        text = _("Do you want to abort it?")
        content = InfoBar.get_message_content(title, text, Gtk.STOCK_DIALOG_QUESTION)
        def response_cb (infobar, response, message):
            message.dismiss()
            abort()
        message = InfoBarMessage(Gtk.MessageType.QUESTION, content, response_cb)
        message.add_button(InfoBarMessageButton(_("Abort"), Gtk.ResponseType.CANCEL))
        gmwidg.showMessage(message)

        def analyse_moves():
            from_current = conf.get("fromCurrent", True)
            start_ply = gmwidg.board.view.shown if from_current else 0
            move_time = int(conf.get("max_analysis_spin", 3))
            thresold = int(conf.get("variation_thresold_spin", 50))
            for board in gamemodel.boards[start_ply:]:
                if stop_event.is_set():
                    break
                @idle_add
                def do():
                    gmwidg.board.view.setShownBoard(board)
                do()
                analyzer.setBoard(board)
                inv_analyzer.setBoard(board)
                time.sleep(move_time+0.1)

                ply = board.ply
                if ply-1 in gamemodel.scores and ply in gamemodel.scores: 
                    color = (ply-1) % 2
                    oldmoves, oldscore, olddepth = gamemodel.scores[ply-1]
                    score_str = prettyPrintScore(oldscore, olddepth)
                    oldscore = oldscore * -1 if color == BLACK else oldscore
                    moves, score, depth = gamemodel.scores[ply]
                    score = score * -1 if color == WHITE else score
                    diff = score-oldscore
                    if (diff > thresold and color==BLACK) or (diff < -1*thresold and color==WHITE):
                        if threat_PV:
                            try:
                                if ply-1 in gamemodel.spy_scores:
                                    oldmoves0, oldscore0, olddepth0 = gamemodel.spy_scores[ply-1]
                                    score_str0 = prettyPrintScore(oldscore0, olddepth0)
                                    pv0 = listToMoves(gamemodel.boards[ply-1], ["--"] + oldmoves0, validate=True)
                                    if len(pv0) > 2:
                                        gamemodel.add_variation(gamemodel.boards[ply-1], pv0, comment="Treatening", score=score_str0)
                            except ParsingError as e:
                                # ParsingErrors may happen when parsing "old" lines from
                                # analyzing engines, which haven't yet noticed their new tasks
                                log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" % \
                                    (' '.join(oldmoves),e))
                        try:
                            pv = listToMoves(gamemodel.boards[ply-1], oldmoves, validate=True)
                            gamemodel.add_variation(gamemodel.boards[ply-1], pv, comment="Better is", score=score_str)
                        except ParsingError as e:
                            # ParsingErrors may happen when parsing "old" lines from
                            # analyzing engines, which haven't yet noticed their new tasks
                            log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" % \
                                (' '.join(oldmoves),e))

            widgets["analyze_game"].hide()
            widgets["analyze_ok_button"].set_sensitive(True)
            conf.set("analyzer_check", old_check_value)
            if threat_PV:
                conf.set("inv_analyzer_check", old_inv_check_value)
            message.dismiss()
                        
        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        hide_window(None)

        return True
    
    widgets["analyze_game"].connect("delete-event", hide_window)
    widgets["analyze_cancel_button"].connect("clicked", hide_window)
    widgets["analyze_ok_button"].connect("clicked", run_analyze)
コード例 #53
0
    def __init__(self):
        self.widgets = uistuff.GladeWidgets("analyze_game.glade")
        self.widgets["analyze_game"].set_transient_for(mainwindow())
        self.stop_event = asyncio.Event()

        uistuff.keep(self.widgets["fromCurrent"], "fromCurrent")
        uistuff.keep(self.widgets["shouldBlack"], "shouldBlack")
        uistuff.keep(self.widgets["shouldWhite"], "shouldWhite")
        uistuff.keep(self.widgets["threatPV"], "threatPV")
        uistuff.keep(self.widgets["showEval"], "showEval")
        uistuff.keep(self.widgets["showBlunder"], "showBlunder")
        uistuff.keep(self.widgets["max_analysis_spin"], "max_analysis_spin")
        uistuff.keep(self.widgets["variation_threshold_spin"],
                     "variation_threshold_spin")

        # Analyzing engines
        uistuff.createCombo(self.widgets["ana_combobox"], name="ana_combobox")

        from pychess.widgets import newGameDialog

        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(self.widgets["ana_combobox"], data)

        discoverer.connect_after("all_engines_discovered",
                                 update_analyzers_store)
        update_analyzers_store(discoverer)

        uistuff.keep(
            self.widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(
                combobox, value, "hint_mode", HINT))

        def hide_window(button, *args):
            self.widgets["analyze_game"].destroy()

        def abort():
            self.analyzer.pause()
            if self.threat_PV:
                self.inv_analyzer.pause()
            self.stop_event.set()
            self.widgets["analyze_game"].destroy()

        def run_analyze(button, *args):
            @asyncio.coroutine
            def coro():
                persp = perspective_manager.get_perspective("games")
                gmwidg = persp.cur_gmwidg()
                gamemodel = gmwidg.gamemodel

                old_check_value = conf.get("analyzer_check")
                conf.set("analyzer_check", True)
                if HINT not in gamemodel.spectators:
                    try:
                        yield from asyncio.wait_for(
                            gamemodel.start_analyzer(HINT), 5.0)
                    except asyncio.TimeoutError:
                        log.error(
                            "Got timeout error while starting hint analyzer")
                        return
                    except Exception:
                        log.error("Unknown error while starting hint analyzer")
                        return
                self.analyzer = gamemodel.spectators[HINT]
                gmwidg.menuitems["hint_mode"].active = True
                self.threat_PV = conf.get("ThreatPV")
                if self.threat_PV:
                    old_inv_check_value = conf.get("inv_analyzer_check")
                    conf.set("inv_analyzer_check", True)
                    if SPY not in gamemodel.spectators:
                        try:
                            yield from asyncio.wait_for(
                                gamemodel.start_analyzer(SPY), 5.0)
                        except asyncio.TimeoutError:
                            log.error(
                                "Got timeout error while starting spy analyzer"
                            )
                            return
                        except Exception:
                            log.error(
                                "Unknown error while starting spy analyzer")
                            return
                    inv_analyzer = gamemodel.spectators[SPY]
                    gmwidg.menuitems["spy_mode"].active = True

                title = _("Game analyzing in progress...")
                text = _("Do you want to abort it?")
                content = InfoBar.get_message_content(
                    title, text, Gtk.STOCK_DIALOG_QUESTION)

                def response_cb(infobar, response, message):
                    conf.set("analyzer_check", old_check_value)
                    if self.threat_PV:
                        conf.set("inv_analyzer_check", old_inv_check_value)
                    message.dismiss()
                    abort()

                message = InfoBarMessage(Gtk.MessageType.QUESTION, content,
                                         response_cb)
                message.add_button(
                    InfoBarMessageButton(_("Abort"), Gtk.ResponseType.CANCEL))
                gmwidg.replaceMessages(message)

                @asyncio.coroutine
                def analyse_moves():
                    should_black = conf.get("shouldBlack")
                    should_white = conf.get("shouldWhite")
                    from_current = conf.get("fromCurrent")
                    start_ply = gmwidg.board.view.shown if from_current else 0
                    move_time = int(conf.get("max_analysis_spin"))
                    threshold = int(conf.get("variation_threshold_spin"))
                    for board in gamemodel.boards[start_ply:]:
                        if self.stop_event.is_set():
                            break

                        gmwidg.board.view.setShownBoard(board)
                        self.analyzer.setBoard(board)
                        if self.threat_PV:
                            inv_analyzer.setBoard(board)
                        yield from asyncio.sleep(move_time + 0.1)

                        ply = board.ply - gamemodel.lowply
                        color = (ply - 1) % 2
                        if ply - 1 in gamemodel.scores and ply in gamemodel.scores and (
                            (color == BLACK and should_black) or
                            (color == WHITE and should_white)):
                            oldmoves, oldscore, olddepth = gamemodel.scores[ply
                                                                            -
                                                                            1]
                            oldscore = oldscore * -1 if color == BLACK else oldscore
                            score_str = prettyPrintScore(oldscore, olddepth)
                            moves, score, depth = gamemodel.scores[ply]
                            score = score * -1 if color == WHITE else score
                            diff = score - oldscore
                            if ((diff > threshold and color == BLACK) or
                                (diff < -1 * threshold and color == WHITE)
                                ) and (gamemodel.moves[ply - 1] != parseAny(
                                    gamemodel.boards[ply - 1], oldmoves[0])):
                                if self.threat_PV:
                                    try:
                                        if ply - 1 in gamemodel.spy_scores:
                                            oldmoves0, oldscore0, olddepth0 = gamemodel.spy_scores[
                                                ply - 1]
                                            score_str0 = prettyPrintScore(
                                                oldscore0, olddepth0)
                                            pv0 = listToMoves(
                                                gamemodel.boards[ply - 1],
                                                ["--"] + oldmoves0,
                                                validate=True)
                                            if len(pv0) > 2:
                                                gamemodel.add_variation(
                                                    gamemodel.boards[ply - 1],
                                                    pv0,
                                                    comment="Threatening",
                                                    score=score_str0,
                                                    emit=False)
                                    except ParsingError as e:
                                        # ParsingErrors may happen when parsing "old" lines from
                                        # analyzing engines, which haven't yet noticed their new tasks
                                        log.debug(
                                            "__parseLine: Ignored (%s) from analyzer: ParsingError%s"
                                            % (' '.join(oldmoves), e))
                                try:
                                    pv = listToMoves(gamemodel.boards[ply - 1],
                                                     oldmoves,
                                                     validate=True)
                                    gamemodel.add_variation(
                                        gamemodel.boards[ply - 1],
                                        pv,
                                        comment="Better is",
                                        score=score_str,
                                        emit=False)
                                except ParsingError as e:
                                    # ParsingErrors may happen when parsing "old" lines from
                                    # analyzing engines, which haven't yet noticed their new tasks
                                    log.debug(
                                        "__parseLine: Ignored (%s) from analyzer: ParsingError%s"
                                        % (' '.join(oldmoves), e))

                    self.widgets["analyze_game"].hide()
                    self.widgets["analyze_ok_button"].set_sensitive(True)
                    conf.set("analyzer_check", old_check_value)
                    if self.threat_PV:
                        conf.set("inv_analyzer_check", old_inv_check_value)
                    message.dismiss()

                    gamemodel.emit("analysis_finished")

                create_task(analyse_moves())
                hide_window(None)

                return True

            create_task(coro())

        self.widgets["analyze_game"].connect("delete-event", hide_window)
        self.widgets["analyze_cancel_button"].connect("clicked", hide_window)
        self.widgets["analyze_ok_button"].connect("clicked", run_analyze)
コード例 #54
0
ファイル: newGameDialog.py プロジェクト: leogregianin/pychess
    def _init(cls):
        cls.white = get_pixbuf("glade/white.png")
        cls.black = get_pixbuf("glade/black.png")

        cls.widgets = uistuff.GladeWidgets("newInOut.glade")
        cls.widgets["newgamedialog"].set_transient_for(mainwindow())

        def on_exchange_players(widget, button_event):
            white = cls.widgets["whitePlayerCombobox"].get_active()
            black = cls.widgets["blackPlayerCombobox"].get_active()
            whiteLevel = cls.widgets["skillSlider1"].get_value()
            blackLevel = cls.widgets["skillSlider2"].get_value()
            cls.widgets["whitePlayerCombobox"].set_active(black)
            cls.widgets["blackPlayerCombobox"].set_active(white)
            cls.widgets["skillSlider1"].set_value(blackLevel)
            cls.widgets["skillSlider2"].set_value(whiteLevel)

        cls.widgets["whitePlayerButton"].set_image(Gtk.Image.new_from_pixbuf(cls.white))
        cls.widgets["whitePlayerButton"].connect("button-press-event", on_exchange_players)
        cls.widgets["blackPlayerButton"].set_image(Gtk.Image.new_from_pixbuf(cls.black))
        cls.widgets["blackPlayerButton"].connect("button-press-event", on_exchange_players)

        uistuff.createCombo(cls.widgets["whitePlayerCombobox"], name="whitePlayerCombobox")
        uistuff.createCombo(cls.widgets["blackPlayerCombobox"], name="blackPlayerCombobox")

        cls.widgets["playersIcon"].set_from_pixbuf(big_people)
        cls.widgets["timeIcon"].set_from_pixbuf(big_time)

        def on_playerCombobox_changed(widget, skill_hbox, skill_level):
            position = widget.get_active()
            skill_hbox.props.visible = position > 0
            if position > 0:
                tree_iter = widget.get_active_iter()
                if tree_iter is not None:
                    engine_name = widget.get_model()[tree_iter][1]
                    engine = discoverer.getEngineByName(engine_name)
                    if engine:
                        pref_level = engine.get("level")
                        if pref_level:
                            skill_level.set_value(pref_level)

        cls.widgets["whitePlayerCombobox"].connect("changed", on_playerCombobox_changed, cls.widgets["skillHbox1"], cls.widgets["skillSlider1"])
        cls.widgets["blackPlayerCombobox"].connect("changed", on_playerCombobox_changed, cls.widgets["skillHbox2"], cls.widgets["skillSlider2"])
        cls.widgets["whitePlayerCombobox"].set_active(0)
        cls.widgets["blackPlayerCombobox"].set_active(1)

        def on_skill_changed(scale, image):
            image.set_from_pixbuf(skillToIcon[int(scale.get_value())])

        cls.widgets["skillSlider1"].connect("value-changed", on_skill_changed, cls.widgets["skillIcon1"])
        cls.widgets["skillSlider2"].connect("value-changed", on_skill_changed, cls.widgets["skillIcon2"])
        cls.widgets["skillSlider1"].set_value(3)
        cls.widgets["skillSlider2"].set_value(3)

        cls.__initTimeRadio("ngblitz", cls.widgets["blitzRadio"], cls.widgets["configImageBlitz"], 5, 0, 0)
        cls.__initTimeRadio("ngrapid", cls.widgets["rapidRadio"], cls.widgets["configImageRapid"], 15, 5, 0)
        cls.__initTimeRadio("ngnormal", cls.widgets["normalRadio"], cls.widgets["configImageNormal"], 45, 15, 0)
        cls.__initTimeRadio("ngclassical", cls.widgets["classicalRadio"], cls.widgets["configImageClassical"], 3, 0, 40)

        cls.__initVariantRadio("ngvariant1", cls.widgets["playVariant1Radio"], cls.widgets["configImageVariant1"])
        cls.__initVariantRadio("ngvariant2", cls.widgets["playVariant2Radio"], cls.widgets["configImageVariant2"])

        def updateCombos(*args):
            if cls.widgets["playNormalRadio"].get_active():
                variant = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant = conf.get("ngvariant1")
            else:
                variant = conf.get("ngvariant2")
            variant1 = conf.get("ngvariant1")
            cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)
            variant2 = conf.get("ngvariant2")
            cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)
            data = [(item[0], item[1]) for item in playerItems[variant]]
            uistuff.updateCombo(cls.widgets["blackPlayerCombobox"], data)
            uistuff.updateCombo(cls.widgets["whitePlayerCombobox"], data)

        discoverer.connect_after("all_engines_discovered", updateCombos)
        updateCombos(discoverer)

        conf.notify_add("ngvariant1", updateCombos)
        conf.notify_add("ngvariant2", updateCombos)
        cls.widgets["playNormalRadio"].connect("toggled", updateCombos)
        cls.widgets["playNormalRadio"].set_tooltip_text(variants[NORMALCHESS].__desc__)
        cls.widgets["playVariant1Radio"].connect("toggled", updateCombos)
        variant1 = conf.get("ngvariant1")
        cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)
        cls.widgets["playVariant2Radio"].connect("toggled", updateCombos)
        variant2 = conf.get("ngvariant2")
        cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)

        # The "variant" has to come before players, because the engine positions
        # in the user comboboxes can be different in different variants
        for key in ("whitePlayerCombobox", "blackPlayerCombobox",
                    "skillSlider1", "skillSlider2", "notimeRadio",
                    "blitzRadio", "rapidRadio", "normalRadio", "classicalRadio",
                    "playNormalRadio", "playVariant1Radio", "playVariant2Radio"):
            uistuff.keep(cls.widgets[key], key)

        # We don't want the dialog to deallocate when closed. Rather we hide
        # it on respond
        cls.widgets["newgamedialog"].connect("delete_event", lambda *a: True)
コード例 #55
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Options on by default
        for key in ("opening_check", "endgame_check", "online_egtb_check",
                    "analyzer_check", "inv_analyzer_check"):
            uistuff.keep(widgets[key], key, first_value=True)

        # Opening book
        default_path = os.path.join(addDataPrefix("pychess_book.bin"))
        path = conf.get("opening_file_entry", default_path)
        conf.set("opening_file_entry", path)

        book_chooser_dialog = Gtk.FileChooserDialog(
            _("Select book file"), mainwindow(), Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        book_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            book_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Opening books"))
        filter.add_pattern("*.bin")
        book_chooser_dialog.add_filter(filter)
        book_chooser_button.set_filename(path)

        self.widgets["bookChooserDock"].add(book_chooser_button)
        book_chooser_button.show()

        def select_new_book(button):
            new_book = book_chooser_dialog.get_filename()
            if new_book:
                conf.set("opening_file_entry", new_book)
            else:
                # restore the original
                book_chooser_dialog.set_filename(path)

        book_chooser_button.connect("file-set", select_new_book)

        def on_opening_check_toggled(check):
            self.widgets["opening_hbox"].set_sensitive(check.get_active())

        self.widgets["opening_check"].connect_after("toggled",
                                                    on_opening_check_toggled)

        # Endgame
        default_path = os.path.join(getDataPrefix())
        egtb_path = conf.get("egtb_path", default_path)
        conf.set("egtb_path", egtb_path)

        egtb_chooser_dialog = Gtk.FileChooserDialog(
            _("Select Gaviota TB path"), mainwindow(),
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        egtb_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            egtb_chooser_dialog)
        egtb_chooser_button.set_current_folder(egtb_path)

        self.widgets["egtbChooserDock"].add(egtb_chooser_button)
        egtb_chooser_button.show()

        def select_egtb(button):
            new_directory = egtb_chooser_dialog.get_filename()
            if new_directory != egtb_path:
                conf.set("egtb_path", new_directory)

        egtb_chooser_button.connect("current-folder-changed", select_egtb)

        def on_endgame_check_toggled(check):
            self.widgets["endgame_hbox"].set_sensitive(check.get_active())

        self.widgets["endgame_check"].connect_after("toggled",
                                                    on_endgame_check_toggled)

        # Analyzing engines
        from pychess.widgets import newGameDialog
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.createCombo(widgets["ana_combobox"], data, name="ana_combobox")
        uistuff.createCombo(widgets["inv_ana_combobox"],
                            data,
                            name="inv_ana_combobox")

        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(widgets["ana_combobox"], data)
            uistuff.updateCombo(widgets["inv_ana_combobox"], data)

        discoverer.connect_after("all_engines_discovered",
                                 update_analyzers_store)
        update_analyzers_store(discoverer)

        # Save, load and make analyze combos active

        # Let Stockfish to be default analyzer in Windows installer
        default = discoverer.getEngineN(-1).get("md5")
        conf.set("ana_combobox", conf.get("ana_combobox", default))
        conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", default))

        def on_analyzer_check_toggled(check):
            self.widgets["analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.widgets.gamewidget import widgets
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio. async (
                            gmwidg.gamemodel.restart_analyzer(HINT))
                        if not widgets["hint_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(HINT)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(HINT)

        self.widgets["analyzers_vbox"].set_sensitive(
            widgets["analyzer_check"].get_active())
        self.widgets["analyzer_check"].connect_after(
            "toggled", on_analyzer_check_toggled)

        def on_invanalyzer_check_toggled(check):
            self.widgets["inv_analyzers_vbox"].set_sensitive(
                check.get_active())
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio. async (gmwidg.gamemodel.restart_analyzer(SPY))
                        if not widgets["spy_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(SPY)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(SPY)

        self.widgets["inv_analyzers_vbox"].set_sensitive(
            widgets["inv_analyzer_check"].get_active())
        self.widgets["inv_analyzer_check"].connect_after(
            "toggled", on_invanalyzer_check_toggled)

        # Give widgets to keeper

        uistuff.keep(
            self.widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(
                combobox, value, "hint_mode", "analyzer_check", HINT))
        uistuff.keep(
            self.widgets["inv_ana_combobox"], "inv_ana_combobox",
            anal_combo_get_value, lambda combobox, value: anal_combo_set_value(
                combobox, value, "spy_mode", "inv_analyzer_check", SPY))

        uistuff.keep(self.widgets["max_analysis_spin"],
                     "max_analysis_spin",
                     first_value=3)
コード例 #56
0
ファイル: preferencesDialog.py プロジェクト: bboutkov/pychess
    def __init__(self, widgets):
        self.widgets = widgets

        # Options on by default
        for key in ("opening_check", "endgame_check", "online_egtb_check",
                    "analyzer_check", "inv_analyzer_check"):
            uistuff.keep(widgets[key], key, first_value=True)

        # Opening book
        default_path = os.path.join(addDataPrefix("pychess_book.bin"))
        path = conf.get("opening_file_entry", default_path)
        conf.set("opening_file_entry", path)

        book_chooser_dialog = Gtk.FileChooserDialog(
            _("Select book file"), None, Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        book_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            book_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Opening books"))
        filter.add_pattern("*.bin")
        book_chooser_dialog.add_filter(filter)
        book_chooser_button.set_filename(path)

        self.widgets["bookChooserDock"].add(book_chooser_button)
        book_chooser_button.show()

        def select_new_book(button):
            new_book = book_chooser_dialog.get_filename()
            if new_book:
                conf.set("opening_file_entry", new_book)
            else:
                # restore the original
                book_chooser_dialog.set_filename(path)

        book_chooser_button.connect("file-set", select_new_book)

        def on_opening_check_toggled(check):
            self.widgets["opening_hbox"].set_sensitive(check.get_active())

        self.widgets["opening_check"].connect_after("toggled",
                                                    on_opening_check_toggled)

        # Endgame
        default_path = os.path.join(getDataPrefix())
        egtb_path = conf.get("egtb_path", default_path)
        conf.set("egtb_path", egtb_path)

        egtb_chooser_dialog = Gtk.FileChooserDialog(
            _("Select Gaviota TB path"), None,
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        egtb_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            egtb_chooser_dialog)
        egtb_chooser_button.set_current_folder(egtb_path)

        self.widgets["egtbChooserDock"].add(egtb_chooser_button)
        egtb_chooser_button.show()

        def select_egtb(button):
            new_directory = egtb_chooser_dialog.get_filename()
            if new_directory != egtb_path:
                conf.set("egtb_path", new_directory)

        egtb_chooser_button.connect("current-folder-changed", select_egtb)

        def on_endgame_check_toggled(check):
            self.widgets["endgame_hbox"].set_sensitive(check.get_active())

        self.widgets["endgame_check"].connect_after("toggled",
                                                    on_endgame_check_toggled)

        # Analyzing engines
        from pychess.widgets import newGameDialog
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.createCombo(widgets["ana_combobox"], data, name="ana_combobox")
        uistuff.createCombo(widgets["inv_ana_combobox"], data, name="inv_ana_combobox")

        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(widgets["ana_combobox"], data)
            uistuff.updateCombo(widgets["inv_ana_combobox"], data)

        discoverer.connect_after("all_engines_discovered",
                                 update_analyzers_store)
        update_analyzers_store(discoverer)

        # Save, load and make analyze combos active

        # Let Stockfish to be default analyzer in Windows installer
        default = discoverer.getEngineN(-1).get("md5")
        conf.set("ana_combobox", conf.get("ana_combobox", default))
        conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", default))

        def on_analyzer_check_toggled(check):
            self.widgets["analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.widgets.gamewidget import widgets
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio.async(gmwidg.gamemodel.restart_analyzer(HINT))
                        if not widgets["hint_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(HINT)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(HINT)

        self.widgets["analyzers_vbox"].set_sensitive(widgets[
            "analyzer_check"].get_active())
        self.widgets["analyzer_check"].connect_after("toggled",
                                                     on_analyzer_check_toggled)

        def on_invanalyzer_check_toggled(check):
            self.widgets["inv_analyzers_vbox"].set_sensitive(check.get_active())
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio.async(gmwidg.gamemodel.restart_analyzer(SPY))
                        if not widgets["spy_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(SPY)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(SPY)

        self.widgets["inv_analyzers_vbox"].set_sensitive(widgets[
            "inv_analyzer_check"].get_active())
        self.widgets["inv_analyzer_check"].connect_after(
            "toggled", on_invanalyzer_check_toggled)

        # Give widgets to keeper

        uistuff.keep(
            self.widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(combobox, value, "hint_mode", "analyzer_check", HINT))
        uistuff.keep(
            self.widgets["inv_ana_combobox"], "inv_ana_combobox",
            anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(combobox, value, "spy_mode", "inv_analyzer_check", SPY))

        uistuff.keep(self.widgets["max_analysis_spin"], "max_analysis_spin", first_value=3)
コード例 #57
0
    def load(self, widgets, connection, lounge):
        self.widgets = widgets
        self.connection = connection
        self.lounge = lounge

        __widget__ = lounge.games_list

        self.games = {}
        self.recpix = load_icon(16, "media-record")
        self.clearpix = get_pixbuf("glade/board.png")
        self.tv = self.widgets["gametreeview"]
        self.store = Gtk.ListStore(FICSGame, GdkPixbuf.Pixbuf, str, int, str,
                                   int, str, str)

        self.game_filter = self.store.filter_new()
        self.game_filter.set_visible_func(self.game_filter_func)

        self.filter_toggles = {}
        self.filter_buttons = ("standard_toggle", "blitz_toggle",
                               "lightning_toggle", "variant_toggle")
        for widget in self.filter_buttons:
            uistuff.keep(self.widgets[widget], widget)
            self.widgets[widget].connect("toggled",
                                         self.on_filter_button_toggled)
            initial = conf.get(widget, True)
            self.filter_toggles[widget] = initial
            self.widgets[widget].set_active(initial)

        self.model = self.game_filter.sort_new_with_model()
        self.tv.set_model(self.model)
        self.tv.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
        self.addColumns(self.tv,
                        "FICSGame",
                        "",
                        _("White"),
                        _("Rating"),
                        _("Black"),
                        _("Rating"),
                        _("Type"),
                        _("Rated"),
                        hide=[0],
                        pix=[1])

        self.tv.get_model().set_sort_func(0, self.pixCompareFunction, 1)
        for i in range(1, 7):
            self.tv.get_model().set_sort_func(i, self.compareFunction, i)
        self.prev_sort_column_id = []
        self.model.connect("sort-column-changed", self.on_sort_column_change)

        self.tv.set_has_tooltip(True)
        self.tv.connect("query-tooltip", self.on_query_tooltip)
        self.selection = self.tv.get_selection()
        self.selection.connect("changed", self.onSelectionChanged)
        self.onSelectionChanged(self.selection)

        try:
            self.tv.set_search_position_func(self.lowLeftSearchPosFunc, None)
        except AttributeError:
            # Unknow signal name is raised by gtk < 2.10
            pass

        def searchCallback(model, column, key, sel_iter, user_data):
            if model.get_value(sel_iter, 2).lower().startswith(key) or \
                    model.get_value(sel_iter, 4).lower().startswith(key):
                return False
            return True

        self.tv.set_search_equal_func(searchCallback, None)

        self.connection.games.connect("FICSGameCreated", self.onGameAdd)
        self.connection.games.connect("FICSGameEnded", self.onGameRemove)
        self.widgets["observeButton"].connect("clicked", self.on_observe)
        self.tv.connect("row-activated", self.on_observe)
        self.connection.bm.connect("obsGameCreated", self.onGameObserved)
        self.connection.bm.connect("obsGameUnobserved", self.onGameUnobserved)

        self.tv.connect('button-press-event', self.button_press_event)
        self.createLocalMenu((OBSERVE, FOLLOW, SEPARATOR, FINGER, ARCHIVED))

        return __widget__
コード例 #58
0
ファイル: Main.py プロジェクト: prvn16/pychess
    def initGlade(self, log_viewer):
        #=======================================================================
        # Init glade and the 'GladeHandlers'
        #=======================================================================
        #Gtk.about_dialog_set_url_hook(self.website)
        widgets = uistuff.GladeWidgets("PyChess.glade")       
        widgets.getGlade().connect_signals(GladeHandlers())

        tasker = TaskerManager()
        tasker.packTaskers (NewGameTasker(), InternetGameTasker())
        widgets["Background"].add(tasker)
        
        #------------------------------------------------------ Redirect widgets
        gamewidget.setWidgets(widgets)
        
        def on_sensitive_changed (widget, prop):
            name = widget.get_property('name')
            sensitive = widget.get_property('sensitive')
            #print "'%s' changed to '%s'" % (name, sensitive)
        widgets['pause1'].connect("notify::sensitive", on_sensitive_changed)
        widgets['resume1'].connect("notify::sensitive", on_sensitive_changed)
        #-------------------------- Main.py still needs a minimum of information
        ionest.handler.connect("gmwidg_created",
                               GladeHandlers.__dict__["on_gmwidg_created"])
        
        #---------------------- The only menuitems that need special initing
        for widget in ("hint_mode", "spy_mode"):
            widgets[widget].set_sensitive(False)

        uistuff.keep(widgets["hint_mode"], "hint_mode", first_value=True)
        uistuff.keep(widgets["spy_mode"], "spy_mode")
        uistuff.keep(widgets["show_sidepanels"], "show_sidepanels")
        uistuff.keep(widgets["auto_call_flag"], "autoCallFlag", first_value=True)
        
        #=======================================================================
        # Show main window and init d'n'd
        #=======================================================================
        widgets["window1"].set_title('%s - PyChess' % _('Welcome'))
        widgets["window1"].connect("delete-event",
                                   GladeHandlers.__dict__["on_quit1_activate"])
        widgets["window1"].connect("key-press-event",
                                   GladeHandlers.__dict__["on_window_key_press"])
        uistuff.keepWindowSize("main", widgets["window1"], (575,479), POSITION_GOLDEN)
        widgets["window1"].show()
        widgets["Background"].show_all()
                
        flags = Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP
        # To get drag in the whole window, we add it to the menu and the
        # background. If it can be gotten to work, the drag_dest_set_proxy
        # method is very interesting.
        #widgets["menubar1"].drag_dest_set(flags, dnd_list, Gdk.DragAction.COPY)
        #widgets["Background"].drag_dest_set(flags, dnd_list, Gdk.DragAction.COPY)
        # TODO: http://code.google.com/p/pychess/issues/detail?id=737
        # The following two should really be set in the glade file
        #widgets["menubar1"].set_events(widgets["menubar1"].get_events() | Gdk.DRAG_STATUS)
        #widgets["Background"].set_events(widgets["Background"].get_events() | Gdk.DRAG_STATUS)
        
        #=======================================================================
        # Init 'minor' dialogs
        #=======================================================================
        
        #------------------------------------------------------------ Log dialog
        if log_viewer:
            from pychess.widgets import LogDialog
            LogDialog.add_destroy_notify(lambda: widgets["log_viewer1"].set_active(0))
        else:
            widgets["log_viewer1"].set_property('sensitive', False)
            
        #---------------------------------------------------------- About dialog
        self.aboutdialog = widgets["aboutdialog1"]
        self.aboutdialog.set_program_name(NAME)
        link = self.aboutdialog.get_website()
        self.aboutdialog.set_copyright("Copyright © 2006-2015")
        self.aboutdialog.set_version(VERSION_NAME+" "+VERSION)
        if os.path.isdir(prefix.addDataPrefix(".git")):
            try:
                label = subprocess.check_output(["git", "describe"])
            except subprocess.CalledProcessError:
                label = ""
            if label:
                comments = self.aboutdialog.get_comments()
                self.git_rev = label
                self.aboutdialog.set_comments("git %s\n%s" % (self.git_rev, comments))
        
        with open(prefix.addDataPrefix("ARTISTS"), encoding="utf-8") as f:
            self.aboutdialog.set_artists(f.read().splitlines())
        with open(prefix.addDataPrefix("AUTHORS"), encoding="utf-8") as f:
            self.aboutdialog.set_authors(f.read().splitlines())
        with open(prefix.addDataPrefix("DOCUMENTERS"), encoding="utf-8") as f:
            self.aboutdialog.set_documenters(f.read().splitlines())
        with open(prefix.addDataPrefix("TRANSLATORS"), encoding="utf-8") as f:
            self.aboutdialog.set_translator_credits(f.read())

        def on_about_response(dialog, response, *args):
            # system-defined GtkDialog responses are always negative, in which    
            # case we want to hide it
            if response < 0:
                self.aboutdialog.hide()
                self.aboutdialog.emit_stop_by_name('response')

        def on_about_close(widget, event=None):
            self.aboutdialog.hide()
            return True

        self.aboutdialog.connect("response", on_about_response)
        self.aboutdialog.connect("close", on_about_close)
        self.aboutdialog.connect("delete-event", on_about_close)

        #---------------------------------------------------- RecentChooser
        def recent_item_activated (self):
            uri = self.get_current_uri()
            try:
                urlopen(unquote(uri)).close()
                newGameDialog.LoadFileExtension.run(self.get_current_uri())
            except (IOError, OSError):
                #shomething wrong whit the uri
                recentManager.remove_item(uri)
                
        #self.menu_recent = Gtk.RecentChooserMenu(recentManager)
        self.menu_recent = Gtk.RecentChooserMenu()
        self.menu_recent.set_show_tips(True)
        self.menu_recent.set_sort_type(Gtk.RecentSortType.MRU)
        self.menu_recent.set_limit(10)
        self.menu_recent.set_name("menu_recent")
        
        self.file_filter = Gtk.RecentFilter()
        self.file_filter.add_mime_type("application/x-chess-pgn")
        self.menu_recent.set_filter(self.file_filter)

        self.menu_recent.connect("item-activated", recent_item_activated)
        widgets["load_recent_game1"].set_submenu(self.menu_recent)
        
        #----------------------------------------------------- Discoverer dialog
        def discovering_started (discoverer, binnames):
            GLib.idle_add(DiscovererDialog.show, discoverer, widgets["window1"], binnames)
        discoverer.connect("discovering_started", discovering_started)
        DiscovererDialog.init(discoverer)
        discoverer.discover()
        
        #------------------------------------------------- Tip of the day dialog
        if conf.get("show_tip_at_startup", False):
            tipOfTheDay.TipOfTheDay.show()
コード例 #59
0
ファイル: preferencesDialog.py プロジェクト: bboutkov/pychess
    def __init__(self, widgets):

        # Init open dialog

        opendialog = Gtk.FileChooserDialog(
            _("Open Sound File"), None, Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.ACCEPT))

        for dir in self.SOUND_DIRS:
            if os.path.isdir(dir):
                opendialog.set_current_folder(dir)
                break

        soundfilter = Gtk.FileFilter()
        soundfilter.set_name(_("Sound files"))
        soundfilter.add_mime_type("audio/%s" % EXT)
        soundfilter.add_pattern("*.%s" % EXT)
        opendialog.add_filter(soundfilter)

        # Get combo icons

        icons = ((_("No sound"), "audio-volume-muted", "audio-volume-muted"),
                 (_("Beep"), "stock_bell", "audio-x-generic"),
                 (_("Select sound file..."), "gtk-open", "document-open"))

        items = []
        for level, stock, altstock in icons:
            image = load_icon(16, stock, altstock)
            items += [(image, level)]

        audioIco = load_icon(16, "audio-x-generic")

        # Set-up combos

        def callback(combobox, index):
            if combobox.get_active() == SOUND_SELECT:
                if opendialog.run() == Gtk.ResponseType.ACCEPT:
                    uri = opendialog.get_uri()
                    model = combobox.get_model()
                    conf.set("sounduri%d" % index, uri)
                    label = unquote(os.path.split(uri)[1])
                    if len(model) == 3:
                        model.append([audioIco, label])
                    else:
                        model.set(model.get_iter((3, )), 1, label)
                    combobox.set_active(3)
                else:
                    combobox.set_active(conf.get("soundcombo%d" % index,
                                                 SOUND_MUTE))
                opendialog.hide()

        for i in range(self.COUNT_OF_SOUNDS):
            combo = widgets["sound%dcombo" % i]
            uistuff.createCombo(combo, items, name="soundcombo%d" % i)
            # combo.set_active(0)
            combo.connect("changed", callback, i)

            label = widgets["soundlabel%d" % i]
            label.props.mnemonic_widget = combo

            uri = conf.get("sounduri%d" % i, "")
            if os.path.isfile(url2pathname(uri[5:])):
                model = combo.get_model()
                model.append([audioIco, unquote(os.path.split(uri)[1])])
                # combo.set_active(3)

        for i in range(self.COUNT_OF_SOUNDS):
            if conf.get("soundcombo%d" % i, SOUND_MUTE) == SOUND_URI and \
                    not os.path.isfile(url2pathname(conf.get("sounduri%d" % i, "")[5:])):
                conf.set("soundcombo%d" % i, SOUND_MUTE)
            uistuff.keep(widgets["sound%dcombo" % i], "soundcombo%d" % i)

        # Init play button

        def playCallback(button, index):
            SoundTab.playAction(index)

        for i in range(self.COUNT_OF_SOUNDS):
            button = widgets["sound%dbutton" % i]
            button.connect("clicked", playCallback, i)

        # Init 'use sound" checkbutton

        def checkCallBack(*args):
            checkbox = widgets["useSounds"]
            widgets["sounds_frame"].set_property("sensitive", checkbox.get_active())

        conf.notify_add("useSounds", checkCallBack)
        widgets["useSounds"].set_active(True)
        uistuff.keep(widgets["useSounds"], "useSounds")
        checkCallBack()

        if not self.getPlayer().ready:
            widgets["useSounds"].set_sensitive(False)
            widgets["useSounds"].set_active(False)

        uistuff.keep(widgets["alarm_spin"], "alarm_spin", first_value=15)