Example #1
0
    def shownChanged(self, boardview, shown):
        if boardview.model is None:
            return
        boardview.bluearrow = None

        if legalMoveCount(boardview.model.getBoardAtPly(
                shown, boardview.shown_variation_idx)) == 0:
            if self.sw.get_child() == self.tv:
                self.sw.remove(self.tv)
                label = Gtk.Label(_(
                    "In this position,\nthere is no legal move."))
                label.set_property("yalign", 0.1)
                self.sw.add_with_viewport(label)
                self.sw.get_child().set_shadow_type(Gtk.ShadowType.NONE)
                self.sw.show_all()
            return

        for advisor in self.advisors:
            advisor.shownChanged(boardview, shown)
        self.tv.expand_all()

        if self.sw.get_child() != self.tv:
            log.warning("bookPanel.Sidepanel.shownChanged: get_child() != tv")
            self.sw.remove(self.sw.get_child())
            self.sw.add(self.tv)
Example #2
0
    def __clean(self, rundata, engine):
        """ Grab the engine from the backup and attach the attributes
            from rundata. The update engine is ready for discovering.
        """

        vmpath, path = rundata

        md5sum = md5_sum(path)

        ######
        # Find the backup engine
        ######
        try:
            backup_engine = next((
                c for c in backup if c["name"] == engine["name"]))
            engine["country"] = backup_engine["country"]
        except StopIteration:
            log.warning(
                "Engine '%s' is not in PyChess predefined known engines list" % engine.get('name'))
            engine['recheck'] = True

        ######
        # Clean it
        ######
        engine['command'] = path
        engine['md5'] = md5sum
        if vmpath is not None:
            engine['vm_command'] = vmpath
        if "variants" in engine:
            del engine["variants"]
        if "options" in engine:
            del engine["options"]
Example #3
0
    def __startBlocking(self, event):
        if self.protover == 1:
            self.emit("readyForMoves")
            return_value = "ready"

        if self.protover == 2:
            try:
                return_value = yield from asyncio.wait_for(self.queue.get(), TIME_OUT_SECOND)
                if return_value == "not ready":
                    return_value = yield from asyncio.wait_for(self.queue.get(), TIME_OUT_SECOND)
                    # Gaviota sends done=0 after "xboard" and after "protover 2" too
                    if return_value == "not ready":
                        return_value = yield from asyncio.wait_for(self.queue.get(), TIME_OUT_SECOND)
                self.emit("readyForOptions")
                self.emit("readyForMoves")
            except asyncio.TimeoutError:
                log.warning("Got timeout error", extra={"task": self.defname})
                raise PlayerIsDead
            except:
                log.warning("Unknown error", extra={"task": self.defname})
                raise PlayerIsDead
            else:
                if return_value == "die":
                    raise PlayerIsDead
                assert return_value == "ready" or return_value == "del"

        if event is not None:
            event.set()
    def scoreAllMoves(self, board):
        result, depth = self.scoreGame(board, False, False)
        if result is None:
            return []

        scores = []
        gen = board.isChecked() and genCheckEvasions or genAllMoves
        for move in gen(board):
            board.applyMove(move)
            if not board.opIsChecked():
                result, depth = self.scoreGame(board, False, False)
                if result is None:
                    log.warning("An EGTB file does not have all its dependencies")
                    board.popMove()
                    return []
                scores.append((move, result, depth))
            board.popMove()

        def mateScore(mrd):
            if mrd[1] == DRAW:
                return 0
            absScore = 32767 - mrd[2]
            if (board.color == WHITE) ^ (mrd[1] == WHITEWON):
                return absScore
            return -absScore

        scores.sort(key=mateScore)
        return scores
Example #5
0
 def _del(self):
     self.egtb.disconnect(self.cid)
     try:
         self.queue.put_nowait(self.StopNow)
     except asyncio.QueueFull:
         log.warning("EndgameAdvisor.gamewidget_closed: Queue.Full")
     self.egtb_task.cancel()
Example #6
0
    def kill(self, reason):
        """ Kills the engine, starting with the 'quit' command, then sigterm and
            eventually sigkill.
            Returns the exitcode, or if engine have already been killed, returns
            None """
        if self.connected:
            self.connected = False
            try:
                try:
                    print("quit", file=self.engine)
                    self.queue.put_nowait("del")
                    self.engine.terminate()

                except OSError as err:
                    # No need to raise on a hang up error, as the engine is dead
                    # anyways
                    if err.errno == 32:
                        log.warning("Hung up Error", extra={"task": self.defname})
                        return err.errno
                    else:
                        raise

            finally:
                # Clear the analyzed data, if any
                self.emit("analyze", [])
Example #7
0
    def __clean(self, rundata, engine):
        """ Grab the engine from the backup and attach the attributes
            from rundata. The update engine is ready for discovering.
        """

        vmpath, path = rundata

        md5sum = md5_sum(path)

        ######
        # Find the backup engine
        ######
        try:
            backup_engine = next((c for c in backup if c["name"] == engine["name"]))
            engine["country"] = backup_engine["country"]
        except StopIteration:
            log.warning("Engine '%s' has not been tested and verified to work with PyChess" % engine.get("name"))
            engine["recheck"] = True

        ######
        # Clean it
        ######
        engine["command"] = path
        engine["md5"] = md5sum
        if vmpath is not None:
            engine["vm_command"] = vmpath
        if "variants" in engine:
            del engine["variants"]
        if "options" in engine:
            del engine["options"]
