Example #1
0
    def __init__ (self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack (*args):
            checkbox = widgets["autoSave"]
            widgets["autosave_grid"].set_property("sensitive", checkbox.get_active())
        conf.notify_add("autoSave", checkCallBack)
        widgets["autoSave"].set_active(False)
        uistuff.keep(widgets["autoSave"], "autoSave")
        checkCallBack()

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

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

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

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

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

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

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames")
    def __init__(self, connection):
        self.connection = connection

        # Lists
        self.publicLists = {}
        self.personalLists = {}
        self.personalBackup = {}
        self.listLock = Semaphore(0)

        self.connection.expect_fromplus(self.onUpdateLists, "Lists:", "(?:\w+\s+is (?:PUBLIC|PERSONAL))|$")

        self.connection.expect_line(self.onUpdateEmptyListitems, "-- (\w+) list: 0 \w+ --")
        self.connection.expect_fromplus(self.onUpdateListitems, "-- (\w+) list: ([1-9]\d*) \w+ --", "(?:\w+ *)+$")

        print >> self.connection.client, "showlist"

        # Variables
        self.variablesBackup = {}
        self.ivariablesBackup = {}
        self.variables = {}
        self.ivariables = {}
        self.varLock = Semaphore(0)

        self.connection.expect_fromplus(
            self.onVariables, "((?:Interface v|V)ariable settings) of (\w+):", "(?:\w*=\w+ *)*$"
        )

        print >> self.connection.client, "variables"
        print >> self.connection.client, "ivariables"

        self.connection.connect("disconnecting", self.stop)

        # Auto flag
        conf.notify_add("autoCallFlag", self.autoFlagNotify)
Example #3
0
    def __init__(self, connection):
        self.connection = connection

        # Lists
        self.publicLists = {}
        self.personalLists = {}
        self.personalBackup = {}

        if self.connection.USCN:
            self.connection.expect_line(self.onUpdateList,
                                        "(?:\w+\s+is (?:PUBLIC|PERSONAL))|$")
        else:
            self.connection.expect_fromplus(
                self.onUpdateLists, "Lists:",
                "(?:\w+\s+is (?:PUBLIC|PERSONAL))|$")

        self.connection.expect_line(self.onUpdateEmptyListitems,
                                    "-- (\w+) list: 0 \w+ --")
        self.connection.expect_fromplus(self.onUpdateListitems,
                                        "-- (\w+) list: ([1-9]\d*) \w+ --",
                                        "(?:\w+ *)+$")

        self.connection.client.run_command("showlist")

        # Auto flag
        conf.notify_add('autoCallFlag', self.autoFlagNotify)
def keep(widget,
         key,
         get_value_=None,
         set_value_=None):  # , first_value=None):
    if widget is None:
        raise AttributeError("key '%s' isn't in widgets" % key)

    for class_, methods_ in METHODS:
        # Use try-except just to make spinx happy...
        try:
            if isinstance(widget, class_):
                getter, setter, signal = methods_
                break
        except TypeError:
            getter, setter, signal = methods_
            break
    else:
        raise AttributeError("I don't have any knowledge of type: '%s'" %
                             widget)

    if get_value_:

        def get_value():
            return get_value_(widget)

    else:
        get_value = getattr(widget, getter)

    if set_value_:

        def set_value(v):
            return set_value_(widget, v)

    else:
        set_value = getattr(widget, setter)

    def setFromConf():
        try:
            v = conf.get(key)
        except TypeError:
            log.warning(
                "uistuff.keep.setFromConf: Key '%s' from conf had the wrong type '%s', ignored"
                % (key, type(conf.get(key))))
            # print("uistuff.keep TypeError %s %s" % (key, conf.get(key)))
        else:
            set_value(v)

    def callback(*args):
        if not conf.hasKey(key) or conf.get(key) != get_value():
            conf.set(key, get_value())

    widget.connect(signal, callback)
    conf.notify_add(key, lambda *args: setFromConf())

    if conf.hasKey(key):
        setFromConf()
    elif conf.get(key) is not None:
        conf.set(key, conf.get(key))
Example #5
0
    def __init__(self, gamemodel=None):
        gtk.DrawingArea.__init__(self)

        if gamemodel == None:
            gamemodel = GameModel()
        self.model = gamemodel
        glock_connect(self.model, "game_started", self.game_started)
        glock_connect_after(self.model, "game_started",
                            self.game_started_after)
        glock_connect_after(self.model, "game_changed", self.game_changed)
        glock_connect_after(self.model, "moves_undoing", self.moves_undoing)
        glock_connect_after(self.model, "game_loading", self.game_loading)
        glock_connect_after(self.model, "game_loaded", self.game_loaded)
        glock_connect_after(self.model, "game_ended", self.game_ended)

        self.connect("expose_event", self.expose)
        self.connect_after("realize", self.on_realized)
        conf.notify_add("showCords", self.on_show_cords)
        conf.notify_add("faceToFace", self.on_face_to_face)
        self.set_size_request(350, 350)

        self.animationStart = time()
        self.lastShown = None
        self.deadlist = []

        self.autoUpdateShown = True

        self.padding = 0  # Set to self.pad when setcords is active
        self.square = 0, 0, 8, 1  # An object global variable with the current
        # board size
        self.pad = 0.13  # Padding applied only when setcords is active

        self._selected = None
        self._hover = None
        self._active = None
        self._redarrow = None
        self._greenarrow = None
        self._bluearrow = None

        self._shown = self.model.ply
        self._showCords = False
        self.showCords = conf.get("showCords", False)
        self._showEnpassant = False
        self.lastMove = None
        self.matrix = cairo.Matrix()
        self.matrixPi = cairo.Matrix.init_rotate(pi)
        self.cordMatricesState = (0, 0)
        self._rotation = 0

        self.drawcount = 0
        self.drawtime = 0

        self.gotStarted = False
        self.animationLock = RLock()
        self.rotationLock = Lock()

        self.draggedPiece = None  # a piece being dragged by the user
Example #6
0
    def __init__(self, connection):
        self.connection = connection

        self.publicLists = {}
        self.personalLists = {}
        self.personalBackup = {}

        # Auto flag
        conf.notify_add('autoCallFlag', self.autoFlagNotify)
 def __init__(self, gamemodel=None):
     gtk.DrawingArea.__init__(self)
     
     if gamemodel == None:
         gamemodel = GameModel()
     self.model = gamemodel
     glock_connect(self.model, "game_started", self.game_started)
     glock_connect_after(self.model, "game_started", self.game_started_after)
     glock_connect_after(self.model, "game_changed", self.game_changed)
     glock_connect_after(self.model, "moves_undoing", self.moves_undoing)
     glock_connect_after(self.model, "game_loading", self.game_loading)
     glock_connect_after(self.model, "game_loaded", self.game_loaded)
     glock_connect_after(self.model, "game_ended", self.game_ended)
     
     self.connect("expose_event", self.expose)
     self.connect_after("realize", self.on_realized)
     conf.notify_add("showCords", self.on_show_cords)
     conf.notify_add("faceToFace", self.on_face_to_face)
     self.set_size_request(350,350)
     
     self.animationStart = time()
     self.lastShown = None
     self.deadlist = []
     
     self.autoUpdateShown = True
     
     self.padding = 0 # Set to self.pad when setcords is active
     self.square = 0, 0, 8, 1 # An object global variable with the current
                              # board size
     self.pad = 0.13 # Padding applied only when setcords is active
     
     self._selected = None
     self._hover = None
     self._active = None
     self._redarrow = None
     self._greenarrow = None
     self._bluearrow = None
     
     self._shown = self.model.ply
     self._showCords = False
     self.showCords = conf.get("showCords", False)
     self._showEnpassant = False
     self.lastMove = None
     self.matrix = cairo.Matrix()
     self.matrixPi = cairo.Matrix.init_rotate(pi)
     self.cordMatricesState = (0, 0)
     self._rotation = 0
     
     self.drawcount = 0
     self.drawtime = 0
     
     self.gotStarted = False
     self.animationLock = RLock()
     self.rotationLock = Lock()
     
     self.draggedPiece = None  # a piece being dragged by the user
Example #8
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.connect("draw", self.expose)
        self.names = [_("White"), _("Black")]

        self.model = None
        self.short_on_time = [False, False]
        self.alarm_spin = conf.get("alarm_spin")

        conf.notify_add("alarm_spin", self.on_alarm_spin)
Example #9
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.connect("draw", self.expose)
        self.names = [_("White"), _("Black")]

        self.model = None
        self.short_on_time = [False, False]
        self.alarm_spin = conf.get("alarm_spin")

        conf.notify_add("alarm_spin", self.on_alarm_spin)
Example #10
0
def keep(widget, key, get_value_=None, set_value_=None, first_value=None):
    if widget is None:
        raise AttributeError("key '%s' isn't in widgets" % key)

    for class_, methods_ in METHODS:
        # Use try-except just to make spinx happy...
        try:
            if isinstance(widget, class_):
                getter, setter, signal = methods_
                break
        except TypeError:
            getter, setter, signal = methods_
            break
    else:
        raise AttributeError("I don't have any knowledge of type: '%s'" %
                             widget)

    if get_value_:
        def get_value():
            return get_value_(widget)
    else:
        get_value = getattr(widget, getter)

    if set_value_:
        def set_value(v):
            return set_value_(widget, v)
    else:
        set_value = getattr(widget, setter)

    def setFromConf():
        try:
            v = conf.get(key)
        except TypeError:
            log.warning("uistuff.keep.setFromConf: Key '%s' from conf had the wrong type '%s', ignored" %
                        (key, type(conf.get(key))))
            if first_value is not None:
                conf.set(key, first_value)
            else:
                conf.set(key, get_value())
        else:
            set_value(v)

    def callback(*args):
        if not conf.hasKey(key) or conf.get(key) != get_value():
            conf.set(key, get_value())

    widget.connect(signal, callback)
    conf.notify_add(key, lambda *args: setFromConf())

    if conf.hasKey(key):
        setFromConf()
    elif first_value is not None:
        conf.set(key, first_value)
Example #11
0
    def __init__(self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack(_):
            """ :Description: Sets the various option based on user interaction with the
                checkboxes in the gui
            """

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

        conf.notify_add("autoSave", checkCallBack)
        uistuff.keep(widgets["autoSave"], "autoSave", first_value=True)
        checkCallBack(_)

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

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

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

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

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

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

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

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveRatingChange"], "saveRatingChange")
        uistuff.keep(widgets["indentPgn"], "indentPgn")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames", first_value=True)
Example #12
0
def workfunc (worker, gamemodel, player0tup, player1tup, loaddata=None):
    log.debug("ionest.workfunc: %s\n %s\n %s\n" % (gamemodel, player0tup, player1tup))
    gmwidg = gamewidget.GameWidget(gamemodel)
    worker.publish((gmwidg,gamemodel))
    
    # Initing players
    players = []
    for i, playertup in enumerate((player0tup, player1tup)):
        type, func, args, prename = playertup
        if type != LOCAL:
            players.append(func(*args))
            #if type == ARTIFICIAL:
            #    def readyformoves (player, color):
            #        gmwidg.setTabText(gmwidg.display_text))
            #    players[i].connect("readyForMoves", readyformoves, i)
        else:
            # Until PyChess has a proper profiles system, as discussed on the
            # issue tracker, we need to give human players special treatment
            player = func(gmwidg, *args)
            players.append(player)
            
            # Connect to conf
            if i == 0 or (i == 1 and player0tup[0] != LOCAL):
                key = "firstName"
                alt = _("You")
            else:
                key = "secondName"
                alt = _("Guest")
            if prename == conf.get(key, alt):
                conf.notify_add(key, lambda *a:player.setName(conf.get(key,alt)))

    if player0tup[0] == ARTIFICIAL and player1tup[0] == ARTIFICIAL:
        def emit_action (action, param):
            if gmwidg.isInFront():
                gamemodel.curplayer.emit("offer", Offer(action, param=param))
        gmwidg.board.connect("action", lambda b,action,param: emit_action(action, param))
    
    gamemodel.setPlayers(players)
    
    # Starting
    if loaddata:
        try:
            uri, loader, gameno, position = loaddata
            gamemodel.loadAndStart (uri, loader, gameno, position)
        except LoadingError, e:
            d = gtk.MessageDialog (type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_OK)
            d.set_markup ("<big><b>%s</b></big>" % e.args[0])
            d.format_secondary_text (e.args[1] + "\n\n" +
                    _("Correct the move, or start playing with what could be read"))
            d.connect("response", lambda d,a: d.hide())
            worker.publish(d.show)
Example #13
0
    def __init__(self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack(_):
            """ :Description: Sets the various option based on user interaction with the
                checkboxes in the gui
            """

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

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

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

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

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

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

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

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

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

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames")
Example #14
0
    def load(self, gmwidg):
        __widget__ = Gtk.ScrolledWindow()
        __widget__.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
        __widget__.add(self.textview)

        self.gamewidget = gmwidg
        self.boardview = gmwidg.board.view
        self.boardview.connect("shownChanged", self.shownChanged)

        self.gamemodel = gmwidg.board.view.model
        self.gamemodel.connect_after("game_loaded", self.game_loaded)
        self.gamemodel.connect_after("game_changed", self.game_changed)
        self.gamemodel.connect_after("game_started", self.update)
        self.gamemodel.connect_after("game_ended", self.update)
        self.gamemodel.connect_after("moves_undone", self.moves_undone)
        self.gamemodel.connect_after("opening_changed", self.update)
        self.gamemodel.connect_after("players_changed", self.players_changed)
        self.gamemodel.connect("variation_added", self.variation_added)
        self.gamemodel.connect("variation_extended", self.variation_extended)
        self.gamemodel.connect("analysis_changed", self.analysis_changed)

        # Connect to preferences
        self.fan = conf.get("figuresInNotation", False)

        def figuresInNotationCallback(none):
            self.fan = conf.get("figuresInNotation", False)
            self.update()

        conf.notify_add("figuresInNotation", figuresInNotationCallback)

        # Elapsed move time
        self.showEmt = conf.get("showEmt", False)

        def showEmtCallback(none):
            self.showEmt = conf.get("showEmt", False)
            self.update()

        conf.notify_add("showEmt", showEmtCallback)

        # Blunders
        self.showBlunder = conf.get("showBlunder", False)

        def showBlunderCallback(none):
            self.showBlunder = conf.get("showBlunder", False)
            self.update()

        conf.notify_add("showBlunder", showBlunderCallback)

        # Eval values
        self.showEval = conf.get("showEval", False)

        def showEvalCallback(none):
            self.showEval = conf.get("showEval", False)
            self.update()

        conf.notify_add("showEval", showEvalCallback)

        return __widget__
Example #15
0
    def load(self, gmwidg):
        __widget__ = Gtk.ScrolledWindow()
        __widget__.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
        __widget__.add(self.textview)

        self.gamewidget = gmwidg
        self.boardview = gmwidg.board.view
        self.boardview.connect("shownChanged", self.shownChanged)

        self.gamemodel = gmwidg.board.view.model
        self.gamemodel.connect_after("game_loaded", self.game_loaded)
        self.gamemodel.connect_after("game_changed", self.game_changed)
        self.gamemodel.connect_after("game_started", self.update)
        self.gamemodel.connect_after("game_ended", self.update)
        self.gamemodel.connect_after("moves_undone", self.moves_undone)
        self.gamemodel.connect_after("opening_changed", self.update)
        self.gamemodel.connect_after("players_changed", self.players_changed)
        self.gamemodel.connect("variation_added", self.variation_added)
        self.gamemodel.connect("variation_extended", self.variation_extended)
        self.gamemodel.connect("analysis_changed", self.analysis_changed)

        # Connect to preferences
        self.fan = conf.get("figuresInNotation", False)

        def figuresInNotationCallback(none):
            self.fan = conf.get("figuresInNotation", False)
            self.update()

        conf.notify_add("figuresInNotation", figuresInNotationCallback)

        # Elapsed move time
        self.showEmt = conf.get("showEmt", False)

        def showEmtCallback(none):
            self.showEmt = conf.get("showEmt", False)
            self.update()

        conf.notify_add("showEmt", showEmtCallback)

        # Blunders
        self.showBlunder = conf.get("showBlunder", False)

        def showBlunderCallback(none):
            self.showBlunder = conf.get("showBlunder", False)
            self.update()

        conf.notify_add("showBlunder", showBlunderCallback)

        # Eval values
        self.showEval = conf.get("showEval", False)

        def showEvalCallback(none):
            self.showEval = conf.get("showEval", False)
            self.update()

        conf.notify_add("showEval", showEvalCallback)

        return __widget__
    def __init__(self, store, engine, mode, tv, boardcontrol):
        if mode == HINT:
            Advisor.__init__(self, store, _("Analysis by %s") % engine, HINT)
            self.tooltip = (
                _(
                    "%s will try to predict which move is best and which side has the advantage"
                )
                % engine
            )
        else:
            Advisor.__init__(self, store, _("Threat analysis by %s") % engine, SPY)
            self.tooltip = (
                _(
                    "%s will identify what threats would exist if it were your opponent's turn to move"
                )
                % engine
            )
        self.engine = engine
        self.tv = tv
        self.active = False
        self.linesExpected = 1
        self.boardview = boardcontrol.view

        self.cid1 = self.engine.connect("analyze", self.on_analyze)
        self.cid2 = self.engine.connect("readyForOptions", self.on_ready_for_options)
        self.cid3 = self.engine.connect_after("readyForMoves", self.on_ready_for_moves)

        self.figuresInNotation = conf.get("figuresInNotation")

        def on_figures_in_notation(none):
            self.figuresInNotation = conf.get("figuresInNotation")

        self.cid4 = conf.notify_add("figuresInNotation", on_figures_in_notation)
Example #17
0
    def load(self, gmwidg):
        self.boardview = gmwidg.board.view
        self.plot = ScorePlot(self.boardview)
        self.sw = __widget__ = Gtk.ScrolledWindow()
        __widget__.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        port = Gtk.Viewport()
        port.add(self.plot)
        port.set_shadow_type(Gtk.ShadowType.NONE)
        __widget__.add(port)
        __widget__.show_all()

        self.plot_cid = self.plot.connect("selected", self.plot_selected)
        self.cid = self.boardview.connect('shownChanged', self.shownChanged)
        self.model_cids = [
            self.boardview.model.connect_after("game_changed", self.game_changed),
            self.boardview.model.connect_after("moves_undone", self.moves_undone),
            self.boardview.model.connect_after("analysis_changed", self.analysis_changed),
            self.boardview.model.connect_after("game_started", self.game_started),
            self.boardview.model.connect_after("game_terminated", self.on_game_terminated),
        ]

        def cb_config_changed(none):
            self.fetch_chess_conf()
            self.plot.redraw()
        self.cids_conf = [
            conf.notify_add("scoreLinearScale", cb_config_changed)
        ]
        self.fetch_chess_conf()

        uistuff.keepDown(__widget__)

        return __widget__
Example #18
0
    def __init__ (self, connection):
        self.connection = connection
        
        # Lists
        self.publicLists = {}
        self.personalLists = {}
        self.personalBackup = {}
        self.listLock = Semaphore(0)
        
        if self.connection.USCN:
            self.connection.expect_line (self.onUpdateList,
                    "(?:\w+\s+is (?:PUBLIC|PERSONAL))|$")
        else:
            self.connection.expect_fromplus (self.onUpdateLists,
                    "Lists:",
                    "(?:\w+\s+is (?:PUBLIC|PERSONAL))|$")
        
        self.connection.expect_line (self.onUpdateEmptyListitems,
                "-- (\w+) list: 0 \w+ --")
        self.connection.expect_fromplus (self.onUpdateListitems,
                "-- (\w+) list: ([1-9]\d*) \w+ --",
                "(?:\w+ *)+$")
        
        self.connection.client.run_command("showlist")
        
        # Variables
        self.variablesBackup = {}
        self.variables = {}
        self.ivariables = {}
        self.varLock = Semaphore(0)
        
        self.connection.expect_fromplus (self.onIVariables,
                "(Interface variable settings of \w+):",
                "(?:\w+=(?:\w+|\?) *)*$")

        self.connection.expect_fromplus (self.onVariables,
                "(Variable settings of \w+):",
                "(?:\w+=(?:\w+|\?) *)*$")
        
        # The order of next two is important to FatICS !
        self.connection.client.run_command("ivariables")
        self.connection.client.run_command("variables")
        
        # Auto flag
        conf.notify_add('autoCallFlag', self.autoFlagNotify)
        
        atexit.register(self.stop)
Example #19
0
def keep(widget, key, get_value_=None, set_value_=None, first_value=None):
    if widget == None:
        raise AttributeError("key '%s' isn't in widgets" % key)

    for class_, methods_ in METHODS:
        if isinstance(widget, class_):
            getter, setter, signal = methods_
            break
    else:
        raise AttributeError("I don't have any knowledge of type: '%s'" %
                             widget)

    if get_value_:
        get_value = lambda: get_value_(widget)
    else:
        get_value = getattr(widget, getter)

    if set_value_:
        set_value = lambda v: set_value_(widget, v)
    else:
        set_value = getattr(widget, setter)

    def setFromConf():
        try:
            v = conf.getStrict(key)
        except TypeError:
            log.warning("uistuff.keep.setFromConf: Key '%s' from conf had the wrong type '%s', ignored" % \
                     (key, type(conf.getStrict(key))))
            if first_value != None:
                conf.set(key, first_value)
            else:
                conf.set(key, get_value())
        else:
            set_value(v)

    def callback(*args):
        if not conf.hasKey(key) or conf.getStrict(key) != get_value():
            conf.set(key, get_value())

    widget.connect(signal, callback)
    conf.notify_add(key, lambda *args: setFromConf())

    if conf.hasKey(key):
        setFromConf()
    elif first_value != None:
        conf.set(key, first_value)
Example #20
0
    def __init__(self, gamemodel, perspective):
        GObject.GObject.__init__(self)
        self.gamemodel = gamemodel
        self.perspective = perspective
        self.cids = {}
        self.closed = False

        # InfoBarMessage with rematch, undo or observe buttons
        self.game_ended_message = None

        self.tabcontent, white_label, black_label, self.game_info_label = self.initTabcontents()
        self.boardvbox, self.board, self.infobar, self.clock = self.initBoardAndClock(self.gamemodel)
        self.stat_hbox = self.initButtons(self.board)

        self.player_name_labels = (white_label, black_label)
        self.infobar.connect("hide", self.infobar_hidden)

        self.notebookKey = Gtk.Alignment()
        self.menuitems = MenuItemsDict()

        self.gamemodel_cids = [
            self.gamemodel.connect_after("game_started", self.game_started),
            self.gamemodel.connect_after("game_ended", self.game_ended),
            self.gamemodel.connect_after("game_changed", self.game_changed),
            self.gamemodel.connect("game_paused", self.game_paused),
            self.gamemodel.connect("game_resumed", self.game_resumed),
            self.gamemodel.connect("moves_undone", self.moves_undone),
            self.gamemodel.connect("game_unended", self.game_unended),
            self.gamemodel.connect("game_saved", self.game_saved),
            self.gamemodel.connect("players_changed", self.players_changed),
            self.gamemodel.connect("analyzer_added", self.analyzer_added),
            self.gamemodel.connect("analyzer_removed", self.analyzer_removed),
            self.gamemodel.connect("message_received", self.message_received),
        ]
        self.players_changed(self.gamemodel)

        self.notify_cids = [conf.notify_add("showFICSgameno", self.on_show_fics_gameno), ]

        if self.gamemodel.display_text:
            if isinstance(self.gamemodel, ICGameModel) and conf.get("showFICSgameno"):
                self.game_info_label.set_text("%s [%s]" % (
                    self.display_text, self.gamemodel.ficsgame.gameno))
            else:
                self.game_info_label.set_text(self.display_text)
        if self.gamemodel.timed:
            self.cids[self.gamemodel.timemodel] = self.gamemodel.timemodel.connect("zero_reached", self.zero_reached)

        self.connections = defaultdict(list)
        if isinstance(self.gamemodel, ICGameModel):
            self.connections[self.gamemodel.connection.bm].append(
                self.gamemodel.connection.bm.connect("player_lagged", self.player_lagged))
            self.connections[self.gamemodel.connection.bm].append(
                self.gamemodel.connection.bm.connect("opp_not_out_of_time", self.opp_not_out_of_time))
        self.cids[self.board.view] = self.board.view.connect("shownChanged", self.shownChanged)

        if isinstance(self.gamemodel, ICGameModel):
            self.gamemodel.gmwidg_ready.set()
Example #21
0
    def __init__(self, widgets):
        # Init 'auto save" checkbutton
        def checkCallBack(*args):
            checkbox = widgets["autoSave"]
            widgets["autosave_grid"].set_property("sensitive",
                                                  checkbox.get_active())

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

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

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

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

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

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

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

        uistuff.keep(widgets["saveEmt"], "saveEmt")
        uistuff.keep(widgets["saveEval"], "saveEval")
        uistuff.keep(widgets["saveOwnGames"], "saveOwnGames")
Example #22
0
    def __init__(self, connection):
        self.connection = connection

        # Lists
        self.publicLists = {}
        self.personalLists = {}
        self.personalBackup = {}
        self.listLock = Semaphore(0)

        self.connection.expect_fromplus(self.onUpdateLists, "Lists:",
                                        "(?:\w+\s+is (?:PUBLIC|PERSONAL))|$")

        self.connection.expect_line(self.onUpdateEmptyListitems,
                                    "-- (\w+) list: 0 \w+ --")
        self.connection.expect_fromplus(self.onUpdateListitems,
                                        "-- (\w+) list: ([1-9]\d*) \w+ --",
                                        "(?:\w+ *)+$")

        print >> self.connection.client, "showlist"

        # Variables
        self.variablesBackup = {}
        self.ivariablesBackup = {}
        self.variables = {}
        self.ivariables = {}
        self.varLock = Semaphore(0)

        self.connection.expect_fromplus(
            self.onVariables, "((?:Interface v|V)ariable settings) of (\w+):",
            "(?:\w*=\w+ *)*$")

        print >> self.connection.client, "variables"
        print >> self.connection.client, "ivariables"

        self.connection.connect("disconnecting", self.stop)

        # Auto flag
        conf.notify_add('autoCallFlag', self.autoFlagNotify)
 def load (self, gmwidg):
     
     widgets = gtk.glade.XML(addDataPrefix("sidepanel/history.glade"))
     __widget__ = widgets.get_widget("panel")
     __widget__.unparent()
     
     self.board = gmwidg.board.view
     
     glock_connect(self.board.model, "game_changed", self.game_changed)
     glock_connect(self.board.model, "game_started", self.game_changed)
     glock_connect(self.board.model, "moves_undoing", self.moves_undoing)
     self.board.connect("shown_changed", self.shown_changed)
     
     # Initialize treeviews
     
     self.numbers = widgets.get_widget("treeview1")
     self.left = widgets.get_widget("treeview2")
     self.right = widgets.get_widget("treeview3")
     
     def fixList (list, xalign=0):
         list.set_model(gtk.ListStore(str))
         renderer = gtk.CellRendererText()
         renderer.set_property("xalign",xalign)
         list.append_column(gtk.TreeViewColumn(None, renderer, text=0))
         list.get_selection().set_mode(gtk.SELECTION_SINGLE)
     
     fixList(self.numbers, 1)
     fixList(self.left, 0)
     fixList(self.right, 0)
     
     self.left.get_selection().connect('changed', self.on_selection_changed,
                                       self.left, 0)
     self.right.get_selection().connect('changed', self.on_selection_changed,
                                        self.right, 1)
     
     widgets.signal_autoconnect ({
         "on_treeview2_key_press_event":lambda w,e:self.key_press_event(1,e),
         "on_treeview3_key_press_event":lambda w,e:self.key_press_event(2,e)
     })
     
     # Lock scrolling
     
     scrollwin = widgets.get_widget("panel")
     
     def changed (vadjust):
         if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
             vadjust.set_value(vadjust.upper-vadjust.page_size)
             vadjust.need_scroll = True
     scrollwin.get_vadjustment().connect("changed", changed)
     
     def value_changed (vadjust):
         vadjust.need_scroll = abs(vadjust.value + vadjust.page_size - \
                     vadjust.upper) < vadjust.step_increment
     scrollwin.get_vadjustment().connect("value-changed", value_changed)
     
     # Connect to preferences
     
     def figuresInNotationCallback (none):
         game = self.board.model
         for board, move in zip(game.boards, game.moves):
             if conf.get("figuresInNotation", False):
                 notat = toFAN(board, move)
             else: notat = toSAN(board, move, True)
             row, col, other = self._ply_to_row_col_other(board.ply+1)
             iter = col.get_model().get_iter((row,))
             col.get_model().set(iter, 0, notat)
     conf.notify_add("figuresInNotation", figuresInNotationCallback)
     
     # Return
     
     return __widget__
Example #24
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)
Example #25
0
def workfunc(worker, gamemodel, player0tup, player1tup, loaddata=None):
    log.debug("ionest.workfunc: %s\n %s\n %s\n" %
              (gamemodel, player0tup, player1tup))
    gmwidg = gamewidget.GameWidget(gamemodel)

    player0 = {}
    player1 = {}
    for player, playertup in ((player0, player0tup), (player1, player1tup)):
        player["name"] = playertup[3]
        player["rating"] = (len(playertup) > 4 and
                            playertup[4]) and "(" + playertup[4] + ")" or None
        player["tabtext"] = player["rating"] and player["name"] + " " + player["rating"] \
                or player["name"]
    text = [player0["tabtext"], _("vs"), player1["tabtext"]]
    gmwidg.setTabText(" ".join(text))

    # Initing analyze engines
    # We have to do this before publishing gmwidg to make sure that
    # gamemodel.*EngineSupportsVariant is set right before on_gmwidg_created() is called

    anaengines = list(discoverer.getAnalyzers())
    specs = {}
    engine = discoverer.getEngineByMd5(conf.get("ana_combobox", 0))
    if engine is None: engine = anaengines[0]
    if gamemodel.variant.board.variant in discoverer.getEngineVariants(engine) or \
       gamemodel.variant.standard_rules:
        if conf.get("analyzer_check", True):
            hintanalyzer = discoverer.initAnalyzerEngine(
                engine, ANALYZING, gamemodel.variant)
            specs[HINT] = hintanalyzer
            log.debug("Hint Analyzer: %s\n" % repr(hintanalyzer))
        gamemodel.hintEngineSupportsVariant = True
    else:
        gamemodel.hintEngineSupportsVariant = False
    engine = discoverer.getEngineByMd5(conf.get("inv_ana_combobox", 0))
    if engine is None: engine = anaengines[0]
    if gamemodel.variant.board.variant in discoverer.getEngineVariants(engine) or \
       gamemodel.variant.standard_rules:
        if conf.get("inv_analyzer_check", True):
            spyanalyzer = discoverer.initAnalyzerEngine(
                engine, INVERSE_ANALYZING, gamemodel.variant)
            specs[SPY] = spyanalyzer
            log.debug("Spy Analyzer: %s\n" % repr(spyanalyzer))
        gamemodel.spyEngineSupportsVariant = True
    else:
        gamemodel.spyEngineSupportsVariant = False

    worker.publish((gmwidg, gamemodel))

    # For updating names
    players = []

    def updateTitle(color=None):

        name0_name1 = gmwidg.getTabText().split(" %s " % _("vs"))
        if not name0_name1:
            name0, name1 = _("White"), _("Black")
        else:
            name0, name1 = name0_name1

        if color is None:
            name0 = repr(players[WHITE])
            name0 += player0["rating"] and " " + player0["rating"] or ""
            name1 = repr(players[BLACK])
            name1 += player1["rating"] and " " + player1["rating"] or ""
        elif color == WHITE:
            name0 = repr(players[WHITE])
            name0 += player0["rating"] and " " + player0["rating"] or ""
        elif color == BLACK:
            name1 = repr(players[BLACK])
            name1 += player1["rating"] and " " + player1["rating"] or ""

        gmwidg.setTabText("%s %s %s" % (name0, _("vs"), name1))

    # Initing players
    for i, playertup in enumerate((player0tup, player1tup)):
        type, func, args = (playertup[0:3])
        if type != LOCAL:
            players.append(func(*args))
            if type == ARTIFICIAL:

                def readyformoves(player, color):
                    updateTitle(color)

                players[i].connect("readyForMoves", readyformoves, i)
        else:
            # Until PyChess has a proper profiles system, as discussed on the
            # issue tracker, we need to give human players special treatment
            ichandle = None
            if len(args) > 2:
                ichandle = args[2]
                args = [v for v in args[0:2]]
            player = func(gmwidg, ichandle=ichandle, *args)
            players.append(player)
            if i == 0 or (i == 1 and player0tup[0] != LOCAL):
                key = "firstName"
                alt = conf.username
            else:
                key = "secondName"
                alt = _("Guest")
            player.setName(conf.get(key, alt))

            def callback(none, color, key, alt):
                players[color].setName(conf.get(key, alt))
                updateTitle(color)

            conf.notify_add(key, callback, i, key, alt)

    worker.publish(updateTitle)

    # Setting game
    gamemodel.setPlayers(players)
    gamemodel.setSpectactors(specs)

    # Starting
    if loaddata:
        try:
            uri, loader, gameno, position = loaddata
            gamemodel.loadAndStart(uri, loader, gameno, position)
        except LoadingError, e:
            d = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
                                  buttons=gtk.BUTTONS_OK)
            d.set_markup("<big><b>%s</b></big>" % e.args[0])
            d.format_secondary_text(e.args[1] + "\n\n" + _(
                "Correct the move, or start playing with what could be read"))
            d.connect("response", lambda d, a: d.hide())
            worker.publish(d.show)
Example #26
0
    def init_layout(self):
        perspective_widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        perspective_manager.set_perspective_widget("games", perspective_widget)

        self.notebooks = {"board": new_notebook("board"),
                          "buttons": new_notebook("buttons"),
                          "messageArea": new_notebook("messageArea")}
        self.main_notebook = self.notebooks["board"]
        for panel in self.sidePanels:
            self.notebooks[panel_name(panel.__name__)] = new_notebook(panel_name(panel.__name__))

        # Initing headbook

        align = gamewidget.createAlignment(4, 4, 0, 4)
        align.set_property("yscale", 0)

        headbook = Gtk.Notebook()
        headbook.set_name("headbook")
        headbook.set_scrollable(True)
        align.add(headbook)
        perspective_widget.pack_start(align, False, True, 0)
        self.show_tabs(not conf.get("hideTabs"))

        # Initing center

        centerVBox = Gtk.VBox()

        # The dock

        self.dock = PyDockTop("main", self)
        self.dockAlign = gamewidget.createAlignment(4, 4, 0, 4)
        self.dockAlign.add(self.dock)
        centerVBox.pack_start(self.dockAlign, True, True, 0)
        self.dockAlign.show()
        self.dock.show()

        self.docks["board"] = (Gtk.Label(label="Board"), self.notebooks["board"], None)
        for panel in self.sidePanels:
            self.docks[panel_name(panel.__name__)][1] = self.notebooks[panel_name(panel.__name__)]

        self.load_from_xml()

        # Default layout of side panels
        if not os.path.isfile(self.dockLocation):
            leaf = self.dock.dock(self.docks["board"][1],
                                  CENTER,
                                  Gtk.Label(label=self.docks["board"][0]),
                                  "board")
            self.docks["board"][1].show_all()
            leaf.setDockable(False)

            # S
            epanel = leaf.dock(self.docks["bookPanel"][1], SOUTH, self.docks["bookPanel"][0],
                               "bookPanel")
            epanel.default_item_height = 45
            epanel = epanel.dock(self.docks["engineOutputPanel"][1], CENTER,
                                 self.docks["engineOutputPanel"][0],
                                 "engineOutputPanel")

            # NE
            leaf = leaf.dock(self.docks["annotationPanel"][1], EAST,
                             self.docks["annotationPanel"][0], "annotationPanel")
            leaf = leaf.dock(self.docks["historyPanel"][1], CENTER,
                             self.docks["historyPanel"][0], "historyPanel")
            leaf = leaf.dock(self.docks["scorePanel"][1], CENTER,
                             self.docks["scorePanel"][0], "scorePanel")

            # SE
            leaf = leaf.dock(self.docks["chatPanel"][1], SOUTH, self.docks["chatPanel"][0],
                             "chatPanel")
            leaf = leaf.dock(self.docks["commentPanel"][1], CENTER,
                             self.docks["commentPanel"][0], "commentPanel")

        def unrealize(dock, notebooks):
            # unhide the panel before saving so its configuration is saved correctly
            self.notebooks["board"].get_parent().get_parent().zoomDown()
            dock.saveToXML(self.dockLocation)
            dock._del()

        self.dock.connect("unrealize", unrealize, self.notebooks)

        hbox = Gtk.HBox()

        # Buttons
        self.notebooks["buttons"].set_border_width(4)
        hbox.pack_start(self.notebooks["buttons"], False, True, 0)

        # The message area
        # TODO: If you try to fix this first read issue #958 and 1018
        align = gamewidget.createAlignment(0, 0, 0, 0)
        # sw = Gtk.ScrolledWindow()
        # port = Gtk.Viewport()
        # port.add(self.notebooks["messageArea"])
        # sw.add(port)
        # align.add(sw)
        align.add(self.notebooks["messageArea"])
        hbox.pack_start(align, True, True, 0)

        def ma_switch_page(notebook, gpointer, page_num):
            notebook.props.visible = notebook.get_nth_page(page_num).\
                get_child().props.visible

        self.notebooks["messageArea"].connect("switch-page", ma_switch_page)
        centerVBox.pack_start(hbox, False, True, 0)

        perspective_widget.pack_start(centerVBox, True, True, 0)
        centerVBox.show_all()
        perspective_widget.show_all()

        perspective_manager.set_perspective_menuitems("games", self.menuitems)

        conf.notify_add("hideTabs", self.tabsCallback)

        # Connecting headbook to other notebooks

        def hb_switch_page(notebook, gpointer, page_num):
            for notebook in self.notebooks.values():
                notebook.set_current_page(page_num)

            gmwidg = self.key2gmwidg[self.getheadbook().get_nth_page(page_num)]
            if isinstance(gmwidg.gamemodel, ICGameModel):
                primary = "primary " + str(gmwidg.gamemodel.ficsgame.gameno)
                gmwidg.gamemodel.connection.client.run_command(primary)

        headbook.connect("switch-page", hb_switch_page)

        if hasattr(headbook, "set_tab_reorderable"):

            def page_reordered(widget, child, new_num, headbook):
                old_num = self.notebooks["board"].page_num(self.key2gmwidg[child].boardvbox)
                if old_num == -1:
                    log.error('Games and labels are out of sync!')
                else:
                    for notebook in self.notebooks.values():
                        notebook.reorder_child(
                            notebook.get_nth_page(old_num), new_num)

            headbook.connect("page-reordered", page_reordered, headbook)
Example #27
0
    def load(self, gmwidg):
        """
        The method initializes the widget, attached events, internal variables, layout...
        """

        # Internal variables
        self.nodelist = []
        self.boardview = gmwidg.board.view
        self.gamemodel = gmwidg.gamemodel
        self.variation_to_remove = None
        if self.gamemodel is None:
            return None

        # Internal objects/helpers
        self.cursor_standard = Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR)
        self.cursor_hand = Gdk.Cursor.new(Gdk.CursorType.HAND2)

        # Text area
        self.textview = Gtk.TextView()
        self.textview.set_wrap_mode(Gtk.WrapMode.WORD)
        self.textbuffer = self.textview.get_buffer()

        # Named tags
        self.tag_remove_variation = self.textbuffer.create_tag(
            "remove-variation")
        self.tag_new_line = self.textbuffer.create_tag("new_line")

        # Anonymous tags
        self.textbuffer.create_tag("move", weight=Pango.Weight.BOLD)
        bg_color, fg_color = set_textview_color(self.textview)
        self.textbuffer.create_tag("scored0", foreground_rgba=fg_color)
        self.textbuffer.create_tag("scored1",
                                   foreground_rgba=Gdk.RGBA(0.2, 0, 0, 1))
        self.textbuffer.create_tag("scored2",
                                   foreground_rgba=Gdk.RGBA(0.4, 0, 0, 1))
        self.textbuffer.create_tag("scored3",
                                   foreground_rgba=Gdk.RGBA(0.6, 0, 0, 1))
        self.textbuffer.create_tag("scored4",
                                   foreground_rgba=Gdk.RGBA(0.8, 0, 0, 1))
        self.textbuffer.create_tag("scored5",
                                   foreground_rgba=Gdk.RGBA(1.0, 0, 0, 1))
        self.textbuffer.create_tag("emt",
                                   foreground="darkgrey",
                                   weight=Pango.Weight.NORMAL)
        self.textbuffer.create_tag("comment", foreground="darkblue")
        self.textbuffer.create_tag("variation-toplevel",
                                   weight=Pango.Weight.NORMAL)
        self.textbuffer.create_tag("variation-even",
                                   foreground="darkgreen",
                                   style="italic")
        self.textbuffer.create_tag("variation-uneven",
                                   foreground="darkred",
                                   style="italic")
        self.textbuffer.create_tag("selected",
                                   background_full_height=True,
                                   background="grey")
        self.textbuffer.create_tag("margin", left_margin=4)
        self.textbuffer.create_tag("variation-margin0", left_margin=20)
        self.textbuffer.create_tag("variation-margin1", left_margin=36)
        self.textbuffer.create_tag("variation-margin2", left_margin=52)

        # Game header
        self.label_info = Gtk.Label()
        self.label_info.props.xalign = 0
        self.label_players = Gtk.Label()
        self.label_players.props.xalign = 0
        self.label_event = Gtk.Label()
        self.label_event.props.xalign = 0
        self.label_opening = Gtk.Label()
        self.label_opening.props.xalign = 0

        # Events
        self.cids_textview = [
            self.textview.connect("motion-notify-event",
                                  self.motion_notify_event),
            self.textview.connect("button-press-event",
                                  self.button_press_event),
        ]
        self.cid_shown_changed = self.boardview.connect(
            "shownChanged", self.on_shownChanged)
        self.cid_remove_variation = self.tag_remove_variation.connect(
            "event", self.tag_event_handler)
        self.cids_gamemodel = [
            self.gamemodel.connect_after("game_loaded", self.on_game_loaded),
            self.gamemodel.connect_after("game_changed", self.on_game_changed),
            self.gamemodel.connect_after("game_started", self.update),
            self.gamemodel.connect_after("game_ended", self.update),
            self.gamemodel.connect_after("moves_undone", self.on_moves_undone),
            self.gamemodel.connect_after("opening_changed", self.update),
            self.gamemodel.connect_after("players_changed",
                                         self.on_players_changed),
            self.gamemodel.connect_after("game_terminated",
                                         self.on_game_terminated),
            self.gamemodel.connect("variation_added", self.variation_added),
            self.gamemodel.connect("variation_extended",
                                   self.variation_extended),
            self.gamemodel.connect("analysis_changed", self.analysis_changed),
            self.gamemodel.connect("analysis_finished", self.update),
        ]
        self.cids_conf = []

        # Load of the preferences
        def cb_config_changed(*args):
            self.fetch_chess_conf()
            self.update()

        self.cids_conf.append(
            conf.notify_add("figuresInNotation", cb_config_changed))
        self.cids_conf.append(conf.notify_add("showEmt", cb_config_changed))
        self.cids_conf.append(conf.notify_add("showBlunder",
                                              cb_config_changed))
        self.cids_conf.append(conf.notify_add("showEval", cb_config_changed))
        self.fetch_chess_conf()

        # Layout
        __widget__ = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        __widget__.pack_start(self.label_info, False, True, 1)
        __widget__.pack_start(self.label_players, False, True, 1)
        __widget__.pack_start(self.label_event, False, True, 1)
        __widget__.pack_start(self.label_opening, False, True, 1)

        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
        sw.add(self.textview)
        __widget__.pack_start(sw, True, True, 0)

        if self.gamemodel.practice_game or self.gamemodel.lesson_game:
            self.infobar = LearnInfoBar(self.gamemodel, self.boardview)
            self.boardview.infobar = self.infobar
            __widget__.pack_start(self.infobar, False, False, 0)

        return __widget__
