示例#1
0
 def start(self):
     if self.mode in (ANALYZING, INVERSE_ANALYZING):
         t = Thread(target=self.__startBlocking, name=fident(self.__startBlocking))
         t.daemon = True
         t.start()
     else:
         self.__startBlocking()
示例#2
0
文件: repeat.py 项目: jcoffee/pychess
def repeat_sleep(func, sleeptime, recur=False):
    """
    Runs func in a thread and repeats it approximately each sleeptime [s]
    until func returns False. Notice that we sleep first, then run. Not the
    other way around. If repeat_sleep is called with recur=True, each call
    will be called with the return value of last call as argument. The
    argument has to be optional, as it wont be used first time, and it has
    to be non-None.
    """

    def run():
        last = time.time()
        val = None
        while True:
            time.sleep(time.time() - last + sleeptime)
            if not time:
                # If python has been shutdown while we were sleeping, the
                # imported modules will be None
                return
            last = time.time()
            if recur and val:
                val = func(val)
            else:
                val = func()
            if not val: break

    thread = Thread(target=run, name=fident(func))
    thread.daemon = True
    thread.start()
示例#3
0
    def __init__(self, func):
        """ Initialize a new GtkWorker around a specific function """
        GObject.GObject.__init__(self)
        Thread.__init__(self, name=fident(func))
        self.daemon = True

        # By some reason we cannot access __gsignals__, so we have to do a
        # little double work here
        #self.connections = {"progressed": 0, "published": 0, "done": 0}
        self.connections = {"published": 0, "done": 0}
        self.handler_ids = {}
        self.name = func.__name__
        self.func = func
        self.cancelled = False
        self.done = False
        #self.progress = 0

        ########################################################################
        # Publish and progress queues                                          #
        ########################################################################

        self.publisher = EmitPublisher(self, "published",
                                       'GtkWorker.publisher',
                                       Publisher.SEND_LIST)
        self.publisher.start()
示例#4
0
文件: Engine.py 项目: well69/pychess
    def putMessage(self, message):
        # TODO: use pandorabots API
        # https://developer.pandorabots.com/docs
        return

        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 err:
                log.warning("Couldn't answer message from online bot: '%s'" %
                            err,
                            extra={"task": self.defname})
                return
            sstring = "<b>DMPGirl:</b>"
            estring = "<br>"
            answer = data[data.find(sstring) +
                          len(sstring):data.find(estring, data.find(sstring))]
            self.emit("offer", Offer(CHAT_ACTION, answer))

        thread = Thread(target=answer, name=fident(answer), args=(message, ))
        thread.daemon = True
        thread.start()
示例#5
0
文件: repeat.py 项目: jcoffee/pychess
def repeat_sleep(func, sleeptime, recur=False):
    """
    Runs func in a thread and repeats it approximately each sleeptime [s]
    until func returns False. Notice that we sleep first, then run. Not the
    other way around. If repeat_sleep is called with recur=True, each call
    will be called with the return value of last call as argument. The
    argument has to be optional, as it wont be used first time, and it has
    to be non-None.
    """
    def run():
        last = time.time()
        val = None
        while True:
            time.sleep(time.time() - last + sleeptime)
            if not time:
                # If python has been shutdown while we were sleeping, the
                # imported modules will be None
                return
            last = time.time()
            if recur and val:
                val = func(val)
            else:
                val = func()
            if not val: break

    thread = Thread(target=run, name=fident(func))
    thread.daemon = True
    thread.start()
示例#6
0
文件: idle_add.py 项目: zuzak/pychess
    def new_func(*args):
        thread = currentThread()
        if thread.name == "MainThread":
            if debug:
                msg = '%s(%s)' % (fident(f), ','.join([str(a) for a in args]))
                log.debug(msg,
                          extra={
                              'task':
                              (thread.ident, thread.name, 'idle_add.new_func')
                          })
            f(*args)
        else:

            def logged_f(*args):
                if debug:
                    msg = '%s(%s)' % (fident(f), ','.join(
                        [str(a) for a in args]))
                    log.debug(msg,
                              extra={
                                  'task': (thread.ident, thread.name,
                                           'idle_add.new_func')
                              })
                f(*args)

            GLib.idle_add(logged_f, *args)