Example #8
0
    def onGameStarted(self, gamemodel):
        if gamemodel.examined:
            if gamemodel.players[0].name == gamemodel.connection.username:
                self.player = gamemodel.players[0]
                self.opplayer = gamemodel.players[1]
            else:
                self.player = gamemodel.players[1]
                self.opplayer = gamemodel.players[0]
        elif gamemodel.isObservationGame():
            # no local player but enable chat to send/receive whisper/kibitz
            pass
        elif gamemodel.players[0].__type__ == LOCAL:
            self.player = gamemodel.players[0]
            self.opplayer = gamemodel.players[1]
            if gamemodel.players[1].__type__ == LOCAL:
                log.warning("Chatpanel loaded with two local players")
        elif gamemodel.players[1].__type__ == LOCAL:
            self.player = gamemodel.players[1]
            self.opplayer = gamemodel.players[0]
        else:
            log.info("Chatpanel loaded with no local players")
            self.chatView.hide()

        if isinstance(gamemodel, ICGameModel):
            if gamemodel.connection.ICC:
                gamemodel.connection.client.run_command("set-2 %s 1" % DG_PLAYERS_IN_MY_GAME)
            else:
                allob = 'allob ' + str(gamemodel.ficsgame.gameno)
                gamemodel.connection.client.run_command(allob)

        if hasattr(self, "player") and not gamemodel.examined and self.player_cid is None:
            self.player_cid = self.player.connect("messageReceived", self.onMessageRecieved)

        self.chatView.enable()
Example #9
0
 def on_drag_received (self, wi, context, x, y, selection, target_type, timestamp):
     uri = selection.data.strip()
     uris = uri.split()
     if len(uris) > 1:
         log.warning("%d files were dropped. Only loading the first" % len(uris))
     uri = uris[0]
     newGameDialog.LoadFileExtension.run(uri)
Example #10
0
 def onOfferAdd (self, match):
     log.debug("OfferManager.onOfferAdd: match.string=%s" % match.string)
     tofrom, index, offertype, parameters = match.groups()
     index = int(index)
     
     if tofrom == "t":
         # ICGameModel keeps track of the offers we've sent ourselves, so we
         # don't need this
         return
     if offertype not in strToOfferType:
         log.warning("OfferManager.onOfferAdd: Declining unknown offer type: " + \
             "offertype=%s parameters=%s index=%d" % (offertype, parameters, index))
         self.connection.client.run_command("decline %d" % index)
     offertype = strToOfferType[offertype]
     if offertype == TAKEBACK_OFFER:
         offer = Offer(offertype, param=int(parameters), index=index)
     else:
         offer = Offer(offertype, index=index)
     self.offers[offer.index] = offer
     
     if offer.type == MATCH_OFFER:
         is_adjourned = False
         if matchreUntimed.match(parameters) != None:
             fname, frating, col, tname, trating, rated, type = \
                 matchreUntimed.match(parameters).groups()
             mins = 0
             incr = 0
             gametype = GAME_TYPES["untimed"]
         else:
             fname, frating, col, tname, trating, rated, gametype, mins, \
                 incr, wildtype, adjourned = matchre.match(parameters).groups()
             if (wildtype and "adjourned" in wildtype) or \
                     (adjourned and "adjourned" in adjourned):
                 is_adjourned = True
             if wildtype and "wild" in wildtype:
                 gametype = wildtype
                 
             try:
                 gametype = GAME_TYPES[gametype]
             except KeyError:
                 log.warning("OfferManager.onOfferAdd: auto-declining " + \
                     "unknown offer type: '%s'\n" % gametype)
                 self.decline(offer)
                 del self.offers[offer.index]
                 return
         
         player = self.connection.players.get(FICSPlayer(fname))
         rating = frating.strip()
         rating = int(rating) if rating.isdigit() else 0
         if gametype.rating_type in player.ratings and \
                 player.ratings[gametype.rating_type].elo != rating:
             player.ratings[gametype.rating_type].elo = rating
         rated = rated != "unrated"
         challenge = FICSChallenge(index, player, int(mins), int(incr), rated, col,
                                   gametype, adjourned=is_adjourned)
         self.emit("onChallengeAdd", challenge)
     
     else:
         log.debug("OfferManager.onOfferAdd: emitting onOfferAdd: %s" % offer)
         self.emit("onOfferAdd", offer)
Example #11
0
def release():
    me = currentThread()
    # As it is the natural state for the MainThread to control the gdklock, we
    # only release it if _rlock has been released so many times that we don't
    # own it any more
    if me.getName() == "MainThread":
        if not has():
            _debug('glock.release', me, '-> threads_leave')
            Gdk.threads_leave()
            _debug('glock.release', me, '<- threads_leave')
        else:
            _debug('glock.release', me, '-> _rlock.release')
            _rlock.release()
            _debug('glock.release', me, '<- _rlock.release')
    # If this is the last unlock, we also free the gdklock.
    elif has():
        if rlock_count(_rlock) == 1:
            _debug('glock.release', me, '-> threads_leave')
            Gdk.threads_leave()
            _debug('glock.release', me, '<- threads_leave')
        _debug('glock.release', me, '-> _rlock.release')
        _rlock.release()
        _debug('glock.release', me, '<- _rlock.release')
    else:
        log.warning("Tried to release un-owned glock\n%s" %
                    "".join(traceback.format_stack()),
                    extra={"task": (me.ident, me.name, 'glock.release')})
 def _loadLibrary(self):
     libName = "libgaviotatb.so.1.0.1"
     try:
         self.libgtb = CDLL(libName)
     except OSError:
         log.warning("Failed to load Gaviota EGTB library %s" % libName)
         return None
     return self.libgtb