Example #28
0
    def load(self, gmwidg):
        self.gmwidg = gmwidg
        self.boardview = gmwidg.board.view

        self.sw = Gtk.ScrolledWindow()
        self.tv = Gtk.TreeView()
        self.tv.set_property("headers_visible", False)
        self.sw.add(self.tv)
        self.sw.show_all()

        self.store = Gtk.TreeStore(GObject.TYPE_PYOBJECT,
                                   GObject.TYPE_PYOBJECT, int, bool, str, bool,
                                   bool)
        self.tv.set_model(self.store)

        # ## move suggested
        moveRenderer = Gtk.CellRendererText()
        moveRenderer.set_property("xalign", 1.0)
        moveRenderer.set_property("yalign", 0)
        c0 = Gtk.TreeViewColumn("Move", moveRenderer)

        def getMoveText(column, cell, store, iter, data):
            board, move, pv = store[iter][0]
            if not move:
                cell.set_property("text", "")
            else:
                if conf.get("figuresInNotation", False):
                    cell.set_property("text", toFAN(board, move))
                else:
                    cell.set_property("text", toSAN(board, move, True))

        c0.set_cell_data_func(moveRenderer, getMoveText)

        # ## strength of the move
        c1 = Gtk.TreeViewColumn("Strength", StrengthCellRenderer(), data=1)

        # ## multipv (number of analysis lines)
        self.multipvRenderer = Gtk.CellRendererSpin()
        adjustment = Gtk.Adjustment(value=conf.get("multipv", 1),
                                    lower=1,
                                    upper=9,
                                    step_incr=1)
        self.multipvRenderer.set_property("adjustment", adjustment)
        self.multipvRenderer.set_property("editable", True)
        self.multipvRenderer.set_property("width_chars", 1)
        c2 = Gtk.TreeViewColumn("PV", self.multipvRenderer, editable=3)
        c2.set_property("min_width", 80)

        def spin_visible(column, cell, store, iter, data):
            if store[iter][2] == 0:
                cell.set_property('visible', False)
            else:
                cell.set_property("text", str(store[iter][2]))
                cell.set_property('visible', True)

        c2.set_cell_data_func(self.multipvRenderer, spin_visible)

        def multipv_edited(renderer, path, text):
            iter = self.store.get_iter(path)
            self.store.set_value(iter, 2, int(text))
            self.advisors[int(path[0])].multipv_edited(int(text))

        self.multipv_cid = self.multipvRenderer.connect(
            'edited', multipv_edited)

        # ## start/stop button for analysis engines
        self.toggleRenderer = CellRendererPixbufXt()
        self.toggleRenderer.set_property("stock-id", "gtk-add")
        c4 = Gtk.TreeViewColumn("StartStop", self.toggleRenderer)

        def cb_visible(column, cell, store, iter, data):
            if not store[iter][6]:
                cell.set_property('visible', False)
            else:
                cell.set_property('visible', True)

            if store[iter][5]:
                cell.set_property("stock-id", "gtk-add")
            else:
                cell.set_property("stock-id", "gtk-remove")

        c4.set_cell_data_func(self.toggleRenderer, cb_visible)

        def toggled_cb(cell, path):
            self.store[path][5] = not self.store[path][5]
            self.advisors[int(path[0])].start_stop(self.store[path][5])

        self.toggle_cid = self.toggleRenderer.connect('clicked', toggled_cb)

        self.tv.append_column(c4)
        self.tv.append_column(c0)
        self.tv.append_column(c1)
        self.tv.append_column(c2)
        # ## header text, or analysis line
        uistuff.appendAutowrapColumn(self.tv, "Details", text=4)

        self.cid = self.boardview.connect("shownChanged", self.shownChanged)
        self.tv_cids = [
            self.tv.connect("cursor_changed", self.selection_changed),
            self.tv.connect("select_cursor_row", self.selection_changed),
            self.tv.connect("row-activated", self.row_activated),
            self.tv.connect("query-tooltip", self.query_tooltip),
        ]
        self.tv.props.has_tooltip = True
        self.tv.set_property("show-expanders", False)

        self.advisors = []
        self.conf_conids = []

        if conf.get("opening_check", 0):
            self.advisors.append(OpeningAdvisor(self.store, self.tv))
        if conf.get("endgame_check", 0):
            advisor = EndgameAdvisor(self.store, self.tv, self.boardview)
            self.advisors.append(advisor)

        self.model_cids = [
            gmwidg.gamemodel.connect("analyzer_added", self.on_analyzer_added),
            gmwidg.gamemodel.connect("analyzer_removed",
                                     self.on_analyzer_removed),
            gmwidg.gamemodel.connect("analyzer_paused",
                                     self.on_analyzer_paused),
            gmwidg.gamemodel.connect("analyzer_resumed",
                                     self.on_analyzer_resumed),
            gmwidg.gamemodel.connect_after("game_terminated",
                                           self.on_game_terminated),
        ]

        def on_opening_check(none):
            if conf.get("opening_check", 0) and self.boardview is not None:
                advisor = OpeningAdvisor(self.store, self.tv)
                self.advisors.append(advisor)
                advisor.shownChanged(self.boardview, self.boardview.shown)
            else:
                for advisor in self.advisors:
                    if advisor.mode == OPENING:
                        parent = advisor.empty_parent()
                        self.store.remove(parent)
                        self.advisors.remove(advisor)

        self.conf_conids.append(
            conf.notify_add("opening_check", on_opening_check))

        def on_opening_file_entry_changed(none):
            default_path = os.path.join(addDataPrefix("pychess_book.bin"))
            path = conf.get("opening_file_entry", default_path)
            if os.path.isfile(path):
                for advisor in self.advisors:
                    if advisor.mode == OPENING and self.boardview is not None:
                        advisor.shownChanged(self.boardview,
                                             self.boardview.shown)

        self.conf_conids.append(
            conf.notify_add("opening_file_entry",
                            on_opening_file_entry_changed))

        def on_endgame_check(none):
            if conf.get("endgame_check", 0):
                advisor = EndgameAdvisor(self.store, self.tv, self.boardview)
                self.advisors.append(advisor)
                advisor.shownChanged(self.boardview, self.boardview.shown)
            else:
                for advisor in self.advisors:
                    if advisor.mode == ENDGAME:
                        advisor._del()
                        parent = advisor.empty_parent()
                        self.store.remove(parent)
                        self.advisors.remove(advisor)

        self.conf_conids.append(
            conf.notify_add("endgame_check", on_endgame_check))

        return self.sw