示例#7
0
def start_thread_dump():
    def thread_dumper():
        def dump_threads():
            id2thread = {}
            for thread in threading.enumerate():
                id2thread[thread.ident] = thread

            stacks = []
            for thread_id, frame in sys._current_frames().items():
                stack = traceback.format_list(traceback.extract_stack(frame))
                if glock.has(thread=id2thread[thread_id]):
                    stacks.append("has glock")
                stacks.append("Thread: %s (%d)" %
                              (id2thread[thread_id].name, thread_id))
                stacks.append("".join(stack))

            log.debug("\n" + "\n".join(stacks))

        while True:
            dump_threads()
            time.sleep(10)

    t = Thread(target=thread_dumper, name=fident(thread_dumper))
    t.daemon = True
    t.start()
示例#8
0
    def __init__(self, timemodel=None, variant=NormalChess):
        GObject.GObject.__init__(self)
        Thread.__init__(self, name=fident(self.run))
        self.daemon = True
        self.variant = variant
        self.boards = [variant.board(setup=True)]

        self.moves = []
        self.scores = {}
        self.players = []

        self.gameno = None
        self.variations = [self.boards]

        self.status = WAITING_TO_START
        self.reason = UNKNOWN_REASON

        if timemodel is None:
            self.timemodel = TimeModel()
        else:
            self.timemodel = timemodel

        self.connections = defaultdict(list)  # mainly for IC subclasses

        now = datetime.datetime.now()
        self.tags = {
            "Event": _("Local Event"),
            "Site": _("Local Site"),
            "Round": 1,
            "Year": now.year,
            "Month": now.month,
            "Day": now.day,
            "Time": "%02d:%02d:00" % (now.hour, now.minute),
            "Result": "*",
        }

        self.endstatus = None
        self.timed = self.timemodel.secs != 0 or self.timemodel.gain != 0

        if self.timed:
            self.tags["TimeControl"] = \
                "%d+%d" % (self.timemodel.minutes*60, self.timemodel.gain)
            # Notice: tags["WhiteClock"] and tags["BlackClock"] are never set
            # on the gamemodel, but simply written or read during saving/
            # loading from pgn. If you want to know the time left for a player,
            # check the time model.

        # Keeps track of offers, so that accepts can be spotted
        self.offers = {}
        # True if the game has been changed since last save
        self.needsSave = False
        # The uri the current game was loaded from, or None if not a loaded game
        self.uri = None

        self.spectators = {}

        self.applyingMoveLock = RLock()
        self.undoLock = RLock()
        self.undoQueue = Queue()
示例#9
0
    def __init__ (self, timemodel=None, variant=NormalChess):        
        GObject.GObject.__init__(self)
        Thread.__init__(self, name=fident(self.run))
        self.daemon = True
        self.variant = variant
        self.boards = [variant.board(setup=True)]
        
        self.moves = []
        self.scores = {}
        self.players = []
        
        self.gameno = None
        self.variations = [self.boards]
        
        self.status = WAITING_TO_START
        self.reason = UNKNOWN_REASON
        
        if timemodel is None:
            self.timemodel = TimeModel()
        else:
            self.timemodel = timemodel
        
        self.connections = defaultdict(list)  # mainly for IC subclasses
        
        now = datetime.datetime.now()
        self.tags = {
            "Event": _("Local Event"),
            "Site":  _("Local Site"),
            "Round": 1,
            "Year":  now.year,
            "Month": now.month,
            "Day":   now.day,
            "Time":  "%02d:%02d:00" % (now.hour, now.minute),
            "Result": "*",
        }

        self.endstatus = None
        self.timed = self.timemodel.secs!=0 or self.timemodel.gain!=0

        if self.timed:
            self.tags["TimeControl"] = \
                "%d+%d" % (self.timemodel.minutes*60, self.timemodel.gain)
            # Notice: tags["WhiteClock"] and tags["BlackClock"] are never set
            # on the gamemodel, but simply written or read during saving/
            # loading from pgn. If you want to know the time left for a player,
            # check the time model.
        
        # Keeps track of offers, so that accepts can be spotted
        self.offers = {}
        # True if the game has been changed since last save
        self.needsSave = False
        # The uri the current game was loaded from, or None if not a loaded game
        self.uri = None
        
        self.spectators = {}
        
        self.applyingMoveLock = RLock()
        self.undoLock = RLock()
        self.undoQueue = Queue()
