示例#1
0
def run(widgets):
    global firstRun, engine_dialog
    if firstRun:
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not (iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"],
                            name="engine_country_combo",
                            ellipsize_mode=Pango.EllipsizeMode.END)
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        engine_dialog = EnginesDialog(widgets)

        def cancel_event(widget, with_confirmation, *args):
            # Confirm if the changes need to be saved
            modified = discoverer.hasChanged()
            if modified and with_confirmation:
                dialog = Gtk.MessageDialog(mainwindow(),
                                           type=Gtk.MessageType.QUESTION,
                                           buttons=Gtk.ButtonsType.YES_NO)
                dialog.set_markup(
                    _("You have unsaved changes. Do you want to save before leaving?"
                      ))
                response = dialog.run()
                dialog.destroy()
                # if response == Gtk.ResponseType.CANCEL:
                #    return False
                if response == Gtk.ResponseType.NO:
                    discoverer.restore()
                if response == Gtk.ResponseType.YES:
                    discoverer.save()

            # Close the window
            widgets["manage_engines_dialog"].hide()
            return True

        def save_event(widget, *args):
            discoverer.save()
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", cancel_event,
                                                 True)
        widgets["engine_cancel_button"].connect("clicked", cancel_event, False)
        widgets["engine_save_button"].connect("clicked", save_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event", lambda w, e: cancel_event(w, True)
            if e.keyval == Gdk.KEY_Escape else None)

    discoverer.backup()
    engine_dialog.widgets["enginebook"].set_current_page(0)
    widgets["manage_engines_dialog"].show()
    if not firstRun:
        engine_dialog.update_store()
    firstRun = False
示例#2
0
def run(widgets):
    global firstRun, engine_dialog
    if firstRun:
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not(iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"], name="engine_country_combo",
                            ellipsize_mode=Pango.EllipsizeMode.END)
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        engine_dialog = EnginesDialog(widgets)

        def cancel_event(widget, with_confirmation, *args):
            # Confirm if the changes need to be saved
            modified = discoverer.hasChanged()
            if modified and with_confirmation:
                dialog = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO)
                dialog.set_markup(_("You have unsaved changes. Do you want to save before leaving?"))
                response = dialog.run()
                dialog.destroy()
                # if response == Gtk.ResponseType.CANCEL:
                #    return False
                if response == Gtk.ResponseType.NO:
                    discoverer.restore()
                if response == Gtk.ResponseType.YES:
                    discoverer.save()

            # Close the window
            widgets["manage_engines_dialog"].hide()
            return True

        def save_event(widget, *args):
            discoverer.save()
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", cancel_event, True)
        widgets["engine_cancel_button"].connect("clicked", cancel_event, False)
        widgets["engine_save_button"].connect("clicked", save_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event",
            lambda w, e: cancel_event(w, True) if e.keyval == Gdk.KEY_Escape else None)

    discoverer.backup()
    engine_dialog.widgets["enginebook"].set_current_page(0)
    widgets["manage_engines_dialog"].show()
    if not firstRun:
        engine_dialog.update_store()
    firstRun = False
示例#3
0
    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)
示例#4
0
    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)
示例#5
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = widgets = tasker_widgets
        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)
        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)
示例#6
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)
示例#7
0
def run(widgets):
    global firstRun
    if firstRun:
        # Bubble sort for the translated countries
        for i in range(len(ISO3166_LIST) - 1, 1, -1):
            for j in range(1, i - 1):
                if ISO3166_LIST[i].country < ISO3166_LIST[j].country:
                    tmp = ISO3166_LIST[i]
                    ISO3166_LIST[i] = ISO3166_LIST[j]
                    ISO3166_LIST[j] = tmp
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not (iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"],
                            name="engine_country_combo")
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        EnginesDialog(widgets)

        def delete_event(widget, *args):
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", delete_event)
        widgets["engines_close_button"].connect("clicked", delete_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event", lambda w, e: delete_event(w)
            if e.keyval == Gdk.KEY_Escape else None)

        firstRun = False

    widgets["manage_engines_dialog"].show()