Example #29
0
    def load(self, gmwidg):
        self.textview = Gtk.TextView()
        self.textview.set_wrap_mode(Gtk.WrapMode.WORD)

        self.cursor_standard = Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR)
        self.cursor_hand = Gdk.Cursor.new(Gdk.CursorType.HAND2)

        self.nodelist = []
        self.oldWidth = 0
        self.autoUpdateSelected = True

        self.textview_cids = [
            self.textview.connect("motion-notify-event",
                                  self.motion_notify_event),
            self.textview.connect("button-press-event",
                                  self.button_press_event),
        ]
        bg_color, fg_color = set_textview_color(self.textview)

        self.textbuffer = self.textview.get_buffer()

        color0 = fg_color
        color1 = Gdk.RGBA(red=0.2, green=0.0, blue=0.0)
        color2 = Gdk.RGBA(red=0.4, green=0.0, blue=0.0)
        color3 = Gdk.RGBA(red=0.6, green=0.0, blue=0.0)
        color4 = Gdk.RGBA(red=0.8, green=0.0, blue=0.0)
        color5 = Gdk.RGBA(red=1.0, green=0.0, blue=0.0)

        self.remove_vari_tag = self.textbuffer.create_tag("remove-variation")
        self.rmv_cid = self.remove_vari_tag.connect("event",
                                                    self.tag_event_handler)

        self.new_line_tag = self.textbuffer.create_tag("new_line")

        self.textbuffer.create_tag("head1")
        self.textbuffer.create_tag("head2", weight=Pango.Weight.BOLD)
        self.textbuffer.create_tag("move", weight=Pango.Weight.BOLD)
        self.textbuffer.create_tag("scored0", foreground_rgba=color0)
        self.textbuffer.create_tag("scored1", foreground_rgba=color1)
        self.textbuffer.create_tag("scored2", foreground_rgba=color2)
        self.textbuffer.create_tag("scored3", foreground_rgba=color3)
        self.textbuffer.create_tag("scored4", foreground_rgba=color4)
        self.textbuffer.create_tag("scored5", foreground_rgba=color5)
        self.textbuffer.create_tag("emt",
                                   foreground="darkgrey",
                                   weight=Pango.Weight.NORMAL)
        self.textbuffer.create_tag("comment", foreground="darkblue")
        self.textbuffer.create_tag("variation-toplevel",
                                   weight=Pango.Weight.NORMAL)
        self.textbuffer.create_tag("variation-even",
                                   foreground="darkgreen",
                                   style="italic")
        self.textbuffer.create_tag("variation-uneven",
                                   foreground="darkred",
                                   style="italic")
        self.textbuffer.create_tag("selected",
                                   background_full_height=True,
                                   background="grey")
        self.textbuffer.create_tag("margin", left_margin=4)
        self.textbuffer.create_tag("variation-margin0", left_margin=20)
        self.textbuffer.create_tag("variation-margin1", left_margin=36)
        self.textbuffer.create_tag("variation-margin2", left_margin=52)

        __widget__ = Gtk.ScrolledWindow()
        __widget__.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
        __widget__.add(self.textview)

        self.boardview = gmwidg.board.view
        self.cid = self.boardview.connect("shownChanged", self.shownChanged)

        self.gamemodel = gmwidg.gamemodel
        self.model_cids = [
            self.gamemodel.connect_after("game_loaded", self.game_loaded),
            self.gamemodel.connect_after("game_changed", self.game_changed),
            self.gamemodel.connect_after("game_started", self.update),
            self.gamemodel.connect_after("game_ended", self.update),
            self.gamemodel.connect_after("moves_undone", self.moves_undone),
            self.gamemodel.connect_after("opening_changed", self.update),
            self.gamemodel.connect_after("players_changed",
                                         self.players_changed),
            self.gamemodel.connect_after("game_terminated",
                                         self.on_game_terminated),
            self.gamemodel.connect("variation_added", self.variation_added),
            self.gamemodel.connect("variation_extended",
                                   self.variation_extended),
            self.gamemodel.connect("analysis_changed", self.analysis_changed),
        ]

        # Connect to preferences
        self.conf_conids = []

        self.fan = conf.get("figuresInNotation", False)

        def figuresInNotationCallback(none):
            self.fan = conf.get("figuresInNotation", False)
            self.update()

        self.conf_conids.append(
            conf.notify_add("figuresInNotation", figuresInNotationCallback))

        # Elapsed move time
        self.showEmt = conf.get("showEmt", False)

        def showEmtCallback(none):
            self.showEmt = conf.get("showEmt", False)
            self.update()

        self.conf_conids.append(conf.notify_add("showEmt", showEmtCallback))

        # Blunders
        self.showBlunder = conf.get("showBlunder", False)

        def showBlunderCallback(none):
            self.showBlunder = conf.get("showBlunder", False)
            self.update()

        self.conf_conids.append(
            conf.notify_add("showBlunder", showBlunderCallback))

        # Eval values
        self.showEval = conf.get("showEval", False)

        def showEvalCallback(none):
            self.showEval = conf.get("showEval", False)
            self.update()

        self.conf_conids.append(conf.notify_add("showEval", showEvalCallback))

        return __widget__