示例#10
0
    def __onTell(self, chatManager, name, title, isadmin, text):

        if self.waitingForPassword:
            if text.strip() == self.password or (not self.password
                                                 and text == "none"):
                self.sudos.add(name)
                self.tellHome("%s gained sudo access" % name)
                self.connection.client.run_command(self.waitingForPassword)
            else:
                chatManager.tellPlayer(name, "Wrong password")
                self.tellHome("%s failed sudo access" % name)
            self.waitingForPassword = None
            return

        args = text.split()

        #if args == ["help"]:
        #    chatManager.tellPlayer(name, self.__usage())

        if args[0] == "sudo":
            command = " ".join(args[1:])
            if name in self.sudos or name == self.owner:
                # Notice: This can be used to make nasty loops
                print(command, file=self.connection.client)
            else:
                print(repr(name), self.sudos)
                chatManager.tellPlayer(name, "Please send me the password")
                self.waitingForPassword = command

        elif args == ["sendlog"]:
            if self.log:
                # TODO: Consider email
                chatManager.tellPlayer(name, "\\n".join(self.log))
            else:
                chatManager.tellPlayer(name, "The log is currently empty")

        else:
            if self.ownerOnline:
                self.tellHome("%s told me '%s'" % (name, text))
            else:

                def onlineanswer(message):
                    data = urlopen(
                        "http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895",
                        urlencode({
                            "message": message,
                            "botcust2": "x"
                        }).encode("utf-8")).read().decode('utf-8')
                    ss = "<b>DMPGirl:</b>"
                    es = "<br>"
                    answer = data[data.find(ss) +
                                  len(ss):data.find(es, data.find(ss))]
                    chatManager.tellPlayer(name, answer)

                t = Thread(target=onlineanswer,
                           name=fident(onlineanswer),
                           args=(text, ))
                t.daemon = True
                t.start()
示例#11
0
 def newFunction(*args, **kw):
     _debug('glocked.newFunction', currentThread(),
            '-> acquire() (f=%s)' % fident(f))
     acquire()
     try:
         return f(*args, **kw)
     finally:
         release()
 def __analyze(self):
     self.thread = Thread(
         target=PyChess._PyChess__analyze,
         name=fident(PyChess._PyChess__analyze),
         args=(self, ),
     )
     self.thread.daemon = True
     self.thread.start()
示例#13
0
 def newFunction(*args, **kw):
     _debug('glocked.newFunction', currentThread(),
            '-> acquire() (f=%s)' % fident(f))
     acquire()
     try:
         return f(*args, **kw)
     finally:
         release()
示例#14
0
 def logged_f(*args):
     if debug:
         msg = '%s(%s)' % (fident(f),
                           ','.join([str(a) for a in args]))
         log.debug(msg,
                   extra={'task': (thread.ident, thread.name,
                                   'idle_add.new_func')})
     f(*args)
示例#15
0
 def start(self):
     if self.mode in (ANALYZING, INVERSE_ANALYZING):
         t = Thread(target=self.__startBlocking,
                    name=fident(self.__startBlocking))
         t.daemon = True
         t.start()
     else:
         self.__startBlocking()
示例#16
0
def repeat (func, *args, **kwargs):
    """ Repeats a function in a new thread until it returns False """
    def run ():
        while func(*args, **kwargs):
            pass
    t = Thread(target=run, name=fident(func))
    t.daemon = True
    t.start()
示例#17
0
    def __onTell(self, chatManager, name, title, isadmin, text):

        if self.waitingForPassword:
            if text.strip() == self.password or (not self.password and
                                                 text == "none"):
                self.sudos.add(name)
                self.tellHome("%s gained sudo access" % name)
                self.connection.client.run_command(self.waitingForPassword)
            else:
                chatManager.tellPlayer(name, "Wrong password")
                self.tellHome("%s failed sudo access" % name)
            self.waitingForPassword = None
            return

        args = text.split()

        #if args == ["help"]:
        #    chatManager.tellPlayer(name, self.__usage())

        if args[0] == "sudo":
            command = " ".join(args[1:])
            if name in self.sudos or name == self.owner:
                # Notice: This can be used to make nasty loops
                print(command, file=self.connection.client)
            else:
                print(repr(name), self.sudos)
                chatManager.tellPlayer(name, "Please send me the password")
                self.waitingForPassword = command

        elif args == ["sendlog"]:
            if self.log:
                # TODO: Consider email
                chatManager.tellPlayer(name, "\\n".join(self.log))
            else:
                chatManager.tellPlayer(name, "The log is currently empty")

        else:
            if self.ownerOnline:
                self.tellHome("%s told me '%s'" % (name, text))
            else:

                def onlineanswer(message):
                    data = urlopen(
                        "http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895",
                        urlencode({"message": message,
                                   "botcust2": "x"}).encode("utf-8")).read(
                                   ).decode('utf-8')
                    bold_ss = "<b>DMPGirl:</b>"
                    break_es = "<br>"
                    answer = data[data.find(bold_ss) + len(bold_ss):data.find(
                        break_es, data.find(bold_ss))]
                    chatManager.tellPlayer(name, answer)

                thread = Thread(target=onlineanswer,
                                name=fident(onlineanswer),
                                args=(text, ))
                thread.daemon = True
                thread.start()