Example #13
0
 def draw(self, game):
     if not game.opponent.adjournment:
         log.warning("AdjournManager.draw: no adjourned game vs %s" %
                     game.opponent)
         return
     log.info("AdjournManager.draw: offering sdraw for adjourned game=%s" %
              game)
     self.connection.client.run_command("sdraw %s" % game.opponent.name)
Example #14
0
 def __setitem__(self, index, seek):
     if not isinstance(index, int): raise TypeError
     if not isinstance(seek, FICSSoughtMatch): raise TypeError
     if index in self:
         log.warning("FICSSeeks: not overwriting seek %s" % repr(seek))
         return
     self.seeks[index] = seek
     self.emit('FICSSeekCreated', seek)
Example #15
0
 def _loadLibrary(self):
     libName = "libgaviotatb.so.1.0.1"
     try:
         self.libgtb = CDLL(libName)
     except OSError:
         log.warning("Failed to load Gaviota EGTB library %s" % libName)
         return None
     return self.libgtb
Example #16
0
 def abort(self, game):
     if not game.opponent.adjournment:
         log.warning("AdjournManager.abort: no adjourned game vs %s" %
                     game.opponent)
         return
     log.info("AdjournManager.abort: offering sabort for adjourned game=%s"
              % game)
     self.connection.client.run_command("sabort %s" % game.opponent.name)
Example #17
0
 def resume(self, game):
     if not game.opponent.adjournment:
         log.warning("AdjournManager.resume: no adjourned game vs %s" %
                     game.opponent)
         return
     log.info("AdjournManager.resume: offering resume for adjourned game=%s"
              % game)
     self.connection.client.run_command("match %s" % game.opponent.name)
Example #18
0
 def onChannelLogLine (self, match):
     if not self.currentLogChannel:
         log.warning("Received log line before channel was set")
         return
     h, m, s, handle, text = match.groups()
     time = self.convTime(int(h), int(m), int(s))
     text = self.entityDecode(text)
     GLib.idle_add(self.emit, "channelLog", self.currentLogChannel, time, handle, text)
Example #19
0
 def resign (self, game):
     """ This is (and draw and abort) are possible even when one's
         opponent is not logged on """
     if not game.opponent.adjournment:
         log.warning("AdjournManager.resign: no adjourned game vs %s" % game.opponent)
         return
     log.info("AdjournManager.resign: resigning adjourned game=%s" % game)
     self.connection.client.run_command("resign %s" % game.opponent.name)
Example #20
0
 def __setitem__ (self, index, seek):
     if not isinstance(index, int): raise TypeError
     if not isinstance(seek, FICSSoughtMatch): raise TypeError
     if index in self:
         log.warning("FICSSeeks: not overwriting seek %s" % repr(seek))
         return
     self.seeks[index] = seek
     self.emit('FICSSeekCreated', seek)
Example #21
0
 def draw(self, game):
     if not game.opponent.adjournment:
         log.warning("AdjournManager.draw: no adjourned game vs %s" %
                     game.opponent)
         return
     log.info("AdjournManager.draw: offering sdraw for adjourned game=%s" %
              game)
     self.connection.client.run_command("sdraw %s" % game.opponent.name)