Example #30
0
def workfunc (worker, gamemodel, player0tup, player1tup, loaddata=None):
    log.debug("ionest.workfunc: %s\n %s\n %s\n" % (gamemodel, player0tup, player1tup))
    gmwidg = gamewidget.GameWidget(gamemodel)

    player0 = {}
    player1 = {}
    for player, playertup in ((player0, player0tup), (player1, player1tup)):
        player["name"] = playertup[3]
        player["rating"] = (len(playertup) > 4 and playertup[4]) and "("+playertup[4]+")" or None
        player["tabtext"] = player["rating"] and player["name"] + " " + player["rating"] \
                or player["name"]
    text = [ player0["tabtext"], _("vs"), player1["tabtext"] ]
    gmwidg.setTabText(" ".join(text))

    # Initing analyze engines
    # We have to do this before publishing gmwidg to make sure that
    # gamemodel.*EngineSupportsVariant is set right before on_gmwidg_created() is called
    
    anaengines = list(discoverer.getAnalyzers())
    specs = {}
    engine = discoverer.getEngineByMd5(conf.get("ana_combobox", 0))
    if engine is None: engine = anaengines[0]
    if gamemodel.variant.board.variant in discoverer.getEngineVariants(engine) or \
       gamemodel.variant.standard_rules:
        if conf.get("analyzer_check", True):
            hintanalyzer = discoverer.initAnalyzerEngine(engine, ANALYZING,
                                                         gamemodel.variant)
            specs[HINT] = hintanalyzer
            log.debug("Hint Analyzer: %s\n" % repr(hintanalyzer))
        gamemodel.hintEngineSupportsVariant = True
    else:
        gamemodel.hintEngineSupportsVariant = False
    engine = discoverer.getEngineByMd5(conf.get("inv_ana_combobox", 0))
    if engine is None: engine = anaengines[0]
    if gamemodel.variant.board.variant in discoverer.getEngineVariants(engine) or \
       gamemodel.variant.standard_rules:
        if conf.get("inv_analyzer_check", True):
            spyanalyzer = discoverer.initAnalyzerEngine(engine, INVERSE_ANALYZING,
                                                        gamemodel.variant)
            specs[SPY] = spyanalyzer
            log.debug("Spy Analyzer: %s\n" % repr(spyanalyzer))
        gamemodel.spyEngineSupportsVariant = True            
    else:
        gamemodel.spyEngineSupportsVariant = False

    worker.publish((gmwidg,gamemodel))

    # For updating names
    players = []
    def updateTitle (color=None):

        name0_name1 = gmwidg.getTabText().split(" %s "%_("vs"))
        if not name0_name1:
            name0, name1 = _("White"), _("Black")
        else: name0, name1 = name0_name1

        if color is None:
            name0 = repr(players[WHITE])
            name0 += player0["rating"] and " "+player0["rating"] or ""
            name1 = repr(players[BLACK])
            name1 += player1["rating"] and " "+player1["rating"] or ""
        elif color == WHITE:
            name0 = repr(players[WHITE])
            name0 += player0["rating"] and " "+player0["rating"] or ""
        elif color == BLACK:
            name1 = repr(players[BLACK])
            name1 += player1["rating"] and " "+player1["rating"] or ""

        gmwidg.setTabText("%s %s %s" % (name0, _("vs"), name1))

    # Initing players
    for i, playertup in enumerate((player0tup, player1tup)):
        type, func, args = (playertup[0:3])
        if type != LOCAL:
            players.append(func(*args))
            if type == ARTIFICIAL:
                def readyformoves (player, color):
                    updateTitle(color)
                players[i].connect("readyForMoves", readyformoves, i)
        else:
            # Until PyChess has a proper profiles system, as discussed on the
            # issue tracker, we need to give human players special treatment
            ichandle = None
            if len(args) > 2:
                ichandle = args[2]
                args = [ v for v in args[0:2] ]
            player = func(gmwidg, ichandle=ichandle, *args)
            players.append(player)
            if i == 0 or (i == 1 and player0tup[0] != LOCAL):
                key = "firstName"
                alt = conf.username
            else:
                key = "secondName"
                alt = _("Guest")
            player.setName(conf.get(key, alt))

            def callback (none, color, key, alt):
                players[color].setName(conf.get(key, alt))
                updateTitle(color)
            conf.notify_add(key, callback, i, key, alt)

    worker.publish(updateTitle)

    # Setting game
    gamemodel.setPlayers(players)
    gamemodel.setSpectactors(specs)

    # Starting
    if loaddata:
        try:
            uri, loader, gameno, position = loaddata
            gamemodel.loadAndStart (uri, loader, gameno, position)
        except LoadingError, e:
            d = gtk.MessageDialog (type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_OK)
            d.set_markup ("<big><b>%s</b></big>" % e.args[0])
            d.format_secondary_text (e.args[1] + "\n\n" +
                    _("Correct the move, or start playing with what could be read"))
            d.connect("response", lambda d,a: d.hide())
            worker.publish(d.show)