示例#8
0
def run(widgets):
    global firstRun
    if firstRun:
        # Bubble sort for the translated countries
        for i in range(len(ISO3166_LIST) - 1, 1, - 1):
            for j in range(1, i - 1):
                if ISO3166_LIST[i].country < ISO3166_LIST[j].country:
                    tmp = ISO3166_LIST[i]
                    ISO3166_LIST[i] = ISO3166_LIST[j]
                    ISO3166_LIST[j] = tmp
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not(iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"], name="engine_country_combo",
                            ellipsize_mode=Pango.EllipsizeMode.END)
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        EnginesDialog(widgets)

        def delete_event(widget, *args):
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", delete_event)
        widgets["engines_close_button"].connect("clicked", delete_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event",
            lambda w, e: delete_event(w) if e.keyval == Gdk.KEY_Escape else None)

        firstRun = False

    widgets["manage_engines_dialog"].show()
 def __init__ (self, widgets):
     
     # Init open dialog
     
     opendialog = gtk.FileChooserDialog (
             _("Open Sound File"), None, gtk.FILE_CHOOSER_ACTION_OPEN,
              (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
               gtk.RESPONSE_ACCEPT))
     
     for dir in self.SOUND_DIRS:
         if os.path.isdir(dir):
             opendialog.set_current_folder(dir)
             break
     
     soundfilter = gtk.FileFilter()
     soundfilter.add_custom(soundfilter.get_needed(),
                            lambda data: data[3] and data[3].startswith("audio/"))
     opendialog.add_filter(soundfilter)
     opendialog.set_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.RESPONSE_ACCEPT:
                 uri = opendialog.get_uri()
                 model = combobox.get_model()
                 conf.set("sounduri%d"%index, uri)
                 label = 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 xrange(self.COUNT_OF_SOUNDS):
         combo = widgets["soundcombo%d"%i]
         uistuff.createCombo (combo, items)
         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(uri[7:]):
             model = combo.get_model()
             model.append([audioIco, os.path.split(uri)[1]])
             combo.set_active(3)
     
     for i in xrange(self.COUNT_OF_SOUNDS):
         if conf.get("soundcombo%d"%i, SOUND_MUTE) == SOUND_URI and \
                 not os.path.isfile(conf.get("sounduri%d"%i,"")[7:]):
             conf.set("soundcombo%d"%i, SOUND_MUTE)
         uistuff.keep(widgets["soundcombo%d"%i], "soundcombo%d"%i)
         #widgets["soundcombo%d"%i].set_active(conf.get("soundcombo%d"%i, SOUND_MUTE))
     
     # Init play button
     
     def playCallback (button, index):
         SoundTab.playAction(index)
     
     for i in range (self.COUNT_OF_SOUNDS):
         button = widgets["soundbutton%d"%i]
         button.connect("clicked", playCallback, i)
     
     # Init 'use sound" checkbutton
     
     def checkCallBack (*args):
         checkbox = widgets["useSounds"]
         widgets["frame23"].set_property("sensitive", checkbox.get_active())
     conf.notify_add("useSounds", checkCallBack)
     widgets["useSounds"].set_active(True)
     uistuff.keep(widgets["useSounds"], "useSounds")
     checkCallBack()
     
     def soundError (player, gstmessage):
         widgets["useSounds"].set_sensitive(False)
         widgets["useSounds"].set_active(False)
     self.getPlayer().connect("error", soundError)
示例#10
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)
示例#11
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)
示例#12
0
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.replaceMessages(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)
                if threat_PV:
                    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)
示例#13
0
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)
示例#14
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)
示例#15
0
    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)
示例#16
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Font chooser
        font = conf.get("movetextFont", "FreeSerif Regular 12")
        font_button = Gtk.FontButton.new_with_font(font)
        demo_text = "♔a1 ♕f8 ♖h8 ♗g7 ♘g2 Ka1 Qf8 Rh8 Bg7 Ng2"
        font_button.set_preview_text(demo_text)
        self.widgets["fontChooserDock"].add(font_button)
        font_button.show()

        def select_font(button):
            conf.set("movetextFont", button.get_font_name())
        font_button.connect("font-set", select_font)

        # 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 style
        uistuff.createCombo(widgets["board_style"], name="board_style")
        data = [(item[0], item[1]) for item in board_items]

        uistuff.createCombo(widgets["board_style"], data)
        uistuff.keep(widgets["board_style"], "board_style", first_value=1)

        # conf.set("board_style", conf.get("board_style", 1))

        # Board frame
        uistuff.createCombo(widgets["board_frame"], name="board_frame")
        data = [(item[0], item[1]) for item in [(None, "no frame")] + board_items[1:]]

        uistuff.createCombo(widgets["board_frame"], data)
        uistuff.keep(widgets["board_frame"], "board_frame", first_value=1)

        # conf.set("board_frame", conf.get("board_frame", 1))

        # 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")