示例#18
0
def start_thread_dump():
    def thread_dumper():
        while True:
            dump_threads()
            time.sleep(10)

    t = Thread(target=thread_dumper, name=fident(thread_dumper))
    t.daemon = True
    t.start()
示例#19
0
def start_thread_dump():
    def thread_dumper():
        while True:
            dump_threads()
            time.sleep(10)

    thread = Thread(target=thread_dumper, name=fident(thread_dumper))
    thread.daemon = True
    thread.start()
示例#20
0
文件: repeat.py 项目: jcoffee/pychess
def repeat(func, *args, **kwargs):
    """ Repeats a function in a new thread until it returns False """
    def run():
        while func(*args, **kwargs):
            pass

    thread = Thread(target=run, name=fident(func))
    thread.daemon = True
    thread.start()
示例#21
0
文件: idle_add.py 项目: zuzak/pychess
 def logged_f(*args):
     if debug:
         msg = '%s(%s)' % (fident(f), ','.join(
             [str(a) for a in args]))
         log.debug(msg,
                   extra={
                       'task': (thread.ident, thread.name,
                                'idle_add.new_func')
                   })
     f(*args)
示例#22
0
 def __go (self):
     def ondone (result):
         if not self.forced:
             self.board.applyMove(parseSAN(self.board,result))
             self.print("move %s" % result)
         # TODO: start pondering, if enabled
     self.thread = Thread(target=PyChess._PyChess__go,
                          name=fident(PyChess._PyChess__go),
                          args=(self,ondone))
     self.thread.daemon = True
     self.thread.start()
示例#23
0
 def __go (self):
     def ondone (result):
         if not self.forced:
             self.board.applyMove(parseSAN(self.board,result))
             print("move %s" % result)
         # TODO: start pondering, if enabled
     self.thread = Thread(target=PyChess._PyChess__go,
                          name=fident(PyChess._PyChess__go),
                          args=(self,ondone))
     self.thread.daemon = True
     self.thread.start()
示例#24
0
 def __init__ (self):
     GObject.GObject.__init__(self)
     Thread.__init__(self, name=fident(self.run))
     self.daemon = True
     self.stop = False
     self.lowply = 0
     self.status = RUNNING
     self.players = []
     self.moves = []
     self.variant = SetupBoard
     self.boards = [self.variant()]
     self.variations = [self.boards]
示例#25
0
 def __init__(self):
     GObject.GObject.__init__(self)
     Thread.__init__(self, name=fident(self.run))
     self.daemon = True
     self.stop = False
     self.lowply = 0
     self.status = RUNNING
     self.players = []
     self.moves = []
     self.variant = SetupBoard
     self.boards = [self.variant()]
     self.variations = [self.boards]
示例#26
0
def cacheGladefile(filename):
    """ Gtk.Builder automatically caches the file, so we only need to use this
        file once """
    if filename not in cachedGlades:
        cachedGlades[filename] = Queue()
        def readit ():
            builder = Gtk.Builder()
            builder.set_translation_domain("pychess")
            builder.add_from_file(addDataPrefix("glade/%s" % filename))
            cachedGlades[filename].put(builder)
        t = Thread(target=readit, name=fident(readit))
        t.daemon = True
        t.start()
示例#27
0
    def __init__ (self, store, tv, boardview):
        Thread.__init__(self, name=fident(self.run))
        self.daemon = True
        # FIXME 'Advisor.name = ...' in Advisor.__init__ overwrites Thread.name
        Advisor.__init__(self, store, _("Endgame Table"), ENDGAME)
        self.egtb = EndgameTable()
        self.tv = tv
        self.boardview = boardview
        self.tooltip = _("The endgame table will show exact analysis when there are few pieces on the board.")
        # TODO: Show a message if tablebases for the position exist but are neither installed nor allowed.

        self.egtb.connect("scored", self.on_scored)
        self.queue = Queue()
        self.start()
示例#28
0
    def __init__ (self, store, tv, boardview):
        Thread.__init__(self, name=fident(self.run))
        self.daemon = True
        # FIXME 'Advisor.name = ...' in Advisor.__init__ overwrites Thread.name
        Advisor.__init__(self, store, _("Endgame Table"), ENDGAME)
        self.egtb = EndgameTable()
        self.tv = tv
        self.boardview = boardview
        self.tooltip = _("The endgame table will show exact analysis when there are few pieces on the board.")
        # TODO: Show a message if tablebases for the position exist but are neither installed nor allowed.

        self.egtb.connect("scored", self.on_scored)
        self.queue = Queue()
        self.start()