def loadDialogWidget(
    widget,
    widget_name,
    config_number,
    get_value_=None,
    set_value_=None,
    first_value=None,
):
    key = widget_name + "-" + str(config_number)

    if widget is None:
        raise AttributeError("key '%s' isn't in widgets" % widget_name)

    for class_, methods_ in METHODS:
        if isinstance(widget, class_):
            getter, setter, signal = methods_
            break
    else:
        if set_value_ is None:
            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)

    if conf.hasKey(key):
        try:
            v = conf.get(key)
        except TypeError:
            log.warning(
                "uistuff.loadDialogWidget: 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)
    elif first_value is not None:
        conf.set(key, first_value)
        set_value(conf.get(key))
    else:
        log.warning(
            'Didn\'t load widget "%s": no conf value and no first_value arg' %
            widget_name)
Example #23
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.jsonpath = addUserConfigPrefix("engines.json")
        self.engines = []
        try:
            with open(self.jsonpath) as fh:
                self.engines = json.load(fh)
        except ValueError as err:
            log.warning(
                "engineNest: Couldn\'t read engines.json, renamed it to .bak\n%s\n%s"
                % (self.jsonpath, err))
            os.rename(self.jsonpath, self.jsonpath + ".bak")
        except IOError as err:
            log.info(
                "engineNest: Couldn\'t open engines.json, creating a new.\n%s"
                % err)

        # Try to detect engines shipping .eng files on Linux (suggested by HGM on talkchess.com forum)
        for protocol in ("xboard", "uci"):
            for path in ("/usr/local/share/games/plugins",
                         "/usr/share/games/plugins"):
                path = os.path.join(path, protocol)
                if os.path.isdir(path):
                    for entry in os.listdir(path):
                        ext = os.path.splitext(entry)[1]
                        if ext == ".eng":
                            with open(os.path.join(path,
                                                   entry)) as file_handle:
                                plugin_spec = file_handle.readline().strip()
                                if not plugin_spec.startswith("plugin spec"):
                                    continue

                                engine_command = file_handle.readline().strip()
                                if self.getEngineByName(
                                        engine_command) is not None:
                                    continue

                                supported_variants = file_handle.readline(
                                ).strip()
                                if not supported_variants.startswith("chess"):
                                    continue

                                new_engine = {}
                                if engine_command.startswith(
                                        "cd "
                                ) and engine_command.find(";") > 0:
                                    parts = engine_command.split(";")
                                    working_directory = parts[0][3:]
                                    engine_command = parts[1]
                                    new_engine[
                                        "workingDirectory"] = working_directory

                                new_engine["protocol"] = protocol
                                new_engine["name"] = engine_command
                                self.engines.append(new_engine)

        # Initial backup of the loaded engines
        self.backup()
Example #24
0
    def _init(cls):
        def callback(widget, allocation):
            cls.widgets["enterGameNotationFrame"].set_size_request(
                223, allocation.height - 4)

        cls.widgets["enterGameNotationSidePanel"].connect_after(
            "size-allocate", callback)

        flags = []
        if isInstalled():
            path = gettext.find("pychess")
        else:
            path = gettext.find("pychess", localedir=addDataPrefix("lang"))
        if path:
            loc = locale.getdefaultlocale()[0][-2:].lower()
            flags.append(addDataPrefix("flags/%s.png" % loc))

        flags.append(addDataPrefix("flags/us.png"))

        cls.ib = ImageButton(flags)
        cls.widgets["imageButtonDock"].add(cls.ib)
        cls.ib.show()

        cls.sourcebuffer = GtkSource.Buffer()
        sourceview = GtkSource.View.new_with_buffer(cls.sourcebuffer)
        sourceview.set_tooltip_text(
            _("Type or paste PGN game or FEN positions here"))
        cls.widgets["scrolledwindow6"].add(sourceview)
        sourceview.show()

        # Pgn format does not allow tabulator
        sourceview.set_insert_spaces_instead_of_tabs(True)
        sourceview.set_wrap_mode(Gtk.WrapMode.WORD)

        man = GtkSource.LanguageManager()
        # Init new version
        if hasattr(man.props, 'search_path'):
            path = os.path.join(getDataPrefix(),
                                "gtksourceview-1.0/language-specs")
            man.props.search_path = man.props.search_path + [path]
            if 'pgn' in man.get_language_ids():
                lang = man.get_language('pgn')
                cls.sourcebuffer.set_language(lang)
            else:
                log.warning("Unable to load pgn syntax-highlighting.")
            cls.sourcebuffer.set_highlight_syntax(True)
        # Init old version
        else:
            os.environ["XDG_DATA_DIRS"] = getDataPrefix() + ":/usr/share/"
            man = LanguageManager()
            for lang in man.get_available_languages():
                if lang.get_name() == "PGN":
                    cls.sourcebuffer.set_language(lang)
                    break
            else:
                log.warning("Unable to load pgn syntax-highlighting.")
            cls.sourcebuffer.set_highlight(True)
Example #25
0
 def onChannelLogLine(self, match):
     if not self.currentLogChannel:
         log.warning("Received log line before channel was set")
         return
     hour, minutes, secs, handle, text = match.groups()
     conv_time = self.convTime(int(hour), int(minutes), int(secs))
     text = self.entityDecode(text)
     GLib.idle_add(self.emit, "channelLog", self.currentLogChannel,
                   conv_time, handle, text)
Example #26
0
def load_icon(size, *alternatives):
    alternatives = list(alternatives)
    name = alternatives.pop(0)
    try:
        return it.load_icon(name, size, Gtk.IconLookupFlags.USE_BUILTIN)
    except:
        if alternatives:
            return load_icon(size, *alternatives)
        log.warning("no %s icon in icon-theme-gnome" % name)
Example #27
0
 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)
Example #28
0
 def setOptionVariant (self, variant):
     if self.features["variants"] is None:
         log.warning("setOptionVariant: engine doesn't support variants", extra={"task":self.defname})
         return
     
     if variant in variants.values() and not variant.standard_rules:
         assert variant.cecp_name in self.features["variants"], \
                 "%s doesn't support %s variant" % (self, variant.cecp_name)
         self.optionQueue.append("variant %s" % variant.cecp_name)
Example #29
0
 def abort(self, game):
     if not game.opponent.adjournment:
         log.warning("AdjournManager.abort: no adjourned game vs %s" %
                     game.opponent)
         return
     log.info(
         "AdjournManager.abort: offering sabort for adjourned game=%s" %
         game)
     self.connection.client.run_command("sabort %s" % game.opponent.name)