Example #31
0
def workfunc (worker, gamemodel, player0tup, player1tup, loaddata=None):
    log.debug("ionest.workfunc: %s\n %s\n %s" % (gamemodel, player0tup, player1tup))

    gmwidg = gamewidget.GameWidget(gamemodel)
    worker.publish((gmwidg,gamemodel))
    
    # Initing players
    players = []
    for i, playertup in enumerate((player0tup, player1tup)):
        type, func, args, prename = playertup
        if type != LOCAL:
            players.append(func(*args))
            #if type == ARTIFICIAL:
            #    def readyformoves (player, color):
            #        gmwidg.setTabText(gmwidg.display_text))
            #    players[i].connect("readyForMoves", readyformoves, i)
        else:
            # Until PyChess has a proper profiles system, as discussed on the
            # issue tracker, we need to give human players special treatment
            player = func(gmwidg, *args)
            players.append(player)
            
            # Connect to conf
            if i == 0 or (i == 1 and player0tup[0] != LOCAL):
                key = "firstName"
                alt = _("You")
            else:
                key = "secondName"
                alt = _("Guest")
            if prename == conf.get(key, alt):
                conf.notify_add(key, lambda *a:player.setName(conf.get(key,alt)))

    if player0tup[0] == ARTIFICIAL and player1tup[0] == ARTIFICIAL:
        def emit_action (action, param):
            if gmwidg.isInFront():
                gamemodel.curplayer.emit("offer", Offer(action, param=param))
        gmwidg.board.connect("action", lambda b,action,param: emit_action(action, param))
    
    log.debug("ionest.workfunc: -> gamemodel.setPlayers(): %s" % (gamemodel))
    gamemodel.setPlayers(players)
    log.debug("ionest.workfunc: <- gamemodel.setPlayers(): %s" % (gamemodel))
    
    # Starting
    if loaddata:
        try:
            uri, loader, gameno, position = loaddata
            gamemodel.loadAndStart (uri, loader, gameno, position)
        except LoadingError as e:
            d = Gtk.MessageDialog (type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK,
                                    message_format=e.args[0])
            d.format_secondary_text (e.args[1])
            d.connect("response", lambda d,a: d.hide())
            worker.publish(d.show)

    else:
        if gamemodel.variant.need_initial_board:
            for player in gamemodel.players:
                player.setOptionInitialBoard(gamemodel)
        log.debug("ionest.workfunc: -> gamemodel.start(): %s" % (gamemodel))
        gamemodel.start()
        log.debug("ionest.workfunc: <- gamemodel.start(): %s" % (gamemodel))
    
    log.debug("ionest.workfunc: returning gmwidg=%s\n gamemodel=%s" % \
        (gmwidg, gamemodel))
    return gmwidg, gamemodel
Example #32
0
def generalStart (gamemodel, player0tup, player1tup, loaddata=None):
    """ The player tuples are:
    (The type af player in a System.const value,
    A callable creating the player,
    A list of arguments for the callable,
    A preliminary name for the player)

    If loaddata is specified, it should be a tuple of:
    (A text uri or fileobj,
    A Savers.something module with a load function capable of loading it,
    An int of the game in file you want to load,
    The position from where to start the game)
    """

    log.debug("ionest.generalStart: %s\n %s\n %s" % (gamemodel, player0tup, player1tup))

    gmwidg = gamewidget.GameWidget(gamemodel)
    gmwidg.connect("game_close_clicked", closeGame, gamemodel)

    #worker.publish((gmwidg,gamemodel))
    gamewidget.attachGameWidget(gmwidg)
    gamenanny.nurseGame(gmwidg, gamemodel)
    log.debug("ionest.generalStart: -> emit gmwidg_created: %s" % (gmwidg))
    handler.emit("gmwidg_created", gmwidg, gamemodel)
    log.debug("ionest.generalStart: <- emit gmwidg_created: %s" % (gmwidg))

    # Initing players
    players = []
    for i, playertup in enumerate((player0tup, player1tup)):
        type, func, args, prename = playertup
        if type != LOCAL:
            players.append(func(*args))
            #if type == ARTIFICIAL:
            #    def readyformoves (player, color):
            #        gmwidg.setTabText(gmwidg.display_text))
            #    players[i].connect("readyForMoves", readyformoves, i)
        else:
            # Until PyChess has a proper profiles system, as discussed on the
            # issue tracker, we need to give human players special treatment
            player = func(gmwidg, *args)
            players.append(player)

            # Connect to conf
            if i == 0 or (i == 1 and player0tup[0] != LOCAL):
                key = "firstName"
                alt = _("You")
            else:
                key = "secondName"
                alt = _("Guest")
            if prename == conf.get(key, alt):
                conf.notify_add(key, lambda *a:player.setName(conf.get(key,alt)))

    if player0tup[0] == ARTIFICIAL and player1tup[0] == ARTIFICIAL:
        def emit_action (action, param):
            if gmwidg.isInFront():
                gamemodel.curplayer.emit("offer", Offer(action, param=param))
        gmwidg.board.connect("action", lambda b,action,param: emit_action(action, param))

    log.debug("ionest.generalStart: -> gamemodel.setPlayers(): %s" % (gamemodel))
    gamemodel.setPlayers(players)
    log.debug("ionest.generalStart: <- gamemodel.setPlayers(): %s" % (gamemodel))

    # Starting
    if loaddata:
        try:
            uri, loader, gameno, position = loaddata
            gamemodel.loadAndStart (uri, loader, gameno, position)
            if position != gamemodel.ply:
                gmwidg.board.view.shown = position
        except LoadingError as e:
            d = Gtk.MessageDialog (type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK)
            d.set_markup(_("<big><b>Error loading game</big></b>"))
            d.format_secondary_text(", ".join(str(a) for a in e.args))
            d.show()
            d.hide()

    else:
        if gamemodel.variant.need_initial_board:
            for player in gamemodel.players:
                player.setOptionInitialBoard(gamemodel)
        log.debug("ionest..generalStart: -> gamemodel.start(): %s" % (gamemodel))
        gamemodel.start()
        log.debug("ionest.generalStart: <- gamemodel.start(): %s" % (gamemodel))

    log.debug("ionest.generalStart: returning gmwidg=%s\n gamemodel=%s" % \
        (gmwidg, gamemodel))
    return gmwidg, gamemodel
Example #33
0
def generalStart(gamemodel, player0tup, player1tup, loaddata=None):
    """ The player tuples are:
        (The type af player in a System.const value,
         A callable creating the player,
         A list of arguments for the callable,
         A preliminary name for the player)

        If loaddata is specified, it should be a tuple of:
        (A text uri or fileobj,
         A Savers.something module with a load function capable of loading it,
         An int of the game in file you want to load,
         The position from where to start the game) """
    log.debug("ionest.generalStart: %s\n %s\n %s" %
              (gamemodel, player0tup, player1tup))

    gmwidg = gamewidget.GameWidget(gamemodel)
    gmwidg.connect("close_clicked", closeGame, gamemodel)

    #worker.publish((gmwidg,gamemodel))
    gamewidget.attachGameWidget(gmwidg)
    gamenanny.nurseGame(gmwidg, gamemodel)
    log.debug("ionest.generalStart: -> emit gmwidg_created: %s" % (gmwidg))
    handler.emit("gmwidg_created", gmwidg, gamemodel)
    log.debug("ionest.generalStart: <- emit gmwidg_created: %s" % (gmwidg))

    # Initing players
    players = []
    for i, playertup in enumerate((player0tup, player1tup)):
        type, func, args, prename = playertup
        if type != LOCAL:
            players.append(func(*args))
            #if type == ARTIFICIAL:
            #    def readyformoves (player, color):
            #        gmwidg.setTabText(gmwidg.display_text))
            #    players[i].connect("readyForMoves", readyformoves, i)
        else:
            # Until PyChess has a proper profiles system, as discussed on the
            # issue tracker, we need to give human players special treatment
            player = func(gmwidg, *args)
            players.append(player)

            # Connect to conf
            if i == 0 or (i == 1 and player0tup[0] != LOCAL):
                key = "firstName"
                alt = _("You")
            else:
                key = "secondName"
                alt = _("Guest")
            if prename == conf.get(key, alt):
                conf.notify_add(key,
                                lambda *a: player.setName(conf.get(key, alt)))

    if player0tup[0] == ARTIFICIAL and player1tup[0] == ARTIFICIAL:

        def emit_action(action, param):
            if gmwidg.isInFront():
                gamemodel.curplayer.emit("offer", Offer(action, param=param))

        gmwidg.board.connect(
            "action", lambda b, action, param: emit_action(action, param))

    log.debug("ionest.generalStart: -> gamemodel.setPlayers(): %s" %
              (gamemodel))
    gamemodel.setPlayers(players)
    log.debug("ionest.generalStart: <- gamemodel.setPlayers(): %s" %
              (gamemodel))

    # Starting
    if loaddata:
        try:
            uri, loader, gameno, position = loaddata
            gamemodel.loadAndStart(uri, loader, gameno, position)
        except LoadingError as e:
            d = Gtk.MessageDialog(type=Gtk.MessageType.WARNING,
                                  buttons=Gtk.ButtonsType.OK)
            d.set_markup(_("<big><b>Error loading game</big></b>"))
            d.format_secondary_text(", ".join(str(a) for a in e.args))
            d.show()
            d.hide()

    else:
        if gamemodel.variant.need_initial_board:
            for player in gamemodel.players:
                player.setOptionInitialBoard(gamemodel)
        log.debug("ionest..generalStart: -> gamemodel.start(): %s" %
                  (gamemodel))
        gamemodel.start()
        log.debug("ionest.generalStart: <- gamemodel.start(): %s" %
                  (gamemodel))

    log.debug("ionest.generalStart: returning gmwidg=%s\n gamemodel=%s" % \
        (gmwidg, gamemodel))
    return gmwidg, gamemodel
Example #34
0
def show_tabs(show):
    if show:
        widgets["mainvbox"].get_children()[1].show_all()
    else:
        widgets["mainvbox"].get_children()[1].hide()


def tabsCallback(none):
    head = getheadbook()
    if not head:
        return
    if head.get_n_pages() == 1:
        show_tabs(not conf.get("hideTabs", False))


conf.notify_add("hideTabs", tabsCallback)

# ###############################################################################
# Handling of the special sidepanels-design-gamewidget used in preferences     #
# ###############################################################################

designGW = None


def showDesignGW():
    global designGW
    if not designGW:
        designGW = GameWidget(GameModel())
    if isDesignGWShown():
        return
    getWidgets()["show_sidepanels"].set_active(True)
Example #35
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)
Example #36
0
    def __init__(self, gamemodel):
        GObject.GObject.__init__(self)
        self.gamemodel = gamemodel
        self.cids = {}
        self.closed = False

        # InfoBarMessage with rematch, undo or observe buttons
        self.game_ended_message = None

        self.tabcontent, white_label, black_label, self.game_info_label = self.initTabcontents(
        )
        self.boardvbox, self.board, self.infobar, self.clock = self.initBoardAndClock(
            self.gamemodel)
        self.stat_hbox = self.initButtons(self.board)

        self.player_name_labels = (white_label, black_label)
        self.infobar.connect("hide", self.infobar_hidden)

        self.notebookKey = Gtk.Alignment()
        self.menuitems = MenuItemsDict()

        self.gamemodel_cids = [
            self.gamemodel.connect_after("game_started", self.game_started),
            self.gamemodel.connect_after("game_ended", self.game_ended),
            self.gamemodel.connect_after("game_changed", self.game_changed),
            self.gamemodel.connect("game_paused", self.game_paused),
            self.gamemodel.connect("game_resumed", self.game_resumed),
            self.gamemodel.connect("moves_undone", self.moves_undone),
            self.gamemodel.connect("game_unended", self.game_unended),
            self.gamemodel.connect("game_saved", self.game_saved),
            self.gamemodel.connect("players_changed", self.players_changed),
            self.gamemodel.connect("analyzer_added", self.analyzer_added),
            self.gamemodel.connect("analyzer_removed", self.analyzer_removed),
            self.gamemodel.connect("analyzer_resumed", self.analyzer_resumed),
            self.gamemodel.connect("analyzer_paused", self.analyzer_paused),
            self.gamemodel.connect("message_received", self.message_received),
        ]
        self.players_changed(self.gamemodel)

        self.notify_cids = [
            conf.notify_add("showFICSgameno", self.on_show_fics_gameno),
        ]

        if self.gamemodel.display_text:
            if isinstance(self.gamemodel, ICGameModel) and conf.get(
                    "showFICSgameno", False):
                self.game_info_label.set_text(
                    "%s [%s]" %
                    (self.display_text, self.gamemodel.ficsgame.gameno))
            else:
                self.game_info_label.set_text(self.display_text)
        if self.gamemodel.timed:
            self.cids[
                self.gamemodel.timemodel] = self.gamemodel.timemodel.connect(
                    "zero_reached", self.zero_reached)

        self.connections = defaultdict(list)
        if isinstance(self.gamemodel, ICGameModel):
            self.connections[self.gamemodel.connection.bm].append(
                self.gamemodel.connection.bm.connect("player_lagged",
                                                     self.player_lagged))
            self.connections[self.gamemodel.connection.bm].append(
                self.gamemodel.connection.bm.connect("opp_not_out_of_time",
                                                     self.opp_not_out_of_time))
        self.cids[self.board.view] = self.board.view.connect(
            "shownChanged", self.shownChanged)

        def do_load_panels(event):
            # self.panels = [panel.Sidepanel().load(self) if panel.__name__ == "bookPanel" else Gtk.ScrolledWindow() for panel in sidePanels]
            self.panels = [
                panel.Sidepanel().load(self) for panel in sidePanels
            ]
            if event is not None:
                event.set()

        thread = currentThread()
        if thread.name == "MainThread":
            do_load_panels(None)
        else:
            event = threading.Event()
            GLib.idle_add(do_load_panels, event)
            event.wait()

        if isinstance(self.gamemodel, ICGameModel):
            self.gamemodel.gmwidg_ready.set()