示例#29
0
 def putMessage (self, message):
     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))
     t = Thread(target=answer, name=fident(answer), args=(message,))
     t.daemon = True
     t.start()
示例#30
0
    def __init__(self, host, ports, username, password):
        GObject.GObject.__init__(self)
        Thread.__init__(self, name=fident(self.run))
        self.daemon = True
        self.host = host
        self.ports = ports
        self.username = username
        self.password = password

        self.connected = False
        self.connecting = False

        self.predictions = set()
        self.predictionsDict = {}
        self.reply_cmd_dict = defaultdict(list)

        # Are we connected to FatICS ?
        self.FatICS = False
示例#31
0
    def __init__ (self, host, ports, username, password):
        GObject.GObject.__init__(self)
        Thread.__init__(self, name=fident(self.run))
        self.daemon = True
        self.host = host
        self.ports = ports
        self.username = username
        self.password = password
        
        self.connected = False
        self.connecting = False
        
        self.predictions = set()
        self.predictionsDict = {}
        self.reply_cmd_dict = defaultdict(list)

        # Are we connected to FatICS ?
        self.FatICS = False
示例#32
0
    def run_analyze(button, *args):
        old_check_value = conf.get("analyzer_check", True)
        conf.set("analyzer_check", True)
        widgets["analyze_ok_button"].set_sensitive(False)
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]
        analyzer = gamemodel.spectators[HINT]

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

                ply = board.ply
                if ply - 1 in gamemodel.scores:
                    color = (ply - 1) % 2
                    oldmoves, oldscore, olddepth = gamemodel.scores[ply - 1]
                    oldscore = oldscore * -1 if color == BLACK else oldscore
                    moves, score, depth = gamemodel.scores[ply]
                    score = score * -1 if color == WHITE else score
                    diff = score - oldscore
                    if (diff > thresold and color == BLACK) or (diff < -1 * thresold and color == WHITE):
                        gamemodel.add_variation(gamemodel.boards[ply - 1], oldmoves)

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

        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        return True
示例#33
0
    def run_analyze(button, *args):
        old_check_value = conf.get("analyzer_check", True)
        conf.set("analyzer_check", True)
        widgets["analyze_ok_button"].set_sensitive(False)
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]
        analyzer = gamemodel.spectators[HINT]

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

                ply = board.ply
                if ply-1 in gamemodel.scores: 
                    color = (ply-1) % 2
                    oldmoves, oldscore, olddepth = gamemodel.scores[ply-1]
                    oldscore = oldscore * -1 if color == BLACK else oldscore
                    moves, score, depth = gamemodel.scores[ply]
                    score = score * -1 if color == WHITE else score
                    diff = score-oldscore
                    if (diff > thresold and color==BLACK) or (diff < -1*thresold and color==WHITE):
                        gamemodel.add_variation(gamemodel.boards[ply-1], oldmoves)
            
            widgets["analyze_game"].hide()
            widgets["analyze_ok_button"].set_sensitive(True)
            conf.set("analyzer_check", old_check_value)
                        
        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        return True
示例#34
0
    def new_func(*args):
        thread = currentThread()
        if thread.name == "MainThread":
            if debug:
                msg = '%s(%s)' % (fident(f), ','.join([str(a) for a in args]))
                log.debug(msg,
                          extra={'task': (thread.ident, thread.name,
                                          'idle_add.new_func')})
            f(*args)
        else:

            def logged_f(*args):
                if debug:
                    msg = '%s(%s)' % (fident(f),
                                      ','.join([str(a) for a in args]))
                    log.debug(msg,
                              extra={'task': (thread.ident, thread.name,
                                              'idle_add.new_func')})
                f(*args)

            GLib.idle_add(logged_f, *args)
示例#35
0
def start_thread_dump ():
    def thread_dumper ():
        def dump_threads ():
            id2thread = {}
            for thread in threading.enumerate():
                id2thread[thread.ident] = thread
            
            stacks = []
            for thread_id, frame in sys._current_frames().items():
                stack = traceback.format_list(traceback.extract_stack(frame))
                stacks.append("Thread: %s (%d)" % (id2thread[thread_id].name, thread_id))
                stacks.append("".join(stack))
            
            log.debug("\n" + "\n".join(stacks))
        
        while True:
            dump_threads()
            time.sleep(10)
    
    t = Thread(target=thread_dumper, name=fident(thread_dumper))
    t.daemon = True
    t.start()