Example #30
0
    def onObserveGameCreated (self, matchlist):
        log.debug("'%s'" % (matchlist[1].string),
            extra={"task": (self.connection.username, "BM.onObserveGameCreated")})
        gameno, wname, wrating, bname, brating, rated, gametype, min, inc = matchlist[1].groups()
        wplayer = self.connection.players.get(FICSPlayer(wname))
        bplayer = self.connection.players.get(FICSPlayer(bname))
        game = FICSGame(wplayer, bplayer, gameno=int(gameno))

        style12 = matchlist[-1].groups()[0]
        gameno = int(gameno)
        wrating = self.parseRating(wrating)
        brating = self.parseRating(brating)
        game_type = GAME_TYPES[gametype]
        
        castleSigns = self.generateCastleSigns(style12, game_type)
        self.castleSigns[gameno] = castleSigns
        gameno, relation, curcol, ply, wname, bname, wms, bms, gain, lastmove, fen = \
                self.parseStyle12(style12, castleSigns)

        if relation == IC_POS_OBSERVING_EXAMINATION:
            pgnHead = [
                ("Event", "FICS %s %s game" % (rated, game_type.fics_name)),
                ("Site", "freechess.org"),
                ("White", wname),
                ("Black", bname),
                ("Result", "*"),
                ("SetUp", "1"),
                ("FEN", fen)
                ]
            pgn = "\n".join(['[%s "%s"]' % line for line in pgnHead]) + "\n*\n"
            game = FICSGame(wplayer, bplayer, gameno=gameno, rated=rated=="rated",
                game_type=game_type, minutes=int(min), inc=int(inc),
                board=FICSBoard(wms, bms, pgn=pgn), relation=relation)
            game = self.connection.games.get(game)
            self.gamesImObserving[game] = None

            self.gamemodelStartedEvents[game.gameno] = threading.Event()
            self.emit("obsGameCreated", game)
            self.gamemodelStartedEvents[game.gameno].wait()
        else:
            game = self.connection.games.get(game, emit=False)
            
            if not game.supported:
                log.warning("Trying to follow an unsupported type game %s" % game.game_type)
                return

            if game.gameno in self.gamemodelStartedEvents:
                log.warning("%s already in gamemodelstartedevents" % game.gameno)
                return
            
            self.gamesImObserving[game] = None
            self.queuedStyle12s[game.gameno] = []
            self.queuedEmits[game.gameno] = []
            self.gamemodelStartedEvents[game.gameno] = threading.Event()

            # FICS doesn't send the move list after 'observe' and 'follow' commands
            self.connection.client.run_command("moves %d" % game.gameno)
Example #31
0
 def resign(self, game):
     """ This is (and draw and abort) are possible even when one's
         opponent is not logged on """
     if not game.opponent.adjournment:
         log.warning("AdjournManager.resign: no adjourned game vs %s" %
                     game.opponent)
         return
     log.info("AdjournManager.resign: resigning adjourned game=%s" % game)
     self.connection.client.run_command("resign %s" % game.opponent.name)
Example #32
0
def load_icon(size, *alternatives):
    alternatives = list(alternatives)
    name = alternatives.pop(0)
    try:
        return it.load_icon(name, size, Gtk.IconLookupFlags.USE_BUILTIN)
    except:
        if alternatives:
            return load_icon(size, *alternatives)
        log.warning("no %s icon in icon-theme-gnome" % name)
Example #33
0
 def __setitem__ (self, index, challenge):
     if not isinstance(index, int): raise TypeError
     if not isinstance(challenge, FICSSoughtMatch): raise TypeError
     if index in self:
         log.warning("FICSChallenges: not overwriting challenge %s" %
                     repr(challenge))
         return
     self.challenges[index] = challenge
     self.emit('FICSChallengeIssued', challenge)
Example #34
0
 def on_drag_received(self, wi, context, x, y, selection, target_type,
                      timestamp):
     uri = selection.data.strip()
     uris = uri.split()
     if len(uris) > 1:
         log.warning("%d files were dropped. Only loading the first" %
                     len(uris))
     uri = uris[0]
     newGameDialog.LoadFileExtension.run(uri)
Example #35
0
 def __setitem__ (self, index, challenge):
     if not isinstance(index, int): raise TypeError
     if not isinstance(challenge, FICSSoughtMatch): raise TypeError
     if index in self:
         log.warning("FICSChallenges: not overwriting challenge %s" %
                     repr(challenge))
         return
     self.challenges[index] = challenge
     self.emit('FICSChallengeIssued', challenge)
Example #36
0
 def resume(self, game):
     if not game.opponent.adjournment:
         log.warning("AdjournManager.resume: no adjourned game vs %s" %
                     game.opponent)
         return
     log.info(
         "AdjournManager.resume: offering resume for adjourned game=%s" %
         game)
     self.connection.client.run_command("match %s" % game.opponent.name)
Example #37
0
 def setOptionVariant (self, variant):
     if self.features["variants"] is None:
         log.warning("setOptionVariant: engine doesn't support variants", extra={"task":self.defname})
         return
     
     if variant in variants.values() and not variant.standard_rules:
         assert variant.cecp_name in self.features["variants"], \
                 "%s doesn't support %s variant" % (self, variant.cecp_name)
         self.optionQueue.append("variant %s" % variant.cecp_name)
Example #38
0
 def setOption (self, key, value):
     """ Set an option, which will be sent to the engine, after the
         'readyForOptions' signal has passed.
         If you want to know the possible options, you should go to
         engineDiscoverer or use the getOption, getOptions and hasOption
         methods, while you are in your 'readyForOptions' signal handler """ 
     if self.readyMoves:
         log.warning("Options set after 'readyok' are not sent to the engine", extra={"task":self.defname})
     self.optionsToBeSent[key] = value
     self.ponderOn = key=="Ponder" and value is True