Example #37
0
def show_tabs(show):
    if show:
        widgets["mainvbox"].get_children()[1].show_all()
    else:
        widgets["mainvbox"].get_children()[1].hide()


def tabsCallback(none):
    head = getheadbook()
    if not head:
        return
    if head.get_n_pages() == 1:
        show_tabs(not conf.get("hideTabs", False))


conf.notify_add("hideTabs", tabsCallback)

# ###############################################################################
# Handling of the special sidepanels-design-gamewidget used in preferences     #
# ###############################################################################

designGW = None


def showDesignGW():
    global designGW
    designGW = GameWidget(GameModel())
    if isDesignGWShown():
        return
    getWidgets()["show_sidepanels"].set_active(True)
    getWidgets()["show_sidepanels"].set_sensitive(False)
Example #38
0
    def load(self, gmwidg):
        __widget__ = Gtk.ScrolledWindow()
        __widget__.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)

        self.numbers = Gtk.TreeView()
        self.numbers.set_property("can_focus", False)
        self.numbers.set_property("sensitive", False)
        self.numbers.set_property("width_request", 35)
        self.numbers.set_fixed_height_mode(True)
        self.left = Gtk.TreeView()
        self.numbers.set_property("width_request", 60)
        self.left.set_fixed_height_mode(True)
        self.right = Gtk.TreeView()
        self.numbers.set_property("width_request", 60)
        self.right.set_fixed_height_mode(True)

        box = Gtk.Box(spacing=0)
        box.pack_start(self.numbers, False, True, 0)
        box.pack_start(self.left, True, True, 0)
        box.pack_start(self.right, True, True, 0)

        port = Gtk.Viewport()
        port.add(box)
        port.set_shadow_type(Gtk.ShadowType.NONE)

        __widget__.add(port)
        __widget__.show_all()

        self.cids = {}
        self.boardview = gmwidg.board.view

        self.model_cids = [
            self.boardview.model.connect_after("game_changed",
                                               self.game_changed),
            self.boardview.model.connect_after("game_started",
                                               self.game_started),
            self.boardview.model.connect_after("moves_undone",
                                               self.moves_undone),
            self.boardview.model.connect_after("game_terminated",
                                               self.on_game_terminated),
        ]
        self.cids[self.boardview] = self.boardview.connect(
            "shownChanged", self.shownChanged)

        # Initialize treeviews

        def fixList(list, xalign=0):
            list.set_property("headers_visible", False)
            list.set_property("rules_hint", True)
            list.set_model(Gtk.ListStore(str))
            renderer = Gtk.CellRendererText()
            renderer.set_property("xalign", xalign)
            column = Gtk.TreeViewColumn(None, renderer, text=0)
            column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
            list.append_column(column)
            list.get_selection().set_mode(Gtk.SelectionMode.SINGLE)

        fixList(self.numbers, 1)
        fixList(self.left, 0)
        fixList(self.right, 0)

        self.cids[self.left] = self.left.connect('cursor_changed',
                                                 self.cursorChanged, self.left,
                                                 0)
        self.cids[self.right] = self.right.connect('cursor_changed',
                                                   self.cursorChanged,
                                                   self.right, 1)

        # Lock scrolling

        self.adjustment = __widget__.get_vadjustment()

        def changed(vadjust):
            if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
                vadjust.set_value(vadjust.get_upper() -
                                  vadjust.get_page_size())
                vadjust.need_scroll = True

        self.adj_cid1 = self.adjustment.connect("changed", changed)

        def value_changed(vadjust):
            vadjust.need_scroll = abs(
                vadjust.get_value() + vadjust.get_page_size() -
                vadjust.get_upper()) < vadjust.get_step_increment()

        self.adj_cid2 = self.adjustment.connect("value-changed", value_changed)

        # Connect to preferences

        def figuresInNotationCallback(none):
            game = self.boardview.model
            for board, move in zip(game.variations[0], game.moves):
                if conf.get("figuresInNotation", False):
                    notat = toFAN(board, move)
                else:
                    notat = toSAN(board, move, True)
                row, col, other = self._ply_to_row_col_other(board.ply + 1)
                iter = col.get_model().get_iter((row, ))
                col.get_model().set(iter, 0, notat)

        self.conf_conid = conf.notify_add("figuresInNotation",
                                          figuresInNotationCallback)

        # Return

        return __widget__
Example #39
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)
 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)
Example #41
0
    def init_layout(self):
        perspective_widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        perspective_manager.set_perspective_widget("games", perspective_widget)

        self.notebooks = {"board": cleanNotebook("board"),
                          "buttons": cleanNotebook("buttons"),
                          "messageArea": cleanNotebook("messageArea")}
        for panel in sidePanels:
            self.notebooks[panel.__name__] = cleanNotebook(panel.__name__)

        # Initing headbook

        align = gamewidget.createAlignment(4, 4, 0, 4)
        align.set_property("yscale", 0)

        headbook = Gtk.Notebook()
        headbook.set_name("headbook")
        headbook.set_scrollable(True)
        align.add(headbook)
        perspective_widget.pack_start(align, False, True, 0)
        self.show_tabs(not conf.get("hideTabs", False))

        # Initing center

        centerVBox = Gtk.VBox()

        # The dock

        self.dock = PyDockTop("main", self)
        self.dockAlign = gamewidget.createAlignment(4, 4, 0, 4)
        self.dockAlign.add(self.dock)
        centerVBox.pack_start(self.dockAlign, True, True, 0)
        self.dockAlign.show()
        self.dock.show()

        self.docks = {"board": (Gtk.Label(label="Board"), self.notebooks["board"])}
        for panel in sidePanels:
            box = dock_panel_tab(panel.__title__, panel.__desc__, panel.__icon__)
            self.docks[panel.__name__] = (box, self.notebooks[panel.__name__])

        if os.path.isfile(dockLocation):
            try:
                self.dock.loadFromXML(dockLocation, self.docks)
            except Exception as e:
                stringio = StringIO()
                traceback.print_exc(file=stringio)
                error = stringio.getvalue()
                log.error("Dock loading error: %s\n%s" % (e, error))
                widgets = gamewidget.getWidgets()
                msg_dia = Gtk.MessageDialog(widgets["main_window"],
                                            type=Gtk.MessageType.ERROR,
                                            buttons=Gtk.ButtonsType.CLOSE)
                msg_dia.set_markup(_(
                    "<b><big>PyChess was unable to load your panel settings</big></b>"))
                msg_dia.format_secondary_text(_(
                    "Your panel settings have been reset. If this problem repeats, \
                    you should report it to the developers"))
                msg_dia.run()
                msg_dia.hide()
                os.remove(dockLocation)
                for title, panel in self.docks.values():
                    title.unparent()
                    panel.unparent()

        if not os.path.isfile(dockLocation):
            leaf = self.dock.dock(self.docks["board"][1],
                                  CENTER,
                                  Gtk.Label(label=self.docks["board"][0]),
                                  "board")
            self.docks["board"][1].show_all()
            leaf.setDockable(False)

            # S
            epanel = leaf.dock(self.docks["bookPanel"][1], SOUTH, self.docks["bookPanel"][0],
                               "bookPanel")
            epanel.default_item_height = 45
            epanel = epanel.dock(self.docks["engineOutputPanel"][1], CENTER,
                                 self.docks["engineOutputPanel"][0],
                                 "engineOutputPanel")

            # NE
            leaf = leaf.dock(self.docks["annotationPanel"][1], EAST,
                             self.docks["annotationPanel"][0], "annotationPanel")
            leaf = leaf.dock(self.docks["historyPanel"][1], CENTER,
                             self.docks["historyPanel"][0], "historyPanel")
            leaf = leaf.dock(self.docks["scorePanel"][1], CENTER,
                             self.docks["scorePanel"][0], "scorePanel")

            # SE
            leaf = leaf.dock(self.docks["chatPanel"][1], SOUTH, self.docks["chatPanel"][0],
                             "chatPanel")
            leaf = leaf.dock(self.docks["commentPanel"][1], CENTER,
                             self.docks["commentPanel"][0], "commentPanel")

        def unrealize(dock, notebooks):
            # unhide the panel before saving so its configuration is saved correctly
            self.notebooks["board"].get_parent().get_parent().zoomDown()
            dock.saveToXML(dockLocation)
            dock._del()

        self.dock.connect("unrealize", unrealize, self.notebooks)

        hbox = Gtk.HBox()

        # Buttons
        self.notebooks["buttons"].set_border_width(4)
        hbox.pack_start(self.notebooks["buttons"], False, True, 0)

        # The message area
        # TODO: If you try to fix this first read issue #958 and 1018
        align = gamewidget.createAlignment(0, 0, 0, 0)
        # sw = Gtk.ScrolledWindow()
        # port = Gtk.Viewport()
        # port.add(self.notebooks["messageArea"])
        # sw.add(port)
        # align.add(sw)
        align.add(self.notebooks["messageArea"])
        hbox.pack_start(align, True, True, 0)

        def ma_switch_page(notebook, gpointer, page_num):
            notebook.props.visible = notebook.get_nth_page(page_num).\
                get_child().props.visible

        self.notebooks["messageArea"].connect("switch-page", ma_switch_page)
        centerVBox.pack_start(hbox, False, True, 0)

        perspective_widget.pack_start(centerVBox, True, True, 0)
        centerVBox.show_all()
        perspective_widget.show_all()

        conf.notify_add("hideTabs", self.tabsCallback)

        # Connecting headbook to other notebooks

        def hb_switch_page(notebook, gpointer, page_num):
            for notebook in self.notebooks.values():
                notebook.set_current_page(page_num)

            gmwidg = self.key2gmwidg[self.getheadbook().get_nth_page(page_num)]
            if isinstance(gmwidg.gamemodel, ICGameModel):
                primary = "primary " + str(gmwidg.gamemodel.ficsgame.gameno)
                gmwidg.gamemodel.connection.client.run_command(primary)

        headbook.connect("switch-page", hb_switch_page)

        if hasattr(headbook, "set_tab_reorderable"):

            def page_reordered(widget, child, new_num, headbook):
                old_num = self.notebooks["board"].page_num(self.key2gmwidg[child].boardvbox)
                if old_num == -1:
                    log.error('Games and labels are out of sync!')
                else:
                    for notebook in self.notebooks.values():
                        notebook.reorder_child(
                            notebook.get_nth_page(old_num), new_num)

            headbook.connect("page-reordered", page_reordered, headbook)
Example #42
0
    def load(self, gmwidg):

        self.gamemodel = gmwidg.board.view.model
        self.black_starts = self.gamemodel.lowply % 2 == 1
        self.model_cids = [
            self.gamemodel.connect_after("game_changed", self.game_changed),
            self.gamemodel.connect_after("game_started", self.game_started),
            self.gamemodel.connect_after("moves_undone", self.moves_undone),
            self.gamemodel.connect_after("game_terminated", self.on_game_terminated),
        ]

        self.tv = Gtk.TreeView()
        self.tv.set_headers_visible(False)
        self.tv.set_grid_lines(True)
        self.tv.set_activate_on_single_click(True)
        self.tv.get_selection().set_mode(Gtk.SelectionMode.NONE)
        self.activated_cell = (None, None)

        def is_row_separator(treemodel, treeiter):
            mvcount, wmove, bmove, row, wbg, bbg = self.store[treeiter]
            return row == 0
        self.tv.set_row_separator_func(is_row_separator)

        self.tv.connect("style-updated", self.on_style_updated)
        movetext_font = conf.get("movetextFont", "FreeSerif Regular 12")

        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("mvcount", renderer, text=0)
        column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
        self.tv.append_column(column)

        self.white_renderer = Gtk.CellRendererText()
        self.white_renderer.set_property("xalign", 1)
        self.white_renderer.set_property("font", movetext_font)
        self.white_column = Gtk.TreeViewColumn("white", self.white_renderer, text=1, background=4)
        self.white_column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
        self.tv.append_column(self.white_column)

        self.black_renderer = Gtk.CellRendererText()
        self.black_renderer.set_property("xalign", 1)
        self.black_renderer.set_property("font", movetext_font)
        self.black_column = Gtk.TreeViewColumn("black", self.black_renderer, text=2, background=5)
        self.black_column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
        self.tv.append_column(self.black_column)

        # To prevent black moves column expand to the right we add a dummy column finally
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("dummy", renderer)
        self.tv.append_column(column)

        scrollwin = Gtk.ScrolledWindow()
        scrollwin.add(self.tv)

        # Our liststore elements will be:
        # mvcount, white move, black move, row number, white move background, black move background
        self.store = Gtk.ListStore(str, str, str, int, str, str)
        self.tv.set_model(self.store)
        self.tv_cid = self.tv.connect('row_activated', self.on_row_activated)

        self.boardview = gmwidg.board.view
        self.cid = self.boardview.connect("shownChanged", self.shownChanged)
        scrollwin.show_all()

        def figuresInNotationCallback(none):
            game = self.boardview.model
            if game.lesson_game:
                return

            for i, move in enumerate(game.moves):
                board = game.variations[0][i]
                ply = game.lowply + i + 1
                if conf.get("figuresInNotation", False):
                    notat = toFAN(board, move)
                else:
                    notat = toSAN(board, move, True)

                row, column = self.ply_to_row_col(ply)

                col = 2 if column == self.black_column else 1
                treeiter = self.store.get_iter(Gtk.TreePath(row))
                self.store.set_value(treeiter, col, notat)

        def font_changed(none):
            movetext_font = conf.get("movetextFont", "FreeSerif Regular 12")
            self.black_renderer.set_property("font", movetext_font)
            self.white_renderer.set_property("font", movetext_font)
            self.shownChanged(self.boardview, self.boardview.shown)

        self.cids_conf = []
        self.cids_conf.append(conf.notify_add("movetextFont", font_changed))
        self.cids_conf.append(conf.notify_add("figuresInNotation", figuresInNotationCallback))

        return scrollwin