示例#36
0
 def __init__ (self, func):
     """ Initialize a new GtkWorker around a specific function """
     GObject.GObject.__init__(self)
     Thread.__init__(self, name=fident(func))
     self.daemon = True
     
     # By some reason we cannot access __gsignals__, so we have to do a
     # little double work here
     #self.connections = {"progressed": 0, "published": 0, "done": 0}
     self.connections = {"published": 0, "done": 0}
     self.handler_ids = {}
     self.name = func.__name__
     self.func = func
     self.cancelled = False
     self.done = False
     #self.progress = 0
     
     ########################################################################
     # Publish and progress queues                                          #
     ########################################################################
     
     self.publisher = EmitPublisher (self, "published",
         'GtkWorker.publisher', Publisher.SEND_LIST)
     self.publisher.start()
示例#37
0
    def _connect (self):
        self.connecting = True
        self.emit("connecting")
        try:
            self.client = TimeSeal()
            
            self.emit('connectingMsg', _("Connecting to server"))
            for i, port in enumerate(self.ports):
                log.debug("Trying port %d" % port, extra={"task": (self.host, "raw")})
                try:
                    self.client.open(self.host, port)
                except socket.error as e:
                    log.debug("Failed to open port %d %s" % (port, e), extra={"task": (self.host, "raw")})
                    if i+1 == len(self.ports):
                        raise
                    else:
                        continue
                else:
                    break
            
            self.client.read_until("login: "******"Logging on to server"))
            
            # login with registered handle
            if self.password:
                print(self.username, file=self.client)
                got = self.client.read_until("password:"******"enter the server as",
                                             "Try again.")
                if got == 0:
                    self.client.sensitive = True
                    print(self.password, file=self.client)
                    self.client.sensitive = False
                # No such name
                elif got == 1:
                    raise LogOnException(NOTREG % self.username)
                # Bad name
                elif got == 2:
                    raise LogOnException(NOTREG % self.username)
            else:
                if self.username:
                    print(self.username, file=self.client)
                else:
                    print("guest", file=self.client)
                got = self.client.read_until("Press return",
                                             "If it is yours, type the password.")
                if got == 1:
                    raise LogOnException(REGISTERED % self.username)
                print(file=self.client)
            
            while True:
                line = self.client.readline()
                if "Invalid password" in line:
                    raise LogOnException(BADPAS)
                elif "is already logged in" in line:
                    raise LogOnException(ALREADYIN % self.username)
                
                match = re.search("\*\*\*\* Starting FICS session as " +
                    "(%s)%s \*\*\*\*" % (NAMES_RE, TITLES_RE), line)
                if match:
                    self.username = match.groups()[0]
                    break
                
            self.emit('connectingMsg', _("Setting up environment"))
            lines = self.client.readuntil(b"ics%")
            self._post_connect_hook(lines)
            self.FatICS = self.client.FatICS
            self.client.name = self.username
            self.client = PredictionsTelnet(self.client, self.predictions,
                                            self.reply_cmd_dict)
            self.client.lines.line_prefix = "fics%"
            self.client.run_command("iset block 1")
            self.client.lines.block_mode = True
            self.client.run_command("iset defprompt 1")
            self.client.run_command("iset ms 1")
            self.client.run_command("set seek 0")
            
            self._start_managers()
            self.connecting = False
            self.connected = True
            self.emit("connected")

            def keep_alive():
                last = time.time()
                while self.isConnected():
                    if time.time()-last > 59*60:
                        self.client.run_command("date")
                        last = time.time()
                    time.sleep(30)
            t = threading.Thread(target=keep_alive, name=fident(keep_alive))
            t.daemon = True
            t.start()
        
        except CanceledException as e:
            log.info("FICSConnection._connect: %s" % repr(e),
                     extra={"task": (self.host, "raw")})
        finally:
            self.connecting = False
示例#38
0
 def newFunction(*args, **kwargs):
     thread = Thread(target=f, name=fident(f), args=args, kwargs=kwargs)
     thread.daemon = True
     thread.start()
示例#39
0
    def run_analyze(button, *args):
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]

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

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

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

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

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

        return True
示例#40
0
 def newFunction(*args, **kwargs):
     thread = Thread(target=f, name=fident(f), args=args, kwargs=kwargs)
     thread.daemon = True
     thread.start()
示例#41
0
 def gentleKill (self, first=1, second=1):
     t = Thread(target=self.__gentleKill_inner,
                name=fident(self.__gentleKill_inner),
                args=(first, second))
     t.daemon = True
     t.start()
示例#42
0
 def __init__(self, parent):
     Thread.__init__(self, name=fident(self.run))
     self.daemon = True
     self.parent = parent