Example #39
0
 def setOption (self, key, value):
     """ Set an option, which will be sent to the engine, after the
         'readyForOptions' signal has passed.
         If you want to know the possible options, you should go to
         engineDiscoverer or use the getOption, getOptions and hasOption
         methods, while you are in your 'readyForOptions' signal handler """ 
     if self.readyMoves:
         log.warning("Options set after 'readyok' are not sent to the engine", extra={"task":self.defname})
     self.optionsToBeSent[key] = value
     self.ponderOn = key=="Ponder" and value is True
Example #40
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.engines = []
        self.jsonpath = addUserConfigPrefix("engines.json")
        try:
            self._engines = json.load(open(self.jsonpath))
        except ValueError as err:
            log.warning(
                "engineNest: Couldn\'t read engines.json, renamed it to .bak\n%s\n%s"
                % (self.jsonpath, err))
            os.rename(self.jsonpath, self.jsonpath + ".bak")
            self._engines = deepcopy(backup)
        except IOError as err:
            log.info(
                "engineNest: Couldn\'t open engines.json, creating a new.\n%s"
                % err)
            self._engines = deepcopy(backup)

        # Try to detect engines shipping .eng files on Linux (suggested by HGM on talkcess.com forum)
        for protocol in ("xboard", "uci"):
            for path in ("/usr/local/share/games/plugins",
                         "/usr/share/games/plugins"):
                path = os.path.join(path, protocol)
                if os.path.isdir(path):
                    for entry in os.listdir(path):
                        ext = os.path.splitext(entry)[1]
                        if ext == ".eng":
                            with open(os.path.join(path, entry)) as file_handle:
                                plugin_spec = file_handle.readline().strip()
                                if not plugin_spec.startswith("plugin spec"):
                                    continue

                                engine_command = file_handle.readline().strip()

                                supported_variants = file_handle.readline().strip()
                                if not supported_variants.startswith("chess"):
                                    continue

                                new_engine = {}
                                if engine_command.startswith("cd ") and engine_command.find(";") > 0:
                                    parts = engine_command.split(";")
                                    working_directory = parts[0][3:]
                                    engine_command = parts[1]
                                    new_engine["workingDirectory"] = working_directory

                                find = False
                                for engine in self._engines:
                                    if engine["name"] == engine_command:
                                        find = True
                                        break

                                if not find:
                                    new_engine["protocol"] = protocol
                                    new_engine["name"] = engine_command
                                    self._engines.append(new_engine)
Example #41
0
 def __handleDead (self, subprocess):
     if self.deadCount < self.restartsOnDead:
         log.warning("Pinger died and restarted (%d/%d)" %
                  (self.deadCount+1, self.restartsOnDead),
                  extra={"task": self.subproc.defname})
         self.stop()
         self.start()
         self.deadCount += 1
     else:
         self.emit("error", _("Died"))
         self.stop()
Example #42
0
 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)
Example #43
0
 def __handleDead(self, subprocess):
     if self.deadCount < self.restartsOnDead:
         log.warning("Pinger died and restarted (%d/%d)" %
                     (self.deadCount + 1, self.restartsOnDead),
                     extra={"task": self.subproc.defname})
         self.stop()
         self.start()
         self.deadCount += 1
     else:
         self.emit("error", _("Died"))
         self.stop()
Example #44
0
    def _init (cls):
        def callback (widget, allocation):
            cls.widgets["enterGameNotationFrame"].set_size_request(
                    223, allocation.height-4)
        cls.widgets["enterGameNotationSidePanel"].connect_after("size-allocate", callback)

        flags = []
        if isInstalled():
            path = gettext.find("pychess")
        else:
            path = gettext.find("pychess", localedir=addDataPrefix("lang"))
        if path:
            loc = locale.getdefaultlocale()[0][-2:].lower()
            flags.append(addDataPrefix("flags/%s.png" % loc))

        flags.append(addDataPrefix("flags/us.png"))

        cls.ib = ImageButton(flags)
        cls.widgets["imageButtonDock"].add(cls.ib)
        cls.ib.show()

        cls.sourcebuffer = GtkSource.Buffer()
        sourceview = GtkSource.View.new_with_buffer(cls.sourcebuffer)
        sourceview.set_tooltip_text(
            _("Type or paste PGN game or FEN positions here"))
        cls.widgets["scrolledwindow6"].add(sourceview)
        sourceview.show()

        # Pgn format does not allow tabulator
        sourceview.set_insert_spaces_instead_of_tabs(True)
        sourceview.set_wrap_mode(Gtk.WrapMode.WORD)

        man = GtkSource.LanguageManager()
        # Init new version
        if hasattr(man.props, 'search_path'):
            path = os.path.join(getDataPrefix(),"gtksourceview-1.0/language-specs")
            man.props.search_path = man.props.search_path + [path]
            if 'pgn' in man.get_language_ids():
                lang = man.get_language('pgn')
                cls.sourcebuffer.set_language(lang)
            else:
                log.warning("Unable to load pgn syntax-highlighting.")
            cls.sourcebuffer.set_highlight_syntax(True)
        # Init old version
        else:
            os.environ["XDG_DATA_DIRS"] = getDataPrefix()+":/usr/share/"
            man = LanguageManager()
            for lang in man.get_available_languages():
                if lang.get_name() == "PGN":
                    cls.sourcebuffer.set_language(lang)
                    break
            else:
                log.warning("Unable to load pgn syntax-highlighting.")
            cls.sourcebuffer.set_highlight(True)