示例#17
0
def initialize(gameDic):

    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

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

    glock_connect_after(discoverer, "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):
        stop_event.set()
        widgets["analyze_game"].hide()
        widgets["analyze_ok_button"].set_sensitive(True)
        return True

    def run_analyze(button, *args):
        old_check_value = conf.get("analyzer_check", True)
        conf.set("analyzer_check", True)
        widgets["analyze_ok_button"].set_sensitive(False)
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]
        analyzer = gamemodel.spectators[HINT]

        def analyse_moves():
            move_time = int(conf.get("max_analysis_spin", 3))
            thresold = int(conf.get("variation_thresold_spin", 50))
            for board in gamemodel.boards:
                if stop_event.is_set():
                    break
                glock.acquire()
                try:
                    gmwidg.board.view.setShownBoard(board)
                finally:
                    glock.release()
                analyzer.setBoard(board)
                time.sleep(move_time + 0.1)

                ply = board.ply
                if ply - 1 in gamemodel.scores:
                    color = (ply - 1) % 2
                    oldmoves, oldscore, olddepth = gamemodel.scores[ply - 1]
                    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):
                        gamemodel.add_variation(gamemodel.boards[ply - 1], oldmoves)

            widgets["analyze_game"].hide()
            widgets["analyze_ok_button"].set_sensitive(True)
            conf.set("analyzer_check", old_check_value)

        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        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)
 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())
示例#19
0
    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)
示例#20
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"), 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)
示例#21
0
    def __init__ (self, widgets):
        self.widgets = widgets
    
        # 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.FILE_CHOOSER_ACTION_OPEN,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        book_chooser_button = gtk.FileChooserButton(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):
            widgets["opening_hbox"].set_sensitive(check.get_active())
        widgets["opening_check"].connect_after("toggled",
                                                on_opening_check_toggled)
        uistuff.keep(widgets["opening_check"], "opening_check")

        # Endgame
        conf.set("online_egtb_check", conf.get("online_egtb_check", 0))
        uistuff.keep(widgets["online_egtb_check"], "online_egtb_check")

        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.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        egtb_chooser_button = gtk.FileChooserButton(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):
            widgets["endgame_hbox"].set_sensitive(check.get_active())
        
        widgets["endgame_check"].connect_after("toggled",
                                                on_endgame_check_toggled)
        uistuff.keep(widgets["endgame_check"], "endgame_check")

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

        from pychess.widgets import newGameDialog
        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)
        glock_connect_after(discoverer, "all_engines_discovered",
                            update_analyzers_store)
        update_analyzers_store(discoverer)

        # 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())
            from pychess.Main import gameDic
            if gameDic:
                if check.get_active():
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.restart_analyzer(HINT)
                else:
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.remove_analyzer(HINT)
        
        widgets["analyzer_check"].connect_after("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())
            from pychess.Main import gameDic
            if gameDic:
                if check.get_active():
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.restart_analyzer(SPY)
                else:
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.remove_analyzer(SPY)

        widgets["inv_analyzer_check"].connect_after("toggled",
                                              on_invanalyzer_check_toggled)
        uistuff.keep(widgets["inv_analyzer_check"], "inv_analyzer_check")
        
        # Give widgets to keeper
        
        def get_value (combobox):
            engine = list(discoverer.getAnalyzers())[combobox.get_active()]
            return engine.get("md5")
        
        def set_value (combobox, value, show_arrow_check, ana_check, analyzer_type):
            engine = discoverer.getEngineByMd5(value)
            if engine is None:
                combobox.set_active(0)
                # This return saves us from the None-engine being used
                # in later code  -Jonas Thiem
                return
            else:
                try:
                    index = list(discoverer.getAnalyzers()).index(engine)
                except ValueError:
                    index = 0
                combobox.set_active(index)
            
            replace_analyzers = False
            if widgets[show_arrow_check].get_active() is True and \
                    widgets[ana_check].get_active() is True:
                replace_analyzers = True
            
            from pychess.Main import gameDic
            for gmwidg in gameDic.keys():
                spectators = gmwidg.gamemodel.spectators
                md5 = engine.get('md5')
                
                if analyzer_type in spectators and \
                        spectators[analyzer_type].md5 != md5:
                    gmwidg.gamemodel.remove_analyzer(analyzer_type)
                    if replace_analyzers:
                        gmwidg.gamemodel.start_analyzer(analyzer_type)
        
        uistuff.keep(widgets["ana_combobox"], "ana_combobox", get_value,
            lambda combobox, value: set_value(combobox, value, "hint_mode",
                                              "analyzer_check", HINT))
        uistuff.keep(widgets["inv_ana_combobox"], "inv_ana_combobox", get_value,
            lambda combobox, value: set_value(combobox, value, "spy_mode",
                                              "inv_analyzer_check", SPY))
示例#22
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 style
        uistuff.createCombo(widgets["board_style"], name="board_style")
        data = [(item[0], item[1]) for item in board_items]

        uistuff.createCombo(widgets["board_style"], data)
        uistuff.keep(widgets["board_style"], "board_style", first_value=1)

        # conf.set("board_style", conf.get("board_style", 1))

        # Board frame
        uistuff.createCombo(widgets["board_frame"], name="board_frame")
        data = [(item[0], item[1])
                for item in [(None, "no frame")] + board_items[1:]]

        uistuff.createCombo(widgets["board_frame"], data)
        uistuff.keep(widgets["board_frame"], "board_frame", first_value=1)

        # conf.set("board_frame", conf.get("board_frame", 1))

        # 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")
示例#23
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.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
                analyzer = gamemodel.spectators[HINT]
                gmwidg.menuitems["hint_mode"].active = True
                threat_PV = conf.get("ThreatPV")
                if 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 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)
                        analyzer.setBoard(board)
                        if 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 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 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)