示例#43
0
 def new_func (*args):
     _debug('idle_add.new_func', '%s(%s)' % (fident(f),
                                             ','.join([str(a) for a in args])))
     GLib.idle_add(f, *args)
示例#44
0
 def run(self):
     t = Thread(target=self.main, name=fident(self.main))
     t.daemon = True
     t.start()
     Gdk.threads_init()
     Gtk.main()
示例#45
0
 def gentleKill(self, first=1, second=1):
     t = Thread(target=self.__gentleKill_inner,
                name=fident(self.__gentleKill_inner),
                args=(first, second))
     t.daemon = True
     t.start()
示例#46
0
 def run(self):
     t = Thread(target=self.main, name=fident(self.main))
     t.daemon = True
     t.start()
     Gdk.threads_init()
     Gtk.main()
示例#47
0
 def __analyze(self):
     self.thread = Thread(target=PyChess._PyChess__analyze,
                          name=fident(PyChess._PyChess__analyze),
                          args=(self, ))
     self.thread.daemon = True
     self.thread.start()
示例#48
0
    def _connect(self):
        self.connecting = True
        self.emit("connecting")
        try:
            self.client = TimeSeal()

            self.emit('connectingMsg', _("Connecting to server"))
            for i, port in enumerate(self.ports):
                log.debug("Trying port %d" % port,
                          extra={"task": (self.host, "raw")})
                try:
                    self.client.open(self.host, port)
                except socket.error as e:
                    log.debug("Failed to open port %d %s" % (port, e),
                              extra={"task": (self.host, "raw")})
                    if i + 1 == len(self.ports):
                        raise
                    else:
                        continue
                else:
                    break

            self.client.read_until("login: "******"Logging on to server"))

            # login with registered handle
            if self.password:
                print(self.username, file=self.client)
                got = self.client.read_until("password:"******"enter the server as",
                                             "Try again.")
                if got == 0:
                    self.client.sensitive = True
                    print(self.password, file=self.client)
                    self.client.sensitive = False
                # No such name
                elif got == 1:
                    raise LogOnException(NOTREG % self.username)
                # Bad name
                elif got == 2:
                    raise LogOnException(NOTREG % self.username)
            else:
                if self.username:
                    print(self.username, file=self.client)
                else:
                    print("guest", file=self.client)
                got = self.client.read_until(
                    "Press return", "If it is yours, type the password.")
                if got == 1:
                    raise LogOnException(REGISTERED % self.username)
                print(file=self.client)

            while True:
                line = self.client.readline()
                if "Invalid password" in line:
                    raise LogOnException(BADPAS)
                elif "is already logged in" in line:
                    raise LogOnException(ALREADYIN % self.username)

                match = re.search(
                    "\*\*\*\* Starting FICS session as " + "(%s)%s \*\*\*\*" %
                    (NAMES_RE, TITLES_RE), line)
                if match:
                    self.username = match.groups()[0]
                    break

            self.emit('connectingMsg', _("Setting up environment"))
            lines = self.client.readuntil(b"ics%")
            self._post_connect_hook(lines)
            self.FatICS = self.client.FatICS
            self.client.name = self.username
            self.client = PredictionsTelnet(self.client, self.predictions,
                                            self.reply_cmd_dict)
            self.client.lines.line_prefix = "fics%"
            self.client.run_command("iset block 1")
            self.client.lines.block_mode = True
            self.client.run_command("iset defprompt 1")
            self.client.run_command("iset ms 1")
            self.client.run_command("set seek 0")

            self._start_managers()
            self.connecting = False
            self.connected = True
            self.emit("connected")

            def keep_alive():
                last = time.time()
                while self.isConnected():
                    if time.time() - last > 59 * 60:
                        self.client.run_command("date")
                        last = time.time()
                    time.sleep(30)

            t = threading.Thread(target=keep_alive, name=fident(keep_alive))
            t.daemon = True
            t.start()

        except CanceledException as e:
            log.info("FICSConnection._connect: %s" % repr(e),
                     extra={"task": (self.host, "raw")})
        finally:
            self.connecting = False