Example #45
0
 def answer (message):
     try:
         data = urlopen("http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895",
                        urlencode({"message":message, "botcust2":"x"}).encode("utf-8")).read().decode('utf-8')
     except IOError as e:
         log.warning("Couldn't answer message from online bot: '%s'" % e,
                  extra={"task":self.defname})
         return
     ss = "<b>DMPGirl:</b>"
     es = "<br>"
     answer = data[data.find(ss)+len(ss) : data.find(es,data.find(ss))]
     self.emit("offer", Offer(CHAT_ACTION, answer))
Example #46
0
 def get_data(URL, fen):
     # Request the page
     url = (URL + fen).replace(" ", "%20")
     try:
         f = urlopen(url)
     except IOError as e:
         log.warning(
             "Unable to read endgame tablebase from the Internet: %s" %
             repr(e))
         data = b""
     data = f.read()
     return data
Example #47
0
    def setLocked (self, locked):
        """ Makes the board insensitive and turns off the tab ready indicator """
        log.debug("GameWidget.setLocked: %s locked=%s" % (self.gamemodel.players, str(locked)))
        self.board.setLocked(locked)
        if not self.tabcontent.get_children(): return
        if len(self.tabcontent.get_child().get_children()) < 2:
            log.warning("GameWidget.setLocked: Not removing last tabcontent child")
            return

        self.light_on_off(not locked)

        log.debug("GameWidget.setLocked: %s: returning" % self.gamemodel.players)
Example #48
0
 def __discoverE (self, engine):       
     subproc = self.initEngine (engine, BLACK)       
     try:                
         subproc.connect('readyForOptions', self.__discoverE2, engine)            
         subproc.prestart() # Sends the 'start line'         
         subproc.start()           
     except SubProcessError as e:
         log.warning("Engine %s failed discovery: %s" % (engine["name"],e))
         self.emit("engine_failed", engine["name"], engine)
     except PlayerIsDead as e:
         # Check if the player died after engine_discovered by our own hands
         if not self.toBeRechecked[engine["name"]][1]:
             log.warning("Engine %s failed discovery: %s" % (engine["name"],e))
             self.emit("engine_failed", engine["name"], engine)
Example #49
0
    def makeMove(self, board1, move, board2):
        """ Gets a move from the engine (for player engines).
            @param board1: The current board
            @param move: The last move made
            @param board2: The board before the last move was made
            @return: The move the engine decided to make
        """
        log.debug(
            "makeMove: move=%s self.movenext=%s board1=%s board2=%s self.board=%s"
            % (move, self.movenext, board1, board2, self.board),
            extra={"task": self.defname})
        assert self.readyMoves
        self.boardLock.acquire()
        try:
            if self.board == board1 or not board2 or self.movenext:
                self.board = board1
                self.__tellEngineToPlayCurrentColorAndMakeMove()
                self.movenext = False
            else:
                self.board = board1
                self.__usermove(board2, move)

                if self.engineIsInNotPlaying:
                    self.__tellEngineToPlayCurrentColorAndMakeMove()
        finally:
            self.boardLock.release()
        self.waitingForMove = True
        self.readyForMoveNowCommand = True

        # Parse outputs
        status = self.returnQueue.get()
        if status == "not ready":
            log.warning(
                "Engine seems to be protover=2, but is treated as protover=1",
                extra={"task": self.defname})
            status = self.returnQueue.get()
        if status == "ready":
            status = self.returnQueue.get()
        if status == "invalid":
            raise InvalidMove
        if status == "del":
            raise PlayerIsDead("Killed by foreign forces")
        if status == "int":
            raise TurnInterrupt

        self.waitingForMove = False
        self.readyForMoveNowCommand = False
        assert isinstance(status, Move), status
        return status
Example #50
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.engines = []
        self.jsonpath = addUserConfigPrefix("engines.json")
        try:
            self._engines = json.load(open(self.jsonpath))
        except ValueError as e:
            log.warning(
                "engineNest: Couldn\'t read engines.json, renamed it to .bak\n%s\n%s"
                % (self.jsonpath, e))
            os.rename(self.jsonpath, self.jsonpath + ".bak")
            self._engines = deepcopy(backup)
        except IOError as e:
            log.info(
                "engineNest: Couldn\'t open engines.json, creating a new.\n%s"
                % e)
            self._engines = deepcopy(backup)

        # Try to detect engines shipping .eng files on Linux (suggested by HGM on talkcess.com forum)
        for protocol in ("xboard", "uci"):
            for path in ("/usr/local/share/games/plugins",
                         "/usr/share/games/plugins"):
                path = os.path.join(path, protocol)
                if os.path.isdir(path):
                    for entry in os.listdir(path):
                        name, ext = os.path.splitext(entry)
                        if ext == ".eng":
                            with open(os.path.join(path, entry)) as f:
                                plugin_spec = f.readline().strip()
                                engine_command = f.readline().strip()
                                new_engine = {}
                                if engine_command.startswith(
                                        "cd "
                                ) and engine_command.find(";") > 0:
                                    parts = engine_command.split(";")
                                    working_directory = parts[0][3:]
                                    engine_command = parts[1]
                                    new_engine[
                                        "workingDirectory"] = working_directory

                                find = False
                                for engine in self._engines:
                                    if engine["name"] == engine_command:
                                        find = True
                                        break
                                if not find:
                                    new_engine["protocol"] = protocol
                                    new_engine["name"] = engine_command
                                    self._engines.append(new_engine)