Example #43
0
    def load (self, gmwidg):
        self.boardcontrol = gmwidg.board
        self.boardview = self.boardcontrol.view
        
        widgets = Gtk.Builder()
        widgets.add_from_file(addDataPrefix("sidepanel/book.glade"))
        self.tv = widgets.get_object("treeview")
        self.sw = widgets.get_object("scrolledwindow")
        self.sw.unparent()
        self.store = Gtk.TreeStore(GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT, int, bool, str, bool, bool)
        self.tv.set_model(self.store)
        
        ### move suggested
        moveRenderer = Gtk.CellRendererText()
        moveRenderer.set_property("xalign", 1.0)
        moveRenderer.set_property("yalign", 0)
        c0 = Gtk.TreeViewColumn("Move", moveRenderer)

        def getMoveText(column, cell, store, iter, data):
            board, move, pv = store[iter][0]
            if not move:
                cell.set_property("text", "")
            else:
                if conf.get("figuresInNotation", False):
                    cell.set_property("text", toFAN(board, move))
                else:
                    cell.set_property("text", toSAN(board, move, True))
        c0.set_cell_data_func(moveRenderer, getMoveText)

        ### strength of the move       
        c1 = Gtk.TreeViewColumn("Strength", StrengthCellRenderer(), data=1)       

        ### multipv (number of analysis lines)
        multipvRenderer = Gtk.CellRendererSpin()
        adjustment = Gtk.Adjustment(value=conf.get("multipv", 1), lower=1, upper=9, step_incr=1)
        multipvRenderer.set_property("adjustment", adjustment)
        multipvRenderer.set_property("editable", True)
        multipvRenderer.set_property("width_chars", 1)
        c2 = Gtk.TreeViewColumn("PV", multipvRenderer, editable=3)
        c2.set_property("min_width", 80)

        def spin_visible(column, cell, store, iter, data):           
            if store[iter][2] == 0:
                cell.set_property('visible', False)
            else:
                cell.set_property("text", str(store[iter][2]))
                cell.set_property('visible', True)
        c2.set_cell_data_func(multipvRenderer, spin_visible)

        def multipv_edited(renderer, path, text):
            iter = self.store.get_iter(path)
            self.store.set_value(iter, 2, int(text))
            self.advisors[int(path[0])].multipv_edited(int(text))
        multipvRenderer.connect('edited', multipv_edited)

        ### start/stop button for analysis engines
        toggleRenderer = CellRendererPixbufXt()
        toggleRenderer.set_property("stock-id", "gtk-add")
        c4 = Gtk.TreeViewColumn("StartStop", toggleRenderer)

        def cb_visible(column, cell, store, iter, data):
            if not store[iter][6]:
                cell.set_property('visible', False)
            else:
                cell.set_property('visible', True)
            
            if store[iter][5]:
                cell.set_property("stock-id", "gtk-add")
            else:
                cell.set_property("stock-id", "gtk-remove")
        c4.set_cell_data_func(toggleRenderer, cb_visible)

        def toggled_cb(cell, path):
            self.store[path][5] = not self.store[path][5]
            self.advisors[int(path[0])].start_stop(self.store[path][5])
        toggleRenderer.connect('clicked', toggled_cb)

        self.tv.append_column(c4)
        self.tv.append_column(c0)
        self.tv.append_column(c1)
        self.tv.append_column(c2)
        ### header text, or analysis line
        uistuff.appendAutowrapColumn(self.tv, "Details", text=4)
        
        self.boardview.connect("shown_changed", self.shown_changed)
        self.tv.connect("cursor_changed", self.selection_changed)
        self.tv.connect("select_cursor_row", self.selection_changed)
        self.tv.connect("row-activated", self.row_activated)
        self.tv.connect("query-tooltip", self.query_tooltip)
        
        self.tv.props.has_tooltip = True
        self.tv.set_property("show-expanders", False)
        
        self.advisors = []

        if conf.get("opening_check", 0):
            self.advisors.append(OpeningAdvisor(self.store, self.tv))
        if conf.get("endgame_check", 0):
            advisor = EndgameAdvisor(self.store, self.tv, self.boardview)
            self.advisors.append(advisor)
            gmwidg.connect("closed", advisor.gamewidget_closed)
            
        gmwidg.gamemodel.connect("analyzer_added", self.on_analyzer_added)
        gmwidg.gamemodel.connect("analyzer_removed", self.on_analyzer_removed)
        gmwidg.gamemodel.connect("analyzer_paused", self.on_analyzer_paused)
        gmwidg.gamemodel.connect("analyzer_resumed", self.on_analyzer_resumed)
        
        def on_opening_check(none):
            if conf.get("opening_check", 0):
                advisor = OpeningAdvisor(self.store, self.tv)
                self.advisors.append(advisor)
                advisor.shown_changed(self.boardview, self.boardview.shown)
            else:
                for advisor in self.advisors:
                    if advisor.mode == OPENING:
                        parent = advisor.empty_parent()
                        self.store.remove(parent)
                        self.advisors.remove(advisor)
        conf.notify_add("opening_check", on_opening_check)

        def on_opening_file_entry_changed(none):
            default_path = os.path.join(addDataPrefix("pychess_book.bin"))
            path = conf.get("opening_file_entry", default_path) 
            if os.path.isfile(path):
                for advisor in self.advisors:
                    if advisor.mode == OPENING:
                        advisor.shown_changed(self.boardview, self.boardview.shown)
        conf.notify_add("opening_file_entry", on_opening_file_entry_changed)

        def on_endgame_check(none):
            if conf.get("endgame_check", 0):
                advisor = EndgameAdvisor(self.store, self.tv, self.boardview)
                self.advisors.append(advisor)
                advisor.shown_changed(self.boardview, self.boardview.shown)
                gmwidg.connect("closed", advisor.gamewidget_closed)
            else:
                for advisor in self.advisors:
                    if advisor.mode == ENDGAME:
                        advisor.gamewidget_closed(gmwidg)
                        parent = advisor.empty_parent()
                        self.store.remove(parent)
                        self.advisors.remove(advisor)
        conf.notify_add("endgame_check", on_endgame_check)

        return self.sw
Example #44
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)
    def load(self, gmwidg):

        self.gamemodel = gmwidg.board.view.model
        self.model_cids = [
            self.gamemodel.connect_after("game_changed", self.game_changed),
            self.gamemodel.connect_after("game_started", self.game_started),
            self.gamemodel.connect_after("moves_undone", self.moves_undone),
            self.gamemodel.connect_after("game_terminated",
                                         self.on_game_terminated),
        ]

        self.tv = Gtk.TreeView()
        self.tv.set_headers_visible(False)
        self.tv.set_grid_lines(True)
        self.tv.set_activate_on_single_click(True)
        self.tv.get_selection().set_mode(Gtk.SelectionMode.NONE)
        self.activated_cell = (None, None)

        def is_row_separator(treemodel, treeiter):
            mvcount, wmove, bmove, row, wbg, bbg = self.store[treeiter]
            return row == 0

        self.tv.set_row_separator_func(is_row_separator)

        self.tv.connect("style-updated", self.on_style_updated)
        movetext_font = conf.get("movetextFont")

        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("mvcount", renderer, text=0)
        column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
        self.tv.append_column(column)

        self.white_renderer = Gtk.CellRendererText()
        self.white_renderer.set_property("xalign", 1)
        self.white_renderer.set_property("font", movetext_font)
        self.white_column = Gtk.TreeViewColumn("white",
                                               self.white_renderer,
                                               text=1,
                                               background=4)
        self.white_column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
        self.tv.append_column(self.white_column)

        self.black_renderer = Gtk.CellRendererText()
        self.black_renderer.set_property("xalign", 1)
        self.black_renderer.set_property("font", movetext_font)
        self.black_column = Gtk.TreeViewColumn("black",
                                               self.black_renderer,
                                               text=2,
                                               background=5)
        self.black_column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
        self.tv.append_column(self.black_column)

        # To prevent black moves column expand to the right we add a dummy column finally
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("dummy", renderer)
        self.tv.append_column(column)

        scrollwin = Gtk.ScrolledWindow()
        scrollwin.add(self.tv)

        # Our liststore elements will be:
        # mvcount, white move, black move, row number, white move background, black move background
        self.store = Gtk.ListStore(str, str, str, int, str, str)
        self.tv.set_model(self.store)
        self.tv_cid = self.tv.connect("row_activated", self.on_row_activated)

        self.boardview = gmwidg.board.view
        self.cid = self.boardview.connect("shownChanged", self.shownChanged)
        scrollwin.show_all()

        self.figuresInNotation = conf.get("figuresInNotation")

        def figuresInNotationCallback(none):
            game = self.boardview.model
            if game.lesson_game:
                return

            self.figuresInNotation = conf.get("figuresInNotation")

            for i, move in enumerate(game.moves):
                board = game.variations[0][i]
                ply = game.lowply + i + 1
                if conf.get("figuresInNotation"):
                    notat = toFAN(board, move)
                else:
                    notat = toSAN(board, move, True)

                row, column = self.ply_to_row_col(ply)

                col = 2 if column == self.black_column else 1
                treeiter = self.store.get_iter(Gtk.TreePath(row))
                self.store.set_value(treeiter, col, notat)

        def font_changed(none):
            movetext_font = conf.get("movetextFont")
            self.black_renderer.set_property("font", movetext_font)
            self.white_renderer.set_property("font", movetext_font)
            self.shownChanged(self.boardview, self.boardview.shown)

        self.cids_conf = []
        self.cids_conf.append(conf.notify_add("movetextFont", font_changed))
        self.cids_conf.append(
            conf.notify_add("figuresInNotation", figuresInNotationCallback))

        return scrollwin
Example #46
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)
Example #47
0
    def load(self, gmwidg):

        widgets = Gtk.Builder()
        widgets.add_from_file(addDataPrefix("sidepanel/history.glade"))
        __widget__ = widgets.get_object("panel")
        __widget__.unparent()

        self.boardview = gmwidg.board.view

        glock_connect(self.boardview.model, "game_changed", self.game_changed)
        glock_connect(self.boardview.model, "game_started", self.game_changed)
        glock_connect(self.boardview.model, "moves_undoing",
                      self.moves_undoing)
        self.boardview.connect("shown_changed", self.shown_changed)

        # Initialize treeviews

        self.numbers = widgets.get_object("treeview1")
        self.left = widgets.get_object("treeview2")
        self.right = widgets.get_object("treeview3")

        def fixList(list, xalign=0):
            list.set_model(Gtk.ListStore(str))
            renderer = Gtk.CellRendererText()
            renderer.set_property("xalign", xalign)
            list.append_column(Gtk.TreeViewColumn(None, renderer, text=0))
            list.get_selection().set_mode(Gtk.SelectionMode.SINGLE)

        fixList(self.numbers, 1)
        fixList(self.left, 0)
        fixList(self.right, 0)

        self.left.get_selection().connect('changed', self.on_selection_changed,
                                          self.left, 0)
        self.right.get_selection().connect('changed',
                                           self.on_selection_changed,
                                           self.right, 1)

        # Lock scrolling

        scrollwin = widgets.get_object("panel")

        def changed(vadjust):
            if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
                vadjust.set_value(vadjust.get_upper() -
                                  vadjust.get_page_size())
                vadjust.need_scroll = True

        scrollwin.get_vadjustment().connect("changed", changed)

        def value_changed(vadjust):
            vadjust.need_scroll = abs(vadjust.get_value() + vadjust.get_page_size() - \
                        vadjust.get_upper()) < vadjust.get_step_increment()

        scrollwin.get_vadjustment().connect("value-changed", value_changed)

        # Connect to preferences

        def figuresInNotationCallback(none):
            game = self.boardview.model
            for board, move in zip(game.variations[0], game.moves):
                if conf.get("figuresInNotation", False):
                    notat = toFAN(board, move)
                else:
                    notat = toSAN(board, move, True)
                row, col, other = self._ply_to_row_col_other(board.ply + 1)
                iter = col.get_model().get_iter((row, ))
                col.get_model().set(iter, 0, notat)

        conf.notify_add("figuresInNotation", figuresInNotationCallback)

        # Return

        return __widget__