示例#49
0
    def _connect(self):
        self.connecting = True
        self.emit("connecting")
        try:
            self.client = TimeSeal()

            self.emit('connectingMsg', _("Connecting to server"))
            for i, port in enumerate(self.ports):
                log.debug("Trying port %d" % port,
                          extra={"task": (self.host, "raw")})
                try:
                    self.client.open(self.host, port)
                except socket.error as err:
                    log.debug("Failed to open port %d %s" % (port, err),
                              extra={"task": (self.host, "raw")})
                    if i + 1 == len(self.ports):
                        raise
                    else:
                        continue
                else:
                    break

            self.client.read_until("login: "******"Logging on to server"))

            # login with registered handle
            if self.password:
                print(self.username, file=self.client)
                got = self.client.read_until(
                    "password:"******"enter the server as", "Try again.")
                if got == 0:
                    self.client.sensitive = True
                    print(self.password, file=self.client)
                # No such name
                elif got == 1:
                    raise LogOnException(NOTREG % self.username)
                # Bad name
                elif got == 2:
                    raise LogOnException(NOTREG % self.username)
            else:
                if self.username:
                    print(self.username, file=self.client)
                else:
                    print("guest", file=self.client)
                got = self.client.read_until(
                    "Press return",
                    "You are connected as a guest",
                    "If it is yours, type the password.",
                    "guest connections have been prevented",
                    "nobody from your site may login without an account.")
                # got = 3
                if got == 2:
                    raise LogOnException(REGISTERED % self.username)
                elif got == 3 or got == 4:
                    raise LogOnException(PREVENTED)
                print(file=self.client)

            while True:
                line = self.client.readline()
                if "Invalid password" in line:
                    raise LogOnException(BADPAS)
                elif "is already logged in" in line:
                    raise LogOnException(ALREADYIN % self.username)

                match = re.search(
                    "\*\*\*\* Starting FICS session as " + "(%s)%s \*\*\*\*" %
                    (ic.NAMES_RE, ic.TITLES_RE), line)
                if match:
                    self.username = match.groups()[0]
                    break

                # USCN specific line
                match = re.search("Created temporary login '(%s)'" % ic.NAMES_RE, line)
                if match:
                    self.username = match.groups()[0]
                    break

                match = re.search("For a list of events, click here:", line)
                if match:
                    break

                # ICC specific line
                match = re.search("help anonymous", line)
                if match:
                    break

                match = re.search("This is the admin message of the day", line)
                if match:
                    break

            self.emit('connectingMsg', _("Setting up environment"))
            lines = self.client.readuntil(b"ics%")
            self._post_connect_hook(lines)
            self.FatICS = self.client.FatICS
            self.USCN = self.client.USCN
            self.ICC = self.client.ICC
            self.client.name = self.username
            self.client = PredictionsTelnet(self.client, self.predictions, self.reply_cmd_dict,
                                            self.replay_dg_dict, self.replay_cn_dict)
            self.client.lines.line_prefix = "aics%" if self.ICC else "fics%"

            if not self.USCN and not self.ICC:
                self.client.run_command("iset block 1")
                self.client.lines.block_mode = True

            if self.ICC:
                self.client.run_command("set level1 5")
                self.client.run_command("set prompt 0")
                self.client.lines.datagram_mode = True

                ic.GAME_TYPES_BY_SHORT_FICS_NAME["B"] = ic.GAME_TYPES["bullet"]
            else:
                ic.GAME_TYPES_BY_SHORT_FICS_NAME["B"] = ic.GAME_TYPES["bughouse"]

            self.client.run_command("iset defprompt 1")
            self.client.run_command("iset ms 1")

            self._start_managers(lines)
            self.connecting = False
            self.connected = True
            self.emit("connected")

            def keep_alive():
                last = time.time()
                while self.isConnected():
                    if time.time() - last > 59 * 60:
                        self.client.run_command("date")
                        last = time.time()
                    time.sleep(30)

            thread = threading.Thread(target=keep_alive, name=fident(keep_alive))
            thread.daemon = True
            thread.start()

        except CanceledException as err:
            log.info("FICSConnection._connect: %s" % repr(err),
                     extra={"task": (self.host, "raw")})
        finally:
            self.connecting = False
示例#50
0
 def __init__(self, parent):
     Thread.__init__(self, name=fident(self.run))
     self.daemon = True
     self.parent = parent
示例#51
0
    def run_analyze(button, *args):
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]

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

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

        def response_cb(infobar, response, message):
            message.dismiss()
            abort()

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

        def analyse_moves():
            from_current = conf.get("fromCurrent", True)
            start_ply = gmwidg.board.view.shown if from_current else 0
            move_time = int(conf.get("max_analysis_spin", 3))
            thresold = int(conf.get("variation_thresold_spin", 50))
            for board in gamemodel.boards[start_ply:]:
                if stop_event.is_set():
                    break

                @idle_add
                def do():
                    gmwidg.board.view.setShownBoard(board)

                do()
                analyzer.setBoard(board)
                if threat_PV:
                    inv_analyzer.setBoard(board)
                time.sleep(move_time + 0.1)

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

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

        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        hide_window(None)

        return True