示例#24
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)
    def __init__(self, widgets):

        # Init open dialog

        opendialog = gtk.FileChooserDialog(
            _("Open Sound File"), None, gtk.FILE_CHOOSER_ACTION_OPEN,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
             gtk.RESPONSE_ACCEPT))

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

        soundfilter = gtk.FileFilter()
        soundfilter.add_custom(
            soundfilter.get_needed(),
            lambda data: data[3] and data[3].startswith("audio/"))
        opendialog.add_filter(soundfilter)
        opendialog.set_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.RESPONSE_ACCEPT:
                    uri = opendialog.get_uri()
                    model = combobox.get_model()
                    conf.set("sounduri%d" % index, uri)
                    label = 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 xrange(self.COUNT_OF_SOUNDS):
            combo = widgets["soundcombo%d" % i]
            uistuff.createCombo(combo, items)
            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(uri[7:]):
                model = combo.get_model()
                model.append([audioIco, os.path.split(uri)[1]])
                combo.set_active(3)

        for i in xrange(self.COUNT_OF_SOUNDS):
            if conf.get("soundcombo%d"%i, SOUND_MUTE) == SOUND_URI and \
                    not os.path.isfile(conf.get("sounduri%d"%i,"")[7:]):
                conf.set("soundcombo%d" % i, SOUND_MUTE)
            uistuff.keep(widgets["soundcombo%d" % i], "soundcombo%d" % i)
            #widgets["soundcombo%d"%i].set_active(conf.get("soundcombo%d"%i, SOUND_MUTE))

        # Init play button

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

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

        # Init 'use sound" checkbutton

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

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

        def soundError(player, gstmessage):
            widgets["useSounds"].set_sensitive(False)
            widgets["useSounds"].set_active(False)

        self.getPlayer().connect("error", soundError)
示例#26
0
    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)
    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())
示例#28
0
    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)
示例#29
0
def initialize(gameDic):
    
    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
    def update_analyzers_store(discoverer):
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.updateCombo(widgets["ana_combobox"], data)
    glock_connect_after(discoverer, "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):
        stop_event.set()
        widgets["analyze_game"].hide()
        widgets["analyze_ok_button"].set_sensitive(True)
        return True
    
    def run_analyze(button, *args):
        old_check_value = conf.get("analyzer_check", True)
        conf.set("analyzer_check", True)
        widgets["analyze_ok_button"].set_sensitive(False)
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]
        analyzer = gamemodel.spectators[HINT]

        def analyse_moves():
            move_time = int(conf.get("max_analysis_spin", 3))
            thresold = int(conf.get("variation_thresold_spin", 50))
            for board in gamemodel.boards:
                if stop_event.is_set():
                    break
                glock.acquire()
                try:
                    gmwidg.board.view.setShownBoard(board)
                finally:
                    glock.release()
                analyzer.setBoard(board)
                time.sleep(move_time+0.1)

                ply = board.ply
                if ply-1 in gamemodel.scores: 
                    color = (ply-1) % 2
                    oldmoves, oldscore, olddepth = gamemodel.scores[ply-1]
                    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):
                        gamemodel.add_variation(gamemodel.boards[ply-1], oldmoves)
            
            widgets["analyze_game"].hide()
            widgets["analyze_ok_button"].set_sensitive(True)
            conf.set("analyzer_check", old_check_value)
                        
        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        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)