Example #48
0
    def init_layout(self):
        perspective_widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        perspective_manager.set_perspective_widget("games", perspective_widget)

        self.notebooks = {"board": new_notebook("board"),
                          "buttons": new_notebook("buttons"),
                          "messageArea": new_notebook("messageArea")}
        self.main_notebook = self.notebooks["board"]
        for panel in self.sidePanels:
            self.notebooks[panel.__name__] = new_notebook(panel.__name__)

        # Initing headbook

        align = gamewidget.createAlignment(4, 4, 0, 4)
        align.set_property("yscale", 0)

        headbook = Gtk.Notebook()
        headbook.set_name("headbook")
        headbook.set_scrollable(True)
        align.add(headbook)
        perspective_widget.pack_start(align, False, True, 0)
        self.show_tabs(not conf.get("hideTabs", False))

        # Initing center

        centerVBox = Gtk.VBox()

        # The dock

        self.dock = PyDockTop("main", self)
        self.dockAlign = gamewidget.createAlignment(4, 4, 0, 4)
        self.dockAlign.add(self.dock)
        centerVBox.pack_start(self.dockAlign, True, True, 0)
        self.dockAlign.show()
        self.dock.show()

        self.docks["board"] = (Gtk.Label(label="Board"), self.notebooks["board"], None)
        for panel in self.sidePanels:
            self.docks[panel.__name__][1] = self.notebooks[panel.__name__]

        self.load_from_xml()

        # Default layout of side panels
        if not os.path.isfile(self.dockLocation):
            leaf = self.dock.dock(self.docks["board"][1],
                                  CENTER,
                                  Gtk.Label(label=self.docks["board"][0]),
                                  "board")
            self.docks["board"][1].show_all()
            leaf.setDockable(False)

            # S
            epanel = leaf.dock(self.docks["bookPanel"][1], SOUTH, self.docks["bookPanel"][0],
                               "bookPanel")
            epanel.default_item_height = 45
            epanel = epanel.dock(self.docks["engineOutputPanel"][1], CENTER,
                                 self.docks["engineOutputPanel"][0],
                                 "engineOutputPanel")

            # NE
            leaf = leaf.dock(self.docks["annotationPanel"][1], EAST,
                             self.docks["annotationPanel"][0], "annotationPanel")
            leaf = leaf.dock(self.docks["historyPanel"][1], CENTER,
                             self.docks["historyPanel"][0], "historyPanel")
            leaf = leaf.dock(self.docks["scorePanel"][1], CENTER,
                             self.docks["scorePanel"][0], "scorePanel")

            # SE
            leaf = leaf.dock(self.docks["chatPanel"][1], SOUTH, self.docks["chatPanel"][0],
                             "chatPanel")
            leaf = leaf.dock(self.docks["commentPanel"][1], CENTER,
                             self.docks["commentPanel"][0], "commentPanel")

        def unrealize(dock, notebooks):
            # unhide the panel before saving so its configuration is saved correctly
            self.notebooks["board"].get_parent().get_parent().zoomDown()
            dock.saveToXML(self.dockLocation)
            dock._del()

        self.dock.connect("unrealize", unrealize, self.notebooks)

        hbox = Gtk.HBox()

        # Buttons
        self.notebooks["buttons"].set_border_width(4)
        hbox.pack_start(self.notebooks["buttons"], False, True, 0)

        # The message area
        # TODO: If you try to fix this first read issue #958 and 1018
        align = gamewidget.createAlignment(0, 0, 0, 0)
        # sw = Gtk.ScrolledWindow()
        # port = Gtk.Viewport()
        # port.add(self.notebooks["messageArea"])
        # sw.add(port)
        # align.add(sw)
        align.add(self.notebooks["messageArea"])
        hbox.pack_start(align, True, True, 0)

        def ma_switch_page(notebook, gpointer, page_num):
            notebook.props.visible = notebook.get_nth_page(page_num).\
                get_child().props.visible

        self.notebooks["messageArea"].connect("switch-page", ma_switch_page)
        centerVBox.pack_start(hbox, False, True, 0)

        perspective_widget.pack_start(centerVBox, True, True, 0)
        centerVBox.show_all()
        perspective_widget.show_all()

        perspective_manager.set_perspective_menuitems("games", self.menuitems)

        conf.notify_add("hideTabs", self.tabsCallback)

        # Connecting headbook to other notebooks

        def hb_switch_page(notebook, gpointer, page_num):
            for notebook in self.notebooks.values():
                notebook.set_current_page(page_num)

            gmwidg = self.key2gmwidg[self.getheadbook().get_nth_page(page_num)]
            if isinstance(gmwidg.gamemodel, ICGameModel):
                primary = "primary " + str(gmwidg.gamemodel.ficsgame.gameno)
                gmwidg.gamemodel.connection.client.run_command(primary)

        headbook.connect("switch-page", hb_switch_page)

        if hasattr(headbook, "set_tab_reorderable"):

            def page_reordered(widget, child, new_num, headbook):
                old_num = self.notebooks["board"].page_num(self.key2gmwidg[child].boardvbox)
                if old_num == -1:
                    log.error('Games and labels are out of sync!')
                else:
                    for notebook in self.notebooks.values():
                        notebook.reorder_child(
                            notebook.get_nth_page(old_num), new_num)

            headbook.connect("page-reordered", page_reordered, headbook)
Example #49
0
    def init_layout(self):
        perspective_widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        perspective_manager.set_perspective_widget("games", perspective_widget)

        self.notebooks = {"board": cleanNotebook("board"),
                          "buttons": cleanNotebook("buttons"),
                          "messageArea": cleanNotebook("messageArea")}
        for panel in sidePanels:
            self.notebooks[panel.__name__] = cleanNotebook(panel.__name__)

        # Initing headbook

        align = gamewidget.createAlignment(4, 4, 0, 4)
        align.set_property("yscale", 0)

        headbook = Gtk.Notebook()
        headbook.set_name("headbook")
        headbook.set_scrollable(True)
        align.add(headbook)
        perspective_widget.pack_start(align, False, True, 0)
        self.show_tabs(not conf.get("hideTabs", False))

        # Initing center

        centerVBox = Gtk.VBox()

        # The dock

        self.dock = PyDockTop("main", self)
        self.dockAlign = gamewidget.createAlignment(4, 4, 0, 4)
        self.dockAlign.add(self.dock)
        centerVBox.pack_start(self.dockAlign, True, True, 0)
        self.dockAlign.show()
        self.dock.show()

        self.docks = {"board": (Gtk.Label(label="Board"), self.notebooks["board"])}
        for panel in sidePanels:
            box = dock_panel_tab(panel.__title__, panel.__desc__, panel.__icon__)
            self.docks[panel.__name__] = (box, self.notebooks[panel.__name__])

        if os.path.isfile(dockLocation):
            try:
                self.dock.loadFromXML(dockLocation, self.docks)
            except Exception as e:
                stringio = StringIO()
                traceback.print_exc(file=stringio)
                error = stringio.getvalue()
                log.error("Dock loading error: %s\n%s" % (e, error))
                msg_dia = Gtk.MessageDialog(mainwindow(),
                                            type=Gtk.MessageType.ERROR,
                                            buttons=Gtk.ButtonsType.CLOSE)
                msg_dia.set_markup(_(
                    "<b><big>PyChess was unable to load your panel settings</big></b>"))
                msg_dia.format_secondary_text(_(
                    "Your panel settings have been reset. If this problem repeats, \
                    you should report it to the developers"))
                msg_dia.run()
                msg_dia.hide()
                os.remove(dockLocation)
                for title, panel in self.docks.values():
                    title.unparent()
                    panel.unparent()

        if not os.path.isfile(dockLocation):
            leaf = self.dock.dock(self.docks["board"][1],
                                  CENTER,
                                  Gtk.Label(label=self.docks["board"][0]),
                                  "board")
            self.docks["board"][1].show_all()
            leaf.setDockable(False)

            # S
            epanel = leaf.dock(self.docks["bookPanel"][1], SOUTH, self.docks["bookPanel"][0],
                               "bookPanel")
            epanel.default_item_height = 45
            epanel = epanel.dock(self.docks["engineOutputPanel"][1], CENTER,
                                 self.docks["engineOutputPanel"][0],
                                 "engineOutputPanel")

            # NE
            leaf = leaf.dock(self.docks["annotationPanel"][1], EAST,
                             self.docks["annotationPanel"][0], "annotationPanel")
            leaf = leaf.dock(self.docks["historyPanel"][1], CENTER,
                             self.docks["historyPanel"][0], "historyPanel")
            leaf = leaf.dock(self.docks["scorePanel"][1], CENTER,
                             self.docks["scorePanel"][0], "scorePanel")

            # SE
            leaf = leaf.dock(self.docks["chatPanel"][1], SOUTH, self.docks["chatPanel"][0],
                             "chatPanel")
            leaf = leaf.dock(self.docks["commentPanel"][1], CENTER,
                             self.docks["commentPanel"][0], "commentPanel")

        def unrealize(dock, notebooks):
            # unhide the panel before saving so its configuration is saved correctly
            self.notebooks["board"].get_parent().get_parent().zoomDown()
            dock.saveToXML(dockLocation)
            dock._del()

        self.dock.connect("unrealize", unrealize, self.notebooks)

        hbox = Gtk.HBox()

        # Buttons
        self.notebooks["buttons"].set_border_width(4)
        hbox.pack_start(self.notebooks["buttons"], False, True, 0)

        # The message area
        # TODO: If you try to fix this first read issue #958 and 1018
        align = gamewidget.createAlignment(0, 0, 0, 0)
        # sw = Gtk.ScrolledWindow()
        # port = Gtk.Viewport()
        # port.add(self.notebooks["messageArea"])
        # sw.add(port)
        # align.add(sw)
        align.add(self.notebooks["messageArea"])
        hbox.pack_start(align, True, True, 0)

        def ma_switch_page(notebook, gpointer, page_num):
            notebook.props.visible = notebook.get_nth_page(page_num).\
                get_child().props.visible

        self.notebooks["messageArea"].connect("switch-page", ma_switch_page)
        centerVBox.pack_start(hbox, False, True, 0)

        perspective_widget.pack_start(centerVBox, True, True, 0)
        centerVBox.show_all()
        perspective_widget.show_all()

        conf.notify_add("hideTabs", self.tabsCallback)

        # Connecting headbook to other notebooks

        def hb_switch_page(notebook, gpointer, page_num):
            for notebook in self.notebooks.values():
                notebook.set_current_page(page_num)

            gmwidg = self.key2gmwidg[self.getheadbook().get_nth_page(page_num)]
            if isinstance(gmwidg.gamemodel, ICGameModel):
                primary = "primary " + str(gmwidg.gamemodel.ficsgame.gameno)
                gmwidg.gamemodel.connection.client.run_command(primary)

        headbook.connect("switch-page", hb_switch_page)

        if hasattr(headbook, "set_tab_reorderable"):

            def page_reordered(widget, child, new_num, headbook):
                old_num = self.notebooks["board"].page_num(self.key2gmwidg[child].boardvbox)
                if old_num == -1:
                    log.error('Games and labels are out of sync!')
                else:
                    for notebook in self.notebooks.values():
                        notebook.reorder_child(
                            notebook.get_nth_page(old_num), new_num)

            headbook.connect("page-reordered", page_reordered, headbook)
Example #50
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)
Example #51
0
 def load (self, gmwidg):
     
     widgets = Gtk.Builder()
     widgets.add_from_file(addDataPrefix("sidepanel/history.glade"))
     __widget__ = widgets.get_object("panel")
     __widget__.unparent()
     
     self.boardview = gmwidg.board.view
     
     self.boardview.model.connect_after("game_changed", self.game_changed)
     self.boardview.model.connect_after("game_started", self.game_started)
     self.boardview.model.connect_after("moves_undoing", self.moves_undoing)
     self.boardview.connect("shown_changed", self.shown_changed)
     
     # Initialize treeviews
     
     self.numbers = widgets.get_object("treeview1")
     self.left = widgets.get_object("treeview2")
     self.right = widgets.get_object("treeview3")
     
     def fixList (list, xalign=0):
         list.set_model(Gtk.ListStore(str))
         renderer = Gtk.CellRendererText()
         renderer.set_property("xalign",xalign)
         list.append_column(Gtk.TreeViewColumn(None, renderer, text=0))
         list.get_selection().set_mode(Gtk.SelectionMode.SINGLE)
     
     fixList(self.numbers, 1)
     fixList(self.left, 0)
     fixList(self.right, 0)
     
     self.left.get_selection().connect('changed', self.on_selection_changed,
                                       self.left, 0)
     self.right.get_selection().connect('changed', self.on_selection_changed,
                                        self.right, 1)
     
     # Lock scrolling
     
     scrollwin = widgets.get_object("panel")
     
     def changed (vadjust):
         if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
             vadjust.set_value(vadjust.get_upper()-vadjust.get_page_size())                
             vadjust.need_scroll = True
     scrollwin.get_vadjustment().connect("changed", changed)
     
     def value_changed (vadjust):
         vadjust.need_scroll = abs(vadjust.get_value() + vadjust.get_page_size() - \
                     vadjust.get_upper()) < vadjust.get_step_increment()
     scrollwin.get_vadjustment().connect("value-changed", value_changed)
     
     # Connect to preferences
     
     def figuresInNotationCallback (none):
         game = self.boardview.model
         for board, move in zip(game.variations[0], game.moves):
             if conf.get("figuresInNotation", False):
                 notat = toFAN(board, move)
             else: notat = toSAN(board, move, True)
             row, col, other = self._ply_to_row_col_other(board.ply+1)
             iter = col.get_model().get_iter((row,))
             col.get_model().set(iter, 0, notat)
     conf.notify_add("figuresInNotation", figuresInNotationCallback)
     
     # Return
     
     return __widget__
    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)
Example #53
0
    def load(self, gmwidg):
        __widget__ = Gtk.ScrolledWindow()
        __widget__.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)

        self.numbers = Gtk.TreeView()
        self.numbers.set_property("can_focus", False)
        self.numbers.set_property("sensitive", False)
        self.numbers.set_property("width_request", 35)
        self.left = Gtk.TreeView()
        self.numbers.set_property("width_request", 60)
        self.right = Gtk.TreeView()
        self.numbers.set_property("width_request", 60)

        box = Gtk.Box(spacing=0)
        box.pack_start(self.numbers, False, True, 0)
        box.pack_start(self.left, True, True, 0)
        box.pack_start(self.right, True, True, 0)

        port = Gtk.Viewport()
        port.add(box)
        port.set_shadow_type(Gtk.ShadowType.NONE)

        __widget__.add(port)
        __widget__.show_all()

        self.cids = {}
        self.boardview = gmwidg.board.view

        self.model_cids = [
            self.boardview.model.connect_after("game_changed", self.game_changed),
            self.boardview.model.connect_after("game_started", self.game_started),
            self.boardview.model.connect_after("moves_undone", self.moves_undone),
            self.boardview.model.connect_after("game_terminated", self.on_game_terminated),
        ]
        self.cids[self.boardview] = self.boardview.connect("shownChanged", self.shownChanged)

        # Initialize treeviews

        def fixList(list, xalign=0):
            list.set_property("headers_visible", False)
            list.set_property("rules_hint", True)
            list.set_model(Gtk.ListStore(str))
            renderer = Gtk.CellRendererText()
            renderer.set_property("xalign", xalign)
            list.append_column(Gtk.TreeViewColumn(None, renderer, text=0))
            list.get_selection().set_mode(Gtk.SelectionMode.SINGLE)

        fixList(self.numbers, 1)
        fixList(self.left, 0)
        fixList(self.right, 0)

        self.cids[self.left] = self.left.connect('cursor_changed', self.cursorChanged, self.left, 0)
        self.cids[self.right] = self.right.connect('cursor_changed', self.cursorChanged, self.right, 1)

        # Lock scrolling

        self.adjustment = __widget__.get_vadjustment()

        def changed(vadjust):
            if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
                vadjust.set_value(vadjust.get_upper() - vadjust.get_page_size(
                ))
                vadjust.need_scroll = True

        self.adj_cid1 = self.adjustment.connect("changed", changed)

        def value_changed(vadjust):
            vadjust.need_scroll = abs(vadjust.get_value() + vadjust.get_page_size() -
                                      vadjust.get_upper()) < vadjust.get_step_increment()

        self.adj_cid2 = self.adjustment.connect("value-changed", value_changed)

        # Connect to preferences

        def figuresInNotationCallback(none):
            game = self.boardview.model
            for board, move in zip(game.variations[0], game.moves):
                if conf.get("figuresInNotation", False):
                    notat = toFAN(board, move)
                else:
                    notat = toSAN(board, move, True)
                row, col, other = self._ply_to_row_col_other(board.ply + 1)
                iter = col.get_model().get_iter((row, ))
                col.get_model().set(iter, 0, notat)

        self.conf_conid = conf.notify_add("figuresInNotation", figuresInNotationCallback)

        # Return

        return __widget__