Example #51
0
    def setLocked(self, locked):
        """ Makes the board insensitive and turns off the tab ready indicator """
        log.debug("GameWidget.setLocked: %s locked=%s" %
                  (self.gamemodel.players, str(locked)))
        self.board.setLocked(locked)
        if not self.tabcontent.get_children(): return
        if len(self.tabcontent.get_child().get_children()) < 2:
            log.warning(
                "GameWidget.setLocked: Not removing last tabcontent child")
            return

        self.light_on_off(not locked)

        log.debug("GameWidget.setLocked: %s: returning" %
                  self.gamemodel.players)
Example #52
0
    def __startBlocking(self, event):
        try:
            return_value = yield from asyncio.wait_for(self.queue.get(), TIME_OUT_SECOND)
        except asyncio.TimeoutError:
            log.warning("Got timeout error", extra={"task": self.defname})
            raise PlayerIsDead
        except:
            log.warning("Unknown error", extra={"task": self.defname})
            raise PlayerIsDead
        else:
            if return_value == 'die':
                raise PlayerIsDead
            assert return_value == "ready" or return_value == "del"

        if event is not None:
            event.set()
Example #53
0
    def __startBlocking(self, event, is_dead):
        try:
            return_value = yield from asyncio.wait_for(self.queue.get(), TIME_OUT_SECOND)
        except asyncio.TimeoutError:
            log.warning("Got timeout error", extra={"task": self.defname})
            is_dead.add(True)
        except Exception:
            log.warning("Unknown error", extra={"task": self.defname})
            is_dead.add(True)
        else:
            if return_value == 'die':
                is_dead.add(True)
            assert return_value == "ready" or return_value == "del"

        if event is not None:
            event.set()
Example #54
0
 def setOption (self, key, value):
     """ Set an option, which will be sent to the engine, after the
         'readyForOptions' signal has passed.
         If you want to know the possible options, you should go to
         engineDiscoverer or use the getOption, getOptions and hasOption
         methods, while you are in your 'readyForOptions' signal handler """ 
     if self.readyMoves:
         log.warning("Options set after 'readyok' are not sent to the engine", extra={"task":self.defname})
     if key == "cores":
         self.optionQueue.append("cores %s" % value)
     elif key == "memory":
         self.optionQueue.append("memory %s" % value)
     elif key.lower() == "ponder":
         self.__setPonder(value==1)
     else:
         self.optionQueue.append("option %s=%s" % (key, value))
Example #55
0
    def _get_lines(self):
        lines = []
        line = self.telnet.readline()
        identifier = 0

        if line.startswith(self.line_prefix):
            line = line[len(self.line_prefix) + 1:]

        if self.block_mode and line.startswith(BLOCK_START):
            parts = line[1:].split(BLOCK_SEPARATOR)
            if len(parts) == 3:
                identifier, code, text = parts
            elif len(parts) == 4:
                identifier, code, error_code, text = parts
            else:
                log.warning("Posing not supported yet",
                            extra={"task": (self.telnet.name, "lines")})
                return lines
            code = int(code)
            identifier = int(identifier)
            line = text if text else self.telnet.readline()

            while not line.endswith(BLOCK_END):
                lines.append(TelnetLine(line, code))
                line = self.telnet.readline()
            lines.append(TelnetLine(line[:-1], code))

            if code != BLKCMD_PASSWORD:
                log.debug(
                    "%s %s %s" %
                    (identifier, code, "\n".join(line.line
                                                 for line in lines).strip()),
                    extra={"task": (self.telnet.name, "command_reply")})
        else:
            code = 0
            lines.append(TelnetLine(line, None))

        if code != BLKCMD_PASSWORD:
            log.debug("\n".join(line.line for line in lines).strip(),
                      extra={"task": (self.telnet.name, "lines")})
        if self.consolehandler:
            if identifier == 0 or identifier in self.show_reply:
                self.consolehandler.handle(lines)
                # self.show_reply.discard(identifier)

        return lines
Example #56
0
    def onGameStarted(self, gamemodel):
        if gamemodel.players[0].__type__ == LOCAL:
            self.player = gamemodel.players[0]
            self.opplayer = gamemodel.players[1]
            if gamemodel.players[1].__type__ == LOCAL:
                log.warning("Chatpanel loaded with two local players")
        elif gamemodel.players[1].__type__ == LOCAL:
            self.player = gamemodel.players[1]
            self.opplayer = gamemodel.players[0]
        else:
            log.info("Chatpanel loaded with no local players")
            self.chatView.hide()

        if hasattr(self, "player"):
            self.player.connect("messageRecieved", self.onMessageReieved)

        self.chatView.enable()
Example #57
0
    async def __discoverE(self, engine):
        subproc = await self.initEngine(engine, BLACK, False)
        subproc.connect('readyForOptions', self.__discoverE2, engine)
        subproc.prestart()  # Sends the 'start line'

        event = asyncio.Event()
        is_dead = set()
        subproc.start(event, is_dead)

        await event.wait()

        if is_dead:
            # Check if the player died after engine_discovered by our own hands
            if not self.toBeRechecked[engine["name"]][1]:
                log.warning("Engine %s failed discovery" % engine["name"])
                self.emit("engine_failed", engine["name"], engine)
            subproc.kill(UNKNOWN_REASON)