code
stringlengths
1
1.72M
language
stringclasses
1 value
import unittest from pychess.Utils.lutils.lmovegen import genAllMoves, genCheckEvasions from pychess.Utils.lutils.LBoard import LBoard from pychess.Utils.lutils.bitboard import toString, iterBits from pychess.Utils.lutils.ldata import * from pychess.Utils.lutils.validator import validateMove from pychess.Utils.lutils.lmove import toSAN, toAN, parseSAN, ParsingError from pychess.Utils.const import * MAXDEPTH = 2 try: import psyco psyco.bind(genAllMoves) except ImportError: print 'psyco not found' class FindMovesTestCase(unittest.TestCase): """Move generator test using perftsuite.epd from http://www.albert.nu/programs/sharper/perft.htm""" def perft(self, board, depth, prevmoves): if depth == 0: self.count += 1 return if board.isChecked(): # If we are checked we can use the genCheckEvasions function as well # as genAllMoves. Here we try both functions to ensure they return # the same result. nmoves = [] for nmove in genAllMoves(board): board.applyMove(nmove) if board.opIsChecked(): board.popMove() continue nmoves.append(nmove) board.popMove() # Validator test self.assertTrue(validateMove(board, nmove)) cmoves = [] for move in genCheckEvasions(board): board.applyMove(move) cmoves.append(move) board.popMove() # Validator test self.assertTrue(validateMove(board, move)) # This is not any kind of alphaBeta sort. Only int sorting, to make # comparison possible nmoves.sort() cmoves.sort() if nmoves == cmoves: for move in cmoves: prevmoves.append(toSAN (board, move)) board.applyMove(move) self.perft(board, depth-1, prevmoves) board.popMove() else: print board print "nmoves" for move in nmoves: print toSAN (board, move) print "cmoves" for move in cmoves: print toSAN (board, move) self.assertEqual(nmoves, cmoves) else: for move in genAllMoves(board): board.applyMove(move) if board.opIsChecked(): board.popMove() continue # Validator test board.popMove() self.assertTrue(validateMove(board, move)) # San test san = toSAN (board, move) try: move2 = parseSAN(board, san) except ParsingError, e: print prevmoves raise ParsingError, e self.assertEqual (move, move2) board.applyMove (move) self.perft(board, depth-1, prevmoves) board.popMove() def setUp(self): self.positions = [] for line in open('gamefiles/perftsuite.epd'): parts = line.split(";") depths = [int(s[3:].rstrip()) for s in parts[1:]] self.positions.append( (parts[0], depths) ) def movegen(self, board, positions): for i, (fen, depths) in enumerate(positions): print i+1, "/", len(positions), "-", fen board.applyFen(fen) hash = board.hash for depth, suposedMoveCount in enumerate(depths): if depth+1 > MAXDEPTH: break self.count = 0 print "searching depth %d for %d moves" % \ (depth+1, suposedMoveCount) self.perft (board, depth+1, []) self.assertEqual(board.hash, hash) self.assertEqual(self.count, suposedMoveCount) def testMovegen1(self): """Testing NORMAL variant move generator with perftsuite.epd""" print self.movegen(LBoard(NORMALCHESS), self.positions) if __name__ == '__main__': unittest.main()
Python
import unittest from pychess.Utils.const import WHITE, ANALYZING, INVERSE_ANALYZING from pychess.Utils.lutils.ldata import MATE_VALUE from pychess.Utils.Move import listToMoves from pychess.Utils.Cord import Cord from pychess.Utils.Board import Board from pychess.Players.CECPEngine import CECPEngine from Queue import Queue from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE class DummyCECPAnalyzerEngine(GObject): __gsignals__ = { "line": (SIGNAL_RUN_FIRST, None, (object,)), "died": (SIGNAL_RUN_FIRST, None, ()), } def __init__(self): GObject.__init__(self) self.defname = 'Dummy' self.Q = Queue() def putline(self, line): self.emit('line', [line]) def write(self, text): if text.strip() == 'protover 2': self.emit('line', ['feature setboard=1 analyze=1 ping=1 draw=0 sigint=0 done=1']) pass def readline(self): return self.Q.get() class EmittingTestCase(unittest.TestCase): def __init__ (self, methodName='runTest'): unittest.TestCase.__init__(self, methodName) self.args = {} def traceSignal(self, object, signal): self.args[object] = None def handler(manager, *args): self.args[object] = args object.connect(signal, handler) def getSignalResults(self, object): return self.args.get(object, None) class CECPTests(EmittingTestCase): def _setupengine(self, mode): engine = DummyCECPAnalyzerEngine() analyzer = CECPEngine(engine, WHITE, 2) def optionsCallback (engine): analyzer.setOptionAnalyzing(mode) analyzer.connect("readyForOptions", optionsCallback) analyzer.prestart() analyzer.start() return engine, analyzer def _testLine(self, engine, analyzer, board, analine, moves, score): self.traceSignal(analyzer, 'analyze') engine.putline(analine) results = self.getSignalResults(analyzer) self.assertNotEqual(results, None, "signal wasn't sent") self.assertEqual(results, (listToMoves(board,moves), score)) def setUp (self): self.engineA, self.analyzerA = self._setupengine(ANALYZING) self.engineI, self.analyzerI = self._setupengine(INVERSE_ANALYZING) def test1(self): """ Test analyzing in forced mate situations """ board = Board('B1n1n1KR/1r5B/6R1/2b1p1p1/2P1k1P1/1p2P2p/1P2P2P/3N1N2 w - - 0 1') self.analyzerA.setBoard([board],[]) self.analyzerI.setBoard([board],[]) self._testLine(self.engineA, self.analyzerA, board, "1. Mat1 0 1 Bxb7#", ['Bxb7#'], MATE_VALUE-1) # Notice, in the opposite situation there is no forced mate. Black can # do Bxe3 or Ne7+, but we just emulate a stupid analyzer not # recognizing this. self._testLine(self.engineI, self.analyzerI, board.switchColor(), "10. -Mat 2 35 64989837 Bd4 Bxb7#", ['Bd4','Bxb7#'], -MATE_VALUE+2) def test2(self): """ Test analyzing in promotion situations """ board = Board('5k2/PK6/8/8/8/6P1/6P1/8 w - - 1 48') self.analyzerA.setBoard([board],[]) self.analyzerI.setBoard([board],[]) self._testLine(self.engineA, self.analyzerA, board, "9. 1833 23 43872584 a8=Q+ Kf7 Qa2+ Kf6 Qd2 Kf5 g4+", ['a8=Q+','Kf7','Qa2+','Kf6','Qd2','Kf5','g4+'], 1833) self._testLine(self.engineI, self.analyzerI, board.switchColor(), "10. -1883 59 107386433 Kf7 a8=Q Ke6 Qa6+ Ke5 Qd6+ Kf5", ['Kf7','a8=Q','Ke6','Qa6+','Ke5','Qd6+','Kf5'], -1883)
Python
import unittest modules_to_test = ( 'ficsmanagers', "bitboard", "draw", "eval", "fen", "frc_castling", "frc_movegen", "move", "movegen", "pgn", "zobrist", 'analysis', ) def suite(): tests = unittest.TestSuite() for module in map(__import__, modules_to_test): tests.addTest(unittest.findTestCases(module)) return tests if __name__ == "__main__": unittest.TextTestRunner(verbosity=2).run(suite())
Python
import sys import unittest from pychess.Utils.Board import Board from pychess.Utils.Move import Move from pychess.Utils.Move import parseSAN, parseFAN, toFAN from pychess.Utils.lutils.lmovegen import genAllMoves class MoveTestCase(unittest.TestCase): def setUp(self): self.board = Board() def test_paresSAN(self): """Testing parseSAN with unambiguous notations variants""" self.board.board.applyFen("4k2B/8/8/8/8/8/8/B3K3 w - - 0 1") self.assertEqual(repr(parseSAN(self.board, 'Ba1b2')), 'a1b2') self.assertEqual(repr(parseSAN(self.board, 'Bh8b2')), 'h8b2') self.assertEqual(repr(parseSAN(self.board, 'Bab2')), 'a1b2') self.assertEqual(repr(parseSAN(self.board, 'Bhb2')), 'h8b2') self.assertEqual(repr(parseSAN(self.board, 'B1b2')), 'a1b2') self.assertEqual(repr(parseSAN(self.board, 'B8b2')), 'h8b2') self.board.board.applyFen("4k2B/8/8/8/8/8/1b6/B3K3 w - - 0 1") self.assertEqual(repr(parseSAN(self.board, 'Ba1xb2')), 'a1b2') self.assertEqual(repr(parseSAN(self.board, 'Bh8xb2')), 'h8b2') self.assertEqual(repr(parseSAN(self.board, 'Baxb2')), 'a1b2') self.assertEqual(repr(parseSAN(self.board, 'Bhxb2')), 'h8b2') self.assertEqual(repr(parseSAN(self.board, 'B1xb2')), 'a1b2') self.assertEqual(repr(parseSAN(self.board, 'B8xb2')), 'h8b2') def test_parseFAN(self): """Testing parseFAN""" board = self.board.board board.applyFen("rnbqkbnr/8/8/8/8/8/8/RNBQKBNR w KQkq - 0 1") for lmove in genAllMoves(board): board.applyMove(lmove) if board.opIsChecked(): board.popMove() continue move = Move(lmove) board.popMove() fan = toFAN(self.board, move) self.assertEqual(parseFAN(self.board, fan), move) if __name__ == '__main__': unittest.main()
Python
import unittest from pychess.Utils.const import * from pychess.Utils.Board import Board from pychess.Utils.lutils.leval import LBoard from pychess.Utils.lutils.lmove import parseAN FEN = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1" class ZobristTestCase(unittest.TestCase): def make_move(self, an_move): self.board.applyMove(parseAN(self.board, an_move)) def setUp(self): self.board = LBoard(Board) self.board.applyFen(FEN) def testZobrist_1(self): """Testing zobrist hashing with simple move and take back""" hash = self.board.hash self.make_move("c3b5") self.board.color = 1 - self.board.color self.make_move("b5c3") self.assertEqual(hash, self.board.hash) def testZobrist_2(self): """Testing zobrist hashing with W00,B00,a1b1 vs. a1b1,B00,W00""" self.make_move("e1g1") self.make_move("e8g8") self.make_move("a1b1") hash1 = self.board.hash self.board.popMove() self.board.popMove() self.board.popMove() self.make_move("a1b1") self.make_move("e8g8") self.make_move("e1g1") hash2 = self.board.hash self.assertEqual(hash1, hash2) def testZobrist_3(self): """Testing zobrist hashing with W000,B000,h1g1 vs. h1g1,B000,W000""" self.make_move("e1c1") self.make_move("e8c8") self.make_move("h1g1") hash1 = self.board.hash self.board.popMove() self.board.popMove() self.board.popMove() self.make_move("h1g1") self.make_move("e8c8") self.make_move("e1c1") hash2 = self.board.hash self.assertEqual(hash1, hash2) def testZobrist_4(self): """Testing zobrist hashing with en-passant""" self.make_move("a2a4") self.make_move("b4a3") self.make_move("e1c1") self.make_move("c7c5") self.make_move("d5c6") self.make_move("e8c8") hash1 = self.board.hash self.board.popMove() self.board.popMove() self.board.popMove() self.board.popMove() self.board.popMove() self.board.popMove() self.make_move("e1c1") self.make_move("c7c5") self.make_move("d5c6") self.make_move("e8c8") self.make_move("a2a4") self.make_move("b4a3") hash2 = self.board.hash self.assertEqual(hash1, hash2) if __name__ == '__main__': unittest.main()
Python
import unittest from pychess.Utils.const import * from pychess.Utils.lutils.LBoard import LBoard from pychess.Utils.lutils.leval import evaluateComplete from pychess.Utils.lutils import leval class EvalTestCase(unittest.TestCase): def setUp (self): self.board = LBoard(NORMALCHESS) self.board.applyFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1") def test1(self): """Testing eval symmetry with startboard (WHITE)""" score = evaluateComplete(self.board, color=WHITE, balanced=True) self.assertEqual(score, 0) def test2(self): """Testing eval symmetry with startboard (BLACK)""" score = evaluateComplete(self.board, color=BLACK, balanced=True) self.assertEqual(score, 0) def test3(self): """Testing eval symmetry between colors with balanced=False""" scorew = evaluateComplete(self.board, color=WHITE) scoreb = evaluateComplete(self.board, color=BLACK) self.assertEqual(scorew, scoreb) def test4(self): """Testing eval symmetry of each function""" funcs = (f for f in dir(leval) if f.startswith("eval")) funcs = (getattr(leval,f) for f in funcs) funcs = (f for f in funcs if callable(f) and f != leval.evalMaterial) sw, phasew = leval.evalMaterial (self.board, WHITE) sb, phaseb = leval.evalMaterial (self.board, BLACK) self.assertEqual(phasew, phaseb) for func in funcs: sw = func(self.board, WHITE, phasew) sb = func(self.board, BLACK, phaseb) #print func, sw, sb self.assertEqual(sw, sb) if __name__ == '__main__': unittest.main()
Python
import sys import unittest from pychess.Utils.Board import Board from pychess.Utils.lutils.LBoard import LBoard from pychess.Savers.pgn import load, walk, movre from pychess.Utils.const import * class PgnTestCase(unittest.TestCase): def test_movre(self): """Testing movre regexp""" moves = "e4 fxg7 g8=Q gxh8=N a2+ axb1# c1=Q+ exd8=N# "+ \ "0-0-0 O-O-O 0-0 O-O Ka1 Kxf8 Kxd4+ "+ \ "Qc3 Rxh8 B1xg7 Nhxg2 Qe4xd5 Rb7+ Bxg4# N8xb2+ Qaxb7# Qd5xe4+" self.assertEqual(' '.join(movre.findall(moves)), ' '.join(moves.split())) def create_test(lines, result, gameno): def test_expected(self): for orig, new in zip(lines.split(), result.split()): # Seems most .PGN unnecessary contains unambiguous notation # when second move candidate is invalid (leaves king in check) # f.e.: 1.e4 e5 2.d4 Nf6 3.Nc3 Bb4 Nge2 if len(orig) == len(new)+1 and orig[0] == new[0] and orig[2:] == new[1:]: continue if orig[-1] in "?!" and new[-1] not in "?!": # pgn export format uses nag break elif orig == "0-0" or orig == "0-0-0": continue self.assertEqual(orig, new) return test_expected #PgnFile = load(open('/home/tamas/PGN/russian_chess.pgn')) #PgnFile = load(open('/home/tamas/PGN/kasp_top.pgn')) #PgnFile = load(open('/home/tamas/PGN/hartwig.pgn')) PgnFile = load(open('gamefiles/world_matches.pgn')) for i, game in enumerate(PgnFile.games): print "%s/%s" % (i+1, len(PgnFile.games)) model = PgnFile.loadToModel(i, quick_parse=False) result = [] walk(model.boards[0], result) result = " ".join(result) status = reprResult[model.status] lines = game[1].replace('. ', '. ').replace('. ', '. ') lines = lines.replace('\r\n', ' ') lines = lines.replace(' )', ')').replace(' )', ')') lines = lines.replace('( ', '(').replace('( ', '(') lines = lines.replace(' }', '}').replace(' }', '}') lines = lines.replace('{ ', '{').replace('{ ', '{') lines = lines.replace('(\r\n', '(').replace('\r\n)', ')') lines = lines.replace('{\r\n', '{').replace('\r\n}', '}') lines = lines.splitlines() lines = [line.strip() for line in lines] lines = ' '.join(lines) result = "%s %s" % (result, status) test_method = create_test(lines, result, i) test_method.__name__ = 'test_game_%d' % (i+1) setattr (PgnTestCase, test_method.__name__, test_method) if __name__ == '__main__': unittest.main()
Python
import unittest import datetime from pychess.Utils.const import WHITE from pychess.ic import * from pychess.ic.FICSObjects import * from pychess.ic.FICSConnection import Connection from pychess.ic.VerboseTelnet import PredictionsTelnet from pychess.ic.managers.AdjournManager import AdjournManager from pychess.ic.managers.GameListManager import GameListManager from pychess.ic.managers.ListAndVarManager import ListAndVarManager from pychess.ic.managers.BoardManager import BoardManager from Queue import Queue class DummyConnection(Connection): class DummyClient(PredictionsTelnet): class DummyTelnet(): def __init__(self): self.Q = Queue() def putline(self, line): self.Q.put(line) def write(self, text): pass def readline(self): return self.Q.get() def __init__(self): PredictionsTelnet.__init__(self, self.DummyTelnet()) def putline(self, line): self.telnet.putline(line) def __init__(self): Connection.__init__(self, 'host', (0,), 'tester', '123456') self.client = self.DummyClient() def putline(self, line): self.client.putline(line) def handleSomeText(self): self.client.handleSomeText(self.predictions) def getUsername(self): return self.username class DummyVarManager: def setVariable (self, name, value): pass def autoFlagNotify (self, *args): pass class EmittingTestCase(unittest.TestCase): ''' Helps working with unittests on emitting objects. Warning: Strong connection to fics managers ''' def runAndAssertEquals(self, signal, lines, expectedResults): self.args = None def handler(manager, *args): self.args = args self.manager.connect(signal, handler) for line in lines: self.connection.putline(line) self.connection.handleSomeText() self.assertNotEqual(self.args, None, "%s signal wasn't sent" % signal) self.assertEqual(self.args, expectedResults) ############################################################################### # AdjournManager ############################################################################### class AdjournManagerTests(EmittingTestCase): def setUp (self): self.connection = DummyConnection() self.connection.lvm = DummyVarManager() self.connection.bm = BoardManager(self.connection) self.connection.adm = AdjournManager(self.connection) self.connection.players = FICSPlayers(self.connection) self.connection.games = FICSGames(self.connection) self.manager = self.connection.adm def test1(self): """Testing an advanced line""" signal = 'onAdjournmentsList' lines = [' C Opponent On Type Str M ECO Date', ' 1: W gbtami N [ wr 2 2] 31-31 W18 --- Wed Dec 23, 06:58 PST 2009', 'fics% '] gametime = datetime.datetime(2009, 12, 23, 6, 58) us = self.connection.players.get(FICSPlayer(self.connection.getUsername())) gbtami = self.connection.players.get(FICSPlayer('gbtami')) game = FICSAdjournedGame(us, gbtami, our_color=WHITE, length=34, time=gametime, rated=True, game_type=GAME_TYPES_BY_FICS_NAME['wild'], private=False, min=2, inc=2) expectedResult = [ game ] self.runAndAssertEquals(signal, lines, (expectedResult,)) def test2(self): """Testing a double line""" signal = 'onAdjournmentsList' lines = [' C Opponent On Type Str M ECO Date', ' 1: W TheDane N [ br 2 12] 0-0 B2 ??? Sun Nov 23, 6:14 CST 1997', ' 2: W PyChess Y [psu 2 12] 39-39 W3 C20 Sun Jan 11, 17:40 ??? 2009', 'fics% '] gametime1 = datetime.datetime(1997, 11, 23, 6, 14) gametime2 = datetime.datetime(2009, 1, 11, 17, 40) game1 = FICSAdjournedGame(FICSPlayer(self.connection.getUsername()), FICSPlayer('TheDane'), our_color=WHITE, length=3, time=gametime1, rated=True, game_type=GAME_TYPES['blitz'], private=False, min=2, inc=12) game2 = FICSAdjournedGame(FICSPlayer(self.connection.getUsername()), FICSPlayer('PyChess'), our_color=WHITE, length=4, time=gametime2, rated=False, game_type=GAME_TYPES['standard'], private=True, min=2, inc=12) expectedResult = [ game1, game2 ] self.runAndAssertEquals(signal, lines, (expectedResult,)) def test3(self): """ The case where player has no games in adjourned """ self.runAndAssertEquals('onAdjournmentsList', ['%s has no adjourned games.' % self.connection.username], ([],)) def test4(self): """ Test acquiring preview without adjournment list """ signal = 'adjournedGamePreview' lines = ['BwanaSlei (1137) vs. mgatto (1336) --- Wed Nov 5, 20:56 PST 2008', 'Rated blitz match, initial time: 5 minutes, increment: 0 seconds.', '', 'Move BwanaSlei mgatto', '---- --------------------- ---------------------', ' 1. e4 (0:00.000) c5 (0:00.000)', ' 2. Nf3 (0:00.000) ', ' {White lost connection; game adjourned} *', 'fics% '] expectedPgn = '[Event "FICS rated blitz game"]\n[Site "FICS"]\n[White "BwanaSlei"]\n' \ '[Black "mgatto"]\n[TimeControl "300+0"]\n[Result "*"]\n' \ '[WhiteClock "0:05:00.000"]\n[BlackClock "0:05:00.000"]\n' \ '[WhiteElo "1137"]\n[BlackElo "1336"]\n[Year "2008"]\n' \ '[Month "11"]\n[Day "5"]\n[Time "20:56:00"]\n' expectedPgn += '1. e4 c5 2. Nf3 *\n' game = FICSAdjournedGame(FICSPlayer("BwanaSlei"), FICSPlayer("mgatto"), rated=True, game_type=GAME_TYPES["blitz"], min=5, inc=0, board=FICSBoard(300000, 300000, expectedPgn), reason=11) game.wplayer.addRating(TYPE_BLITZ, 1137) game.bplayer.addRating(TYPE_BLITZ, 1336) expectedResults = (game,) self.runAndAssertEquals(signal, lines, expectedResults) def test5(self): """ Test acquiring preview with adjournment list """ signal = 'adjournedGamePreview' lines = ['C Opponent On Type Str M ECO Date', '1: W BabyLurking Y [ br 5 0] 29-13 W27 D37 Fri Nov 5, 04:41 PDT 2010', '', 'mgatto (1233) vs. BabyLurking (1455) --- Fri Nov 5, 04:33 PDT 2010', 'Rated blitz match, initial time: 5 minutes, increment: 0 seconds.', '', 'Move mgatto BabyLurking', '---- ---------------- ----------------', '1. Nf3 (0:00) d5 (0:00)', '2. d4 (0:03) Nf6 (0:00)', '3. c4 (0:03) e6 (0:00)', ' {Game adjourned by mutual agreement} *'] expectedPgn = '[Event "FICS rated blitz game"]\n[Site "FICS"]\n[White "mgatto"]\n' \ '[Black "BabyLurking"]\n[TimeControl "300+0"]\n[Result "*"]\n' \ '[WhiteClock "0:04:54.000"]\n[BlackClock "0:05:00.000"]\n' \ '[WhiteElo "1233"]\n[BlackElo "1455"]\n[Year "2010"]\n[Month "11"]' \ '\n[Day "5"]\n[Time "04:33:00"]\n1. Nf3 d5 2. d4 Nf6 3. c4 e6 *\n' game = FICSAdjournedGame(FICSPlayer("mgatto"), FICSPlayer("BabyLurking"), rated=True, game_type=GAME_TYPES["blitz"], min=5, inc=0, board=FICSBoard(294000, 300000, expectedPgn), reason=6) game.wplayer.addRating(TYPE_BLITZ, 1233) game.bplayer.addRating(TYPE_BLITZ, 1455) expectedResults = (game,) self.runAndAssertEquals(signal, lines, expectedResults) ############################################################################### # GameListManager ############################################################################### class GameListManagerTests(EmittingTestCase): def setUp (self): self.connection = DummyConnection() # The real one stucks #self.connection.lvm = ListAndVarManager(self.connection) self.connection.lvm = DummyVarManager() self.manager = GameListManager(self.connection) def test1 (self): """ Seek add """ signal = 'addSeek' lines = ['<s> 10 w=warbly ti=00 rt=1291 t=3 i=0 r=r tp=blitz c=? rr=1200-1400 a=t f=t'] expectedResult = {'gameno':'10', 'gametype': GAME_TYPES["blitz"], 'rmin':1200, 'rmax':1400, 'cp':False, 'rt':'1291', 'manual':False, 'title': '', 'w':'warbly', 'r':'r', 't':'3', 'i':'0'} self.runAndAssertEquals(signal, lines, (expectedResult,)) lines = ['<s> 124 w=leaderbeans ti=02 rt=1637E t=3 i=0 r=u tp=blitz c=B rr=0-9999 a=t f=f'] expectedResult = {'gameno':'124', 'gametype': GAME_TYPES["blitz"], 'rmin':0, 'rmax':9999, 'cp':True, 'rt':'1637', 'manual':False, 'title': '(C)', 'w':'leaderbeans', 'r':'u', 't':'3', 'i':'0'} self.runAndAssertEquals(signal, lines, (expectedResult,)) lines = ['<s> 14 w=microknight ti=00 rt=1294 t=15 i=0 r=u tp=standard c=? rr=1100-1450 a=f f=f'] expectedResult = {'gameno':'14', 'gametype': GAME_TYPES["standard"], 'rmin':1100, 'rmax':1450, 'cp':False, 'rt':'1294', 'manual':True, 'title': '', 'w':'microknight', 'r':'u', 't':'15', 'i':'0'} self.runAndAssertEquals(signal, lines, (expectedResult,)) def test2 (self): """ Seek clear """ self.runAndAssertEquals('clearSeeks', ['<sc>'], ()) def test3 (self): """ Seek remove (ignore remove) """ lines = ['<s> 124 w=leaderbeans ti=02 rt=1637E t=3 i=0 r=u tp=blitz c=B rr=0-9999 a=t f=f', '<sr> 124'] self.runAndAssertEquals('removeSeek', lines, ('124',)) def test4 (self): # This test case should be implemented when the ficsmanager.py unit testing # is able to chain managers like the real fics code does. This is because # this test case tests verifies that this line is caught in BoardManager.py # rather than being accidentally caught by the on_player_list() regex in # GameManager.py (or elsewhere). # #lines = ['Game 342: Game clock paused.'] pass # And so on...
Python
from __future__ import with_statement import unittest from pychess.Savers import pgn from pychess.Utils.lutils import ldraw class DrawTestCase(unittest.TestCase): def setUp(self): with open('gamefiles/3fold.pgn') as f1: self.PgnFile1 = pgn.load(f1) with open('gamefiles/bilbao.pgn') as f2: self.PgnFile2 = pgn.load(f2) with open('gamefiles/material.pgn') as f3: self.PgnFile3 = pgn.load(f3) def test1(self): """Testing the same position, for the third time""" for i, game in enumerate(self.PgnFile1.games): model = self.PgnFile1.loadToModel(i) lboard = model.boards[-2].board self.assertTrue(ldraw.repetitionCount(lboard) < 3) lboard = model.boards[-1].board self.assertEqual(ldraw.repetitionCount(lboard), 3) def test2(self): """Testing the 50 move rule""" for i, game in enumerate(self.PgnFile2.games): model = self.PgnFile2.loadToModel(i) lboard = model.boards[-2].board self.assertEqual(ldraw.testFifty(lboard), False) lboard = model.boards[-1].board self.assertEqual(ldraw.testFifty(lboard), True) def test3(self): """Testing too few material""" for i, game in enumerate(self.PgnFile3.games): model = self.PgnFile3.loadToModel(i) lboard = model.boards[-2].board self.assertEqual(ldraw.testMaterial(lboard), False) lboard = model.boards[-1].board self.assertEqual(ldraw.testMaterial(lboard), True) if __name__ == '__main__': unittest.main()
Python
import unittest from pychess.Utils.lutils.lmovegen import genAllMoves, genCheckEvasions from pychess.Utils.lutils.LBoard import LBoard from pychess.Utils.lutils.bitboard import toString, iterBits from pychess.Utils.lutils.ldata import * from pychess.Utils.lutils.validator import validateMove from pychess.Utils.lutils.lmove import toSAN, toAN, parseSAN, ParsingError from pychess.Utils.const import * try: import psyco psyco.bind(genAllMoves) except ImportError: print 'psyco not found' class FRCFindMovesTestCase(unittest.TestCase): """Move generator test using perftsuite.epd from http://www.albert.nu/programs/sharper/perft.htm""" MAXDEPTH = 0 def perft(self, board, depth, prevmoves): if depth == 0: self.count += 1 return for move in genAllMoves(board): board.applyMove(move) if board.opIsChecked(): board.popMove() continue # Validator test board.popMove() self.assertTrue(validateMove(board, move)) board.applyMove (move) self.perft(board, depth-1, prevmoves) board.popMove() def setUp(self): self.positions1 = [] for line in open('gamefiles/perftsuite.epd'): parts = line.split(";") depths = [int(s[3:].rstrip()) for s in parts[1:]] self.positions1.append( (parts[0], depths) ) self.positions2 = [] for line in open('gamefiles/frc_perftsuite.epd'): parts = line.split(";") depths = [int(s[3:].rstrip()) for s in parts[1:]] self.positions2.append( (parts[0], depths) ) def movegen(self, board, positions): for i, (fen, depths) in enumerate(positions): fen = fen.split() castl = fen[2] castl = castl.replace("K", "H") castl = castl.replace("Q", "A") castl = castl.replace("k", "h") castl = castl.replace("q", "a") fen[2] = castl fen = ' '.join(fen) print i+1, "/", len(positions), "-", fen board.applyFen(fen) for depth, suposedMoveCount in enumerate(depths): if depth+1 > self.MAXDEPTH: break self.count = 0 print "searching depth %d for %d moves" % \ (depth+1, suposedMoveCount) self.perft (board, depth+1, []) self.assertEqual(self.count, suposedMoveCount) def testMovegen1(self): """Testing FRC variant move generator with perftsuite.epd""" print self.MAXDEPTH = 2 self.movegen(LBoard(FISCHERRANDOMCHESS), self.positions1) def testMovegen2(self): """Testing FRC variant move generator with frc_perftsuite.epd""" print self.MAXDEPTH = 2 self.movegen(LBoard(FISCHERRANDOMCHESS), self.positions2) if __name__ == '__main__': unittest.main()
Python
import unittest import random import operator from pychess.Utils.lutils.bitboard import * class BitboardTestCase(unittest.TestCase): def setUp (self): self.positionSets = [] # Random positions. Ten of each length. Will also include range(64) and # range(0) for i in xrange(10): for length in xrange(64): if length: positions = random.sample(xrange(64), length) board = reduce(operator.or_, (1<<(63-i) for i in positions)) self.positionSets.append( (positions, createBoard(board)) ) else: self.positionSets.append( ([], createBoard(0)) ) def test1(self): """Testing setbit and clearbit""" for positions,board in self.positionSets: b = createBoard(0) for pos in positions: b = setBit(b, pos) self.assertEqual(b, board) for pos in positions: b = clearBit(b, pos) self.assertEqual(b, createBoard(0)) def test2(self): """Testing firstbit and lastbit""" for positions,board in self.positionSets: if positions: positions.sort() self.assertEqual(positions[0], firstBit(board)) self.assertEqual(positions[-1], lastBit(board)) def test3(self): """Testing bitlength""" for positions,board in self.positionSets: self.assertEqual(len(positions), bitLength(board)) def test4(self): """Testing iterbits""" for positions,board in self.positionSets: positions.sort() itered = list(iterBits(board)) itered.sort() self.assertEqual(positions, itered) if __name__ == '__main__': unittest.main()
Python
import unittest from pychess.Utils.Board import Board from pychess.Utils.lutils.LBoard import LBoard import sys class FenTestCase(unittest.TestCase): def setUp(self): self.positions = [] for line in open('gamefiles/perftsuite.epd'): semi = line.find(" ;") self.positions.append(line[:semi]) def testFEN(self): """Testing board-FEN conversion with several positions""" print board = LBoard(Board) for i, fenstr in enumerate(self.positions[1:]): sys.stdout.write("#") board.applyFen(fenstr) fenstr2 = board.asFen() self.assertEqual(fenstr, fenstr2) print if __name__ == '__main__': unittest.main()
Python
import unittest from pychess.Utils.const import * from pychess.Utils.lutils.leval import LBoard from pychess.Utils.lutils.lmove import newMove, FLAG from pychess.Utils.lutils.lmovegen import genCastles # TODO: add more test data data = ( ("r3k2r/8/8/8/8/8/8/R3K2R w AH - 0 1", [(E1, G1, KING_CASTLE), (E1, C1, QUEEN_CASTLE)]), ("r3k2r/8/8/8/8/8/8/R3K2R b ah - 0 1", [(E8, G8, KING_CASTLE), (E8, C8, QUEEN_CASTLE)]), ("1br3kr/2p5/8/8/8/8/8/1BR3KR w CH - 0 2", [(G1, G1, KING_CASTLE), (G1, C1, QUEEN_CASTLE)]), ("1br3kr/2p5/8/8/8/8/8/1BR3KR b ch - 0 2", [(G8, G8, KING_CASTLE), (G8, C8, QUEEN_CASTLE)]), ("2r1k2r/8/8/8/8/8/8/2R1K2R w H - 0 1", [(E1, G1, KING_CASTLE)]), ("2r1k2r/8/8/8/8/8/8/2R1K2R b h - 0 1", [(E8, G8, KING_CASTLE)]), ("3rk1qr/8/8/8/8/8/8/3RK1QR w - - 0 1", []), ("3rk1qr/8/8/8/8/8/8/3RK1QR b - - 0 1", []), ) class FRCCastlingTestCase(unittest.TestCase): def testFRCCastling(self): """Testing FRC castling movegen""" print board = LBoard(FISCHERRANDOMCHESS) for fen, castles in data: print fen board.applyFen(fen) #print board moves = [move for move in genCastles(board)] self.assertEqual(len(moves), len(castles)) for i, castle in enumerate(castles): kfrom, kto, flag = castle self.assertEqual(moves[i], newMove(kfrom, kto, flag)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # -*- coding: UTF-8 -*- import sys, inspect, os from os import listdir, chdir, getcwd from os.path import isdir, join, split docdir = getcwd() print repr ("cd %s" % sys.argv[1]) chdir(sys.argv[1]) todir = "./" def search (path, extension): for file in listdir(path): file = join (path, file) if isdir (file) and not split(file)[1].startswith("."): yield file for f in search (file, extension): yield f elif file.endswith (extension): yield file index = False for file in search (todir, "py"): file = file[len(todir):] file = file.replace("/",".") if file.endswith(".py"): file = inspect.getmodulename(file) print repr("pydoc -w %s" % file) os.system("pydoc -w %s" % file) print repr("mv %s.html %s" % (file, docdir)) os.system("mv %s.html %s" % (file, docdir)) if file.find(".") < 0: index = file if index: print repr ("cd %s" % docdir) chdir(docdir) print repr("ln -s %s.html index.html" % index) os.system("ln -s %s.html index.html" % index) import webbrowser webbrowser.open("index.html")
Python
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import with_statement import collections ############################# # Configuration starts here # ############################# FILENAME = 'TRANSLATORS' POOLSIZE = 7 ########################### # Configuration ends here # ########################### from urllib import urlopen from multiprocessing import Pool import re print "Getting data from Rosetta Launchpad..." data = urlopen('http://translations.launchpad.net/pychess/trunk/+translations').read() langs = re.findall('/pychess/trunk/\+pots/pychess/(.*?)/\+translate', data) langs.sort() def findContributors(lang): site = "https://translations.launchpad.net/pychess/trunk/+pots/pychess/%s/+translate" % lang data = urlopen(site).read() language = re.findall("<h1>Browsing (.*?) translation</h1>", data)[0] start = data.find('Contributors to this translation') pers = re.findall('class="sprite person">(.*?)</a>', data[start:]) print "Did", language return [language, pers] with open(FILENAME,'w') as file: pool = Pool(POOLSIZE) contributors = pool.map(findContributors, langs) for lang, (language, pers) in zip(langs, contributors): print >> file, "[%s] %s" % (lang, language) for per in pers: print >> file, " " + per print >> file
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- from getpass import getpass from smtplib import SMTP, SMTPConnectError, SMTPAuthenticationError, SMTPRecipientsRefused from email.mime.text import MIMEText mail = 'pychess@gmail.com' passw = getpass('password: ') smtp = 'smtp.gmail.com' to = 'python-announce-list@python.org, pygtk@daa.com.au' subject = '[ANNOUNCE] PyChess Staunton 0.10' body = """======================================== Announcement for PyChess Staunton 0.10 ======================================== We have had a lot of last minute fixes since the release candidate. A few of them for bugs that have been around a long time. In particular there has been a lot of stabilization of CECP and UCI, so they should now work with an even wider set of engines. You can even run windows engines through wine. Another important addition to our project is our new website at pychess.org. The website has a good introduction to the client and the community, and in the future it will hopefully be filled with chess related functionality. Sharing your games online could be a great such future. The main new features of the release are still: * Support for chess variants, PyChess? now allows you to play Fischer Random with your majors huffled, to play Losers chess with being mated as your goal, or simply playing odds chess as an additional way of giving a player a handicap. * On-line play which has been enhanced with chat support. Besides chatting with your opponent, the FICS community has several channels, in which you can discuss chess and varies of other topics. * The FICS support has also been improved with built-in Timeseal support. This helps to terminate lag, and is especially helpful in very fast games, like bullet chess. * If you prefer to play off-line, PyChess? now lets you choose from eight different play-strengths. The built in PyChess? engine has as well been extended 'in both extremes' now making many more human like mistakes in the easy mode, and playing at more than double strength in the hard mode, utilizing end game tables. * UI-wise, PyChess? takes use of a new pure-python docking widget, which lets you rearrange the sidepanels by wish. I would really like to thank everyone who have helped to move Staunton forward to a release, and I hope our next release - PyChess? Anderssen 1.0 - will be out on a slightly shorter cycle. Please help spread the news of the release to users around the world, And if you notice that the translation for your language isn't fully updated, head to Rosetta now, and we'll fix it in the 0.10.1 release. ======================================== About PyChess ======================================== PyChess is a gtk chess client, originally developed for gnome, but running well under all other linux desktops. (Which we know of, at least). PyChess is 100% python code, from the top of the UI to the bottom of the chess engine, and all code is licensed under the Gnu Public License. The goal of PyChess is to provide an advanced chess client for linux following the Gnome Human Interface Guidelines. The client should be usable to those new to chess, who just want to play a short game and get back to their work, as well as those who wants to use the computer to further enhance their play. Very briefly, the following gives a picture of how far we have come. In our minds however, we have only finished 10% of the stuff we want. * Lets you play against lots of chess engines in the CECP and UCI formats in many different difficulties. The easiest one being very easy. * If you like to play against other of the human speices, PyChess supports online play on the FICS servers. * Games can be saved in the PGN, EPD and FEN chess fileformats for later continuation or analysis. * If you make mistakes or is going for lunch, PyChess lets you undo or pause the game at any time. However if you play online, you need to wait for you opponent to accept the offer. * When you are in lack of inspiration, PyChess offers an opening book and so called hint- and spy- arrows, which shows you what the computer would do in your place, and what it would do if you opponent could move just now. * Further, PyChess offers a rich and while simple interface, with sound, animation and Human Interface in the main row. If you would like help fix the translation of PyChess in your language, see http://code.google.com/p/pychess/wiki/RosettaTranslates to get started. Thanks, PyChess team Homepage: http://pychess.org Downloads: http://pychess.org/downloads Screenshots: http://pychess.org/about Project page: http://code.google.com/p/pychess Bug list: http://code.google.com/p/pychess/issues/list Mailing list: http://groups.google.com/group/pychess-people """ if __name__ == '__main__': msg = MIMEText(body) msg['Subject'] = subject msg['From'] = mail msg['To'] = to try: server = SMTP(smtp) except SMTPConnectError, ex: print '\n%s'%ex print '\nConnecting to Gmail account...' try: server.login(mail, passw) except SMTPAuthenticationError, ex: print '\n%s'%ex print 'Sending message...' try: server.sendmail(mail, to, msg.as_string()) except SMTPRecipientsRefused, ex: print '\n%s'%ex print 'Email send ok.' server.quit()
Python
#!/usr/bin/env python """ Which - locate a command * adapted from proposal__ by Erik Demaine and patch__ by Brian Curtin, which adds this feature__ to shutil __ http://bugs.python.org/file8185/find_in_path.py __ http://bugs.python.org/file15381/shutil_which.patch __ http://bugs.python.org/issue444582 * which_files() returns generator, which() returns first match, or raises IOError(errno.ENOENT) * searches current directory before ``PATH`` on Windows, but not before an explicitly passed path * accepts both string or iterable for an explicitly passed path, or pathext * accepts an explicitly passed empty path, or pathext (either '' or []) * does not search ``PATH`` for files that have a path specified in their name already * uses ``PATHEXT`` on Windows, providing a default value for different Windows versions .. function:: which_files(file [, mode=os.F_OK | os.X_OK[, path=None[, pathext=None]]]) Generate full paths, where the *file* is accesible under *mode* and is located in the directory passed as a part of the *file* name, or in any directory on *path* if a base *file* name is passed. The *mode* matches an existing executable file by default. The *path* defaults to the ``PATH`` environment variable, or to :const:`os.defpath` if the ``PATH`` variable is not set. On Windows, a current directory is searched before directories in the ``PATH`` variable, but not before directories in an explicitly passed *path* string or iterable. The *pathext* is used to match files with any of the extensions appended to *file*. On Windows, it defaults to the ``PATHEXT`` environment variable. If the ``PATHEXT`` variable is not set, then the default *pathext* value is hardcoded for different Windows versions, to match the actual search performed on command execution. On Windows <= 4.x, ie. NT and older, it defaults to '.COM;.EXE;.BAT;.CMD'. On Windows 5.x, ie. 2k/XP/2003, the extensions '.VBS;.VBE;.JS;.JSE;.WSF;.WSH' are appended, On Windows >= 6.x, ie. Vista/2008/7, the extension '.MSC' is further appended. The actual search on command execution may differ under Wine_, which may use a `different default value`__, that is `not treated specially here`__. In each directory, the *file* is first searched without any additional extension, even when a *pathext* string or iterable is explicitly passed. .. _Wine: http://www.winehq.org/ __ http://source.winehq.org/source/programs/cmd/wcmdmain.c#L1019 __ http://wiki.winehq.org/DeveloperFaq#detect-wine .. function:: which(file [, mode=os.F_OK | os.X_OK[, path=None[, pathext=None]]]) Return the first full path matched by :func:`which_files`, or raise :exc:`IOError` (:const:`errno.ENOENT`). """ __docformat__ = 'restructuredtext en' __all__ = 'which which_files'.split() import sys, os, os.path _windows = sys.platform.startswith('win') if _windows: def _getwinpathext(*winver): """ Return the default PATHEXT value for a particular Windows version. On Windows <= 4.x, ie. NT and older, it defaults to '.COM;.EXE;.BAT;.CMD'. On Windows 5.x, ie. 2k/XP/2003, the extensions '.VBS;.VBE;.JS;.JSE;.WSF;.WSH' are appended, On Windows >= 6.x, ie. Vista/2008/7, the extension '.MSC' is further appended. Availability: Windows >>> def test(extensions, *winver): ... result = _getwinpathext(*winver) ... expected = os.pathsep.join(['.%s' % ext.upper() for ext in extensions.split()]) ... assert result == expected, 'getwinpathext: %s != %s' % (result, expected) >>> test('com exe bat cmd', 3) >>> test('com exe bat cmd', 4) >>> test('com exe bat cmd vbs vbe js jse wsf wsh', 5) >>> test('com exe bat cmd vbs vbe js jse wsf wsh msc', 6) >>> test('com exe bat cmd vbs vbe js jse wsf wsh msc', 7) """ if not winver: winver = sys.getwindowsversion() return os.pathsep.join('.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC'.split(';')[:( winver[0] < 5 and 4 or winver[0] < 6 and -1 or None )]) def which_files(file, mode=os.F_OK | os.X_OK, path=None, pathext=None): """ Generate full paths, where the file*is accesible under mode and is located in the directory passed as a part of the file name, or in any directory on path if a base file name is passed. The mode matches an existing executable file by default. The path defaults to the PATH environment variable, or to os.defpath if the PATH variable is not set. On Windows, a current directory is searched before directories in the PATH variable, but not before directories in an explicitly passed path string or iterable. The pathext is used to match files with any of the extensions appended to file. On Windows, it defaults to the ``PATHEXT`` environment variable. If the PATHEXT variable is not set, then the default pathext value is hardcoded for different Windows versions, to match the actual search performed on command execution. On Windows <= 4.x, ie. NT and older, it defaults to '.COM;.EXE;.BAT;.CMD'. On Windows 5.x, ie. 2k/XP/2003, the extensions '.VBS;.VBE;.JS;.JSE;.WSF;.WSH' are appended, On Windows >= 6.x, ie. Vista/2008/7, the extension '.MSC' is further appended. The actual search on command execution may differ under Wine, which may use a different default value, that is not treated specially here. In each directory, the file is first searched without any additional extension, even when a pathext string or iterable is explicitly passed. >>> def test(expected, *args, **argd): ... result = list(which_files(*args, **argd)) ... assert result == expected, 'which_files: %s != %s' % (result, expected) ... ... try: ... result = [ which(*args, **argd) ] ... except IOError: ... result = [] ... assert result[:1] == expected[:1], 'which: %s != %s' % (result[:1], expected[:1]) >>> ### Set up >>> import stat, tempfile >>> dir = tempfile.mkdtemp(prefix='test-') >>> ext = '.ext' >>> tmp = tempfile.NamedTemporaryFile(prefix='command-', suffix=ext, dir=dir) >>> name = tmp.name >>> file = os.path.basename(name) >>> here = os.path.join(os.curdir, file) >>> nonexistent = '%s-nonexistent' % name >>> path = os.pathsep.join([ nonexistent, name, dir, dir ]) ... # Test also that duplicates are removed, and non-existent objects ... # or non-directories in path do not trigger any exceptions. >>> ### Test permissions >>> test(_windows and [name] or [], file, path=path) >>> test(_windows and [name] or [], file, mode=os.X_OK, path=path) ... # executable flag is not needed on Windows >>> test([name], file, mode=os.F_OK, path=path) >>> test([name], file, mode=os.R_OK, path=path) >>> test([name], file, mode=os.W_OK, path=path) >>> test([name], file, mode=os.R_OK|os.W_OK, path=path) >>> os.chmod(name, stat.S_IRWXU) >>> test([name], file, mode=os.R_OK|os.W_OK|os.X_OK, path=path) >>> ### Test paths >>> _save_path = os.environ.get('PATH', '') >>> cwd = os.getcwd() >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> test([], nonexistent, path=path) >>> test([name], file, path=path) >>> test([name], name, path=path) >>> test([name], name, path='') >>> test([name], name, path=nonexistent) >>> os.chdir(dir) >>> test([name], file, path=path) >>> test([here], file, path=os.curdir) >>> test([name], name, path=os.curdir) >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> os.environ['PATH'] = path >>> test(_windows and [here] or [name], file) ... # current directory is always searched first on Windows >>> os.environ['PATH'] = os.curdir >>> test([here], file) >>> test([name], name) >>> os.environ['PATH'] = '' >>> test(_windows and [here] or [], file) >>> os.environ['PATH'] = nonexistent >>> test(_windows and [here] or [], file) >>> os.chdir(cwd) >>> os.environ['PATH'] = path >>> test([name], file) >>> os.environ['PATH'] = _save_path >>> ### Test extensions >>> test([], file[:-4], path=path, pathext='') >>> test([], file[:-4], path=path, pathext=nonexistent) >>> test([name], file[:-4], path=path, pathext=ext) >>> test([name], file, path=path, pathext=ext) >>> test([name], file, path=path, pathext='') >>> test([name], file, path=path, pathext=nonexistent) >>> ### Tear down >>> tmp.close() >>> os.rmdir(dir) """ filepath, file = os.path.split(file) if filepath: path = (filepath,) elif path is None: path = os.environ.get('PATH', os.defpath).split(os.pathsep) if _windows and not os.curdir in path: path.insert(0, os.curdir) # current directory is always searched first on Windows elif isinstance(path, basestring): path = path.split(os.pathsep) if pathext is None: pathext = [''] if _windows: pathext += (os.environ.get('PATHEXT', '') or _getwinpathext()).lower().split(os.pathsep) elif isinstance(pathext, basestring): pathext = pathext.split(os.pathsep) if not '' in pathext: pathext.insert(0, '') # always check command without extension, even for an explicitly passed pathext seen = set() for dir in path: if dir: # only non-empty directories are searched id = os.path.normcase(os.path.abspath(dir)) if not id in seen: # each directory is searched only once seen.add(id) woex = os.path.join(dir, file) for ext in pathext: name = woex + ext if os.path.exists(name) and os.access(name, mode): yield name def which(file, mode=os.F_OK | os.X_OK, path=None, pathext=None): """ Return the first full path matched by which_files(), or raise IOError(errno.ENOENT). >>> # See which_files() for a doctest. """ try: return iter(which_files(file, mode, path, pathext)).next() except StopIteration: try: from errno import ENOENT except ImportError: ENOENT = 2 raise IOError(ENOENT, '%s not found' % (mode & os.X_OK and 'command' or 'file'), file) if __name__ == '__main__': import doctest doctest.testmod()
Python
""" This is a pool for reusing threads """ from threading import Thread, Condition, Lock import GtkWorker import Queue import inspect import os import sys import threading import traceback import cStringIO import atexit if not hasattr(Thread, "_Thread__bootstrap_inner"): class SafeThread (Thread): def encaps(self): try: self._Thread__bootstrap_inner() except: if self.__daemonic and (sys is None or sys.__doc__ is None): return raise setattr(SafeThread, "_Thread__bootstrap_inner", SafeThread._Thread__bootstrap) setattr(SafeThread, "_Thread__bootstrap", SafeThread.encaps) threading.Thread = SafeThread maxThreads = sys.maxint class ThreadPool: def __init__ (self): self.queue = Queue.Queue() self.lock = Lock() self.threads = 0 def start (self, func, *args, **kw): self.lock.acquire() try: a = self.queue.get_nowait() except Queue.Empty: if self.threads < maxThreads: self.threads += 1 a = self.Worker(self.queue) a.setDaemon(True) a.start() else: a = self.queue.get(timeout=5) from pychess.System.Log import log log.warn("Couldn't get a thread after 5s") a = self.queue.get() a.func = lambda: func(*args, **kw) a.name = self._getThreadName(a, func) a.wcond.acquire() a.wcond.notify() a.wcond.release() self.lock.release() def _getThreadName (self, thread, func): try: framerecord = inspect.stack()[2] except TypeError: return "" # d = os.path.basename(os.path.dirname(framerecord[1])) f = os.path.basename(framerecord[1]) # f = os.sep.join((d, f)) caller = ":".join([str(v) for v in (f,) + framerecord[2:4]]) module = inspect.getmodule(func) lineno = inspect.getsourcelines(func)[1] callee = ":".join((module.__name__, str(lineno), func.__name__)) if module is GtkWorker or "repeat" in str(module): framerecord = inspect.stack()[3] # d = os.path.basename(os.path.dirname(framerecord[1])) f = os.path.basename(framerecord[1]) # f = os.sep.join((d, f)) callee += " -- " + ":".join([str(v) for v in (f,) + framerecord[2:4]]) s = caller + " -- " + callee for repl in ("pychess.", "System.", "Players."): s = s.replace(repl, "") return s class Worker (threading.Thread): def __init__ (self, queue): Thread.__init__(self) self.func = None self.wcond = Condition() self.queue = queue self.running = True atexit.register(self.__del__) # We catch the trace from the thread, that created the worker stringio = cStringIO.StringIO() traceback.print_stack(file=stringio) self.tracestack = traceback.extract_stack() def run (self): try: while True: if self.func: try: self.func() except Exception, e: #try: # if glock._rlock._RLock__owner == self: # # As a service we take care of releasing the gdk # # lock when a thread breaks to avoid freezes # for i in xrange(glock._rlock._RLock__count): # glock.release() #except AssertionError, e: # print e # pass _, _, exc_traceback = sys.exc_info() list = self.tracestack[:-2] + \ traceback.extract_tb(exc_traceback)[2:] error = "".join(traceback.format_list(list)) print error.rstrip() print str(e.__class__), e self.func = None self.queue.put(self) self.wcond.acquire() self.wcond.wait() self.wcond.release() except: #self.threads -= 1 if self.running: raise def __del__ (self): self.running = False pool = ThreadPool() class PooledThread (object): def start (self): pool.start(self.run) def run (self): pass def join (self, timeout=None): raise NotImplementedError def setName (self, name): raise NotImplementedError def getName (self): raise NotImplementedError def isAlive (self): raise NotImplementedError def isDaemon (self): return True def setDaemon (self): raise NotImplementedError
Python
import os, atexit from pychess.System.Log import log from ConfigParser import SafeConfigParser configParser = SafeConfigParser() from pychess.System.prefix import addUserConfigPrefix section = "General" path = addUserConfigPrefix("config") if os.path.isfile(path): configParser.readfp(open(path)) if not configParser.has_section(section): configParser.add_section(section) if not configParser.has_section(section+"_Types"): configParser.add_section(section+"_Types") atexit.register(lambda: configParser.write(open(path,"w"))) idkeyfuncs = {} conid = 0 typeEncode = { str: repr(str), unicode: repr(unicode), int: repr(int), float: repr(float), bool: repr(bool) } typeDecode = { repr(str): configParser.get, repr(unicode): configParser.get, repr(int): configParser.getint, repr(float): configParser.getfloat, repr(bool): configParser.getboolean, } def notify_add (key, func, args): global conid idkeyfuncs[conid] = (key, func, args) conid += 1 return conid def notify_remove (conid): del idkeyfuncs[conid] def get (key): decoder = typeDecode[configParser.get(section+"_Types", key)] return decoder(section, key) def set (key, value): try: configParser.set (section, key, str(value)) configParser.set (section+"_Types", key, typeEncode[type(value)]) except Exception, e: log.error("Unable to save configuration '%s'='%s' because of error: %s %s"% (repr(key), repr(value), e.__class__.__name__, ", ".join(str(a) for a in e.args))) for key_, func, args in idkeyfuncs.values(): if key_ == key: func (None, *args) def hasKey (key): return configParser.has_option(section, key) and \ configParser.has_option(section+"_Types", key)
Python
from threading import Lock from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE from Log import log try: import pygst pygst.require('0.10') import gst except ImportError, e: log.error("Unable to import gstreamer. All sound will be mute.\n%s" % e) class Player (GObject): __gsignals__ = { 'end': (SIGNAL_RUN_FIRST, TYPE_NONE, ()), 'error': (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)) } def checkSound(self): self.emit("error", None) def play(self, uri): pass else: class Player (GObject): __gsignals__ = { 'end': (SIGNAL_RUN_FIRST, TYPE_NONE, ()), 'error': (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)) } def __init__(self): GObject.__init__(self) self.player = gst.element_factory_make("playbin") self.player.get_bus().add_watch(self.onMessage) def onMessage(self, bus, message): if message.type == gst.MESSAGE_ERROR: # Sound seams sometimes to work, even though errors are dropped. # Therefore we really can't do anything to test. # self.emit("error", message) simpleMessage, advMessage = message.parse_error() log.warn("Gstreamer error '%s': %s" % (simpleMessage, advMessage)) self.__del__() elif message.type == gst.MESSAGE_EOS: self.emit("end") return True def play(self, uri): self.player.set_state(gst.STATE_READY) self.player.set_property("uri", uri) self.player.set_state(gst.STATE_PLAYING) def __del__ (self): self.player.set_state(gst.STATE_NULL)
Python
from array import array class MultiArray: def __init__ (self, oneLineData, *lengths): self.lengths = lengths self.data = oneLineData def get (self, *indexes): index = 0 for depth, i in enumerate(indexes[::-1]): index += i*self.lengths[depth]**depth return self.data[index]
Python
""" This is a dictionary, that supports a max of items. This is good for the transportation table, as some old entries might not be useable any more, as the position has totally changed """ from UserDict import UserDict from threading import Lock class LimitedDict (UserDict): def __init__ (self, maxSize): UserDict.__init__(self) assert maxSize > 0 self.maxSize = maxSize self.krono = [] self.lock = Lock() def __setitem__ (self, key, item): self.lock.acquire() try: if not key in self: if len(self) >= self.maxSize: try: del self[self.krono[0]] except KeyError: pass # Overwritten del self.krono[0] self.data[key] = item self.krono.append(key) finally: self.lock.release()
Python
import os, sys, time, gobject, traceback, threading from GtkWorker import EmitPublisher, Publisher from prefix import getUserDataPrefix, addUserDataPrefix from pychess.Utils.const import LOG_DEBUG, LOG_LOG, LOG_WARNING, LOG_ERROR from pychess.System.glock import gdklocks from pychess.System.ThreadPool import pool MAXFILES = 10 DEBUG = True labels = {LOG_DEBUG: "Debug", LOG_LOG: "Log", LOG_WARNING: "Warning", LOG_ERROR: "Error"} class LogPipe: def __init__ (self, to, flag=""): self.to = to self.flag = flag def write (self, data): try: self.to.write(data) except IOError: if self.flag == "stdout": # Certainly hope we never end up here pass else: log.error("Could not write data '%s' to pipe '%s'" % (data, repr(self.to))) if log: log.debug (data, self.flag) #self.flush() def flush (self): self.to.flush() #log.debug (".flush()", self.flag) def fileno (self): return self.to.fileno() class Log (gobject.GObject): __gsignals__ = { "logged": (gobject.SIGNAL_RUN_FIRST, None, (object,)) } # list of (str, float, str, int) def __init__ (self, logpath): gobject.GObject.__init__(self) self.file = open(logpath, "w") self.printTime = True # We store everything in this list, so that the LogDialog, which is # imported a little later, will have all data ever given to Log. # When Dialog inits, it will set this list to None, and we will stop # appending data to it. Ugly? Somewhat I guess. self.messages = [] self.publisher = EmitPublisher (self, "logged", Publisher.SEND_LIST) self.publisher.start() def _format (self, task, message, type): t = time.strftime ("%H:%M:%S") return "%s %s %s: %s" % (t, task, labels[type], message.decode("latin-1")) def _log (self, task, message, type): if not message: return if self.messages != None: self.messages.append((task, time.time(), message, type)) self.publisher.put((task, time.time(), message, type)) if self.printTime: message = self._format(task, message, type) self.printTime = message.endswith("\n") try: self.file.write(message) self.file.flush() except IOError, e: if not type == LOG_ERROR: self.error("Unable to write '%s' to log file because of error: %s" % \ (message, ", ".join(str(a) for a in e.args))) if type in (LOG_ERROR, LOG_WARNING) and task != "stdout": print message def debug (self, message, task="Default"): if DEBUG: self._log (task, message, LOG_DEBUG) def log (self, message, task="Default"): self._log (task, message, LOG_LOG) def warn (self, message, task="Default"): self._log (task, message, LOG_WARNING) def error (self, message, task="Default"): self._log (task, message, LOG_ERROR) oldlogs = [l for l in os.listdir(getUserDataPrefix()) if l.endswith(".log")] if len(oldlogs) >= MAXFILES: oldlogs.sort() try: os.remove(addUserDataPrefix(oldlogs[0])) except OSError, e: pass newName = time.strftime("%Y-%m-%d_%H-%M-%S") + ".log" log = Log(addUserDataPrefix(newName)) sys.stdout = LogPipe(sys.stdout, "stdout") sys.stderr = LogPipe(sys.stderr, "stdout") def start_thread_dump (): def thread_dumper (): def dump_threads (): id2name = {} for thread in threading.enumerate(): id2name[thread.ident] = thread.name stacks = [] for thread_id, frame in sys._current_frames().items(): stack = traceback.format_list(traceback.extract_stack(frame)) if thread_id in gdklocks: stacks.append("Thread GdkLock count: %s" % str(gdklocks[thread_id])) stacks.append("Thread: %s (%d)" % (id2name[thread_id], thread_id)) stacks.append("".join(stack)) log.debug("\n".join(stacks)) while 1: dump_threads() time.sleep(10) pool.start(thread_dumper)
Python
# -*- coding: UTF-8 -*- from gobject import GObject, SIGNAL_RUN_FIRST from pychess.System.Log import log from pychess.System.SubProcess import SubProcess, searchPath import re class Pinger (GObject): """ The recieved signal contains the time it took to get response from the server in millisecconds. -1 means that some error occurred """ __gsignals__ = { "recieved": (SIGNAL_RUN_FIRST, None, (float,)), "error": (SIGNAL_RUN_FIRST, None, (str,)) } def __init__ (self, host): GObject.__init__(self) self.host = host self.subproc = None self.expression = re.compile("time=([\d\.]+) (m?s)") # We need untranslated error messages in regexp search # below, so have to use deferred translation here def _(msg): return msg error = _("Destination Host Unreachable") self.errorExprs = ( re.compile("(%s)" % error), ) del _ self.restartsOnDead = 3 self.deadCount = 0 def start (self): assert not self.subproc self.subproc = SubProcess(searchPath("ping"), [self.host], env={"LANG":"en"}) self.conid1 = self.subproc.connect("line", self.__handleLines) self.conid2 = self.subproc.connect("died", self.__handleDead) def __handleLines (self, subprocess, lines): for line in lines: self.__handleLine(line) def __handleLine (self, line): match = self.expression.search(line) if match: time, unit = match.groups() time = float(time) if unit == "s": time *= 1000 self.emit("recieved", time) else: for expr in self.errorExprs: match = expr.search(line) if match: msg = match.groups()[0] self.emit("error", _(msg)) def __handleDead (self, subprocess): if self.deadCount < self.restartsOnDead: log.warn("Pinger died and restarted (%d/%d)\n" % (self.deadCount+1, self.restartsOnDead), self.subproc.defname) self.stop() self.start() self.deadCount += 1 else: self.emit("error", _("Died")) self.stop() def stop (self): assert self.subproc exitCode = self.subproc.gentleKill() self.subproc.disconnect(self.conid1) self.subproc.disconnect(self.conid2) self.subproc = None if __name__ == "__main__": pinger = Pinger("google.com") def callback(pinger, time): print time pinger.connect("recieved", callback) pinger.start() import time time.sleep(5) pinger.stop() time.sleep(3)
Python
""" This module provides some basic functions for accessing pychess datefiles in system or user space """ import os import sys from os import makedirs from os.path import isdir, join, dirname, abspath ################################################################################ # Locate files in system space # ################################################################################ # Test if we are installed on the system, or are being run from tar/svn if sys.prefix in __file__: for sub in ("share", "games", "share/games", "local/share", "local/games", "local/share/games"): _prefix = join (sys.prefix, sub, "pychess") if isdir(_prefix): _installed = True break else: raise Exception("can't find the pychess data directory") else: _prefix = abspath (join (dirname (__file__), "../../..")) _installed = False def addDataPrefix (subpath): return abspath (join (_prefix, subpath)) def getDataPrefix (): return _prefix def isInstalled (): return _installed ################################################################################ # Locate files in user space # ################################################################################ # The glib.get_user_*_dir() XDG functions below require pygobject >= 2.18 try: from glib import get_user_data_dir, get_user_config_dir, get_user_cache_dir except ImportError: def __get_user_dir (xdg_env_var, fallback_dir_path): try: directory = os.environ[xdg_env_var] except KeyError: directory = join(os.environ["HOME"], fallback_dir_path) return directory def get_user_data_dir (): return __get_user_dir("XDG_DATA_HOME", ".local/share") def get_user_config_dir (): return __get_user_dir("XDG_CONFIG_HOME", ".config") def get_user_cache_dir (): return __get_user_dir("XDG_CACHE_HOME", ".cache") pychess = "pychess" def getUserDataPrefix (): return join(get_user_data_dir(), pychess) def addUserDataPrefix (subpath): return join(getUserDataPrefix(), subpath) def getEngineDataPrefix (): return join(getUserDataPrefix(), "engines") def addEngineDataPrefix (subpath): return join(getEngineDataPrefix(), subpath) def getUserConfigPrefix (): return join(get_user_config_dir(), pychess) def addUserConfigPrefix (subpath): return join(getUserConfigPrefix(), subpath) def getUserCachePrefix (): return join(get_user_cache_dir(), pychess) def addUserCachePrefix (subpath): return join(getUserCachePrefix(), subpath) for directory in (getUserDataPrefix(), getEngineDataPrefix(), getUserConfigPrefix(), getUserCachePrefix()): if not isdir(directory): makedirs(directory, mode=0700)
Python
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475160 # Was accepted into Python 2.5, but earlier versions still have # to do stuff manually import threading from Queue import Queue def TaskQueue (): if hasattr(Queue, "task_done"): return Queue() return _TaskQueue() class _TaskQueue(Queue): def __init__(self): Queue.__init__(self) self.all_tasks_done = threading.Condition(self.mutex) self.unfinished_tasks = 0 def _put(self, item): Queue._put(self, item) self.unfinished_tasks += 1 def task_done(self): """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. """ self.all_tasks_done.acquire() try: unfinished = self.unfinished_tasks - 1 if unfinished <= 0: if unfinished < 0: raise ValueError('task_done() called too many times') self.all_tasks_done.notifyAll() self.unfinished_tasks = unfinished finally: self.all_tasks_done.release() def join(self): """Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. """ self.all_tasks_done.acquire() try: while self.unfinished_tasks: self.all_tasks_done.wait() finally: self.all_tasks_done.release()
Python
import os import sys import signal import errno import time import threading import gtk import gobject from pychess.Utils.const import * from Log import log from which import which from pychess.System.ThreadPool import pool from pychess.System import glock from pychess.System.GtkWorker import EmitPublisher class SubProcessError (Exception): pass class TimeOutError (Exception): pass def searchPath (file, access=os.R_OK, altpath=None): if altpath and os.path.isfile(altpath): if not os.access (altpath, access): log.warn("Not enough permissions on %s\n" % altpath) else: return altpath try: return which(file, mode=access) except IOError: log.log("%s not found\n" % file) return None subprocesses = [] def finishAllSubprocesses (): for subprocess in subprocesses: if subprocess.subprocExitCode[0] == None: subprocess.gentleKill(0,0.3) for subprocess in subprocesses: subprocess.subprocFinishedEvent.wait() class SubProcess (gobject.GObject): __gsignals__ = { "line": (gobject.SIGNAL_RUN_FIRST, None, (object,)), "died": (gobject.SIGNAL_RUN_FIRST, None, ()) } def __init__(self, path, args=[], warnwords=[], env=None, chdir="."): gobject.GObject.__init__(self) self.path = path self.args = args self.warnwords = warnwords self.env = env or os.environ self.buffer = "" self.linePublisher = EmitPublisher(self, "line", EmitPublisher.SEND_LIST) self.linePublisher.start() self.defname = os.path.split(path)[1] self.defname = self.defname[:1].upper() + self.defname[1:].lower() t = time.time() self.defname = (self.defname, time.strftime("%H:%m:%%.3f",time.localtime(t)) % (t%60)) log.debug(path+"\n", self.defname) argv = [str(u) for u in [self.path]+self.args] self.pid, stdin, stdout, stderr = gobject.spawn_async(argv, working_directory=chdir, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=gobject.SPAWN_DO_NOT_REAP_CHILD|gobject.SPAWN_SEARCH_PATH) self.__channelTags = [] self.inChannel = self._initChannel(stdin, None, None, False) readFlags = gobject.IO_IN|gobject.IO_HUP#|gobject.IO_ERR self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False) self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True) self.channelsClosed = False self.channelsClosedLock = threading.Lock() gobject.child_watch_add(self.pid, self.__child_watch_callback) self.subprocExitCode = (None, None) self.subprocFinishedEvent = threading.Event() self.subprocFinishedEvent.clear() subprocesses.append(self) pool.start(self._wait4exit) def _initChannel (self, filedesc, callbackflag, callback, isstderr): channel = gobject.IOChannel(filedesc) if sys.platform != "win32": channel.set_flags(gobject.IO_FLAG_NONBLOCK) if callback: tag = channel.add_watch(callbackflag, callback, isstderr) self.__channelTags.append(tag) return channel def _closeChannels (self): self.channelsClosedLock.acquire() try: if self.channelsClosed == True: return self.channelsClosed = True finally: self.channelsClosedLock.release() for tag in self.__channelTags: gobject.source_remove(tag) for channel in (self.inChannel, self.outChannel, self.errChannel): try: channel.close() except gobject.GError, error: pass def __setup (self): os.nice(15) def __child_watch_callback (self, pid, code): # Kill the engine on any signal but 'Resource temporarily unavailable' if code != errno.EWOULDBLOCK: if type(code) == str: log.error(code+"\n", self.defname) else: log.error(os.strerror(code)+"\n", self.defname) self.emit("died") self.gentleKill() def __io_cb (self, channel, condition, isstderr): while True: try: line = channel.next()#readline() except StopIteration: self._wait4exit() self.__child_watch_callback(*self.subprocExitCode) break if not line: return True if isstderr: log.error(line, self.defname) else: for word in self.warnwords: if word in line: log.warn(line, self.defname) break else: log.debug(line, self.defname) self.linePublisher.put(line) def write (self, data): if self.channelsClosed: log.warn("Chan closed for %r" % data, self.defname) return log.log(data, self.defname) self.inChannel.write(data) if data.endswith("\n"): try: self.inChannel.flush() except gobject.GError, e: log.error(str(e)+". Last line wasn't sent.\n", self.defname) def _wait4exit (self): try: pid, code = os.waitpid(self.pid, 0) except OSError, error: if error.errno == errno.ECHILD: pid, code = self.pid, error.errno else: raise self.subprocExitCode = (code, os.strerror(code)) def sendSignal (self, sign): try: if sys.platform != "win32": os.kill(self.pid, signal.SIGCONT) os.kill(self.pid, sign) except OSError, error: if error.errno == errno.ESRCH: #No such process pass else: raise OSError, error def gentleKill (self, first=1, second=1): if pool is not None: pool.start(self.__gentleKill_inner, first, second) def __gentleKill_inner (self, first, second): self.resume() self._closeChannels() time.sleep(first) code, string = self.subprocExitCode if code == None: self.sigterm() time.sleep(second) code, string = self.subprocExitCode if code == None: self.sigkill() self.subprocFinishedEvent.set() return self.subprocExitCode[0] self.subprocFinishedEvent.set() return code self.subprocFinishedEvent.set() return code def pause (self): self.sendSignal(signal.SIGSTOP) def resume (self): if sys.platform != "win32": self.sendSignal(signal.SIGCONT) def sigkill (self): self.sendSignal(signal.SIGKILL) def sigterm (self): self.sendSignal(signal.SIGTERM) def sigint (self): self.sendSignal(signal.SIGINT) if __name__ == "__main__": loop = gobject.MainLoop() paths = ("igang.dk", "google.com", "google.dk", "myspace.com", "yahoo.com") maxlen = max(len(p) for p in paths) def callback (subp, line, path): print "\t", path.ljust(maxlen), line.rstrip("\n") for path in paths: subp = SubProcess("/bin/ping", [path]) subp.connect("line", callback, path) loop.run()
Python
import gconf from os.path import normpath GDIR = '/apps/pychess/' c = gconf.client_get_default() c.add_dir(GDIR[:-1], gconf.CLIENT_PRELOAD_NONE) def notify_add (key, func): key = normpath(GDIR+key) return c.notify_add(key, func) def notify_remove (conid): c.notify_remove(conid) def get (key): key = normpath(GDIR+key) value = c.get(key) if value.type == gconf.VALUE_BOOL: return value.get_bool() if value.type == gconf.VALUE_FLOAT: return value.get_float() if value.type == gconf.VALUE_INT: return value.get_int() if value.type == gconf.VALUE_STRING: return value.get_string() def set (key, value): key = normpath(GDIR+key) typ = type(value) if typ == bool: c.set_bool(value) if typ == float: c.set_float(value) if typ == int: c.set_int(value) if typ == str: c.set_string(value) def any (gen): for item in gen: if item: return True return False def hasKey (key): key = normpath(GDIR+key) return any(key == entry.get_key() for entry in c.all_entries(GDIR))
Python
""" This is a threadsafe wrapper sqlite. It is not classbased, so only one database can be open at a time """ import sqlite3 as sqlite import Queue, time, os from threading import Thread sqlqueue = Queue.Queue() SQL_CMD, END_CMD = range(2) class DbWrapper(Thread): def __init__(self, path): Thread.__init__(self) self.setDaemon(True) self.path = path def run(self): con = sqlite.connect(self.path) cur = con.cursor() while True: cmd, queries, resultqueue = sqlqueue.get() # print "Conn %d -> %s -> %s" % (self.nr, cmd, queries) if cmd == SQL_CMD: commitneeded = False res = [] for sql in queries: try: cur.execute(sql) except Exception, e: print sql raise e if not sql.upper().startswith("SELECT"): commitneeded = True res += cur.fetchall() if commitneeded: con.commit() resultqueue.put(res) else: # allow other threads to stop sqlqueue.put((cmd, queries, resultqueue)) resultqueue.put(None) break def connect (path): wrap = DbWrapper(path) wrap.start() def close (): resultqueue = Queue.Queue() sqlqueue.put((END_CMD, [], resultqueue)) resultqueue.get() def execSQL (*queries): resultqueue = Queue.Queue() sqlqueue.put((SQL_CMD, queries, resultqueue)) return resultqueue.get() if __name__ == "__main__": dbname = "test.db" connect (dbname) execSQL ("drop table if exists people", "create table people (name_last, age integer)") # don't add connections before creating table connect (dbname) # insert one row execSQL ("insert into people (name_last, age) values ('Smith', 80)") # insert two rows in one transaction execSQL ("insert into people (name_last, age) values ('Jones', 55)", "insert into people (name_last, age) values ('Gruns', 25)") for name, age in execSQL ("select * from people"): print "%s: %d" % (name, age) close() os.remove(dbname)
Python
import sys, traceback from threading import RLock, currentThread from gtk.gdk import threads_enter, threads_leave import time from pychess.System.prefix import addUserDataPrefix #logfile = open(addUserDataPrefix(time.strftime("%Y-%m-%d_%H-%M-%S") + "-glocks.log"), "w") debug = False debug_stream = sys.stdout gdklocks = {} _rlock = RLock() def has(): me = currentThread() if type(_rlock._RLock__owner) == int: return _rlock._RLock__owner == me._Thread__ident return _rlock._RLock__owner == me def acquire(): me = currentThread() t = time.strftime("%H:%M:%S") if me.ident not in gdklocks: gdklocks[me.ident] = 0 # Ensure we don't deadlock if another thread is waiting on threads_enter # while we wait on _rlock.acquire() if me.getName() == "MainThread" and not has(): if debug: print >> debug_stream, "%s %s: %s: glock.acquire: ---> threads_leave()" % (t, me.ident, me.name) threads_leave() gdklocks[me.ident] -= 1 if debug: print >> debug_stream, "%s %s: %s: glock.acquire: <--- threads_leave()" % (t, me.ident, me.name) # Acquire the lock, if it is not ours, or add one to the recursive counter if debug: print >> debug_stream, "%s %s: %s: glock.acquire: ---> _rlock.acquire()" % (t, me.ident, me.name) _rlock.acquire() if debug: print >> debug_stream, "%s %s: %s: glock.acquire: <--- _rlock.acquire()" % (t, me.ident, me.name) # If it is the first time we lock, we will acquire the gdklock if _rlock._RLock__count == 1: if debug: print >> debug_stream, "%s %s: %s: glock.acquire: ---> threads_enter()" % (t, me.ident, me.name) threads_enter() gdklocks[me.ident] += 1 if debug: print >> debug_stream, "%s %s: %s: glock.acquire: <--- threads_enter()" % (t, me.ident, me.name) def release(): me = currentThread() t = time.strftime("%H:%M:%S") # 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(): if debug: print >> debug_stream, "%s %s: %s: glock.release: ---> threads_leave()" % (t, me.ident, me.name) threads_leave() gdklocks[me.ident] -= 1 if debug: print >> debug_stream, "%s %s: %s: glock.release: <--- threads_leave()" % (t, me.ident, me.name) else: if debug: print >> debug_stream, "%s %s: %s: glock.release: ---> _rlock.release()" % (t, me.ident, me.name) _rlock.release() if debug: print >> debug_stream, "%s %s: %s: glock.release: <--- _rlock.release()" % (t, me.ident, me.name) # If this is the last unlock, we also free the gdklock. elif has(): if _rlock._RLock__count == 1: if debug: print >> debug_stream, "%s %s: %s: glock.release: ---> threads_leave()" % (t, me.ident, me.name) threads_leave() gdklocks[me.ident] -= 1 if debug: print >> debug_stream, "%s %s: %s: glock.release: <--- threads_leave()" % (t, me.ident, me.name) if debug: print >> debug_stream, "%s %s: %s: glock.release: ---> _rlock.release()" % (t, me.ident, me.name) _rlock.release() if debug: print >> debug_stream, "%s %s: %s: glock.release: <--- _rlock.release()" % (t, me.ident, me.name) else: print "%s %s: %s: Warning: Tried to release unowned glock\nTraceback was: %s" % \ (t, me.ident, me.name, traceback.extract_stack()) def glock_connect(emitter, signal, function, *args, **kwargs): def handler(emitter, *extra): acquire() try: function(emitter, *extra) finally: release() if "after" in kwargs and kwargs["after"]: return emitter.connect_after(signal, handler, *args) return emitter.connect(signal, handler, *args) def glock_connect_after(emitter, signal, function, *args): return glock_connect(emitter, signal, function, after=True, *args) def glocked(f): def newFunction(*args, **kw): acquire() try: return f(*args, **kw) finally: release() return newFunction if __name__ == "__main__": from threading import Thread def do (): acquire() acquire() release() print _rlock._RLock__owner print currentThread() release() print _rlock._RLock__owner t = Thread(target=do) t.start() t.join()
Python
from pychess.System import conf, glock from pychess.System.Log import log from pychess.System.ThreadPool import pool from pychess.System.prefix import addDataPrefix from pychess.widgets.ToggleComboBox import ToggleComboBox import Queue import colorsys import gtk.glade import pango import re import webbrowser def createCombo (combo, data): ls = gtk.ListStore(gtk.gdk.Pixbuf, str) for icon, label in data: ls.append([icon, label]) combo.clear() combo.set_model(ls) crp = gtk.CellRendererPixbuf() crp.set_property('xalign',0) crp.set_property('xpad', 2) combo.pack_start(crp, False) combo.add_attribute(crp, 'pixbuf', 0) crt = gtk.CellRendererText() crt.set_property('xalign',0) crt.set_property('xpad', 4) combo.pack_start(crt, True) combo.add_attribute(crt, 'text', 1) #crt.set_property('ellipsize', pango.ELLIPSIZE_MIDDLE) def updateCombo (combo, data): def get_active(combobox): model = combobox.get_model() active = combobox.get_active() if active < 0: return None return model[active][1] last_active = get_active(combo) ls = combo.get_model() ls.clear() new_active = 0 for i, row in enumerate(data): ls.append(row) if last_active == row[1]: new_active = i combo.set_active(new_active) def genColor (n, startpoint=0): assert n >= 1 # This splits the 0 - 1 segment in the pizza way h = (2*n-1)/(2.**int.bit_length(n-1))-1 h = (h + startpoint) % 1 # We set saturation based on the amount of green, scaled to the interval # [0.6..0.8]. This ensures a consistent lightness over all colors. rgb = colorsys.hsv_to_rgb(h, 1, 1) rgb = colorsys.hsv_to_rgb(h, 1, (1-rgb[1])*0.2+0.6) # This algorithm ought to balance colors more precisely, but it overrates # the lightness of yellow, and nearly makes it black # yiq = colorsys.rgb_to_yiq(*rgb) # rgb = colorsys.yiq_to_rgb(.125, yiq[1], yiq[2]) return rgb def keepDown (scrolledWindow): def changed (vadjust): if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll: vadjust.set_value(vadjust.upper-vadjust.page_size) vadjust.need_scroll = True scrolledWindow.get_vadjustment().connect("changed", changed) def value_changed (vadjust): vadjust.need_scroll = abs(vadjust.value + vadjust.page_size - \ vadjust.upper) < vadjust.step_increment scrolledWindow.get_vadjustment().connect("value-changed", value_changed) def appendAutowrapColumn (treeview, defwidth, name, **kvargs): cell = gtk.CellRendererText() cell.props.wrap_mode = pango.WRAP_WORD cell.props.wrap_width = defwidth column = gtk.TreeViewColumn(name, cell, **kvargs) treeview.append_column(column) def callback (treeview, allocation, column, cell): otherColumns = (c for c in treeview.get_columns() if c != column) newWidth = allocation.width - sum(c.get_width() for c in otherColumns) newWidth -= treeview.style_get_property("horizontal-separator") * 2 if cell.props.wrap_width == newWidth or newWidth <= 0: return cell.props.wrap_width = newWidth store = treeview.get_model() iter = store.get_iter_first() while iter and store.iter_is_valid(iter): store.row_changed(store.get_path(iter), iter) iter = store.iter_next(iter) treeview.set_size_request(0,-1) treeview.connect_after("size-allocate", callback, column, cell) scroll = treeview.get_parent() if isinstance(scroll, gtk.ScrolledWindow): scroll.set_policy(gtk.POLICY_NEVER, scroll.get_policy()[1]) return cell METHODS = ( # gtk.SpinButton should be listed prior to gtk.Entry, as it is a # subclass, but requires different handling (gtk.SpinButton, ("get_value", "set_value", "value-changed")), (gtk.Entry, ("get_text", "set_text", "changed")), (gtk.Expander, ("get_expanded", "set_expanded", "notify::expanded")), (gtk.ComboBox, ("get_active", "set_active", "changed")), # gtk.ToggleComboBox should be listed prior to gtk.ToggleButton, as it is a # subclass, but requires different handling (ToggleComboBox, ("_get_active", "_set_active", "changed")), (gtk.ToggleButton, ("get_active", "set_active", "toggled")), (gtk.CheckMenuItem, ("get_active", "set_active", "toggled")), (gtk.Range, ("get_value", "set_value", "value-changed"))) def keep (widget, key, get_value_=None, set_value_=None, first_value=None): if widget == None: raise AttributeError, "key '%s' isn't in widgets" % key for class_, methods_ in METHODS: if isinstance(widget, class_): getter, setter, signal = methods_ break else: raise AttributeError, "I don't have any knowledge of type: '%s'" % widget if get_value_: get_value = lambda: get_value_(widget) else: get_value = getattr(widget, getter) if set_value_: set_value = lambda v: set_value_(widget, v) else: set_value = getattr(widget, setter) def setFromConf (): try: v = conf.getStrict(key) except TypeError: log.warn("uistuff.keep.setFromConf: Key '%s' from conf had the wrong type '%s', ignored" % \ (key, type(conf.getStrict(key)))) if first_value != None: conf.set(key, first_value) else: conf.set(key, get_value()) else: set_value(v) def callback(*args): if not conf.hasKey(key) or conf.getStrict(key) != get_value(): conf.set(key, get_value()) widget.connect(signal, callback) conf.notify_add(key, lambda *args: setFromConf()) if conf.hasKey(key): setFromConf() elif first_value != None: conf.set(key, first_value) # loadDialogWidget() and saveDialogWidget() are similar to uistuff.keep() but are needed # for saving widget values for gtk.Dialog instances that are loaded with different # sets of values/configurations and which also aren't instant save like in # uistuff.keep(), but rather are saved later if and when the user clicks # the dialog's OK button def loadDialogWidget (widget, widget_name, config_number, get_value_=None, set_value_=None, first_value=None): key = widget_name + "-" + str(config_number) if widget == 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_ == None: raise AttributeError, "I don't have any knowledge of type: '%s'" % widget if get_value_: get_value = lambda: get_value_(widget) else: get_value = getattr(widget, getter) if set_value_: set_value = lambda v: set_value_(widget, v) else: set_value = getattr(widget, setter) if conf.hasKey(key): try: v = conf.getStrict(key) except TypeError: log.warn("uistuff.loadDialogWidget: 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) elif first_value != None: conf.set(key, first_value) set_value(conf.getStrict(key)) else: log.warn("Didn't load widget \"%s\": no conf value and no first_value arg" % \ widget_name) def saveDialogWidget (widget, widget_name, config_number, get_value_=None): key = widget_name + "-" + str(config_number) if widget == 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 get_value_ == None: raise AttributeError, "I don't have any knowledge of type: '%s'" % widget if get_value_: get_value = lambda: get_value_(widget) else: get_value = getattr(widget, getter) if not conf.hasKey(key) or conf.getStrict(key) != get_value(): conf.set(key, get_value()) POSITION_NONE, POSITION_CENTER, POSITION_GOLDEN = range(3) def keepWindowSize (key, window, defaultSize=None, defaultPosition=POSITION_NONE): """ You should call keepWindowSize before show on your windows """ key = key + "window" def savePosition (window, *event): width = window.get_allocation().width height = window.get_allocation().height x, y = window.get_position() if width <= 0: log.error("Setting width = '%d' for %s to conf" % (width,key)) if height <= 0: log.error("Setting height = '%d' for %s to conf" % (height,key)) conf.set(key+"_width", width) conf.set(key+"_height", height) conf.set(key+"_x", x) conf.set(key+"_y", y) window.connect("delete-event", savePosition, "delete-event") def loadPosition (window): width, height = window.get_size_request() if conf.hasKey(key+"_width") and conf.hasKey(key+"_height"): width = conf.getStrict(key+"_width") height = conf.getStrict(key+"_height") window.resize(width, height) elif defaultSize: width, height = defaultSize window.resize(width, height) if conf.hasKey(key+"_x") and conf.hasKey(key+"_y"): window.move(conf.getStrict(key+"_x"), conf.getStrict(key+"_y")) elif defaultPosition in (POSITION_CENTER, POSITION_GOLDEN): monitor_x, monitor_y, monitor_width, monitor_height = getMonitorBounds() x = int(monitor_width/2-width/2) + monitor_x if defaultPosition == POSITION_CENTER: y = int(monitor_height/2-height/2) + monitor_y else: # Place the window on the upper golden ratio line y = int(monitor_height/2.618-height/2) + monitor_y window.move(x, y) loadPosition(window) # In rare cases, gtk throws some gtk_size_allocation error, which is # probably a race condition. To avoid the window forgets its size in # these cases, we add this extra hook def callback (window): loadPosition(window) onceWhenReady(window, callback) # Some properties can only be set, once the window is sufficiently initialized, # This function lets you queue your request until that has happened. def onceWhenReady(window, func, *args, **kwargs): def cb(window, alloc, func, *args, **kwargs): func(window, *args, **kwargs) window.disconnect(handler_id) handler_id = window.connect_after("size-allocate", cb, func, *args, **kwargs) def getMonitorBounds(): screen = gtk.gdk.screen_get_default() root_window = screen.get_root_window() mouse_x, mouse_y, mouse_mods = root_window.get_pointer() current_monitor_number = screen.get_monitor_at_point(mouse_x,mouse_y) monitor_geometry = screen.get_monitor_geometry(current_monitor_number) return monitor_geometry.x, monitor_geometry.y, monitor_geometry.width, monitor_geometry.height tooltip = gtk.Window(gtk.WINDOW_POPUP) tooltip.set_name('gtk-tooltip') tooltip.ensure_style() tooltipStyle = tooltip.get_style() def makeYellow (box): def on_box_expose_event (box, event): box.style.paint_flat_box (box.window, gtk.STATE_NORMAL, gtk.SHADOW_NONE, None, box, "tooltip", box.allocation.x, box.allocation.y, box.allocation.width, box.allocation.height) def cb (box): box.set_style(tooltipStyle) box.connect("expose-event", on_box_expose_event) onceWhenReady(box, cb) linkre = re.compile("http://(?:www\.)?\w+\.\w{2,4}[^\s]+") emailre = re.compile("[\w\.]+@[\w\.]+\.\w{2,4}") def initTexviewLinks (textview, text): tags = [] textbuffer = textview.get_buffer() while True: linkmatch = linkre.search(text) emailmatch = emailre.search(text) if not linkmatch and not emailmatch: textbuffer.insert (textbuffer.get_end_iter(), text) break if emailmatch and (not linkmatch or \ emailmatch.start() < linkmatch.start()): s = emailmatch.start() e = emailmatch.end() type = "email" else: s = linkmatch.start() e = linkmatch.end() if text[e-1] == ".": e -= 1 type = "link" textbuffer.insert (textbuffer.get_end_iter(), text[:s]) tag = textbuffer.create_tag (None, foreground="blue", underline=pango.UNDERLINE_SINGLE) tags.append([tag, text[s:e], type, textbuffer.get_end_iter()]) textbuffer.insert_with_tags ( textbuffer.get_end_iter(), text[s:e], tag) tags[-1].append(textbuffer.get_end_iter()) text = text[e:] def on_press_in_textview (textview, event): iter = textview.get_iter_at_location (int(event.x), int(event.y)) if not iter: return for tag, link, type, s, e in tags: if iter.has_tag(tag): tag.props.foreground = "red" break def on_release_in_textview (textview, event): iter = textview.get_iter_at_location (int(event.x), int(event.y)) if not iter: return for tag, link, type, s, e in tags: if iter and iter.has_tag(tag) and \ tag.props.foreground_gdk.red == 0xffff: if type == "link": webbrowser.open(link) else: webbrowser.open("mailto:"+link) tag.props.foreground = "blue" stcursor = gtk.gdk.Cursor(gtk.gdk.XTERM) linkcursor = gtk.gdk.Cursor(gtk.gdk.HAND2) def on_motion_in_textview(textview, event): textview.window.get_pointer() iter = textview.get_iter_at_location (int(event.x), int(event.y)) if not iter: return for tag, link, type, s, e in tags: if iter.has_tag(tag): textview.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor ( linkcursor) break else: textview.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(stcursor) textview.connect ("motion-notify-event", on_motion_in_textview) textview.connect ("leave_notify_event", on_motion_in_textview) textview.connect("button_press_event", on_press_in_textview) textview.connect("button_release_event", on_release_in_textview) def LinkLabel (text, url): label = gtk.Label() eventbox = gtk.EventBox() label.set_markup("<span color='blue'><u>%s</u></span>" % text) eventbox.add(label) def released (eventbox, event): webbrowser.open(url) label.set_markup("<span color='blue'><u>%s</u></span>" % text) eventbox.connect("button_release_event", released) def pressed (eventbox, event): label.set_markup("<span color='red'><u>%s</u></span>" % text) eventbox.connect("button_press_event", pressed) eventbox.connect_after("realize", lambda w: w.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND2))) return eventbox cachedGlades = {} def cacheGladefile(filename): """ gtk.glade automatically caches the file, so we only need to use this file once """ if filename not in cachedGlades: cachedGlades[filename] = Queue.Queue() def readit (): glade = gtk.glade.XML(addDataPrefix("glade/%s" % filename)) cachedGlades[filename].put(glade) pool.start(readit) class GladeWidgets: """ A simple class that wraps a the glade get_widget function into the python __getitem__ version """ def __init__ (self, filename): self.glade = None try: if filename in cachedGlades: self.glade = cachedGlades[filename].get(block=False) except Queue.Empty: pass if not self.glade: glock.acquire() # print "uistuff.py:gladefile = %s" % filename self.glade = gtk.glade.XML(addDataPrefix("glade/%s" % filename)) glock.release() self.extras = {} def __getitem__(self, key): if key in self.extras: return self.extras[key] return self.glade.get_widget(key) def __setitem__(self, key, widget): self.extras[key] = widget def getGlade (self): return self.glade
Python
import urllib, os def splitUri (uri): uri = urllib.url2pathname(uri) # escape special chars uri = uri.strip('\r\n\x00') # remove \r\n and NULL return uri.split("://") def protoopen (uri): """ Function for opening many things """ try: return urllib.urlopen(uri) except (IOError, OSError): pass try: return open(uri) except (IOError, OSError): pass raise IOError, "Protocol isn't supported by pychess" def protosave (uri, append=False): """ Function for saving many things """ splitted = splitUri(uri) if splitted[0] == "file": if append: return file(splitted[1], "a") return file(splitted[1], "w") elif len(splitted) == 1: if append: return file(splitted[0], "a") return file(splitted[0], "w") raise IOError, "PyChess doesn't support writing to protocol" def isWriteable (uri): """ Returns true if protoopen can open a write pipe to the uri """ splitted = splitUri(uri) if splitted[0] == "file": return os.access (splitted[1], os.W_OK) elif len(splitted) == 1: return os.access (splitted[0], os.W_OK) return False
Python
from ctypes import * l=CDLL('librsvg-2-2.dll') g=CDLL('libgobject-2.0-0.dll') g.g_type_init() class Props(): def __init__(self, dimension): self.width, self.height = dimension class rsvgHandle(): class RsvgDimensionData(Structure): _fields_ = [("width", c_int), ("height", c_int), ("em",c_double), ("ex",c_double)] class PycairoContext(Structure): _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__), ("ctx", c_void_p), ("base", c_void_p)] def __init__(self, path): self.path = path error = '' self.handle = l.rsvg_handle_new_from_file(self.path,error) self.props = Props(self.get_dimension_data()) def get_dimension_data(self): svgDim = self.RsvgDimensionData() l.rsvg_handle_get_dimensions(self.handle,byref(svgDim)) return (svgDim.width,svgDim.height) def render_cairo(self, ctx): ctx.save() z = self.PycairoContext.from_address(id(ctx)) l.rsvg_handle_render_cairo(self.handle, z.ctx) ctx.restore() class rsvgClass(): def Handle(self,file): return rsvgHandle(file) rsvg = rsvgClass()
Python
""" The task of this module is to provide easy saving/loading of configurations It also supports gconf like connection, so you get notices when a property has changed. """ # gconf's notify all seams to be broken #try: # import gconf # import conf_gconf as confmodule #except: import conf_configParser as confmodule """Module for using gconf without having to care about types""" def notify_add (key, func, *args): """The signature for func must be self, client, *args, **kwargs""" assert isinstance(key, str) return confmodule.notify_add(key, func, args) def notify_remove (conid): confmodule.notify_remove(conid) def getStrict (key): assert hasKey (key) return confmodule.get(key) def get (key, alternative): if hasKey (key): return confmodule.get(key) if callable(alternative): alternative = alternative() return alternative def set (key, value): confmodule.set(key, value) def hasKey (key): return confmodule.hasKey(key) import sys, os if sys.platform == "win32": username = os.environ["USERNAME"] del sys, os else: from os import getuid from pwd import getpwuid userdata = getpwuid(getuid()) realname = userdata.pw_gecos.split(",")[0] if realname: username = realname else: username = userdata.pw_name del getuid, getpwuid del sys, os del userdata, realname
Python
# -*- coding: UTF-8 -*- import time from pychess.System.ThreadPool import pool def repeat (func, *args, **kwargs): """ Repeats a function in a new thread until it returns False """ def run (): while func(*args, **kwargs): pass pool.start(run) def repeat_sleep (func, sleeptime, recur=False): """ Runs func in a threadpool, and repeats it approximately each sleeptime [s]. 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 pool.start(run)
Python
from threading import Thread import Queue from gobject import GObject, SIGNAL_RUN_FIRST from ThreadPool import PooledThread import glock # # IDEA: We could implement gdk prioritizing by using a global PriorityQueue # class Publisher (PooledThread): """ Publisher can be used when a thread is often spitting out results, and you want to process these results in gtk as soon as possible. While waiting for gdk access, results will be stored, and depending on the send policy, either the entire list, or only the last item will be sent as an argument to the function specified in the __init__ """ SEND_LIST, SEND_LAST = range(2) def __init__ (self, func, sendPolicy): self.queue = Queue.Queue() self.func = func self.sendPolicy = sendPolicy def run (self): while True: v = self.queue.get() if v == self.StopNow: break glock.acquire() try: l = [v] while True: try: v = self.queue.get_nowait() except Queue.Empty: break else: if v == self.StopNow: break l.append(v) if self.sendPolicy == self.SEND_LIST: self.func(l) elif self.sendPolicy == self.SEND_LAST: self.func(l[-1]) finally: glock.release() def put (self, task): self.queue.put(task) def __del__ (self): self.queue.put(self.StopNow) class StopNow(Exception): pass class EmitPublisher (Publisher): """ EmitPublisher is a version of Publisher made for the common task of emitting a signal after waiting for the gdklock """ def __init__ (self, parrent, signal, sendPolicy): Publisher.__init__(self, lambda v: parrent.emit(signal, v), sendPolicy) class GtkWorker (GObject, Thread): __gsignals__ = { "progressed": (SIGNAL_RUN_FIRST, None, (float,)), "published": (SIGNAL_RUN_FIRST, None, (object,)), "done": (SIGNAL_RUN_FIRST, None, (object,)) } def __init__ (self, func): """ Initialize a new GtkWorker around a specific function """ GObject.__init__(self) Thread.__init__(self) # 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.handler_ids = {} self.func = func self.cancelled = False self.done = False self.progress = 0 ######################################################################## # Publish and progress queues # ######################################################################## self.publisher = EmitPublisher (self, "published", Publisher.SEND_LIST) self.publisher.start() self.progressor = EmitPublisher (self, "progressed", Publisher.SEND_LAST) self.progressor.start() ############################################################################ # We override the connect/disconnect methods in order to count the number # # of clients connected to each signal. # # This is done for performance reasons, as some work can be skipped, if no # # clients are connected anyways # ############################################################################ def _mul_connect (self, method, signal, handler, *args): self.connections[signal] += 1 handler_id = method (self, signal, handler, *args) self.handler_ids[handler_id] = signal return handler_id def connect (self, detailed_signal, handler, *args): return self._mul_connect (GObject.connect, detailed_signal, handler, *args) def connect_after (self, detailed_signal, handler, *args): return self._mul_connect (GObject.connect_after, detailed_signal, handler, *args) def connect_object (self, detailed_signal, handler, gobject, *args): return self._mul_connect (GObject.connect_object, detailed_signal, handler, gobject, *args) def connect_object_after (self, detailed_signal, handler, gobject, *args): return self._mul_connect (GObject.connect, detailed_signal, handler, gobject, *args) def disconnect (self, handler_id): self.connections[self.handler_ids[handler_id]] -= 1 del self.handler_ids[handler_id] return GObject.disconnect(self, handler_id) handler_disconnect = disconnect ############################################################################ # The following methods (besides run()) are used to interact with the # # worker # ############################################################################ def get (self, timeout=None): """ 'get' will block until the processed function returns, timeout happens, or the work is cancelled. You can test if you were cancelled by the isCancelled() method afterwards. If you call the isAlive() method afterwards and it returns True, then you must have hit the timeout. Notice, cancelling will not make 'get' unblock, even if you build isCancelled() calls into your function. Warning: the get function assumes that if you are the MainThread you have the gdklock and if you are not the MainThread you don't have the gdklock. If this is not true, and the work is not done, calling get will result in a deadlock. If you haven't used the gtk.gdk.threads_enter nor gtk.gdk.threads_leave function, everything should be fine.""" if not self.isDone(): glock.release() self.join(timeout) glock.acquire() if self.isAlive(): return None # if self.done != True by now, the worker thread must have exited abnormally assert self.isDone() return self.result def execute (self): """ Start the worker """ if not self.isDone(): self.start() def run (self): self.result = self.func(self) self.done = True if self.connections["done"] >= 1: glock.acquire() try: # In python 2.5 we can use self.publishQueue.join() to wait for # all publish items to have been processed. self.emit("done", self.result) finally: glock.release() def cancel (self): """ Cancel work. As python has no way of trying to interupt a thread, we don't try to do so. The cancelled attribute is simply set to true, which means that no more signals are emitted. You can build 'isCancelled' calls into your function, to help it exit when it doesn't need to run anymore. while not worker.isCancelled(): ... """ self.cancelled = True self.publisher.__del__() self.progressor.__del__() ############################################################################ # Get stuf # ############################################################################ def isCancelled (self): return self.cancelled def isDone (self): return self.done def getProgress (self): return self.progress ############################################################################ # These methods are used by the function to indicate progress and publish # # process # ############################################################################ def setProgress (self, progress): """ setProgress should be called from inside the processed function. When the gdklock gets ready, it will emit the "progressed" signal, with the value of the latest setProgress call """ if self.isCancelled(): return if self.progress != progress: self.progress = progress self.progressor.put(progress) def publish (self, val): """ Publish should be called from inside the processed function. It will queue up the latest results, and when we get access to the gdklock, it will emit the "published" signal. """ if self.connections["published"] < 1 or self.isCancelled(): return self.publisher.put(val) ############################################################################ # Other # ############################################################################ def __del__ (self): self.cancel() ################################################################################ # Demo usage # ################################################################################ if __name__ == "__main__": def findPrimes (worker): limit = 10**4. primes = [] for n in xrange(2, int(limit)+1): for p in primes: if worker.isCancelled(): return primes if p > n**2: break if n % p == 0: break else: primes.append(n) worker.publish(n) worker.setProgress(n/limit) return primes import gtk w = gtk.Window() vbox = gtk.VBox() w.add(vbox) worker = GtkWorker(findPrimes) sbut = gtk.Button("Start") def callback (button, *args): sbut.set_sensitive(False) worker.execute() sbut.connect("clicked", callback) vbox.add(sbut) cbut = gtk.Button("Cancel") def callback (button, *args): cbut.set_sensitive(False) worker.cancel() cbut.connect("clicked", callback) vbox.add(cbut) gbut = gtk.Button("Get") def callback (button, *args): gbut.set_sensitive(False) print "Found:", worker.get() gbut.connect("clicked", callback) vbox.add(gbut) prog = gtk.ProgressBar() def callback (worker, progress): prog.set_fraction(progress) worker.connect("progressed", callback) vbox.add(prog) field = gtk.Entry() def process (worker, primes): field.set_text(str(primes[-1])) worker.connect("published", process) vbox.add(field) def done (worker, result): print "Finished, Cancelled:", worker.isCancelled() worker.connect("done", done) w.connect("destroy", gtk.main_quit) w.show_all() gtk.gdk.threads_init() gtk.main()
Python
import socket import re, sre_constants from copy import copy from pychess.System.Log import log class Prediction: def __init__ (self, callback, *regexps): self.callback = callback self.regexps = [] self.hash = hash(callback) for regexp in regexps: self.hash ^= hash(regexp) if not hasattr("match", regexp): # FICS being fairly case insensitive, we can compile with IGNORECASE # to easy some expressions self.regexps.append(re.compile(regexp, re.IGNORECASE)) def __hash__ (self): return self.hash def __cmp__ (self, other): return self.callback == other.callback and \ self.regexps == other.regexps def __repr__ (self): return "<Prediction to %s>" % self.callback.__name__ RETURN_NO_MATCH, RETURN_MATCH, RETURN_NEED_MORE = range(3) class LinePrediction (Prediction): def __init__ (self, callback, regexp): Prediction.__init__(self, callback, regexp) def handle(self, line): match = self.regexps[0].match(line) if match: self.callback(match) return RETURN_MATCH return RETURN_NO_MATCH class ManyLinesPrediction (Prediction): def __init__ (self, callback, regexp): Prediction.__init__(self, callback, regexp) self.matchlist = [] def handle(self, line): match = self.regexps[0].match(line) if match: self.matchlist.append(match) return RETURN_NEED_MORE if self.matchlist: self.callback(self.matchlist) return RETURN_NO_MATCH class NLinesPrediction (Prediction): def __init__ (self, callback, *regexps): Prediction.__init__(self, callback, *regexps) self.matchlist = [] def handle(self, line): regexp = self.regexps[len(self.matchlist)] match = regexp.match(line) if match: self.matchlist.append(match) if len(self.matchlist) == len(self.regexps): self.callback(self.matchlist) del self.matchlist[:] return RETURN_MATCH return RETURN_NEED_MORE return RETURN_NO_MATCH class FromPlusPrediction (Prediction): def __init__ (self, callback, regexp0, regexp1): Prediction.__init__(self, callback, regexp0, regexp1) self.matchlist = [] def handle (self, line): if not self.matchlist: match = self.regexps[0].match(line) if match: self.matchlist.append(match) return RETURN_NEED_MORE else: match = self.regexps[1].match(line) if match: self.matchlist.append(match) return RETURN_NEED_MORE else: self.callback(self.matchlist) del self.matchlist[:] return RETURN_NO_MATCH return RETURN_NO_MATCH class FromToPrediction (Prediction): def __init__ (self, callback, regexp0, regexp1): Prediction.__init__(self, callback, regexp0, regexp1) self.matchlist = [] def handle (self, line): if not self.matchlist: match = self.regexps[0].match(line) if match: self.matchlist.append(match) return RETURN_NEED_MORE else: match = self.regexps[1].match(line) if match: self.matchlist.append(match) self.callback(self.matchlist) del self.matchlist[:] return RETURN_MATCH else: self.matchlist.append(line) return RETURN_NEED_MORE return RETURN_NO_MATCH class PredictionsTelnet: def __init__ (self, telnet): self.telnet = telnet self.__state = None self.__stripLines = True self.__linePrefix = None def getStripLines(self): return self.__stripLines def getLinePrefix(self): return self.__linePrefix def setStripLines(self, value): self.__stripLines = value def setLinePrefix(self, value): self.__linePrefix = value def handleSomeText (self, predictions): # The prediations list may be changed at any time, so to avoid # "changed size during iteration" errors, we make a shallow copy temppreds = copy(predictions) line = self.telnet.readline() line = line.lstrip() if self.getLinePrefix() and self.getLinePrefix() in line: while line.startswith(self.getLinePrefix()): line = line[len(self.getLinePrefix()):] if self.getStripLines(): line = line.lstrip() origLine = line if self.getStripLines(): line = line.strip() log.debug(line+"\n", (repr(self.telnet), "lines")) if self.__state: answer = self.__state.handle(line) if answer != RETURN_NO_MATCH: log.debug(line+"\n", (repr(self.telnet), repr(self.__state.callback.__name__))) if answer in (RETURN_NO_MATCH, RETURN_MATCH): self.__state = None if answer in (RETURN_MATCH, RETURN_NEED_MORE): return if not self.__state: for prediction in temppreds: answer = prediction.handle(line) if answer != RETURN_NO_MATCH: log.debug(line+"\n", (repr(self.telnet), repr(prediction.callback.__name__))) if answer == RETURN_NEED_MORE: self.__state = prediction if answer in (RETURN_MATCH, RETURN_NEED_MORE): break else: log.debug(origLine, (repr(self.telnet), "nonmatched")) def write(self, str): return self.telnet.write(str) def close (self): self.telnet.close()
Python
import re from gobject import * import threading from pychess.System.Log import log from pychess.Savers.pgn import msToClockTimeTag from pychess.Utils.const import * from pychess.ic import * from pychess.ic.VerboseTelnet import * from pychess.ic.FICSObjects import * names = "(\w+)" titles = "((?:\((?:GM|IM|FM|WGM|WIM|TM|SR|TD|SR|CA|C|U|D|B|T|\*)\))+)?" ratedexp = "(rated|unrated)" ratings = "\(\s*([-0-9+]+|UNR)\)" weekdays = ("Mon","Tue","Wed","Thu","Fri","Sat","Sun") months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] # "Thu Oct 14, 20:36 PDT 2010" dates = "(%s)\s+(%s)\s+(\d+),\s+(\d+):(\d+)\s+([A-Z\?]+)\s+(\d{4})" % \ ("|".join(weekdays), "|".join(months)) moveListHeader1Str = "%s %s vs. %s %s --- %s" % (names, ratings, names, ratings, dates) moveListHeader1 = re.compile(moveListHeader1Str) moveListHeader2Str = "%s ([^ ]+) match, initial time: (\d+) minutes, increment: (\d+) seconds\." % \ ratedexp moveListHeader2 = re.compile(moveListHeader2Str, re.IGNORECASE) sanmove = "([a-hxOoKQRBN0-8+#=-]{2,7})" movetime = "\((\d+):(\d\d)(?:\.(\d\d\d))?\)" moveListMoves = re.compile("(\d+)\. +(?:%s|\.\.\.) +%s *(?:%s +%s)?" % \ (sanmove, movetime, sanmove, movetime)) fileToEpcord = (("a3","b3","c3","d3","e3","f3","g3","h3"), ("a6","b6","c6","d6","e6","f6","g6","h6")) relations = { "-4": IC_POS_INITIAL, "-3": IC_POS_ISOLATED, "-2": IC_POS_OBSERVING_EXAMINATION, "2": IC_POS_EXAMINATING, "-1": IC_POS_OP_TO_MOVE, "1": IC_POS_ME_TO_MOVE, "0": IC_POS_OBSERVING } def parse_reason (result, reason, wname=None): """ Parse the result value and reason line string for the reason and return the result and reason the game ended. result -- The result of the game, if known. It can be "None", but if it is "DRAW", then wname must be supplied """ if result in (WHITEWON, BLACKWON): if "resigns" in reason: reason = WON_RESIGN elif "disconnection" in reason: reason = WON_DISCONNECTION elif "time" in reason: reason = WON_CALLFLAG elif "checkmated" in reason: reason = WON_MATE elif "adjudication" in reason: reason = WON_ADJUDICATION else: reason = UNKNOWN_REASON elif result == DRAW: assert wname is not None if "repetition" in reason: reason = DRAW_REPITITION elif "material" in reason and "time" in reason: if (wname + " ran out of time").lower() in reason: reason = DRAW_BLACKINSUFFICIENTANDWHITETIME else: reason = DRAW_WHITEINSUFFICIENTANDBLACKTIME elif "material" in reason: reason = DRAW_INSUFFICIENT elif "time" in reason: reason = DRAW_CALLFLAG elif "agreement" in reason: reason = DRAW_AGREE elif "stalemate" in reason: reason = DRAW_STALEMATE elif "50" in reason: reason = DRAW_50MOVES elif "length" in reason: # FICS has a max game length on 800 moves reason = DRAW_LENGTH elif "adjudication" in reason: reason = DRAW_ADJUDICATION else: reason = UNKNOWN_REASON elif result == ADJOURNED or "adjourned" in reason: result = ADJOURNED if "courtesy" in reason: if "white" in reason: reason = ADJOURNED_COURTESY_WHITE else: reason = ADJOURNED_COURTESY_BLACK elif "agreement" in reason: reason = ADJOURNED_AGREEMENT elif "connection" in reason: if "white" in reason: reason = ADJOURNED_LOST_CONNECTION_WHITE elif "black" in reason: reason = ADJOURNED_LOST_CONNECTION_BLACK else: reason = ADJOURNED_LOST_CONNECTION elif "server" in reason: reason = ADJOURNED_SERVER_SHUTDOWN else: reason = UNKNOWN_REASON elif "aborted" in reason: result = ABORTED if "agreement" in reason: reason = ABORTED_AGREEMENT elif "moves" in reason: # lost connection and too few moves; game aborted * reason = ABORTED_EARLY elif "move" in reason: # Game aborted on move 1 * reason = ABORTED_EARLY elif "shutdown" in reason: reason = ABORTED_SERVER_SHUTDOWN elif "adjudication" in reason: reason = ABORTED_ADJUDICATION else: reason = UNKNOWN_REASON elif "courtesyadjourned" in reason: result = ADJOURNED reason = ADJOURNED_COURTESY elif "courtesyaborted" in reason: result = ABORTED reason = ABORTED_COURTESY else: result = UNKNOWN_STATE reason = UNKNOWN_REASON return result, reason class BoardManager (GObject): __gsignals__ = { 'playGameCreated' : (SIGNAL_RUN_FIRST, None, (object,)), 'obsGameCreated' : (SIGNAL_RUN_FIRST, None, (object,)), 'boardUpdate' : (SIGNAL_RUN_FIRST, None, (int, int, int, str, str, str, str, int, int)), 'obsGameEnded' : (SIGNAL_RUN_FIRST, None, (object,)), 'curGameEnded' : (SIGNAL_RUN_FIRST, None, (object,)), 'obsGameUnobserved' : (SIGNAL_RUN_FIRST, None, (object,)), 'gamePaused' : (SIGNAL_RUN_FIRST, None, (int, bool)), 'tooManySeeks' : (SIGNAL_RUN_FIRST, None, ()), 'matchDeclined' : (SIGNAL_RUN_FIRST, None, (object,)), } castleSigns = {} queuedStyle12s = {} def __init__ (self, connection): GObject.__init__(self) self.connection = connection self.connection.expect_line (self.onStyle12, "<12> (.+)") self.connection.expect_line (self.onWasPrivate, "Sorry, game (\d+) is a private game\.") self.connection.expect_line (self.tooManySeeks, "You can only have 3 active seeks.") self.connection.expect_line (self.matchDeclined, "%s declines the match offer." % names) self.connection.expect_n_lines (self.onPlayGameCreated, "Creating: %s %s %s %s %s ([^ ]+) (\d+) (\d+)(?: \(adjourned\))?" % (names, ratings, names, ratings, ratedexp), "{Game (\d+) \(%s vs\. %s\) (?:Creating|Continuing) %s ([^ ]+) match\." % (names, names, ratedexp), "", "<12> (.+)") self.connection.expect_fromto (self.onObserveGameCreated, "Movelist for game (\d+):", "{Still in progress} \*") self.connection.expect_line (self.onGamePause, "Game (\d+): Game clock (paused|resumed)\.") self.connection.expect_line (self.onUnobserveGame, "Removing game (\d+) from observation list\.") self.queuedEmits = {} self.gamemodelStartedEvents = {} self.ourGameno = "" # The ms ivar makes the remaining second fields in style12 use ms self.connection.lvm.setVariable("ms", True) # Style12 is a must, when you don't want to parse visualoptimized stuff self.connection.lvm.setVariable("style", "12") # When we observe fischer games, this puts a startpos in the movelist self.connection.lvm.setVariable("startpos", True) # movecase ensures that bc3 will never be a bishop move self.connection.lvm.setVariable("movecase", True) # don't unobserve games when we start a new game self.connection.lvm.setVariable("unobserve", "3") self.connection.lvm.setVariable("formula", "") self.connection.lvm.autoFlagNotify(None) # gameinfo <g1> doesn't really have any interesting info, at least not # until we implement crasyhouse and stuff # self.connection.lvm.setVariable("gameinfo", True) # We don't use deltamoves as fisc won't send them with variants #self.connection.lvm.setVariable("compressmove", True) def start (self): self.connection.games.connect("FICSGameEnded", self.onGameEnd) @classmethod def parseStyle12 (cls, line, castleSigns=None): fields = line.split() curcol = fields[8] == "B" and BLACK or WHITE gameno = int(fields[15]) relation = relations[fields[18]] ply = int(fields[25])*2 - (curcol == WHITE and 2 or 1) lastmove = fields[28] != "none" and fields[28] or None wname = fields[16] bname = fields[17] wms = int(fields[23]) bms = int(fields[24]) gain = int(fields[20]) # Board data fenrows = [] for row in fields[:8]: fenrow = [] spaceCounter = 0 for c in row: if c == "-": spaceCounter += 1 else: if spaceCounter: fenrow.append(str(spaceCounter)) spaceCounter = 0 fenrow.append(c) if spaceCounter: fenrow.append(str(spaceCounter)) fenrows.append("".join(fenrow)) fen = "/".join(fenrows) fen += " " # Current color fen += fields[8].lower() fen += " " # Castling if fields[10:14] == ["0","0","0","0"]: fen += "-" else: if fields[10] == "1": fen += castleSigns[0].upper() if fields[11] == "1": fen += castleSigns[1].upper() if fields[12] == "1": fen += castleSigns[0].lower() if fields[13] == "1": fen += castleSigns[1].lower() fen += " " # 1 0 1 1 when short castling k1 last possibility # En passant if fields[9] == "-1": fen += "-" else: fen += fileToEpcord [1-curcol] [int(fields[9])] fen += " " # Half move clock fen += str(max(int(fields[14]),0)) fen += " " # Standard chess numbering fen += fields[25] return gameno, relation, curcol, ply, wname, bname, wms, bms, gain, lastmove, fen def onStyle12 (self, match): style12 = match.groups()[0] gameno = int(style12.split()[15]) if gameno in self.queuedStyle12s: self.queuedStyle12s[gameno].append(style12) return if self.gamemodelStartedEvents.has_key(gameno): self.gamemodelStartedEvents[gameno].wait() castleSigns = self.castleSigns[gameno] gameno, relation, curcol, ply, wname, bname, wms, bms, gain, lastmove, fen = \ self.parseStyle12(style12, castleSigns) self.emit("boardUpdate", gameno, ply, curcol, lastmove, fen, wname, bname, wms, bms) def onGameModelStarted (self, gameno): self.gamemodelStartedEvents[gameno].set() def onWasPrivate (self, match): # When observable games were added to the list later than the latest # full send, private information will not be known. gameno = int(match.groups()[0]) try: game = self.connection.games.get_game_by_gameno(gameno) except KeyError: return game.private = True def tooManySeeks (self, match): self.emit("tooManySeeks") def matchDeclined (self, match): decliner, = match.groups() decliner = self.connection.players.get(FICSPlayer(decliner), create=False) self.emit("matchDeclined", decliner) @classmethod def generateCastleSigns (cls, style12, game_type): if game_type.variant_type == FISCHERRANDOMCHESS: backrow = style12.split()[0] leftside = backrow.find("r") rightside = backrow.find("r", leftside+1) return (reprFile[rightside], reprFile[leftside]) else: return ("k", "q") @staticmethod def parseRating (rating): if rating: m = re.match("[0-9]{2,}", rating) if m: return int(m.group(0)) else: return 0 else: return 0 def onPlayGameCreated (self, matchlist): log.debug("BM.onPlayGameCreated: %s\n%s\n" % (matchlist[0].string, matchlist[1].string)) wname, wrating, bname, brating, rated, type, min, inc = matchlist[0].groups() gameno, wname, bname, rated, type = matchlist[1].groups() style12 = matchlist[-1].groups()[0] gameno = int(gameno) wrating = self.parseRating(wrating) brating = self.parseRating(brating) rated = rated == "rated" game_type = GAME_TYPES[type] 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) wplayer = self.connection.players.get(FICSPlayer(wname)) bplayer = self.connection.players.get(FICSPlayer(bname)) for player, rating in ((wplayer, wrating), (bplayer, brating)): if game_type.rating_type in player.ratings and \ player.ratings[game_type.rating_type].elo != rating: player.ratings[game_type.rating_type].elo = rating game = FICSGame(wplayer, bplayer, gameno=gameno, rated=rated, game_type=game_type, min=int(min), inc=int(inc), board=FICSBoard(wms, bms, fen=fen)) game = self.connection.games.get(game) for player in (wplayer, bplayer): if player.status != IC_STATUS_PLAYING: player.status = IC_STATUS_PLAYING if player.game != game: player.game = game self.ourGameno = gameno self.gamemodelStartedEvents[gameno] = threading.Event() self.gamemodelStartedEvents[gameno].clear() self.emit("playGameCreated", game) def parseGame (self, matchlist, gameclass, in_progress=False): """ Parses the header and movelist for an observed or stored game from its matchlist (an re.match object) into a gameclass (FICSGame or subclass of) object. in_progress - should be True for an observed game matchlist, and False for stored/adjourned games """ ################# observed game movelist example: # Movelist for game 64: # # Ajido (2281) vs. IMgooeyjim (2068) --- Thu Oct 14, 20:36 PDT 2010 # Rated standard match, initial time: 15 minutes, increment: 3 seconds. # # Move Ajido IMgooeyjim # ---- --------------------- --------------------- # 1. d4 (0:00.000) Nf6 (0:00.000) # 2. c4 (0:04.061) g6 (0:00.969) # 3. Nc3 (0:13.280) Bg7 (0:06.422) # {Still in progress} * # ################## stored game example: # BwanaSlei (1137) vs. mgatto (1336) --- Wed Nov 5, 20:56 PST 2008 # Rated blitz match, initial time: 5 minutes, increment: 0 seconds. # # Move BwanaSlei mgatto # ---- --------------------- --------------------- # 1. e4 (0:00.000) c5 (0:00.000) # 2. d4 (0:05.750) cxd4 (0:03.020) # ... # 23. Qxf3 (1:05.500) # {White lost connection; game adjourned} * # ################## stored wild/3 game with style12: # kurushi (1626) vs. mgatto (1627) --- Thu Nov 4, 10:33 PDT 2010 # Rated wild/3 match, initial time: 3 minutes, increment: 0 seconds. # # <12> nqbrknrn pppppppp -------- -------- -------- -------- PPPPPPPP NQBRKNRN W -1 0 0 0 0 0 17 kurushi mgatto -4 3 0 39 39 169403 45227 1 none (0:00.000) none 0 1 0 # # Move kurushi mgatto # ---- --------------------- --------------------- # 1. Nb3 (0:00.000) d5 (0:00.000) # 2. Nhg3 (0:00.386) e5 (0:03.672) # ... # 28. Rxd5 (0:00.412) # {Black lost connection; game adjourned} * # ################## stored game movelist following stored game(s): # Stored games for mgatto: # C Opponent On Type Str M ECO Date # 1: W BabyLurking Y [ br 5 0] 29-13 W27 D37 Fri Nov 5, 04:41 PDT 2010 # 2: W gbtami N [ wr 5 0] 32-34 W14 --- Thu Oct 21, 00:14 PDT 2010 # # mgatto (1233) vs. BabyLurking (1455) --- Fri Nov 5, 04:33 PDT 2010 # Rated blitz match, initial time: 5 minutes, increment: 0 seconds. # # Move mgatto BabyLurking # ---- ---------------- ---------------- # 1. Nf3 (0:00) d5 (0:00) # 2. d4 (0:03) Nf6 (0:00) # 3. c4 (0:03) e6 (0:00) # {White lost connection; game adjourned} * # ################### stored game movelist following stored game(s): ### Note: A wild stored game in this format won't be parseable into a board because ### it doesn't come with a style12 that has the start position, so we warn and return ################### # Stored games for mgatto: # C Opponent On Type Str M ECO Date # 1: W gbtami N [ wr 5 0] 32-34 W14 --- Thu Oct 21, 00:14 PDT 2010 # # mgatto (1627) vs. gbtami (1881) --- Thu Oct 21, 00:10 PDT 2010 # Rated wild/fr match, initial time: 5 minutes, increment: 0 seconds. # # Move mgatto gbtami # ---- ---------------- ---------------- # 1. d4 (0:00) b6 (0:00) # 2. b3 (0:06) d5 (0:03) # 3. c4 (0:08) e6 (0:03) # 4. e3 (0:04) dxc4 (0:02) # 5. bxc4 (0:02) g6 (0:09) # 6. Nd3 (0:12) Bg7 (0:02) # 7. Nc3 (0:10) Ne7 (0:03) # 8. Be2 (0:08) c5 (0:05) # 9. a4 (0:07) cxd4 (0:38) # 10. exd4 (0:06) Bxd4 (0:03) # 11. O-O (0:10) Qc6 (0:06) # 12. Bf3 (0:16) Qxc4 (0:04) # 13. Bxa8 (0:03) Rxa8 (0:14) # {White lost connection; game adjourned} * # ################## other reasons the game could be stored/adjourned: # Game courtesyadjourned by (Black|White) # Still in progress # This one must be a FICS bug # Game adjourned by mutual agreement # (White|Black) lost connection; game adjourned # Game adjourned by ((server shutdown)|(adjudication)|(simul holder)) index = 0 if in_progress: gameno = int(matchlist[index].groups()[0]) index += 2 header1 = matchlist[index] if isinstance(matchlist[index], str) \ else matchlist[index].group() wname, wrating, bname, brating, weekday, month, day, hour, minute, \ timezone, year = moveListHeader1.match(header1).groups() wrating = self.parseRating(wrating) brating = self.parseRating(brating) rated, game_type, minutes, increment = \ moveListHeader2.match(matchlist[index+1]).groups() minutes = int(minutes) increment = int(increment) game_type = GAME_TYPES[game_type] reason = matchlist[-1].group().lower() result = None if in_progress else ADJOURNED result, reason = parse_reason(result, reason) index += 3 if matchlist[index].startswith("<12>"): style12 = matchlist[index][5:] castleSigns = self.generateCastleSigns(style12, game_type) gameno, relation, curcol, ply, wname, bname, wms, bms, gain, lastmove, \ fen = self.parseStyle12(style12, castleSigns) initialfen = fen movesstart = index + 4 else: if game_type.rating_type == TYPE_WILD: # we need a style12 start position to correctly parse a wild/* board log.error("BoardManager.parseGame: no style12 for %s board.\n" % game_type.fics_name) return None castleSigns = ("k", "q") initialfen = None movesstart = index + 2 if in_progress: self.castleSigns[gameno] = castleSigns moves = {} wms = bms = minutes * 60 * 1000 for line in matchlist[movesstart:-1]: if not moveListMoves.match(line): log.error("BoardManager.parseGame: unmatched line: \"%s\"\n" % \ repr(line)) raise moveno, wmove, wmin, wsec, wmsec, bmove, bmin, bsec, bmsec = \ moveListMoves.match(line).groups() ply = int(moveno)*2-2 # TODO: add {[%emt 3.889]} move time PGN tags to each move if wmove: moves[ply] = wmove wms -= (int(wmin) * 60 * 1000) + (int(wsec) * 1000) if wmsec is not None: wms -= int(wmsec) if int(moveno) > 1 and increment > 0: wms += (increment * 1000) if bmove: moves[ply+1] = bmove bms -= (int(bmin) * 60 * 1000) + (int(bsec) * 1000) if bmsec is not None: bms -= int(bmsec) if int(moveno) > 1 and increment > 0: bms += (increment * 1000) if in_progress: # Apply queued board updates for style12 in self.queuedStyle12s[gameno]: gameno, relation, curcol, ply, wname, bname, wms, bms, gain, lastmove, fen = \ self.parseStyle12(style12, castleSigns) if lastmove == None: continue moves[ply-1] = lastmove # Updated the queuedMoves in case there has been a takeback for moveply in moves.keys(): if moveply > ply-1: del moves[moveply] del self.queuedStyle12s[gameno] pgnHead = [ ("Event", "FICS %s %s game" % (rated.lower(), game_type.fics_name)), ("Site", "FICS"), ("White", wname), ("Black", bname), ("TimeControl", "%d+%d" % (minutes * 60, increment)), ("Result", "*"), ("WhiteClock", msToClockTimeTag(wms)), ("BlackClock", msToClockTimeTag(bms)), ] if wrating != 0: pgnHead += [ ("WhiteElo", wrating) ] if brating != 0: pgnHead += [ ("BlackElo", brating) ] if year and month and day and hour and minute: pgnHead += [ ("Year", int(year)), ("Month", months.index(month)+1), ("Day", int(day)), ("Time", "%02d:%02d:00" % (int(hour), int(minute))), ] if initialfen: pgnHead += [ ("SetUp", "1"), ("FEN", initialfen) ] if game_type.variant_type == FISCHERRANDOMCHESS: pgnHead += [ ("Variant", "Fischerandom") ] # FR is the only variant used in this tag by the PGN generator @ # ficsgames.com. They put all the other wild/* stuff only in the # "Event" header. pgn = "\n".join(['[%s "%s"]' % line for line in pgnHead]) + "\n" moves = moves.items() moves.sort() for ply, move in moves: if ply % 2 == 0: pgn += "%d. " % (ply/2+1) pgn += move + " " pgn += "*\n" wplayer = self.connection.players.get(FICSPlayer(wname)) bplayer = self.connection.players.get(FICSPlayer(bname)) for player, rating in ((wplayer, wrating), (bplayer, brating)): if game_type.rating_type in player.ratings and \ player.ratings[game_type.rating_type].elo != rating and \ player.ratings[game_type.rating_type].elo == 0: player.ratings[game_type.rating_type].elo = rating game = gameclass(wplayer, bplayer, game_type=game_type, rated=(rated.lower() == "rated"), min=minutes, inc=increment, board=FICSBoard(wms, bms, pgn=pgn)) if in_progress: game.gameno = gameno else: game.reason = reason game = self.connection.games.get(game, emit=False) return game def onObserveGameCreated (self, matchlist): game = self.parseGame(matchlist, FICSGame, in_progress=True) self.emit ("obsGameCreated", game) if game.gameno in self.gamemodelStartedEvents: self.gamemodelStartedEvents[game.gameno].wait() for emit in self.queuedEmits[game.gameno]: emit() del self.queuedEmits[game.gameno] def onGameEnd (self, games, game): if game.gameno == self.ourGameno: if game.gameno in self.gamemodelStartedEvents: self.gamemodelStartedEvents[game.gameno].wait() self.emit("curGameEnded", game) self.ourGameno = "" # update player info on players that changed rating/status while we # were playing because we can't get rating change info when playing # a game print >> self.connection.client, "who IsblwL" del self.gamemodelStartedEvents[game.gameno] else: if game.gameno in self.queuedEmits: self.queuedEmits[game.gameno].append( lambda:self.emit("obsGameEnded", game)) elif game.gameno in self.gamemodelStartedEvents: self.gamemodelStartedEvents[game.gameno].wait() self.emit("obsGameEnded", game) def onGamePause (self, match): gameno, state = match.groups() gameno = int(gameno) if gameno in self.queuedEmits: self.queuedEmits[gameno].append( lambda:self.emit("gamePaused",gameno, state=="paused")) else: if gameno in self.gamemodelStartedEvents: self.gamemodelStartedEvents[gameno].wait() self.emit("gamePaused", gameno, state=="paused") def onUnobserveGame (self, match): gameno = int(match.groups()[0]) del self.gamemodelStartedEvents[gameno] try: game = self.connection.games.get_game_by_gameno(gameno) except KeyError: return self.emit("obsGameUnobserved", game) # TODO: delete self.castleSigns[gameno] ? ############################################################################ # Interacting # ############################################################################ def isPlaying (self): return bool(self.ourGameno) def sendMove (self, move): print >> self.connection.client, move def resign (self): print >> self.connection.client, "resign" def callflag (self): print >> self.connection.client, "flag" def observe (self, game): if not game.gameno in self.gamemodelStartedEvents: self.queuedStyle12s[game.gameno] = [] self.queuedEmits[game.gameno] = [] self.gamemodelStartedEvents[game.gameno] = threading.Event() self.gamemodelStartedEvents[game.gameno].clear() print >> self.connection.client, "observe %d" % game.gameno print >> self.connection.client, "moves %d" % game.gameno def unobserve (self, game): if game.gameno is not None: print >> self.connection.client, "unobserve %d" % game.gameno def play (self, seekno): print >> self.connection.client, "play %s" % seekno def accept (self, offerno): print >> self.connection.client, "accept %s" % offerno def decline (self, offerno): print >> self.connection.client, "decline %s" % offerno if __name__ == "__main__": from pychess.ic.FICSConnection import Connection con = Connection("","","","") bm = BoardManager(con) print bm._BoardManager__parseStyle12("rkbrnqnb pppppppp -------- -------- -------- -------- PPPPPPPP RKBRNQNB W -1 1 1 1 1 0 161 GuestNPFS GuestMZZK -1 2 12 39 39 120 120 1 none (0:00) none 1 0 0", ("d","a")) print bm._BoardManager__parseStyle12("rnbqkbnr pppp-ppp -------- ----p--- ----PP-- -------- PPPP--PP RNBQKBNR B 5 1 1 1 1 0 241 GuestGFFC GuestNXMP -4 2 12 39 39 120000 120000 1 none (0:00.000) none 0 0 0", ("k","q"))
Python
from gobject import * import threading import re from math import ceil import time from pychess.System.Log import log titles = "(?:\([A-Z*]+\))*" names = "([A-Za-z]+)"+titles titlesC = re.compile(titles) namesC = re.compile(names) CHANNEL_SHOUT = "shout" CHANNEL_CSHOUT = "cshout" class ChatManager (GObject): __gsignals__ = { 'channelMessage' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, bool, bool, str, str)), 'kibitzMessage' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, str)), 'privateMessage' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, str, bool, str)), 'bughouseMessage' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, str)), 'announcement' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), 'channelAdd' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), 'channelRemove' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), 'channelJoinError': (SIGNAL_RUN_FIRST, TYPE_NONE, (str, str)), 'channelLog' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, int, str, str)), 'toldChannel' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, int)), 'recievedChannels' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object)), 'recievedNames' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object)), } def __init__ (self, connection): GObject.__init__(self) self.connection = connection self.connection.expect_line_plus (self.onPrivateMessage, "%s(\*)?(?:\[(\d+)\])? (?:tells you|says): (.*)" % names) self.connection.expect_line_plus (self.onAnnouncement, "\s*\*\*ANNOUNCEMENT\*\* (.*)") self.connection.expect_line_plus (self.onChannelMessage, "%s(\*)?\((\d+)\): (.*)" % names) self.connection.expect_line_plus (self.onShoutMessage, "%s(\*)? (c-)?shouts: (.*)" % names) self.connection.expect_line_plus (self.onShoutMessage, "--> %s(\*)?:? (.*)" % names) self.connection.expect_fromto (self.onChannelList, "channels only for their designated topics.", "SPECIAL NOTE") self.connection.expect_line (lambda m: self.emit('channelAdd', m.groups()[0]), "\[(\d+)\] added to your channel list.") self.connection.expect_line (lambda m: self.emit('channelRemove', m.groups()[0]), "\[(\d+)\] removed to your channel list.") self.connection.expect_line (lambda m: self.emit('channelJoinError', *m.groups()), "Only (.+?) may join channel (\d+)\.") self.connection.expect_line (self.getNoChannelPlayers, "Channel \d+ is empty\.") self.connection.expect_fromto (self.getChannelPlayers, "Channel (\d+)(?: \"(\w+)\")?: (.+)", "(\d+) player(?: is|s are) in channel \d+\.") self.connection.expect_fromto (self.gotPlayerChannels, "%s is in the following channels:" % names, "(?!(?:\d+\s+)+)") #self.connection.expect_line (self.toldChannel, # '\(told (\d+) players in channel (\d+) ".+"\)') #(told Chronatog) #Only chess advisers and admins may join channel 63. #Only (.+?) may sey send tells to channel (\d+). #Only admins may send tells to channel 0. #Only registered users may send tells to channels other than 4, 7 and 53. self.currentLogChannel = None self.connection.expect_line (self.onChannelLogStart, ":Channel (\d+|shout|c-shout) log for the last \d+ minutes:$") self.connection.expect_line (self.onChannelLogLine, ":\[(\d+):(\d+):(\d+)\] (?:(?:--> )?%s(?: shouts)?)\S* (.+)$" % names) self.connection.expect_line (self.onChannelLogBreak, ":Use \"tell chLog Next\" to print more.$") #TODO handling of this case is nessesary for console: #fics% tell 1 hi #You are not in channel 1, auto-adding you if possible. self.connection.lvm.setVariable("kibitz", "0") self.connection.lvm.setVariable("ctell", "1") self.connection.lvm.setVariable("tell", "1") self.connection.lvm.setVariable("height", "240") print >> self.connection.client, "inchannel %s" % self.connection.username print >> self.connection.client, "help channel_list" self.getChannelsLock = threading.Semaphore() self.getChannelsLock.acquire() self.channels = {} def getChannels(self): self.getChannelsLock.acquire() self.getChannelsLock.release() return self.channels def getJoinedChannels(self): channels = self.connection.lvm.getList("channel") if self.connection.lvm.getVariable("shout"): channels.add(CHANNEL_SHOUT) if self.connection.lvm.getVariable("cshout"): channels.add(CHANNEL_CSHOUT) return channels channelListItem = re.compile("((?:\d+,?)+)\s*(.*)") def onChannelList(self, matchlist): self.channels = [(CHANNEL_SHOUT, _("Shout")), (CHANNEL_CSHOUT, _("Chess Shout"))] numbers = set(range(256)) #TODO: Use limits->Server->Channels for line in matchlist[1:-1]: match = self.channelListItem.match(line) if not match: continue ids, desc = match.groups() for id in ids.split(","): numbers.remove(int(id)) self.channels.append((id, desc)) for i in numbers: self.channels.append((str(i), _("Unofficial channel %d" % i))) self.getChannelsLock.release() def getNoChannelPlayers (self, match): channel = match.groups()[0] self.emit('recievedNames', channel, []) def getChannelPlayers(self, matchlist): channel, name, people = matchlist[0].groups() people += " " + " ".join(matchlist[1:-1]) people = namesC.findall(titlesC.sub("",people)) self.emit('recievedNames', channel, people) def gotPlayerChannels(self, matchlist): name = matchlist[0].groups() list = [] for line in matchlist[1:-1]: list += line.split() def onPrivateMessage (self, matchlist): name, isadmin, gameno, text = matchlist[0].groups() text += " " + " ".join(matchlist[1:]) text = self.entityDecode(text) self.emit("privateMessage", name, "title", isadmin, text) def onAnnouncement (self, matchlist): text = matchlist[0].groups()[0] text += " " + " ".join(matchlist[1:-1]) text = self.entityDecode(text) self.emit("announcement", text) def onChannelMessage (self, matchlist): name, isadmin, channel, text = matchlist[0].groups() text += " " + " ".join(matchlist[1:]) text = self.entityDecode(text) isme = name.lower() == self.connection.username.lower() self.emit("channelMessage", name, isadmin, isme, channel, text) def onShoutMessage (self, matchlist): if len(matchlist[0].groups()) == 4: name, isadmin, type, text = matchlist[0].groups() elif len(matchlist[0].groups()) == 3: name, isadmin, text = matchlist[0].groups() type = "" text += " " + " ".join(matchlist[1:]) text = self.entityDecode(text) isme = name.lower() == self.connection.username.lower() # c-shout should be used ONLY for chess-related messages, such as # questions about chess or announcing being open for certain kinds of # chess matches. Use "shout" for non-chess messages. # t-shout is used to invite to tournaments if type == "c-": self.emit("channelMessage", name, isadmin, isme, CHANNEL_CSHOUT, text) else: self.emit("channelMessage", name, isadmin, isme, CHANNEL_SHOUT, text) def toldChannel (self, match): amount, channel = match.groups() self.emit("toldChannel", channel, int(amount)) def onChannelLogStart (self, match): channel, = match.groups() self.currentLogChannel = channel def onChannelLogLine (self, match): if not self.currentLogChannel: log.warn("Recieved 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) self.emit("channelLog", self.currentLogChannel, time, handle, text) def onChannelLogBreak (self, match): print >> self.connection.client, "xtell chlog Next" def convTime (self, h, m, s): # Convert to timestamp tlist = [u for u in time.localtime()] tstamp = time.mktime(tlist[0:3]+[h, m, s, 0, 0, 0]) # Difference to now in hours dif = (tstamp-time.time())/60./60. # As we know there is maximum 30 minutes in difference, we can guess when the # message was sent, without knowing the sending time zone return tstamp - ceil(dif)*60*60 entityExpr = re.compile("&#x([a-f0-9]+);") def entityDecode (self, text): return self.entityExpr.sub(lambda m: unichr(int(m.groups()[0],16)), text) def entityEncode (self, text): buf = [] for c in text: if not 32 <= ord(c) <= 127: c = "&#" + hex(ord(c))[1:] + ";" buf.append(c) return "".join(buf) def getChannelLog (self, channel, minutes=30): """ Channel can be channel_id, shout or c-shout """ assert 1 <= minutes <= 120 # Using the chlog bot print >> self.connection.client, "xtell chlog show %s -t %d" % (channel,minutes) def getPlayersChannels (self, player): print >> self.connection.client, "inchannel %s" % player def getPeopleInChannel (self, channel): if channel in (CHANNEL_SHOUT, CHANNEL_CSHOUT): people = self.connection.players.get_online_playernames() self.emit('recievedNames', channel, people) print >> self.connection.client, "inchannel %s" % channel def joinChannel (self, channel): if channel in (CHANNEL_SHOUT, CHANNEL_CSHOUT): self.connection.lvm.setVariable(channel, True) print >> self.connection.client, "+channel %s" % channel def removeChannel (self, channel): if channel in (CHANNEL_SHOUT, CHANNEL_CSHOUT): self.connection.lvm.setVariable(channel, False) print >> self.connection.client, "-channel %s" % channel def mayTellChannel (self, channel): if self.connection.isRegistred() or channel in ("4", "7", "53"): return True return False def tellPlayer (self, player, message): message = self.entityEncode(message) print >> self.connection.client, "tell %s %s" % (player, message) def tellChannel (self, channel, message): message = self.entityEncode(message) if channel == CHANNEL_SHOUT: print >> self.connection.client, "shout %s" % message elif channel == CHANNEL_CSHOUT: print >> self.connection.client, "cshout %s" % message else: print >> self.connection.client, "tell %s %s" % (channel, message) def tellAll (self, message): message = self.entityEncode(message) print >> self.connection.client, "shout %s" % message def tellGame (self, gameno, message): message = self.entityEncode(message) print >> self.connection.client, "xkibitz %s %s" % (gameno, message) def tellOpponent (self, message): message = self.entityEncode(message) print >> self.connection.client, "say %s" % message def tellBughousePartner (self, message): message = self.stripChars(message) print >> self.connection.client, "ptell %s" % message def tellUser (self, player, message): IS_TD = False if IS_TD: MAX_COM_SIZE = 1024 #TODO: Get from limits for i in xrange(0,len(message),MAX_COM_SIZE): chunk = message[i:i+MAX_COM_SIZE] chunk = chunk.replace("\n", "\\n") chunk = self.entityEncode(chunk) print >> self.connection.client, "qell %s %s" % (player, chunk) else: for line in message.strip().split("\n"): self.tellPlayer(player, line)
Python
import re import datetime from gobject import * from BoardManager import BoardManager, moveListHeader1Str, names, months, dates from pychess.ic import * from pychess.ic.FICSObjects import FICSAdjournedGame, FICSPlayer from pychess.Utils.const import * from pychess.System.Log import log class AdjournManager (GObject): __gsignals__ = { 'adjournedGameAdded' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'onAdjournmentsList' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'adjournedGamePreview' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), } def __init__ (self, connection): GObject.__init__(self) self.connection = connection self.connection.expect_line (self.__onStoredResponseNO, "%s has no adjourned games\." % self.connection.username) self.connection.expect_fromto (self.__onSmovesResponse, moveListHeader1Str, # "\s*{((?:Game courtesyadjourned by (Black|White))|(?:Still in progress)|(?:Game adjourned by mutual agreement)|(?:(White|Black) lost connection; game adjourned)|(?:Game adjourned by ((?:server shutdown)|(?:adjudication)|(?:simul holder))))} \*") "\s*{.*(?:(?:[Gg]ame.*adjourned)|(?:Still in progress)).*}\s*\*") self.connection.expect_fromplus(self.__onStoredResponseYES, "\s*C Opponent\s+On Type\s+Str\s+M\s+ECO\s+Date", "\s*\d+: (B|W) %s\s+(Y|N) \[([a-z ]{3})\s+(\d+)\s+(\d+)\]\s+(\d+)-(\d+)\s+(W|B)(\d+)\s+(---|\?\?\?|[A-Z]\d+)\s+%s" % (names, dates)) self.connection.expect_line (self.__onAdjournedGameResigned, "You have resigned the game\.") self.connection.bm.connect("curGameEnded", self.__onCurGameEnded) self.queryAdjournments() #TODO: Connect to {Game 67 (MAd vs. Sandstrom) Game adjourned by mutual agreement} * #TODO: Connect to adjourned game as adjudicated def __onStoredResponseYES (self, matchlist): #Stored games of User: # C Opponent On Type Str M ECO Date # 1: W TheDane N [ br 2 12] 0-0 B2 ??? Sun Nov 23, 6:14 CST 1997 # 2: W PyChess Y [psu 2 12] 39-39 W3 C20 Sun Jan 11, 17:40 ??? 2009 # 3: B cjavad N [ wr 2 2] 31-31 W18 --- Wed Dec 23, 06:58 PST 2009 adjournments = [] for match in matchlist[1:]: our_color = match.groups()[0] opponent_name, opponent_online = match.groups()[1:3] game_type = match.groups()[3] minutes, gain = match.groups()[4:6] str_white, str_black = match.groups()[6:8] next_color = match.groups()[8] move_num = match.groups()[9] eco = match.groups()[10] week, month, day, hour, minute, timezone, year = match.groups()[11:18] gametime = datetime.datetime(int(year), months.index(month)+1, int(day), int(hour), int(minute)) private = game_type[0] == "p" rated = game_type[2] == "r" gametype = GAME_TYPES_BY_SHORT_FICS_NAME[game_type[1]] our_color = our_color == "B" and BLACK or WHITE minutes = int(minutes) gain = int(gain) length = (int(move_num)-1)*2 if next_color == "B": length += 1 user = self.connection.players.get( FICSPlayer(self.connection.getUsername())) opponent = self.connection.players.get(FICSPlayer(opponent_name)) wplayer, bplayer = (user, opponent) if our_color == WHITE \ else (opponent, user) game = FICSAdjournedGame(wplayer, bplayer, game_type=gametype, rated=rated, our_color=our_color, length=length, time=gametime, min=minutes, inc=gain, private=private) if game.opponent.adjournment != True: game.opponent.adjournment = True if game not in self.connection.games: game = self.connection.games.get(game, emit=False) self.emit("adjournedGameAdded", game) adjournments.append(game) self.emit("onAdjournmentsList", adjournments) def __onStoredResponseNO (self, match): self.emit("onAdjournmentsList", []) def __onSmovesResponse (self, matchlist): game = self.connection.bm.parseGame(matchlist, FICSAdjournedGame, in_progress=False) if game is None: return self.emit("adjournedGamePreview", game) def __onAdjournedGameResigned (self, match): self.queryAdjournments() def __onCurGameEnded (self, bm, game): if game.result == ADJOURNED: self.queryAdjournments() def queryAdjournments (self): print >> self.connection.client, "stored" def queryMoves (self, game): print >> self.connection.client, "smoves %s" % game.opponent.name def challenge (self, playerName): print >> self.connection.client, "match %s" % playerName 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.warn("AdjournManager.resign: no adjourned game vs %s\n" % game.opponent) return log.log("AdjournManager.resign: resigning adjourned game=%s\n" % game) print >> self.connection.client, "resign %s" % game.opponent.name def draw (self, game): if not game.opponent.adjournment: log.warn("AdjournManager.draw: no adjourned game vs %s\n" % game.opponent) return log.log("AdjournManager.draw: offering sdraw for adjourned game=%s\n" % game) print >> self.connection.client, "sdraw %s" % game.opponent.name def abort (self, game): if not game.opponent.adjournment: log.warn("AdjournManager.abort: no adjourned game vs %s\n" % game.opponent) return log.log("AdjournManager.abort: offering sabort for adjourned game=%s\n" % game) print >> self.connection.client, "sabort %s" % game.opponent.name def resume (self, game): if not game.opponent.adjournment: log.warn("AdjournManager.resume: no adjourned game vs %s\n" % game.opponent) return log.log("AdjournManager.resume: offering resume for adjourned game=%s\n" % game) print >> self.connection.client, "match %s" % game.opponent.name #(a) Users who have more than 15 stored games are restricted from starting new #games. If this situation happens to you, review your stored games and see #which ones might be eligible for adjudication (see "help adjudication").
Python
from gobject import * sanmove = "([a-hxOoKQRBN0-8+#=-]{2,7})" class ErrorManager (GObject): __gsignals__ = { 'onCommandNotFound' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), 'onAmbiguousMove' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), 'onIllegalMove' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), } def __init__ (self, connection): GObject.__init__(self) connection.expect_line (self.onError, "(.*?): Command not found\.") connection.expect_line (self.onAmbiguousMove, "Ambiguous move \((%s)\)\." % sanmove) connection.expect_line (self.onIllegalMove, "Illegal move \((%s)\)\." % sanmove) def onError (self, match): command = match.groups()[0] self.emit("onCommandNotFound", command) def onAmbiguousMove (self, match): move = match.groups()[0] self.emit("onAmbiguousMove", move) def onIllegalMove (self, match): move = match.groups()[0] self.emit("onIllegalMove", move)
Python
import re from gobject import GObject, SIGNAL_RUN_FIRST from pychess.Utils.const import * from pychess.Utils.Offer import Offer from pychess.System.Log import log from pychess.ic import * names = "\w+(?:\([A-Z\*]+\))*" rated = "(rated|unrated)" colors = "(?:\[(white|black)\])?" ratings = "\(([0-9\ \-\+]{4})\)" loaded_from = "(?: Loaded from (wild.*))?" adjourned = "(?: (\(adjourned\)))?" matchreUntimed = re.compile ("(\w+) %s %s ?(\w+) %s %s (untimed)\s*" % \ (ratings, colors, ratings, rated) ) matchre = re.compile( "(\w+) %s %s ?(\w+) %s %s (\w+) (\d+) (\d+)%s%s" % \ (ratings, colors, ratings, rated, loaded_from, adjourned)) #<pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) [black] GuestNXMP (----) unrated blitz 2 12 #<pf> 16 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated wild 2 12 Loaded from wild/fr #<pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated blitz 2 12 (adjourned) #<pf> 45 w=GuestGYXR t=match p=GuestGYXR (----) Lobais (----) unrated losers 2 12 #<pf> 45 w=GuestYDDR t=match p=GuestYDDR (----) mgatto (1358) unrated untimed #<pf> 71 w=joseph t=match p=joseph (1632) mgatto (1742) rated wild 5 1 Loaded from wild/fr (adjourned) # # Known offers: abort accept adjourn draw match pause unpause switch takeback # strToOfferType = { "draw": DRAW_OFFER, "abort": ABORT_OFFER, "adjourn": ADJOURN_OFFER, "takeback": TAKEBACK_OFFER, "pause": PAUSE_OFFER, "unpause": RESUME_OFFER, "switch": SWITCH_OFFER, "resign": RESIGNATION, "flag": FLAG_CALL, "match": MATCH_OFFER } offerTypeToStr = {} for k,v in strToOfferType.iteritems(): offerTypeToStr[v] = k class OfferManager (GObject): __gsignals__ = { 'onOfferAdd' : (SIGNAL_RUN_FIRST, None, (object,)), 'onOfferRemove' : (SIGNAL_RUN_FIRST, None, (object,)), 'onOfferDeclined' : (SIGNAL_RUN_FIRST, None, (object,)), 'onChallengeAdd' : (SIGNAL_RUN_FIRST, None, (str, object)), 'onChallengeRemove' : (SIGNAL_RUN_FIRST, None, (str,)), 'onActionError' : (SIGNAL_RUN_FIRST, None, (object, int)), } def __init__ (self, connection): GObject.__init__(self) self.connection = connection self.connection.expect_line (self.onOfferAdd, "<p(t|f)> (\d+) w=%s t=(\w+) p=(.+)" % names) self.connection.expect_line (self.onOfferRemove, "<pr> (\d+)") for ficsstring, offer, error in ( ("You cannot switch sides once a game is underway.", Offer(SWITCH_OFFER), ACTION_ERROR_SWITCH_UNDERWAY), ("Opponent is not out of time.", Offer(FLAG_CALL), ACTION_ERROR_NOT_OUT_OF_TIME), ("The clock is not ticking yet.", Offer(PAUSE_OFFER), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not ticking.", Offer(FLAG_CALL), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not paused.", Offer(RESUME_OFFER), ACTION_ERROR_CLOCK_NOT_PAUSED)): self.connection.expect_line ( lambda match: self.emit("onActionError", offer, error), ficsstring) self.connection.expect_line (self.notEnoughMovesToUndo, "There are (?:(no)|only (\d+) half) moves in your game\.") self.connection.expect_line (self.noOffersToAccept, "There are no ([^ ]+) offers to (accept).") self.connection.expect_line (self.onOfferDeclined, "\w+ declines the (draw|takeback|pause|unpause|abort|adjourn) request\.") self.lastPly = 0 self.offers = {} self.connection.lvm.setVariable("formula", "!suicide & !crazyhouse & !bughouse & !atomic") self.connection.lvm.setVariable("pendinfo", True) def onOfferDeclined (self, match): log.debug("OfferManager.onOfferDeclined: match.string=%s\n" % match.string) type = match.groups()[0] offer = Offer(strToOfferType[type]) self.emit("onOfferDeclined", offer) def noOffersToAccept (self, match): offertype, request = match.groups() if request == "accept": error = ACTION_ERROR_NONE_TO_ACCEPT elif request == "withdraw": error = ACTION_ERROR_NONE_TO_WITHDRAW elif request == "decline": error = ACTION_ERROR_NONE_TO_DECLINE offer = Offer(strToOfferType[offertype]) self.emit("onActionError", offer, error) def notEnoughMovesToUndo (self, match): ply = match.groups()[0] or match.groups()[1] if ply == "no": ply = 0 else: ply = int(ply) offer = Offer(TAKEBACK_OFFER, param=self.lastPly-ply) self.emit("onActionError", offer, ACTION_ERROR_TOO_LARGE_UNDO) def onOfferAdd (self, match): log.debug("OfferManager.onOfferAdd: match.string=%s\n" % match.string) tofrom, index, offertype, parameters = match.groups() 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.warn("OfferManager.onOfferAdd: Declining unknown offer type: " + \ "offertype=%s parameters=%s index=%s\n" % (offertype, parameters, index)) print >> self.connection.client, "decline", index offertype = strToOfferType[offertype] if offertype == TAKEBACK_OFFER: offer = Offer(offertype, param=int(parameters), index=int(index)) else: offer = Offer(offertype, index=int(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.warn("OfferManager.onOfferAdd: auto-declining " + \ "unknown offer type: '%s'\n" % gametype) self.decline(offer) del self.offers[offer.index] return # TODO: get the ficsplayer and update their rating to this one # rather than emitting it in match rating = frating.strip() rating = rating.isdigit() and rating or "0" rated = rated == "unrated" and "u" or "r" match = {"gametype": gametype, "w": fname, "rt": rating, "r": rated, "t": mins, "i": incr, "is_adjourned": is_adjourned} self.emit("onChallengeAdd", index, match) else: log.debug("OfferManager.onOfferAdd: emitting onOfferAdd: %s\n" % offer) self.emit("onOfferAdd", offer) def onOfferRemove (self, match): log.debug("OfferManager.onOfferRemove: match.string=%s\n" % match.string) index = int(match.groups()[0]) if not index in self.offers: return if self.offers[index].type == MATCH_OFFER: self.emit("onChallengeRemove", index) else: self.emit("onOfferRemove", self.offers[index]) del self.offers[index] ### def challenge (self, playerName, game_type, startmin, incsec, rated, color=None): log.debug("OfferManager.challenge: %s %s %s %s %s %s\n" % \ (playerName, game_type, startmin, incsec, rated, color)) rchar = rated and "r" or "u" if color != None: cchar = color == WHITE and "w" or "b" else: cchar = "" s = "match %s %d %d %s %s" % \ (playerName, startmin, incsec, rchar, cchar) if isinstance(game_type, VariantGameType): s += " " + game_type.seek_text print s print >> self.connection.client, s def offer (self, offer, curply): log.debug("OfferManager.offer: curply=%s %s\n" % (curply, offer)) self.lastPly = curply s = offerTypeToStr[offer.type] if offer.type == TAKEBACK_OFFER: s += " " + str(curply - offer.param) print >> self.connection.client, s ### def withdraw (self, offer): log.debug("OfferManager.withdraw: %s\n" % offer) print >> self.connection.client, "withdraw t", offerTypeToStr[offer.type] def accept (self, offer): log.debug("OfferManager.accept: %s\n" % offer) if offer.index != None: self.acceptIndex(offer.index) else: print >> self.connection.client, "accept t", offerTypeToStr[offer.type] def decline (self, offer): log.debug("OfferManager.decline: %s\n" % offer) if offer.index != None: self.declineIndex(offer.index) else: print >> self.connection.client, "decline t", offerTypeToStr[offer.type] def acceptIndex (self, index): log.debug("OfferManager.acceptIndex: index=%s\n" % index) print >> self.connection.client, "accept", index def declineIndex (self, index): log.debug("OfferManager.declineIndex: index=%s\n" % index) print >> self.connection.client, "decline", index def playIndex (self, index): log.debug("OfferManager.playIndex: index=%s\n" % index) print >> self.connection.client, "play", index
Python
from gobject import * class AutoLogOutManager (GObject): __gsignals__ = { 'logOut': (SIGNAL_RUN_FIRST, None, ()) } def __init__ (self, connection): GObject.__init__(self) self.connection = connection self.connection.expect_line (self.onLogOut, "\*\*\*\* Auto-logout because you were idle more than \d+ minutes\. \*\*\*\*") self.connection.expect_line (self.onLogOut, "Logging you out\.") self.connection.expect_line (self.onLogOut, "\*\*\*\* .+? has arrived - you can't both be logged in\. \*\*\*\*") def onLogOut (self, match): self.emit("logOut")
Python
from threading import RLock from gobject import * import re from time import time from pychess.ic import * from pychess.Utils.const import * from pychess.Utils.Rating import Rating from pychess.System.Log import log types = "(?:blitz|standard|lightning|wild|bughouse|crazyhouse|suicide|losers|atomic)" rated = "(rated|unrated)" colors = "(?:\[(white|black)\]\s?)?" ratings = "([\d\+\-]{1,4})" titleslist = "(?:GM|IM|FM|WGM|WIM|TM|SR|TD|SR|CA|C|U|D|B|T|\*)" titles = "((?:\(%s\))+)?" % titleslist names = "(\w+)%s" % titles mf = "(?:([mf]{1,2})\s?)?" # FIXME: Needs support for day, hour, min, sec times = "[, ]*".join("(?:(\d+) %s)?" % s for s in ("days", "hrs", "mins", "secs")) # "73 days, 5 hrs, 55 mins" # ('73', '5', '55', None) class FingerObject: def __init__ (self, name = ""): self.__fingerTime = time() self.__name = name self.__status = None self.__upTime = 0 self.__idleTime = 0 self.__busyMessage = "" self.__lastSeen = 0 self.__totalTimeOnline = 0 self.__created = 0 # Since field from % of life online self.__email = "" self.__sanctions = "" self.__adminLevel = "" self.__timeseal = False self.__notes = [""]*10 self.__gameno = "" self.__color = WHITE self.__opponent = "" self.__silence = False self.__titles = None self.__rating = {} def getName (self): """ Returns the name of the user, without any title sufixes """ return self.__name def getStatus (self): """ Returns the current user-status as a STATUS constant """ return self.__status def getUpTime(self): """ Returns the when the user logged on Not set when status == STATUS_OFFLINE """ return self.__upTime + time() - self.__fingerTime def getIdleTime(self): """ Returns the when the last time the user did something active Not set when status == STATUS_OFFLINE """ return self.__idleTime + time() - self.__fingerTime def getBusyMessage(self): """ Returns the userset idle message This is set when status == STATUS_BUSY or sometimes when status == STATUS_PLAYING """ return self.__busyMessage def getLastSeen(self): """ Returns when the user logged off This is only set when status == STATUS_OFFLINE This is not set, if the user has never logged on """ return self.__lastSeen def getTotalTimeOnline(self): """ Returns how many seconds the user has been on FICS since the account was created. This is not set, if the user has never logged on """ return self.__totalTimeOnline + time() - self.__fingerTime def getCreated(self): """ Returns when the account was created """ return self.__created def getEmail(self): """ Returns the email adress of the user. This will probably only be set for the logged in user """ return self.__email def getSanctions(self): """ Returns any sanctions the user has against them. This is usually an empty string """ return self.__sanctions def getAdminLevel(self): """ Returns the admin level as a string Only set for admins. """ return self.__adminLevel def getTimeseal(self): """ Returns True if the user is using timeseal for fics connection """ return self.__timeseal def getNotes(self): """ Returns a list of the ten finger notes """ return self.__notes def getGameno(self): """ Returns the gameno of the game in which user is currently playing This is only set when status == STATUS_PLAYING """ return self.__gameno def getColor(self): """ If status == STATUS_PLAYING getColor returns the color witch the player has got in the game. Otherwise always WHITE is returned """ return self.__color def getOpponent(self): """ Returns the opponent of the user in his current game This is only set when status == STATUS_PLAYING """ return self.__opponent def getSilence(self): """ Return True if the user is playing in silence This is only set when status == STATUS_PLAYING """ return self.__silence def getRating(self, type=None): if type == None: return self.__rating return self.__rating[type] def getTitles(self): return self.__titles def setName(self, value): self.__name = value def setStatus(self, value): self.__status = value def setUpTime(self, value): """ Use relative seconds """ self.__upTime = value def setIdleTime(self, value): """ Use relative seconds """ self.__idleTime = value def setBusyMessage(self, value): """ Use relative seconds """ self.__busyMessage = value def setLastSeen(self, value): """ Use relative seconds """ self.__lastSeen = value def setTotalTimeOnline(self, value): """ Use relative seconds """ self.__totalTimeOnline = value def setCreated(self, value): """ Use relative seconds """ self.__created = value def setEmail(self, value): self.__email = value def setSanctions(self, value): self.__sanctions = value def setAdminLevel(self, value): self.__adminLevel = value def setTimeseal(self, value): self.__timeseal = value def setNote(self, index, note): self.__notes[index] = note def setGameno(self, value): self.__gameno = value def setColor(self, value): self.__color = value def setOpponent(self, value): self.__opponent = value def setSilence(self, value): self.__silence = value def setRating(self, type, rating): self.__rating[type] = rating def setTitles(self, titles): self.__titles = titles class FingerManager (GObject): __gsignals__ = { 'fingeringFinished' : (SIGNAL_RUN_FIRST, None, (object,)), 'ratingAdjusted' : (SIGNAL_RUN_FIRST, None, (str, str)), } def __init__ (self, connection): GObject.__init__(self) self.connection = connection fingerLines = ( "(?P<never>%s has never connected\.)" % names, "Last disconnected: (?P<last>.+)", "On for: (?P<uptime>.+?) +Idle: (?P<idletime>.+)", "%s is in (?P<silence>silence) mode\." % names, "\(playing game (?P<gameno>\d+): (?P<p1>\S+?)%s vs. (?P<p2>\S+?)%s\)" % (titles,titles), "\(%s (?P<busymessage>.+?)\)" % names, "%s has not played any rated games\." % names, "rating +RD +win +loss +draw +total +best", "(?P<gametype>%s) +(?P<ratings>.+)" % types, "Email *: (?P<email>.+)", "Sanctions *: (?P<sanctions>.+)", "Total time online: (?P<tto>.+)", "% of life online: [\d\.]+ \(since (?P<created>.+?)\)", "Timeseal [ \\d] : (?P<timeseal>Off|On)", "Admin Level: (?P<adminlevel>.+)", "(?P<noteno>\d+): *(?P<note>.*)", "$" ) self.connection.expect_fromplus (self.onFinger, "Finger of %s:" % names, "$|".join(fingerLines)) self.connection.lvm.setVariable("nowrap", True) # We don't use this. Rather we use BoardManagers "gameEnded", after # which we do a refinger. This is to ensure not only rating, but also # wins/looses/draws are updated #self.connection.expect(self.onRatingAdjust, # "%s rating adjustment: (\d+) --> (\d+)" % types # Notice if you uncomment this: The expression has to be compiled with # re.IGNORECASE, or the first letter of 'type' must be capital def parseDate (self, date): # Tue Mar 11, 10:56 PDT 2008 return 1 def parseShortDate (self, date): # 24-Oct-2007 return 1 def parseTime (self, time): # 3 days, 2 hrs, 53 mins return 1 def onFinger (self, matchlist): finger = FingerObject() name = matchlist[0].groups()[0] finger.setName(name) if matchlist[0].groups()[1]: titles = re.findall(titleslist, matchlist[0].groups()[1]) finger.setTitles(titles) for match in matchlist[1:]: if not match.group(): continue groupdict = match.groupdict() if groupdict["never"] != None: finger.setStatus(IC_STATUS_OFFLINE) elif groupdict["last"] != None: finger.setStatus(IC_STATUS_OFFLINE) finger.setLastSeen(self.parseDate(groupdict["last"])) elif groupdict["uptime"] != None: finger.setStatus(IC_STATUS_ACTIVE) finger.setUpTime(self.parseTime(groupdict["uptime"])) finger.setIdleTime(self.parseTime(groupdict["idletime"])) elif groupdict["silence"] != None: finger.setSilence(True) elif groupdict["gameno"] != None: finger.setStatus(IC_STATUS_PLAYING) finger.setGameno(groupdict["gameno"]) if groupdict["p1"].lower() == self.connection.getUsername().lower(): finger.setColor(WHITE) finger.setOpponent(groupdict["p2"]) else: finger.setColor(BLACK) finger.setOpponent(groupdict["p1"]) elif groupdict["busymessage"] != None: finger.setStatus(IC_STATUS_BUSY) finger.setBusyMessage(groupdict["busymessage"]) elif groupdict["gametype"] != None: gametype = GAME_TYPES_BY_FICS_NAME[groupdict["gametype"].lower()] ratings = groupdict["ratings"].split() del ratings[5] # We don't need the totals field ratings[1] = float(ratings[1]) if len(ratings) == 5: args = map(int, ratings) rating = Rating(gametype.rating_type, *args) else: bestTime = self.parseShortDate(ratings[6][1:-1]) args = map(int,ratings[:6]) + [bestTime] rating = Rating(gametype.rating_type, *args) finger.setRating(gametype.rating_type, rating) elif groupdict["email"] != None: finger.setEmail(groupdict["email"]) elif groupdict["sanctions"] != None: finger.setSanctions(groupdict["sanctions"]) elif groupdict["tto"] != None: finger.setTotalTimeOnline(self.parseTime(groupdict["tto"])) elif groupdict["created"] != None: finger.setTotalTimeOnline(self.parseDate(groupdict["created"])) elif groupdict["timeseal"] != None: finger.setTimeseal(groupdict["timeseal"] == "On") elif groupdict["adminlevel"] != None: finger.setAdminLevel(groupdict["adminlevel"]) elif groupdict["noteno"] != None: finger.setNote(int(groupdict["noteno"])-1, groupdict["note"]) else: log.debug("Ignored fingerline: %s\n" % repr(match.group())) self.emit ("fingeringFinished", finger) def onRatingAdjust (self, match): # Notice: This is only recived for us, not for other persons we finger type, old, new = match.groups() self.emit("ratingAdjusted", type, new) def finger (self, user): print >> self.connection.client, "finger %s /sblLw" % user def setFingerNote (self, note, message): assert 1 <= note <= 10 print >> self.connection.client, "set %d %s" % (note, message) def setBusyMessage (self, message): """ Like set busy is really busy right now. """ self.connection.lvm.setVariable("busy", message)
Python
from pychess.System import conf from threading import Semaphore class ListAndVarManager: def __init__ (self, connection): self.connection = connection # Lists self.publicLists = {} self.personalLists = {} self.personalBackup = {} self.listLock = Semaphore(0) self.connection.expect_fromplus (self.onUpdateLists, "Lists:", "(?:\w+\s+is (?:PUBLIC|PERSONAL))|$") self.connection.expect_line (self.onUpdateEmptyListitems, "-- (\w+) list: 0 \w+ --") self.connection.expect_fromplus (self.onUpdateListitems, "-- (\w+) list: ([1-9]\d*) \w+ --", "(?:\w+ *)+$") print >> self.connection.client, "showlist" # Variables self.variablesBackup = {} self.ivariablesBackup = {} self.variables = {} self.ivariables = {} self.varLock = Semaphore(0) self.connection.expect_fromplus (self.onVariables, "((?:Interface v|V)ariable settings) of (\w+):", "(?:\w*=\w+ *)*$") print >> self.connection.client, "variables" print >> self.connection.client, "ivariables" self.connection.connect("disconnecting", self.stop) # Auto flag conf.notify_add('autoCallFlag', self.autoFlagNotify) def isReady (self): return self.listLock._Semaphore__value and self.varLock._Semaphore__value def stop (self, connection): if not self.isReady(): return # Restore personal lists for listName in self.personalLists.keys(): backup = self.personalBackup[listName] inuse = self.personalLists[listName] # Remove which are in use but not in backup for item in inuse-backup: self.removeFromList(listName, item) # Add which are in backup but not in use: for item in backup-inuse: self.addToList(listName, item) # Restore variables for key, usedvalue in self.variables.iteritems(): if key in self.variablesBackup and usedvalue != self.variablesBackup[key]: self.setVariable(key, usedvalue) #for key, usedvalue in self.ivariables.iteritems(): # if usedvalue != self.ivariablesBackup[key]: # self.setVariable(key, usedvalue) # Lists def onUpdateLists (self, matchlist): self.publicLists.clear() self.personalLists.clear() for line in [m.group(0) for m in matchlist[1:] if m.group(0)]: name, _, public_personal = line.split() print >> self.connection.client, "showlist %s" % name if public_personal == "PUBLIC": self.publicLists[name] = set() else: self.personalLists[name] = set() def onUpdateEmptyListitems (self, match): listName = match.groups()[0] if listName in self.publicLists: self.publicLists[listName] = set() else: self.personalLists[listName] = set() if not listName in self.personalBackup: self.personalBackup[listName] = set() # Unlock if people are waiting of the backup if not self.listLock._Semaphore__value and \ len(self.personalLists) == len(self.personalBackup): self.listLock.release() def onUpdateListitems (self, matchlist): listName, itemCount = matchlist[0].groups() items = set() for match in matchlist[1:]: items.update(match.group().split()) if listName in self.publicLists: self.publicLists[listName] = items else: self.personalLists[listName] = items if not listName in self.personalBackup: self.personalBackup[listName] = items # Unlock if people are waiting of the backup if not self.listLock._Semaphore__value and \ len(self.personalLists) == len(self.personalBackup): self.listLock.release() # Variables def onVariables (self, matchlist): type, name = matchlist[0].groups() isIvars = "interface" in type.lower() for line in [m.group(0) for m in matchlist[1:] if m.group(0)]: for kv in line.split(): k,v = kv.split("=") if isIvars: self.ivariables[k] = v if k not in self.ivariablesBackup: self.ivariablesBackup[k] = v else: self.variables[k] = v if k not in self.variablesBackup: self.variablesBackup[k] = v # Unlock if people are waiting of the backup and we've got the normal # variable backup set. The interface variables automatically reset if not self.varLock._Semaphore__value and self.variablesBackup: self.varLock.release() def autoFlagNotify(self, none): self.setVariable('autoflag', conf.get('autoCallFlag',False)) print 'notify flag', conf.get('autoCallFlag',False) # User methods def getList (self, listName): self.listLock.acquire() self.listLock.release() if listName in self.publicLists: return self.publicLists(listName) return self.personalLists[listName] def addToList (self, listName, value): self.listLock.acquire() self.listLock.release() print >> self.connection.client, "+%s %s" % (listName, value) self.lists[listName].append(value) def removeFromList (self, listName, value): self.listLock.acquire() self.listLock.release() print >> self.connection.client, "-%s %s" % (listName, value) self.lists[listName].append(value) def getVariable (self, name): self.varLock.acquire() self.varLock.release() if name in self.variables: return self.variables[name] return self.ivariables[name] def setVariable (self, name, value): self.varLock.acquire() self.varLock.release() if name in self.ivariables: print >> self.connection.client, "iset %s %s" % (name, value) self.ivariables[name] = value else: print >> self.connection.client, "set %s %s" % (name, value) self.variables[name] = value
Python
import re from gobject import * types = "(Blitz|Lightning|Standard)" days = "(Mon|Tue|Wed|Thu|Fri|Sat|Sun)" months = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" AMOUNT_OF_NEWSITEMS = 5 FICS_SENDS = 10 class NewsManager (GObject): __gsignals__ = { 'readingNews' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'readNews' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), } def __init__ (self, connection): GObject.__init__(self) self.connection = connection self.news = {} self.connection.expect_line (self.onNewsItem, "(\d+) \(%s, %s +(\d+)\) (.+)" % (days, months)) print >> self.connection.client, "news" def onNewsItem (self, match): no, weekday, month, day, title = match.groups() line = match.group() self.news[no] = [_(weekday), _(month), day, title, ""] self.emit("readingNews", self.news[no]) if len(self.news) <= AMOUNT_OF_NEWSITEMS: # the "news" command, gives us the latest 10 news items from the # oldest to the newest. # We only want the 5 newest, so we skip the first 5 entries. return elif len(self.news) == FICS_SENDS: # No need to check the expression any more self.connection.unexpect (self.onNewsItem) def onFullNewsItem (matchlist): self.connection.unexpect(onFullNewsItem) details = "" for line in matchlist[1:-1]: if line.startswith("\\"): line = " "+line[1:].strip() details += line.replace(" ", " ") self.news[no][4] = details self.emit("readNews", self.news[no]) self.connection.expect_fromto (onFullNewsItem, re.escape(line), "Posted by.*") print >> self.connection.client, "news %s" % no
Python
from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE import re from pychess.Utils.const import * from pychess.ic import * from pychess.ic.FICSObjects import * from pychess.ic.managers.BoardManager import parse_reason from pychess.System.Log import log rated = "(rated|unrated)" colors = "(?:\[(white|black)\]\s?)?" ratings = "([\d\+\- ]{1,4})" titleslist = "(?:GM|IM|FM|WGM|WIM|TM|SR|TD|CA|C|U|D|B|T|\*)" titleslist_re = re.compile(titleslist) titles = "((?:\(%s\))+)?" % titleslist names = "([a-zA-Z]+)%s" % titles mf = "(?:([mf]{1,2})\s?)?" whomatch = "(?:(?:([-0-9+]{1,4})([\^~:\#. &])%s))" % names whomatch_re = re.compile(whomatch) rating_re = re.compile("[0-9]{2,}") deviation_estimated_re = re.compile("E") deviation_provisional_re = re.compile("P") class GameListManager (GObject): __gsignals__ = { 'addSeek' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'removeSeek' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), 'clearSeeks' : (SIGNAL_RUN_FIRST, TYPE_NONE, ()), 'playerConnected' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'playerDisconnected' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'playerWhoI' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'playerWho' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'playerUnavailable' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), 'playerAvailable' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), } def __init__ (self, connection): GObject.__init__(self) self.connection = connection self.connection.expect_line (self.on_seek_clear, "<sc>") self.connection.expect_line (self.on_seek_add, "<s> (.+)") self.connection.expect_line (self.on_seek_add, "<sn> (.+)") self.connection.expect_line (self.on_seek_remove, "<sr> ([\d ]+)") self.connection.expect_line (self.on_game_list, "(\d+) %s (\w+)\s+%s (\w+)\s+\[(p| )(%s)(u|r)\s*(\d+)\s+(\d+)\]\s*(\d+):(\d+)\s*-\s*(\d+):(\d+) \(\s*(\d+)-\s*(\d+)\) (W|B):\s*(\d+)" % (ratings, ratings, "|".join(GAME_TYPES_BY_SHORT_FICS_NAME.keys()))) self.connection.expect_line (self.on_game_add, "\{Game (\d+) \(([A-Za-z]+) vs\. ([A-Za-z]+)\) (?:Creating|Continuing) (u?n?rated) ([^ ]+) match\.\}$") self.connection.expect_line (self.on_game_remove, "\{Game (\d+) \(([A-Za-z]+) vs\. ([A-Za-z]+)\) ([A-Za-z']+) (.+)\} (\*|1/2-1/2|1-0|0-1)$") self.connection.expect_line (self.on_player_connect, "<wa> ([A-Za-z]+)([\^~:\#. &])(\\d{2})" + "(\d{1,4})([P E])" * 5) self.connection.expect_line (self.on_player_disconnect, "<wd> ([A-Za-z]+)") self.connection.expect_line (self.on_player_whoI, "([A-Za-z]+)([\^~:\#. &])(\\d{2})" + "(\d{1,4})([P E])" * 5) self.connection.expect_line (self.on_player_who, "%s(?:\s{2,}%s)+" % (whomatch, whomatch)) self.connection.expect_line (self.on_player_unavailable, "%s is no longer available for matches." % names) self.connection.expect_fromto (self.on_player_available, "%s Blitz \(%s\), Std \(%s\), Wild \(%s\), Light\(%s\), Bug\(%s\)" % (names, ratings, ratings, ratings, ratings, ratings), "is now available for matches.") self.connection.lvm.setVariable("seekinfo", True) self.connection.lvm.setVariable("seekremove", True) #self.connection.lvm.setVariable("seek", False) self.connection.lvm.setVariable("showownseek", True) self.connection.lvm.setVariable("gin", True) self.connection.lvm.setVariable("pin", True) self.connection.lvm.setVariable("allresults", True) # TODO: This makes login take alot longer... # we send the first who command mainly to get title info like (TM) print >> self.connection.client, "who" # and this second one is mainly for getting rating information print >> self.connection.client, "who IsblwL" #b: blitz l: lightning u: untimed e: examined game #s: standard w: wild x: atomic z: crazyhouse #B: Bughouse L: losers S: Suicide print >> self.connection.client, "games /sblwL" #self.connection.lvm.setVariable("availmax", True) #self.connection.lvm.setVariable("availmin", True) self.connection.lvm.setVariable("availinfo", True) def seek (self, startmin, incsec, game_type, rated, ratings=(0, 9999), color=None, manual=False): log.debug("GameListManager.seek: %s %s %s %s %s %s %s\n" % \ (startmin, incsec, game_type, rated, str(ratings), color, manual)) rchar = rated and "r" or "u" if color != None: cchar = color == WHITE and "w" or "b" else: cchar = "" manual = "m" if manual else "" s = "seek %d %d %s %s %d-%d %s" % \ (startmin, incsec, rchar, cchar, ratings[0], ratings[1], manual) if isinstance(game_type, VariantGameType): s += " " + game_type.seek_text print s print >> self.connection.client, s def refreshSeeks (self): print >> self.connection.client, "iset seekinfo 1" ### def on_seek_add (self, match): parts = match.groups()[0].split(" ") # The <s> message looks like: # <s> index w=name_from ti=titles rt=rating t=time i=increment # r=rated('r')/unrated('u') tp=type("wild/fr", "wild/4","blitz") # c=color rr=rating_range(lower-upper) a=automatic?('t'/'f') # f=formula_checked('t'/f') seek = {"gameno": parts[0]} for key, value in [p.split("=") for p in parts[1:] if p]: if key in ('w', 'r', 't', 'i'): seek[key] = value if key == "tp": try: seek["gametype"] = GAME_TYPES[value] except KeyError: return if key == "rr": seek["rmin"], seek["rmax"] = value.split("-") seek["rmin"] = int(seek["rmin"]) seek["rmax"] = int(seek["rmax"]) elif key == "ti": seek["cp"] = bool(int(value) & 2) # 0x2 - computer title = "" for hex in HEX_TO_TITLE.keys(): if int(value, 16) & hex: title += "(" + \ TITLE_TYPE_DISPLAY_TEXTS_SHORT[HEX_TO_TITLE[hex]] + ")" seek["title"] = title elif key == "rt": if value[-1] in (" ", "P", "E"): seek[key] = value[:-1] else: seek[key] = value elif key == "a": seek["manual"] = value == "f" # Must be accepted manually self.emit("addSeek", seek) def on_seek_clear (self, *args): self.emit("clearSeeks") def on_seek_remove (self, match): for key in match.groups()[0].split(" "): if not key: continue self.emit("removeSeek", key) ### def on_game_list (self, match): gameno, wrating, wname, brating, bname, private, shorttype, rated, min, \ inc, wmin, wsec, bmin, bsec, wmat, bmat, color, movno = match.groups() try: gametype = GAME_TYPES_BY_SHORT_FICS_NAME[shorttype] except KeyError: return wplayer = self.connection.players.get(FICSPlayer(wname)) bplayer = self.connection.players.get(FICSPlayer(bname)) game = FICSGame(wplayer, bplayer, gameno=int(gameno), rated=(rated == "r"), private=(private == "p"), min=int(min), inc=int(inc), game_type=gametype) for player, rating in ((wplayer, wrating), (bplayer, brating)): if player.status != IC_STATUS_PLAYING: player.status = IC_STATUS_PLAYING if player.game != game: player.game = game rating = self.parseRating(rating) if player.ratings[gametype.rating_type].elo != rating: player.ratings[gametype.rating_type].elo = rating self.connection.games.get(game) def on_game_add (self, match): gameno, wname, bname, rated, game_type = match.groups() if game_type not in GAME_TYPES: return wplayer = self.connection.players.get(FICSPlayer(wname)) bplayer = self.connection.players.get(FICSPlayer(bname)) game = FICSGame(wplayer, bplayer, gameno=int(gameno), rated=(rated == "rated"), game_type=GAME_TYPES[game_type]) for player in (wplayer, bplayer): if player.status != IC_STATUS_PLAYING: player.status = IC_STATUS_PLAYING if player.game != game: player.game = game self.connection.games.get(game) def on_game_remove (self, match): gameno, wname, bname, person, comment, result = match.groups() result, reason = parse_reason(reprResult.index(result), comment, wname=wname) wplayer = FICSPlayer(wname) try: wplayer = self.connection.players.get(wplayer, create=False) wplayer.restore_previous_status() # no status update will be sent by # FICS if the player doesn't become available, so we restore # previous status first (not necessarily true, but the best guess) except KeyError: pass bplayer = FICSPlayer(bname) try: bplayer = self.connection.players.get(bplayer, create=False) bplayer.restore_previous_status() except KeyError: pass game = FICSGame(wplayer, bplayer, gameno=int(gameno), result=result, reason=reason) game = self.connection.games.get(game, emit=False) self.connection.games.game_ended(game) # Do this last to give anybody connected to the game's signals a chance # to disconnect from them first wplayer.game = None bplayer.game = None ### def __parseStatus (self, status): if status == "^": return IC_STATUS_PLAYING elif status == " ": return IC_STATUS_AVAILABLE elif status == ".": return IC_STATUS_IDLE elif status == "#": return IC_STATUS_EXAMINING elif status == ":": return IC_STATUS_NOT_AVAILABLE elif status == "~": return IC_STATUS_RUNNING_SIMUL_MATCH elif status == "&": return IC_STATUS_IN_TOURNAMENT @staticmethod def parseRating (rating): if rating: m = rating_re.match(rating) if m: return int(m.group(0)) else: return 0 else: return 0 def __parseDeviation (self, deviation): if deviation_estimated_re.match(deviation): return DEVIATION_ESTIMATED elif deviation_provisional_re.match(deviation): return DEVIATION_PROVISIONAL else: return DEVIATION_NONE def __parseTitleHex (self, titlehex): titles = set() for hex in HEX_TO_TITLE: if int(titlehex, 16) & hex: titles.add(HEX_TO_TITLE[hex]) return titles def __parseTitles (self, titles): _titles = set() if titles: for title in titleslist_re.findall(titles): if title in TITLES: _titles.add(TITLES[title]) return _titles def on_player_connect (self, match): name, status, titlehex, blitz, blitzdev, std, stddev, light, lightdev, \ wild, wilddev, losers, losersdev = match.groups() player = self.connection.players.get(FICSPlayer(name)) copy = player.copy() copy.online = True copy.status = self.__parseStatus(status) copy.titles |= self.__parseTitleHex(titlehex) for ratingtype, elo, dev in \ ((TYPE_BLITZ, blitz, blitzdev), (TYPE_STANDARD, std, stddev), (TYPE_LIGHTNING, light, lightdev), (TYPE_WILD, wild, wilddev), (TYPE_LOSERS, losers, losersdev)): copy.ratings[ratingtype].elo = self.parseRating(elo) copy.ratings[ratingtype].deviation = self.__parseDeviation(dev) player.update(copy) def on_player_disconnect (self, match): name = match.groups()[0] self.connection.players.player_disconnected(FICSPlayer(name)) def on_player_whoI (self, match): self.on_player_connect(match) def on_player_who (self, match): for blitz, status, name, titles in whomatch_re.findall(match.string): player = self.connection.players.get(FICSPlayer(name)) copy = player.copy() copy.online = True copy.status = self.__parseStatus(status) copy.titles |= self.__parseTitles(titles) copy.ratings[TYPE_BLITZ].elo = self.parseRating(blitz) player.update(copy) def on_player_unavailable (self, match): name, titles = match.groups() player = self.connection.players.get(FICSPlayer(name)) copy = player.copy() copy.titles |= self.__parseTitles(titles) # we get here after players start a game, so we make sure that we don't # overwrite IC_STATUS_PLAYING if copy.game is None and copy.status != IC_STATUS_PLAYING: copy.status = IC_STATUS_NOT_AVAILABLE player.update(copy) def on_player_available (self, matches): name, titles, blitz, std, wild, light, bug = matches[0].groups() player = self.connection.players.get(FICSPlayer(name)) copy = player.copy() copy.online = True copy.status = IC_STATUS_AVAILABLE copy.titles |= self.__parseTitles(titles) copy.ratings[TYPE_BLITZ].elo = self.parseRating(blitz) copy.ratings[TYPE_STANDARD].elo = self.parseRating(std) copy.ratings[TYPE_LIGHTNING].elo = self.parseRating(light) copy.ratings[TYPE_WILD].elo = self.parseRating(wild) player.update(copy) if __name__ == "__main__": assert type_to_display_text("Loaded from eco/a00") == type_to_display_text("eco/a00") == "Eco A00" assert type_to_display_text("wild/fr") == Variants.variants[FISCHERRANDOMCHESS].name assert type_to_display_text("blitz") == GAME_TYPES["blitz"].display_text
Python
from FICSConnection import FICSConnection, LogOnError from ICLounge import ICLounge from pychess.System import glock, uistuff from pychess.Utils.const import * import gtk import gobject import re import socket import webbrowser dialog = None def run(): global dialog if not dialog: dialog = ICLogon() dialog.show() elif dialog.lounge: dialog.lounge.present() else: dialog.present() class AutoLogoutException (Exception): pass class ICLogon: def __init__ (self): self.widgets = uistuff.GladeWidgets("fics_logon.glade") uistuff.keepWindowSize("fics_logon", self.widgets["fics_logon"], defaultPosition=uistuff.POSITION_GOLDEN) self.widgets["fics_logon"].connect('key-press-event', lambda w, e: e.keyval == gtk.keysyms.Escape and w.hide()) def on_logOnAsGuest_toggled (check): self.widgets["nameLabel"].set_sensitive(not check.get_active()) self.widgets["nameEntry"].set_sensitive(not check.get_active()) self.widgets["passwordLabel"].set_sensitive(not check.get_active()) self.widgets["passEntry"].set_sensitive(not check.get_active()) self.widgets["logOnAsGuest"].connect("toggled", on_logOnAsGuest_toggled) uistuff.keep(self.widgets["logOnAsGuest"], "logOnAsGuest") uistuff.keep(self.widgets["nameEntry"], "usernameEntry") uistuff.keep(self.widgets["passEntry"], "passwordEntry") uistuff.makeYellow(self.widgets["messagePanel"]) self.widgets["cancelButton"].connect("clicked", self.onCancel, True) self.widgets["stopButton"].connect("clicked", self.onCancel, False) self.widgets["fics_logon"].connect("delete-event", self.onClose) self.widgets["createNewButton"].connect("clicked", self.onCreateNew) self.widgets["connectButton"].connect("clicked", self.onConnectClicked) self.connection = None self.lounge = None def show (self): self.widgets["fics_logon"].show() def present (self): self.widgets["fics_logon"].present() def hide (self): self.widgets["fics_logon"].hide() def showConnecting (self): self.widgets["progressbarBox"].show() self.widgets["mainbox"].set_sensitive(False) self.widgets["connectButton"].hide() self.widgets["stopButton"].show() def pulse (): self.widgets["progressbar"].pulse() return not self.connection.isConnected() self.pulser = gobject.timeout_add(30, pulse) def showNormal (self): self.widgets["mainbox"].set_sensitive(True) self.widgets["connectButton"].show() self.widgets["fics_logon"].set_default(self.widgets["connectButton"]) self.widgets["stopButton"].hide() self.widgets["progressbarBox"].hide() self.widgets["progressbar"].set_text("") gobject.source_remove(self.pulser) def showMessage (self, connection, message): self.widgets["progressbar"].set_text(message) def onCancel (self, widget, hide): if self.connection and self.connection.isConnecting(): self.connection.close() self.connection = None self.showNormal() if hide: self.widgets["fics_logon"].hide() return True def onClose (self, widget, event): self.onCancel(widget, True) return True def onCreateNew (self, button): webbrowser.open("http://www.freechess.org/Register/index.html") def showError (self, connection, error): # Don't bring up errors, if we have pressed "stop" if self.connection != connection: return True text = str(error) if isinstance (error, IOError): title = _("Connection Error") elif isinstance (error, LogOnError): title =_("Log on Error") elif isinstance (error, EOFError): title = _("Connection was closed") elif isinstance (error, socket.error): title = _("Connection Error") text = ", ".join(map(str,error.args)) elif isinstance (error, socket.gaierror) or \ isinstance (error, socket.herror): title = _("Address Error") text = ", ".join(map(str,error.args)) elif isinstance (error, AutoLogoutException): title = _("Auto-logout") text = _("You have been logged out because you were idle more than 60 minutes") else: title = str(error.__class__) self.showNormal() pars = str(text).split("\n") textsVbox = self.widgets["textsVbox"] while len(textsVbox.get_children()) > len(pars)+1: child = textsVbox.get_children()[-1] textsVbox.remove(child) while len(textsVbox.get_children()) < len(pars)+1: label = gtk.Label() label.set_size_request(476, -1) label.props.selectable = True label.props.wrap = True label.props.xalign = 0 label.props.justify = gtk.JUSTIFY_LEFT textsVbox.add(label) def callback (textsVbox, allocation): for child in textsVbox.get_children(): child.set_size_request(allocation.width, -1) textsVbox.connect_after("size-allocate", callback) textsVbox.get_children()[0].set_markup("<b><big>%s</big></b>" % title) for i, par in enumerate(pars): textsVbox.get_children()[i+1].set_text(par) self.widgets["messagePanel"].show_all() def onConnected (self, connection): self.lounge = ICLounge(connection) self.hide() self.lounge.show() self.lounge.connect("logout", lambda iclounge: self.onDisconnected(None)) glock.glock_connect(self.lounge, "autoLogout", lambda iclounge: self.onAutologout(None)) self.showNormal() self.widgets["messagePanel"].hide() def onDisconnected (self, connection): global dialog dialog = None def onAutologout (self, alm): self.show() self.lounge = None self.connection = None self.showError(None, AutoLogoutException()) def onConnectClicked (self, button): if self.widgets["logOnAsGuest"].get_active(): username = "guest" password = "" else: username = self.widgets["nameEntry"].get_text() password = self.widgets["passEntry"].get_text() ports = self.widgets["portsEntry"].get_text() ports = map(int, re.findall("\d+", ports)) if not 23 in ports: ports.append(23) if not 5000 in ports: ports.append(5000) self.showConnecting() self.connection = FICSConnection("freechess.org", ports, username, password) glock.glock_connect(self.connection, "connected", self.onConnected) glock.glock_connect(self.connection, "error", self.showError) glock.glock_connect(self.connection, "connectingMsg", self.showMessage) self.connection.start()
Python
import re, socket from gobject import GObject, SIGNAL_RUN_FIRST import pychess from pychess.System.Log import log from pychess.System.ThreadPool import PooledThread from pychess.Utils.const import * from managers.GameListManager import GameListManager from managers.FingerManager import FingerManager from managers.NewsManager import NewsManager from managers.BoardManager import BoardManager from managers.OfferManager import OfferManager from managers.ChatManager import ChatManager from managers.ListAndVarManager import ListAndVarManager from managers.AutoLogOutManager import AutoLogOutManager from managers.ErrorManager import ErrorManager from managers.AdjournManager import AdjournManager from FICSObjects import FICSPlayers, FICSGames from TimeSeal import TimeSeal from VerboseTelnet import LinePrediction from VerboseTelnet import ManyLinesPrediction from VerboseTelnet import FromPlusPrediction from VerboseTelnet import FromToPrediction from VerboseTelnet import PredictionsTelnet from VerboseTelnet import NLinesPrediction class LogOnError (StandardError): pass class Connection (GObject, PooledThread): __gsignals__ = { 'connecting': (SIGNAL_RUN_FIRST, None, ()), 'connectingMsg': (SIGNAL_RUN_FIRST, None, (str,)), 'connected': (SIGNAL_RUN_FIRST, None, ()), 'disconnecting': (SIGNAL_RUN_FIRST, None, ()), 'disconnected': (SIGNAL_RUN_FIRST, None, ()), 'error': (SIGNAL_RUN_FIRST, None, (object,)), } def __init__ (self, host, ports, username, password): GObject.__init__(self) self.host = host self.ports = ports self.username = username self.password = password self.connected = False self.connecting = False self.predictions = set() self.predictionsDict = {} def expect (self, prediction): self.predictions.add(prediction) self.predictionsDict[prediction.callback] = prediction def unexpect (self, callback): self.predictions.remove(self.predictionsDict.pop(callback)) def expect_line (self, callback, regexp): self.expect(LinePrediction(callback, regexp)) def expect_many_lines (self, callback, regexp): self.expect(ManyLinesPrediction(callback, regexp)) def expect_n_lines (self, callback, *regexps): self.expect(NLinesPrediction(callback, *regexps)) def expect_line_plus (self, callback, regexp): def callback_decorator (matchlist): callback([matchlist[0]]+[m.group(0) for m in matchlist[1:]]) self.expect(FromPlusPrediction(callback_decorator, regexp, "\ (.*)")) def expect_fromplus (self, callback, regexp0, regexp1): self.expect(FromPlusPrediction(callback, regexp0, regexp1)) def expect_fromto (self, callback, regexp0, regexp1): self.expect(FromToPrediction(callback, regexp0, regexp1)) def cancel (self): raise NotImplementedError() def close (self): raise NotImplementedError() def getUsername (self): return self.username def isRegistred (self): return self.password def isConnected (self): return self.connected def isConnecting (self): return self.connecting EOF = _("The connection was broken - got \"end of file\" message") NOTREG = _("'%s' is not a registered name") BADPAS = _("The entered password was invalid.\n" + \ "If you have forgot your password, go to http://www.freechess.org/cgi-bin/Utilities/requestPassword.cgi to request a new one over email.") class FICSConnection (Connection): def __init__ (self, host, ports, username="guest", password=""): Connection.__init__(self, host, ports, username, password) self.registred = None 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\n" % port, (self.host, "raw")) try: self.client.open(self.host, port) except socket.error, e: if e.args[0] != 111 or i+1 == len(self.ports): raise else: break self.client.read_until("login: ") self.emit('connectingMsg', _("Logging on to server")) if self.username and self.username != "guest": print >> self.client, self.username got = self.client.read_until("password:", "enter the server as", "Try again.") if got == 0: self.client.sensitive = True print >> self.client, self.password self.client.sensitive = False self.registred = True # No such name elif got == 1: raise LogOnError, NOTREG % self.username # Bad name elif got == 2: raise LogOnError, NOTREG % self.username else: print >> self.client, "guest" self.client.read_until("Press return") print >> self.client self.registred = False while True: line = self.client.readline() if "Invalid password" in line: raise LogOnError, BADPAS match = re.search("\*\*\*\* Starting FICS session as "+ "([A-Za-z]+)(?:\([A-Z*]+\))* \*\*\*\*", line) if match: self.username = match.groups()[0] break self.client.readuntil("fics%") self.emit('connectingMsg', _("Setting up environment")) self.client = PredictionsTelnet(self.client) self.client.setStripLines(True) self.client.setLinePrefix("fics%") # Important: As the other managers use ListAndVarManager, we need it # to be instantiated first. We might decide that the purpose of this # manager is different - used by different parts of the code - so it # should be implemented into the FICSConnection somehow. self.lvm = ListAndVarManager(self) while not self.lvm.isReady(): self.client.handleSomeText(self.predictions) self.lvm.setVariable("interface", NAME+" "+pychess.VERSION) # FIXME: Some managers use each other to avoid regexp collapse. To # avoid having to init the in a specific order, connect calls should # be moved to a "start" function, so all managers would be in # the connection object when they are called self.em = ErrorManager(self) self.glm = GameListManager(self) self.bm = BoardManager(self) self.fm = FingerManager(self) self.nm = NewsManager(self) self.om = OfferManager(self) self.cm = ChatManager(self) self.alm = AutoLogOutManager(self) self.adm = AdjournManager(self) self.players = FICSPlayers(self) self.games = FICSGames(self) self.bm.start() self.players.start() self.games.start() self.connecting = False self.connected = True self.emit("connected") finally: self.connecting = False def run (self): try: try: if not self.isConnected(): self._connect() while self.isConnected(): self.client.handleSomeText(self.predictions) except Exception, e: if self.connected: self.connected = False for errortype in (IOError, LogOnError, EOFError, socket.error, socket.gaierror, socket.herror): if isinstance(e, errortype): self.emit("error", e) break else: raise finally: self.emit("disconnected") def close (self): self.emit("disconnecting") if self.isConnected(): try: print >> self.client, "quit" except Exception, e: for errortype in (IOError, LogOnError, EOFError, socket.error, socket.gaierror, socket.herror): if isinstance(e, errortype): break else: raise e self.connected = False self.client.close() def isRegistred (self): assert self.registred != None return self.registred def getUsername (self): assert self.username != None return self.username
Python
#session import socket, errno import telnetlib import re import gobject import random import time import platform import getpass from pychess.System.Log import log ENCODE = [ord(i) for i in "Timestamp (FICS) v1.0 - programmed by Henrik Gram."] ENCODELEN = len(ENCODE) G_RESPONSE = '\x029' FILLER = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" IAC_WONT_ECHO = ''.join([telnetlib.IAC, telnetlib.WONT, telnetlib.ECHO]) class TimeSeal: BUFFER_SIZE = 4096 sensitive = False def open (self, address, port): if hasattr(self, "closed") and self.closed: return self.port = port self.address = address self.connected = False self.closed = False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.stateinfo = None try: sock.connect((address,port)) except socket.error, (err, desc): if err != errno.EINPROGRESS: raise self.sock = sock self.buf = '' self.writebuf = '' print >> self, self.get_init_string() self.cook_some() def close (self): self.closed = True if hasattr(self, "sock"): self.sock.close() def encode(self, inbuf, timestamp = None): assert inbuf == "" or inbuf[-1] != "\n" if not timestamp: timestamp = int(time.time()*1000 % 1e7) enc = inbuf + '\x18%d\x19' % timestamp padding = 12 - len(enc)%12 filler = random.sample(FILLER, padding) enc += "".join(filler) buf = [ord(i) for i in enc] for i in range(0, len(buf), 12): buf[i + 11], buf[i] = buf[i], buf[i + 11] buf[i + 9], buf[i + 2] = buf[i + 2], buf[i + 9] buf[i + 7], buf[i + 4] = buf[i + 4], buf[i + 7] encode_offset = random.randrange(ENCODELEN) for i in xrange(len(buf)): buf[i] |= 0x80 j = (i+encode_offset) % ENCODELEN buf[i] = chr((buf[i] ^ ENCODE[j]) - 32) buf.append( chr(0x80 | encode_offset)) return ''.join(buf) def get_init_string(self): """ timeseal header: TIMESTAMP|bruce|Linux gruber 2.6.15-gentoo-r1 #9 PREEMPT Thu Feb 9 20:09:47 GMT 2006 i686 Intel(R) Celeron(R) CPU 2.00GHz GenuineIntel GNU/Linux| 93049 """ user = getpass.getuser() uname = ' '.join(list(platform.uname())) return "TIMESTAMP|%(user)s|%(uname)s|" % locals() def decode(self, buf, stateinfo = None): expected_table = "\n\r[G]\n\r" final_state = len(expected_table) g_count = 0 result = [] if stateinfo: state, lookahead = stateinfo else: state, lookahead = 0, [] lenb = len(buf) idx = 0 while idx < lenb: ch = buf[idx] expected = expected_table[state] if ch == expected: state += 1 if state == final_state: g_count += 1 lookahead = [] state = 0 else: lookahead.append(ch) idx += 1 elif state == 0: result.append(ch) idx += 1 else: result.extend(lookahead) lookahead = [] state = 0 return ''.join(result), g_count, (state, lookahead) def write(self, str): self.writebuf += str if "\n" not in self.writebuf: return if self.closed: return i = self.writebuf.rfind("\n") str = self.writebuf[:i] self.writebuf = self.writebuf[i+1:] logstr = "*"*len(str) if self.sensitive else str log.log(logstr+"\n", (repr(self), "raw")) str = self.encode(str) self.sock.send(str+"\n") def readline(self): return self.readuntil("\n") def readuntil(self, until): while True: i = self.buf.find(until) if i >= 0: stuff = self.buf[:i+len(until)] self.buf = self.buf[i+len(until):] return stuff self.cook_some() def cook_some (self): recv = self.sock.recv(self.BUFFER_SIZE) if len(recv) == 0: return if not self.connected: log.debug(recv, (repr(self), "raw")) self.buf += recv if "Starting FICS session" in self.buf: self.connected = True self.buf = self.buf.replace(IAC_WONT_ECHO, '') else: recv, g_count, self.stateinfo = self.decode(recv, self.stateinfo) recv = recv.replace("\r","") log.debug(recv, (repr(self), "raw")) for i in range(g_count): print >> self, G_RESPONSE self.buf += recv def read_until (self, *untils): while True: for i, until in enumerate(untils): start = self.buf.find(until) if start >= 0: self.buf = self.buf[:start] return i self.cook_some() def __repr__ (self): return self.address
Python
from pychess.System.Log import log from pychess.Utils.GameModel import GameModel from pychess.Utils.Offer import Offer from pychess.Utils.const import * from pychess.Players.Human import Human from pychess.ic import GAME_TYPES class ICGameModel (GameModel): def __init__ (self, connection, ficsgame, timemodel): assert ficsgame.game_type in GAME_TYPES.values() GameModel.__init__(self, timemodel, ficsgame.game_type.variant) self.connection = connection self.ficsgame = ficsgame connections = self.connections connections[connection.bm].append(connection.bm.connect("boardUpdate", self.onBoardUpdate)) connections[connection.bm].append(connection.bm.connect("obsGameEnded", self.onGameEnded)) connections[connection.bm].append(connection.bm.connect("curGameEnded", self.onGameEnded)) connections[connection.bm].append(connection.bm.connect("gamePaused", self.onGamePaused)) connections[connection.om].append(connection.om.connect("onActionError", self.onActionError)) connections[connection].append(connection.connect("disconnected", self.onDisconnected)) rated = "rated" if ficsgame.rated else "unrated" # This is in the format that ficsgame.com writes these PGN headers self.tags["Event"] = "FICS %s %s game" % (rated, ficsgame.game_type.fics_name) self.tags["Site"] = "FICS" def __repr__ (self): s = GameModel.__repr__(self) s = s.replace("<GameModel", "<ICGameModel") s = s.replace(", players=", ", ficsgame=%s, players=" % self.ficsgame) return s @property def display_text (self): t = "[ " if self.timemodel: t += self.timemodel.display_text + " " t += self.ficsgame.display_rated.lower() + " " if self.ficsgame.game_type.display_text: t += self.ficsgame.game_type.display_text + " " return t + "]" def __disconnect (self): if self.connections is None: return for obj in self.connections: # Humans need to stay connected post-game so that "GUI > Actions" works if isinstance(obj, Human): continue for handler_id in self.connections[obj]: if obj.handler_is_connected(handler_id): log.debug("ICGameModel.__disconnect: object=%s handler_id=%s\n" % \ (repr(obj), repr(handler_id))) obj.disconnect(handler_id) self.connections = None def hasGuestPlayers (self): for player in (self.ficsgame.wplayer, self.ficsgame.bplayer): if player.isGuest(): return True return False def onBoardUpdate (self, bm, gameno, ply, curcol, lastmove, fen, wname, bname, wms, bms): log.debug(("ICGameModel.onBoardUpdate: id=%s self.ply=%s self.players=%s gameno=%s " + \ "wname=%s bname=%s ply=%s curcol=%s lastmove=%s fen=%s wms=%s bms=%s\n") % \ (str(id(self)), str(self.ply), repr(self.players), str(gameno), str(wname), str(bname), \ str(ply), str(curcol), str(lastmove), str(fen), str(wms), str(bms))) if gameno != self.ficsgame.gameno or len(self.players) < 2 or wname != self.players[0].ichandle \ or bname != self.players[1].ichandle: return log.debug("ICGameModel.onBoardUpdate: id=%d, self.players=%s: updating time and/or ply\n" % \ (id(self), str(self.players))) if self.timemodel: log.debug("ICGameModel.onBoardUpdate: id=%d self.players=%s: updating timemodel\n" % \ (id(self), str(self.players))) self.timemodel.updatePlayer (WHITE, wms/1000.) self.timemodel.updatePlayer (BLACK, bms/1000.) if ply < self.ply: log.debug("ICGameModel.onBoardUpdate: id=%d self.players=%s self.ply=%d ply=%d: TAKEBACK\n" % \ (id(self), str(self.players), self.ply, ply)) offers = self.offers.keys() for offer in offers: if offer.type == TAKEBACK_OFFER: # There can only be 1 outstanding takeback offer for both players on FICS, # (a counter-offer by the offeree for a takeback for a different number of # moves replaces the initial offer) so we can safely remove all of them del self.offers[offer] self.undoMoves(self.ply-ply) def onGameEnded (self, bm, ficsgame): if ficsgame == self.ficsgame and len(self.players) >= 2: log.debug( "ICGameModel.onGameEnded: self.players=%s ficsgame=%s\n" % \ (repr(self.players), repr(ficsgame))) self.end(ficsgame.result, ficsgame.reason) def setPlayers (self, players): GameModel.setPlayers(self, players) if self.players[WHITE].icrating: self.tags["WhiteElo"] = self.players[WHITE].icrating if self.players[BLACK].icrating: self.tags["BlackElo"] = self.players[BLACK].icrating def onGamePaused (self, bm, gameno, paused): if paused: self.pause() else: self.resume() # we have to do this here rather than in acceptRecieved(), because # sometimes FICS pauses/unpauses a game clock without telling us that the # original offer was "accepted"/"received", such as when one player offers # "pause" and the other player responds not with "accept" but "pause" for offer in self.offers.keys(): if offer.type in (PAUSE_OFFER, RESUME_OFFER): del self.offers[offer] def onDisconnected (self, connection): if self.status in (WAITING_TO_START, PAUSED, RUNNING): self.end (KILLED, DISCONNECTED) ############################################################################ # Offer management # ############################################################################ def offerRecieved (self, player, offer): log.debug("ICGameModel.offerRecieved: offerer=%s %s\n" % (repr(player), offer)) if player == self.players[WHITE]: opPlayer = self.players[BLACK] else: opPlayer = self.players[WHITE] if offer.type == CHAT_ACTION: opPlayer.putMessage(offer.param) elif offer.type in (RESIGNATION, FLAG_CALL): self.connection.om.offer(offer, self.ply) elif offer.type in OFFERS: if offer not in self.offers: log.debug("ICGameModel.offerRecieved: %s.offer(%s)\n" % (repr(opPlayer), offer)) self.offers[offer] = player opPlayer.offer(offer) # If the offer was an update to an old one, like a new takebackvalue # we want to remove the old one from self.offers for offer_ in self.offers.keys(): if offer.type == offer_.type and offer != offer_: del self.offers[offer_] def acceptRecieved (self, player, offer): log.debug("ICGameModel.acceptRecieved: accepter=%s %s\n" % (repr(player), offer)) if player.__type__ == LOCAL: if offer not in self.offers or self.offers[offer] == player: player.offerError(offer, ACTION_ERROR_NONE_TO_ACCEPT) else: log.debug("ICGameModel.acceptRecieved: connection.om.accept(%s)\n" % offer) self.connection.om.accept(offer) del self.offers[offer] # We don't handle any ServerPlayer calls here, as the fics server will # know automatically if he/she accepts an offer, and will simply send # us the result. def checkStatus (self): pass def onActionError (self, om, offer, error): self.emit("action_error", offer, error) # # End # def end (self, status, reason): if self.status in UNFINISHED_STATES: self.__disconnect() if self.isObservationGame(): self.connection.bm.unobserve(self.ficsgame) else: self.connection.om.offer(Offer(ABORT_OFFER), -1) self.connection.om.offer(Offer(RESIGNATION), -1) GameModel.end(self, status, reason)
Python
import datetime import gobject from gobject import GObject, SIGNAL_RUN_FIRST from pychess.Utils.IconLoader import load_icon from pychess.Utils.Rating import Rating from pychess.Utils.const import * from pychess.ic import TYPE_BLITZ, TYPE_STANDARD, TYPE_LIGHTNING, TYPE_WILD, \ TYPE_LOSERS, TITLE_TYPE_DISPLAY_TEXTS, TITLE_TYPE_DISPLAY_TEXTS_SHORT, \ GAME_TYPES_BY_RATING_TYPE, TYPE_UNREGISTERED, TYPE_COMPUTER, TYPE_ADMINISTRATOR, \ GAME_TYPES_BY_FICS_NAME, GAME_TYPES class FICSPlayer (GObject): def __init__ (self, name, online=False, status=IC_STATUS_OFFLINE, game=None, titles=None, ratings=None): assert type(name) is str, name assert type(online) is bool, online GObject.__init__(self) self.name = name self.online = online self._status = status self.status = status self.game = None self.adjournment = False if titles is None: self.titles = set() else: self.titles = titles if ratings is None: self.ratings = {} for ratingtype in (TYPE_BLITZ, TYPE_STANDARD, TYPE_LIGHTNING, TYPE_WILD, TYPE_LOSERS): ratingobj = Rating(ratingtype, 0) self.setRating(ratingtype, ratingobj) else: self.ratings = ratings def long_name (self, game_type=None): name = self.name if game_type is None: rating = self.getRatingForCurrentGame() else: rating = self.getRating(game_type.rating_type) if rating is not None: rating = rating.elo if rating: name += " (%d)" % rating title = self.display_titles() if title: name += " %s" % title return name def get_online (self): return self._online def set_online (self, online): self._online = online online = gobject.property(get_online, set_online) @property def display_online (self): if self.online: return _("Online") else: return _("Offline") def get_status (self): return self._status def set_status (self, status): self._previous_status = self._status self._status = status status = gobject.property(get_status, set_status) def restore_previous_status (self): self.status = self._previous_status @property def display_status (self): status = "" if self.status == IC_STATUS_AVAILABLE: status = _("Available") elif self.status == IC_STATUS_PLAYING: status = _("Playing") game = self.game if game is not None: status += " " + game.display_text elif self.status == IC_STATUS_IDLE: status = _("Idle") elif self.status == IC_STATUS_EXAMINING: status = _("Examining") elif self.status in (IC_STATUS_NOT_AVAILABLE, IC_STATUS_BUSY): status = _("Not Available") elif self.status == IC_STATUS_RUNNING_SIMUL_MATCH: status = _("Running Simul Match") elif self.status == IC_STATUS_IN_TOURNAMENT: status = _("In Tournament") # log.debug("display_status: returning \"%s\" for %s\n" % (status, self)) return status def get_game (self): return self._game def set_game (self, game): self._game = game game = gobject.property(get_game, set_game) def get_titles (self): return self._titles def set_titles (self, titles): self._titles = titles titles = gobject.property(get_titles, set_titles) def display_titles (self, long=False): r = "" for title in self.titles: if long: r += " (" + TITLE_TYPE_DISPLAY_TEXTS[title] + ")" else: r += " (" + TITLE_TYPE_DISPLAY_TEXTS_SHORT[title] + ")" return r @property def blitz (self): return self.getRating(TYPE_BLITZ).elo @property def standard (self): return self.getRating(TYPE_STANDARD).elo @property def lightning (self): return self.getRating(TYPE_LIGHTNING).elo @property def wild (self): return self.getRating(TYPE_WILD).elo @property def losers (self): return self.getRating(TYPE_LOSERS).elo def __hash__ (self): """ Two players are equal if the first 10 characters of their name match. This is to facilitate matching players from output of commands like the 'game' command which only return the first 10 characters of a player's name """ return hash(self.name[0:10].lower()) def __eq__ (self, player): if type(self) == type(player) and hash(self) == hash(player): return True else: return False def __repr__ (self): r = "name='%s'" % (self.name + self.display_titles()) r += ", online=%s" % repr(self.online) r += ", adjournment=%s" % repr(self.adjournment) r += ", status=%i" % self.status game = self.game if game != None: r += ", game.gameno=%d" % game.gameno r += ", game.private=" + repr(game.private) else: r += ", game=None" for rating_type in (TYPE_BLITZ, TYPE_STANDARD, TYPE_LIGHTNING, TYPE_WILD, TYPE_LOSERS): if rating_type in self.ratings: r += ", ratings[%s] = (" % \ GAME_TYPES_BY_RATING_TYPE[rating_type].display_text r += self.ratings[rating_type].__repr__() + ")" return "<FICSPlayer " + r + ">" def isAvailableForGame (self): if self.status in \ (IC_STATUS_PLAYING, IC_STATUS_BUSY, IC_STATUS_OFFLINE, IC_STATUS_RUNNING_SIMUL_MATCH, IC_STATUS_NOT_AVAILABLE, IC_STATUS_EXAMINING, IC_STATUS_IN_TOURNAMENT): return False else: return True def isObservable (self): if self.status in (IC_STATUS_PLAYING, IC_STATUS_EXAMINING) and \ self.game is not None and not self.game.private: return True else: return False def isGuest (self): if TYPE_UNREGISTERED in self.titles: return True else: return False def isComputer (self): if TYPE_COMPUTER in self.titles: return True else: return False def isAdmin (self): if TYPE_ADMINISTRATOR in self.titles: return True else: return False @classmethod def getIconByRating (cls, rating, size=16): assert type(rating) == int, "rating not an int: %s" % str(rating) if rating >= 1900: return load_icon(size, "weather-storm") elif rating >= 1600: return load_icon(size, "weather-showers") elif rating >= 1300: return load_icon(size, "weather-overcast") elif rating >= 1000: return load_icon(size, "weather-few-clouds") else: return load_icon(size, "weather-clear") def getIcon (self, size=16, gametype=None): assert type(size) == int, "size not an int: %s" % str(size) if self.isGuest(): return load_icon(size, "stock_people", "system-users") elif self.isComputer(): return load_icon(size, "computer", "stock_notebook") elif self.isAdmin(): return load_icon(size, "security-high", "stock_book_blue") else: if gametype: rating = self.getRating(gametype.rating_type) rating = rating.elo if rating is not None else 0 else: rating = self.getStrength() return self.getIconByRating(rating, size) def getMarkup (self, gametype=None): markup = "<big><b>%s</b></big>" % self.name if self.isGuest(): markup += " <big>(%s)</big>" % \ TITLE_TYPE_DISPLAY_TEXTS[TYPE_UNREGISTERED] else: if gametype: rating = self.getRating(gametype.rating_type) rating = rating.elo if rating is not None else 0 else: rating = self.getStrength() if rating < 1: rating = _("Unrated") markup += " <big>(%s)</big>" % rating if self.display_titles() != "": markup += "<big>%s</big>" % self.display_titles(long=True) return markup def getRating (self, rating_type): if rating_type in self.ratings: return self.ratings[rating_type] else: return None def setRating (self, rating_type, ratingobj): self.ratings[rating_type] = ratingobj def addRating (self, rating_type, rating): if rating == None: return ratingobj = Rating(rating_type, rating) self.ratings[rating_type] = ratingobj def copy (self): player = FICSPlayer(self.name, online=self.online, status=self.status, titles=self.titles.copy(), ratings={}) for ratingtype, rating in self.ratings.iteritems(): player.ratings[ratingtype] = rating.copy() player.game = self.game player.adjournment = self.adjournment return player def update (self, player): if not isinstance(player, FICSPlayer): raise TypeError if self.game != player.game: self.game = player.game if self.adjournment != player.adjournment: self.adjournment = player.adjournment if not self.titles >= player.titles: self.titles |= player.titles for ratingtype in (TYPE_BLITZ, TYPE_STANDARD, TYPE_LIGHTNING, TYPE_WILD, TYPE_LOSERS): self.ratings[ratingtype].update(player.ratings[ratingtype]) if self.status != player.status: self.status = player.status # do last so rating info is there when notifications are generated if self.online != player.online: self.online = player.online def getRatingMean (self): ratingtotal = 0 numratings = 0 for ratingtype in self.ratings: if self.ratings[ratingtype].elo == 0: continue if self.ratings[ratingtype].deviation == DEVIATION_NONE: ratingtotal += self.ratings[ratingtype].elo * 3 numratings += 3 elif self.ratings[ratingtype].deviation == DEVIATION_ESTIMATED: ratingtotal += self.ratings[ratingtype].elo * 2 numratings += 2 elif self.ratings[ratingtype].deviation == DEVIATION_PROVISIONAL: ratingtotal += self.ratings[ratingtype].elo * 1 numratings += 1 return numratings > 0 and ratingtotal / numratings or 0 # FIXME: this isn't very accurate because of inflated standard ratings # and deflated lightning ratings and needs work # IDEA: use rank in addition to rating to determine strength def getStrength (self): if TYPE_BLITZ in self.ratings and \ self.ratings[TYPE_BLITZ].deviation == DEVIATION_NONE: return self.ratings[TYPE_BLITZ].elo elif TYPE_LIGHTNING in self.ratings and \ self.ratings[TYPE_LIGHTNING].deviation == DEVIATION_NONE: return self.ratings[TYPE_LIGHTNING].elo else: return self.getRatingMean() def getRatingForCurrentGame (self): """ Note: This will not work for adjourned or history games since player.game is not set in those cases """ if self.game == None: return None rating = self.getRating(self.game.game_type.rating_type) if rating != None: return rating.elo else: return None class FICSPlayers (GObject): __gsignals__ = { 'FICSPlayerEntered' : (SIGNAL_RUN_FIRST, None, (object,)), 'FICSPlayerExited' : (SIGNAL_RUN_FIRST, None, (object,)) } def __init__ (self, connection): GObject.__init__(self) self.players = {} self.players_cids = {} self.connection = connection def start (self): # self.connection.fm.connect("fingeringFinished", self.onFinger) pass def __getitem__ (self, player): if type(player) is not FICSPlayer: raise TypeError("%s" % repr(player)) if hash(player) in self.players: return self.players[hash(player)] else: raise KeyError def __setitem__ (self, key, value): """ key and value must be the same FICSPlayer object """ if type(key) is not FICSPlayer: raise TypeError if type(value) is not FICSPlayer: raise TypeError if key != value: raise Exception("Not the same: %s %s" % (repr(key), repr(value))) if hash(value) in self.players: raise Exception("%s already exists in %s" % (repr(value), repr(self))) self.players[hash(value)] = value self.players_cids[hash(value)] = value.connect("notify::online", self.online_changed) def __delitem__ (self, player): if type(player) is not FICSPlayer: raise TypeError if player in self: del self.players[hash(player)] if hash(player) in self.players_cids: if player.handler_is_connected(self.players_cids[hash(player)]): player.disconnect(self.players_cids[hash(player)]) del self.players_cids[hash(player)] def __contains__ (self, player): if type(player) is not FICSPlayer: raise TypeError if hash(player) in self.players: return True else: return False def keys(self): return self.players.keys() def items(self): return self.players.items() def iteritems(self): return self.players.iteritems() def iterkeys(self): return self.players.iterkeys() def itervalues(self): return self.players.itervalues() def values(self): return self.players.values() def online_changed (self, player, property): if player.online: self.emit("FICSPlayerEntered", player) # This method is a temporary hack until ChatWindow/ChatManager are # converted to use FICSPlayer references rather than player's names def get_online_playernames (self): names = [] for player in self.players.itervalues(): if player.online: names.append(player.name) return names def get (self, player, create=True): # TODO: lock if player in self: player = self[player] elif create: self[player] = player else: raise KeyError return player def player_disconnected (self, player): if player in self: player = self[player] if player.adjournment: player.online = False player.status = IC_STATUS_OFFLINE else: del self[player] self.emit('FICSPlayerExited', player) # def onFinger (self, fm, finger): # player = FICSPlayer(finger.getName()) # if player in self: # self[player].finger = finger # # TODO: merge ratings and titles from finger object into ficsplayer object class FICSBoard: def __init__ (self, wms, bms, fen=None, pgn=None): assert type(wms) is int, wms assert type(bms) is int, bms self.wms = wms self.bms = bms # assert fen != None or pgn != None self.fen = fen self.pgn = pgn class FICSGame (GObject): def __init__ (self, wplayer, bplayer, gameno=None, game_type=None, rated=False, min=None, inc=None, result=None, reason=None, board=None, private=False): assert isinstance(wplayer, FICSPlayer), wplayer assert isinstance(bplayer, FICSPlayer), bplayer assert gameno is None or type(gameno) is int, gameno assert type(rated) is bool, rated assert game_type is None or game_type is GAME_TYPES_BY_FICS_NAME["wild"] \ or game_type in GAME_TYPES.values(), game_type assert min is None or type(min) is int, min assert inc is None or type(inc) is int, inc assert result is None or type(result) is int, result assert reason is None or type(reason) is int, reason assert board is None or isinstance(board, FICSBoard), board assert type(private) is bool, private GObject.__init__(self) self.wplayer = wplayer self.bplayer = bplayer self.gameno = gameno self.rated = rated self.game_type = game_type self.min = min # not always set ("game created ..." message doesn't specify) self.inc = inc # not always set ("game created ..." message doesn't specify) self.result = result self.reason = reason self.board = board self.private = private def __hash__ (self): return hash(":".join((self.wplayer.name[0:10].lower(), self.bplayer.name[0:10].lower(), str(self.gameno)))) def __eq__ (self, game): if isinstance(game, FICSGame) and hash(self) == hash(game): return True else: return False def __repr__ (self): r = "<FICSGame wplayer=%s, bplayer=%s" % \ (repr(self.wplayer), repr(self.bplayer)) if self.gameno is not None: r += ", gameno=%d" % self.gameno r += ", game_type=%s" % self.game_type r += self.rated and ", rated=True" or ", rated=False" if self.min != None: r += ", min=%i" % self.min if self.inc != None: r += ", inc=%i" % self.inc if self.result != None: r += ", result=%i" % self.result if self.reason != None: r += ", reason=%i" % self.reason r += ", private=%s>" % repr(self.private) return r def get_private (self): return self._private def set_private (self, private): self._private = private private = gobject.property(get_private, set_private) @property def display_rated (self): if self.rated: return _("Rated") else: return _("Unrated") @property def display_text (self): text = "" gametype = self.game_type if gametype is not None: text += gametype.display_text if self.private: text += " (" + _("Private") + ")" return text @property def display_timecontrol (self): t = "" if self.min is not None: t = _("%d min") % self.min if self.inc is not None and self.inc != 0: t += _(" + %d sec") % self.inc return t def update (self, game): if self.rated != game.rated: self.rated = game.rated if self.private != game.private: self.private = game.private if game.min is not None and self.min != game.min: self.min = game.min if game.inc is not None and self.inc != game.inc: self.inc = game.inc if game.game_type is not None and \ self.game_type != game.game_type and not \ (self.game_type is not None and \ game.game_type is GAME_TYPES_BY_FICS_NAME["wild"]): self.game_type = game.game_type if game.result is not None and self.result != game.result: self.result = game.result if game.reason is not None and self.reason != game.reason: self.reason = game.reason if game.board is not None and self.board != game.board: self.board = game.board class FICSAdjournedGame (FICSGame): def __init__ (self, wplayer, bplayer, our_color=None, length=None, time=None, rated=False, game_type=None, private=False, min=None, inc=None, result=None, reason=None, board=None): assert our_color is None or our_color in (WHITE, BLACK), our_color assert length is None or type(length) is int, length assert time is None or type(time) is datetime.datetime, time FICSGame.__init__(self, wplayer, bplayer, rated=rated, private=private, game_type=game_type, min=min, inc=inc, result=result, reason=reason, board=board) self.our_color = our_color self.length = length self.time = time def __repr__ (self): s = FICSGame.__repr__(self)[0:-1] s = s.replace("<FICSGame", "<FICSAdjournedGame") if self.our_color != None: s += ", our_color=%i" % self.our_color if self.length != None: s += ", length=%i" % self.length if self.time != None: s += ", time=%s" % self.display_time return s + ">" @property def display_time (self): if self.time is not None: return self.time.strftime("%x %H:%M") @property def opponent (self): if self.our_color == WHITE: return self.bplayer elif self.our_color == BLACK: return self.wplayer class FICSGames (GObject): __gsignals__ = { 'FICSGameCreated' : (SIGNAL_RUN_FIRST, None, (object,)), 'FICSGameEnded' : (SIGNAL_RUN_FIRST, None, (object,)), 'FICSAdjournedGameRemoved' : (SIGNAL_RUN_FIRST, None, (object,)), } def __init__ (self, connection): GObject.__init__(self) self.games = {} self.games_by_gameno = {} self.connection = connection def start (self): self.connection.adm.connect("onAdjournmentsList", self.onAdjournmentsList) self.connection.bm.connect("curGameEnded", self.onCurGameEnded) def __getitem__ (self, game): if not isinstance(game, FICSGame): raise TypeError("Not a FICSGame: %s" % repr(game)) if hash(game) in self.games: return self.games[hash(game)] else: raise KeyError def __setitem__ (self, key, value): """ key and value must be the same game """ if not isinstance(key, FICSGame): raise TypeError if not isinstance(value, FICSGame): raise TypeError if key != value: raise Exception("Not the same: %s %s" % (repr(key), repr(value))) if hash(value) in self.games: raise Exception("%s already exists in %s" % (repr(value), repr(self))) self.games[hash(value)] = value self.games_by_gameno[value.gameno] = value def __delitem__ (self, game): if not isinstance(game, FICSGame): raise TypeError if game in self: del self.games[hash(game)] if game.gameno in self.games_by_gameno: del self.games_by_gameno[game.gameno] def __contains__ (self, game): if not isinstance(game, FICSGame): raise TypeError if hash(game) in self.games: return True else: return False def keys(self): return self.games.keys() def items(self): return self.games.items() def iteritems(self): return self.games.iteritems() def iterkeys(self): return self.games.iterkeys() def itervalues(self): return self.games.itervalues() def values(self): return self.games.values() def get_game_by_gameno (self, gameno): if type(gameno) is not int: raise TypeError return self.games_by_gameno[gameno] def get (self, game, create=True, emit=True): # TODO: lock if game in self: self[game].update(game) game = self[game] elif create: self[game] = game if emit: self.emit("FICSGameCreated", game) else: raise KeyError return game def game_ended (self, game): if game in self: game = self[game] del self[game] self.emit("FICSGameEnded", game) def onAdjournmentsList (self, adm, adjournments): for game in self.values(): if isinstance(game, FICSAdjournedGame): if game not in adjournments: del self[game] game.opponent.adjournment = False self.emit("FICSAdjournedGameRemoved", game) def onCurGameEnded (self, bm, game): for _game in self.values(): if isinstance(_game, FICSAdjournedGame): for player in (game.wplayer, game.bplayer): if player == _game.opponent: del self[_game] _game.opponent.adjournment = False self.emit("FICSAdjournedGameRemoved", _game) class FICSSeek: def __init__ (self, name, min, inc, rated, color, game_type, rmin=0, rmax=9999): assert game_type in GAME_TYPES, game_type self.seeker = name self.min = min self.inc = inc self.rated = rated self.color = color self.game_type = game_type self.rmin = rmin # minimum rating one has to have to be offered this seek self.rmax = rmax # maximum rating one has to have to be offered this seek
Python
# -*- coding: utf-8 -*- import Queue from StringIO import StringIO from time import strftime, localtime, time from math import e from operator import attrgetter from itertools import groupby import gtk, gobject, pango, re from gtk.gdk import pixbuf_new_from_file from gobject import GObject, SIGNAL_RUN_FIRST from pychess.ic import * from pychess.System import conf, glock, uistuff from pychess.System.GtkWorker import Publisher from pychess.System.prefix import addDataPrefix from pychess.System.ping import Pinger from pychess.System.Log import log from pychess.widgets import ionest from pychess.widgets import gamewidget from pychess.widgets.ChatWindow import ChatWindow from pychess.widgets.SpotGraph import SpotGraph from pychess.widgets.ChainVBox import ChainVBox from pychess.widgets.preferencesDialog import SoundTab from pychess.widgets.InfoBar import * from pychess.Utils.const import * from pychess.Utils.GameModel import GameModel from pychess.Utils.IconLoader import load_icon from pychess.Utils.TimeModel import TimeModel from pychess.Players.ICPlayer import ICPlayer from pychess.Players.Human import Human from pychess.Savers import pgn, fen from pychess.Variants import variants from pychess.Variants.normal import NormalChess from FICSObjects import * from ICGameModel import ICGameModel from pychess.Utils.Rating import Rating class ICLounge (GObject): __gsignals__ = { 'logout' : (SIGNAL_RUN_FIRST, None, ()), 'autoLogout' : (SIGNAL_RUN_FIRST, None, ()), } def __init__ (self, c): GObject.__init__(self) self.connection = c self.widgets = w = uistuff.GladeWidgets("fics_lounge.glade") uistuff.keepWindowSize("fics_lounge", self.widgets["fics_lounge"]) self.infobar = InfoBar() self.infobar.hide() self.widgets["fics_lounge_infobar_vbox"].pack_start(self.infobar, expand=False, fill=False) def on_window_delete (window, event): self.close() self.emit("logout") return True self.widgets["fics_lounge"].connect("delete-event", on_window_delete) def on_logoffButton_clicked (button): self.close() self.emit("logout") self.widgets["logoffButton"].connect("clicked", on_logoffButton_clicked) def on_autoLogout (alm): self.close() self.emit("autoLogout") self.connection.alm.connect("logOut", on_autoLogout) self.connection.connect("disconnected", lambda connection: self.close()) self.connection.connect("error", self.on_connection_error) # workaround for https://code.google.com/p/pychess/issues/detail?id=677 self.connection.nm.connect("readNews", self.on_news_item) if self.connection.isRegistred(): numtimes = conf.get("numberOfTimesLoggedInAsRegisteredUser", 0) + 1 conf.set("numberOfTimesLoggedInAsRegisteredUser", numtimes) global sections sections = ( VariousSection(w,c), UserInfoSection(w,c), NewsSection(w,c), SeekTabSection(w,c, self.infobar), SeekGraphSection(w,c), PlayerTabSection(w,c), GameTabSection(w,c), AdjournedTabSection(w,c, self.infobar), ChatWindow(w,c), #ConsoleWindow(w,c), SeekChallengeSection(w,c), # This is not really a section. It handles server messages which # don't correspond to a running game Messages(w,c, self.infobar), # This is not really a section. Merely a pair of BoardManager connects # which takes care of ionest and stuff when a new game is started or # observed CreatedBoards(w,c) ) @glock.glocked def on_news_item (self, nm, news): self.widgets["show_chat_button"].set_sensitive(True) def show (self): self.widgets["fics_lounge"].show() def present (self): self.widgets["fics_lounge"].present() def on_connection_error (self, connection, error): log.warn("ICLounge.on_connection_error: %s\n" % repr(error)) self.close() @glock.glocked def close (self): if self.widgets != None: self.widgets["fics_lounge"].hide() global sections if 'sections' in globals() and sections != None: for i in range(len(sections)): if hasattr(sections[i], "__del__"): sections[i].__del__() sections = None if self.connection != None: self.connection.close() self.connection = None self.widgets = None ################################################################################ # Initialize Sections # ################################################################################ class Section (object): def get_infobarmessage_content (self, player, text, gametype=None): content = gtk.HBox() icon = gtk.Image() icon.set_from_pixbuf(player.getIcon(size=32, gametype=gametype)) content.pack_start(icon, expand=False, fill=False, padding=4) label = gtk.Label() label.set_markup(player.getMarkup(gametype=gametype)) content.pack_start(label, expand=False, fill=False) label = gtk.Label() label.set_markup(text) content.pack_start(label, expand=False, fill=False) return content ############################################################################ # Initialize Various smaller sections # ############################################################################ class VariousSection(Section): def __init__ (self, widgets, connection): #sizeGroup = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL) #sizeGroup.add_widget(widgets["show_chat_label"]) #sizeGroup.add_widget(widgets["show_console_label"]) #sizeGroup.add_widget(widgets["log_off_label"]) connection.em.connect("onCommandNotFound", lambda em, cmd: log.error("Fics answered '%s': Command not found" % cmd)) ############################################################################ # Initialize User Information Section # ############################################################################ class UserInfoSection(Section): def __init__ (self, widgets, connection): self.widgets = widgets self.connection = connection self.pinger = None self.dock = self.widgets["fingerTableDock"] self.connection.fm.connect("fingeringFinished", self.onFinger) self.connection.fm.finger(self.connection.getUsername()) self.connection.bm.connect("curGameEnded", lambda *args: self.connection.fm.finger(self.connection.getUsername())) self.widgets["usernameLabel"].set_markup( "<b>%s</b>" % self.connection.getUsername()) def __del__ (self): if self.pinger != None: self.pinger.stop() def onFinger (self, fm, finger): if finger.getName().lower() != self.connection.getUsername().lower(): print finger.getName(), self.connection.getUsername() return glock.acquire() try: rows = 1 if finger.getRating(): rows += len(finger.getRating())+1 if finger.getEmail(): rows += 1 if finger.getCreated(): rows += 1 table = gtk.Table(6, rows) table.props.column_spacing = 12 table.props.row_spacing = 4 def label(value, xalign=0, is_error=False): if type(value) == float: value = str(int(value)) if is_error: label = gtk.Label() label.set_markup('<span size="larger" foreground="red">' + value + "</span>") else: label = gtk.Label(value) label.props.xalign = xalign return label row = 0 if finger.getRating(): for i, item in enumerate((_("Rating"), _("Win"), _("Draw"), _("Loss"))): table.attach(label(item, xalign=1), i+1,i+2,0,1) row += 1 for rating_type, rating in finger.getRating().iteritems(): ratinglabel = label( \ GAME_TYPES_BY_RATING_TYPE[rating_type].display_text + ":") table.attach(ratinglabel, 0, 1, row, row+1) if rating_type is TYPE_WILD: ratinglabel.set_tooltip_text( _("On FICS, your \"Wild\" rating encompasses all of the following variants at all time controls:\n") + ", ".join([gt.display_text for gt in WildGameType.instances()])) table.attach(label(rating.elo, xalign=1), 1, 2, row, row+1) table.attach(label(rating.wins, xalign=1), 2, 3, row, row+1) table.attach(label(rating.draws, xalign=1), 3, 4, row, row+1) table.attach(label(rating.losses, xalign=1), 4, 5, row, row+1) row += 1 table.attach(gtk.HSeparator(), 0, 6, row, row+1, ypadding=2) row += 1 if finger.getSanctions() != "": table.attach(label(_("Sanctions")+":", is_error=True), 0, 1, row, row+1) table.attach(label(finger.getSanctions()), 1, 6, row, row+1) row += 1 if finger.getEmail(): table.attach(label(_("Email")+":"), 0, 1, row, row+1) table.attach(label(finger.getEmail()), 1, 6, row, row+1) row += 1 if finger.getCreated(): table.attach(label(_("Spent")+":"), 0, 1, row, row+1) s = strftime("%Y %B %d ", localtime(time())) s += _("online in total") table.attach(label(s), 1, 6, row, row+1) row += 1 table.attach(label(_("Ping")+":"), 0, 1, row, row+1) pingLabel = gtk.Label(_("Connecting")+"...") pingLabel.props.xalign = 0 self.pinger = pinger = Pinger("freechess.org") def callback (pinger, pingtime): if type(pingtime) == str: pingLabel.set_text(pingtime) elif pingtime == -1: pingLabel.set_text(_("Unknown")) else: pingLabel.set_text("%.0f ms" % pingtime) pinger.connect("recieved", callback) pinger.connect("error", callback) pinger.start() table.attach(pingLabel, 1, 6, row, row+1) row += 1 if not self.connection.isRegistred(): vbox = gtk.VBox() table.attach(vbox, 0, 6, row, row+1) label0 = gtk.Label(_("You are currently logged in as a guest.\nA guest is not able to play rated games, and thus the offer of games will be smaller.")) label0.props.xalign = 0 label0.props.wrap = True label0.props.width_request = 300 vbox.add(label0) eventbox = uistuff.LinkLabel(_("Register now"), "http://www.freechess.org/Register/index.html") vbox.add(eventbox) if self.dock.get_children(): self.dock.remove(self.dock.get_children()[0]) self.dock.add(table) self.dock.show_all() finally: glock.release() ############################################################################ # Initialize News Section # ############################################################################ class NewsSection(Section): def __init__(self, widgets, connection): self.widgets = widgets connection.nm.connect("readNews", self.onNewsItem) def onNewsItem (self, nm, news): glock.acquire() try: weekday, month, day, title, details = news dtitle = "%s, %s %s: %s" % (weekday, month, day, title) label = gtk.Label(dtitle) label.props.width_request = 300 label.props.xalign = 0 label.set_ellipsize(pango.ELLIPSIZE_END) expander = gtk.Expander() expander.set_label_widget(label) expander.set_tooltip_text(title) textview = gtk.TextView () textview.set_wrap_mode (gtk.WRAP_WORD) textview.set_editable (False) textview.set_cursor_visible (False) textview.props.pixels_above_lines = 4 textview.props.pixels_below_lines = 4 textview.props.right_margin = 2 textview.props.left_margin = 6 uistuff.initTexviewLinks(textview, details) alignment = gtk.Alignment() alignment.set_padding(3, 6, 12, 0) alignment.props.xscale = 1 alignment.add(textview) expander.add(alignment) expander.show_all() self.widgets["newsVBox"].pack_end(expander) finally: glock.release() ############################################################################ # Initialize Lists # ############################################################################ class ParrentListSection (Section): """ Parrent for sections mainly consisting of a large treeview """ def __init__ (self): def updateLists (queuedCalls): for task in queuedCalls: func = task[0] func(*task[1:]) self.listPublisher = Publisher(updateLists, Publisher.SEND_LIST) self.listPublisher.start() def addColumns (self, treeview, *columns, **keyargs): if "hide" in keyargs: hide = keyargs["hide"] else: hide = [] if "pix" in keyargs: pix = keyargs["pix"] else: pix = [] for i, name in enumerate(columns): if i in hide: continue if i in pix: crp = gtk.CellRendererPixbuf() crp.props.xalign = .5 column = gtk.TreeViewColumn(name, crp, pixbuf=i) else: crt = gtk.CellRendererText() column = gtk.TreeViewColumn(name, crt, text=i) column.set_sort_column_id(i) column.set_resizable(True) column.set_reorderable(True) treeview.append_column(column) def lowLeftSearchPosFunc (self, tv, search_dialog): x = tv.allocation.x + tv.get_toplevel().window.get_position()[0] y = tv.allocation.y + tv.get_toplevel().window.get_position()[1] + \ tv.allocation.height search_dialog.move(x, y) search_dialog.show_all() def pixCompareFunction (self, treemodel, iter0, iter1, column): pix0 = treemodel.get_value(iter0, column) pix1 = treemodel.get_value(iter1, column) if type(pix0) == gtk.gdk.Pixbuf and type(pix1) == gtk.gdk.Pixbuf: return cmp(pix0.get_pixels(), pix1.get_pixels()) return cmp(pix0, pix1) def timeCompareFunction (self, treemodel, iter0, iter1, column): (minute0, minute1) = (treemodel.get_value(iter0, 7), treemodel.get_value(iter1, 7)) return cmp(minute0, minute1) ######################################################################## # Initialize Seek List # ######################################################################## class SeekTabSection (ParrentListSection): def __init__ (self, widgets, connection, infobar): ParrentListSection.__init__(self) self.widgets = widgets self.connection = connection self.infobar = infobar self.messages = {} self.seeks = {} self.challenges = {} self.seekPix = pixbuf_new_from_file(addDataPrefix("glade/seek.png")) self.chaPix = pixbuf_new_from_file(addDataPrefix("glade/challenge.png")) self.manSeekPix = pixbuf_new_from_file(addDataPrefix("glade/manseek.png")) self.tv = self.widgets["seektreeview"] self.store = gtk.ListStore(str, gtk.gdk.Pixbuf, str, int, str, str, str, float, str, str) self.tv.set_model(gtk.TreeModelSort(self.store)) self.addColumns (self.tv, "gameno", "", _("Name"), _("Rating"), _("Rated"), _("Type"), _("Clock"), "gametime", "textcolor", "tooltip", hide=[0,7,8,9], pix=[1] ) self.tv.set_search_column(2) self.tv.set_tooltip_column(9,) for i in range(1, 7): self.tv.get_model().set_sort_func(i, self.compareFunction, i) try: self.tv.set_search_position_func(self.lowLeftSearchPosFunc) except AttributeError: # Unknow signal name is raised by gtk < 2.10 pass for n in range(1, 6): column = self.tv.get_column(n) for cellrenderer in column.get_cell_renderers(): column.add_attribute(cellrenderer, "foreground", 8) self.selection = self.tv.get_selection() self.lastSeekSelected = None self.selection.set_select_function(self.selectFunction, full=True) self.selection.connect("changed", self.onSelectionChanged) self.widgets["clearSeeksButton"].connect("clicked", self.onClearSeeksClicked) self.widgets["acceptButton"].connect("clicked", self.onAcceptClicked) self.widgets["declineButton"].connect("clicked", self.onDeclineClicked) self.tv.connect("row-activated", self.row_activated) self.connection.glm.connect("addSeek", lambda glm, seek: self.listPublisher.put((self.onAddSeek, seek)) ) self.connection.glm.connect("removeSeek", lambda glm, gameno: self.listPublisher.put((self.onRemoveSeek, gameno)) ) self.connection.om.connect("onChallengeAdd", lambda om, index, match: self.listPublisher.put((self.onChallengeAdd, index, match)) ) self.connection.om.connect("onChallengeRemove", lambda om, index: self.listPublisher.put((self.onChallengeRemove, index)) ) self.connection.glm.connect("clearSeeks", lambda glm: self.listPublisher.put((self.onClearSeeks,)) ) self.connection.bm.connect("playGameCreated", lambda bm, game: self.listPublisher.put((self.onPlayingGame,)) ) self.connection.bm.connect("curGameEnded", lambda bm, game: self.listPublisher.put((self.onCurGameEnded,)) ) def selectFunction (self, selection, model, path, is_selected): if model[path][8] == "grey": return False else: return True def __isAChallengeOrOurSeek (self, row): gameno = row[0] textcolor = row[8] if (gameno is not None and gameno.startswith("C")) or (textcolor == "grey"): return True else: return False def compareFunction (self, model, iter0, iter1, column): row0 = list(model[model.get_path(iter0)]) row1 = list(model[model.get_path(iter1)]) is_ascending = True if self.tv.get_column(column-1).get_sort_order() is \ gtk.SORT_ASCENDING else False if self.__isAChallengeOrOurSeek(row0) and not self.__isAChallengeOrOurSeek(row1): if is_ascending: return -1 else: return 1 elif self.__isAChallengeOrOurSeek(row1) and not self.__isAChallengeOrOurSeek(row0): if is_ascending: return 1 else: return -1 elif column is 6: return self.timeCompareFunction(model, iter0, iter1, column) else: value0 = row0[column] value0 = value0.lower() if isinstance(value0, str) else value0 value1 = row1[column] value1 = value1.lower() if isinstance(value1, str) else value1 return cmp(value0, value1) def __updateActiveSeeksLabel (self): count = len(self.seeks) + len(self.challenges) self.widgets["activeSeeksLabel"].set_text(_("Active seeks: %d") % count) def onAddSeek (self, seek): time = _("%(min)s min") % {'min': seek["t"]} if seek["i"] != "0": time += _(" + %(sec)s sec") % {'sec': seek["i"]} rated = seek["r"] == "u" and _("Unrated") or _("Rated") pix = seek["manual"] and self.manSeekPix or self.seekPix try: player = self.connection.players[FICSPlayer(seek["w"])] except KeyError: return textcolor = "grey" if player.name == self.connection.getUsername() \ else "black" is_rated = False if seek["r"] == "u" else True tooltiptext = SeekGraphSection.getSeekTooltipText(player, seek["rt"], is_rated, seek["manual"], seek["gametype"], seek["t"], seek["i"], rmin=seek["rmin"], rmax=seek["rmax"]) seek_ = [seek["gameno"], pix, player.name + player.display_titles(), int(seek["rt"]), rated, seek["gametype"].display_text, time, float(seek["t"] + "." + seek["i"]), textcolor, tooltiptext] if textcolor == "grey": ti = self.store.prepend(seek_) self.tv.scroll_to_cell(self.store.get_path(ti)) self.widgets["clearSeeksButton"].set_sensitive(True) else: ti = self.store.append(seek_) self.seeks [seek["gameno"]] = ti self.__updateActiveSeeksLabel() def onRemoveSeek (self, gameno): if not gameno in self.seeks: # We ignore removes we haven't added, as it seams fics sends a # lot of removes for games it has never told us about return treeiter = self.seeks [gameno] if not self.store.iter_is_valid(treeiter): return self.store.remove (treeiter) del self.seeks[gameno] self.__updateActiveSeeksLabel() def onChallengeAdd (self, index, match): log.debug("onChallengeAdd: %s\n" % match) SoundTab.playAction("aPlayerChecks") time = _("%(min)s min") % {'min': match["t"]} if match["i"] != "0": time += _(" + %(sec)s sec") % {'sec': match["i"]} rated = match["r"] == "u" and _("Unrated") or _("Rated") try: player = self.connection.players[FICSPlayer(match["w"])] except KeyError: return nametitle = player.name + player.display_titles() is_rated = False if match["r"] == "u" else True is_manual = False # TODO: differentiate between challenges and manual-seek-accepts # (wait until seeks are comparable FICSSeek objects to do this) if match["is_adjourned"]: text = _(" would like to resume your adjourned <b>%s</b> " + \ "<b>%s</b> game.") % (time, match["gametype"].display_text) else: text = _(" challenges you to a <b>%s</b> %s <b>%s</b> game.") \ % (time, rated.lower(), match["gametype"].display_text) content = self.get_infobarmessage_content(player, text, gametype=match["gametype"]) def callback (infobar, response): if response == gtk.RESPONSE_ACCEPT: self.connection.om.acceptIndex(index) elif response == gtk.RESPONSE_NO: self.connection.om.declineIndex(index) message = InfoBarMessage(gtk.MESSAGE_QUESTION, content, callback) message.add_button(InfoBarMessageButton(_("Accept Challenge"), gtk.RESPONSE_ACCEPT)) message.add_button(InfoBarMessageButton(_("Decline Challenge"), gtk.RESPONSE_NO)) message.add_button(InfoBarMessageButton(_("Ignore Challenge"), gtk.RESPONSE_CANCEL)) self.messages[index] = message self.infobar.push_message(message) tooltiptext = SeekGraphSection.getSeekTooltipText(player, match["rt"], is_rated, is_manual, match["gametype"], match["t"], match["i"]) ti = self.store.prepend (["C"+index, self.chaPix, nametitle, int(match["rt"]), rated, match["gametype"].display_text, time, float(match["t"] + "." + match["i"]), "black", tooltiptext]) self.challenges[index] = ti self.__updateActiveSeeksLabel() self.widgets["seektreeview"].scroll_to_cell(self.store.get_path(ti)) def onChallengeRemove (self, index): if not index in self.challenges: return if index in self.messages: self.messages[index].dismiss() del self.messages[index] ti = self.challenges[index] if not self.store.iter_is_valid(ti): return self.store.remove(ti) del self.challenges[index] self.__updateActiveSeeksLabel() def onClearSeeks (self): self.store.clear() self.seeks = {} self.__updateActiveSeeksLabel() def onAcceptClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return index = model.get_value(iter, 0) if index.startswith("C"): index = index[1:] self.connection.om.acceptIndex(index) else: self.connection.om.playIndex(index) if index in self.messages: self.messages[index].dismiss() del self.messages[index] def onDeclineClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return index = model.get_value(iter, 0) if index.startswith("C"): index = index[1:] self.connection.om.declineIndex(index) if index in self.messages: self.messages[index].dismiss() del self.messages[index] def onClearSeeksClicked (self, button): print >> self.connection.client, "unseek" self.widgets["clearSeeksButton"].set_sensitive(False) def row_activated (self, treeview, path, view_column): model, iter = self.tv.get_selection().get_selected() if iter == None: return index = model.get_value(iter, 0) if index != self.lastSeekSelected: return if path != model.get_path(iter): return self.onAcceptClicked(None) def onSelectionChanged (self, selection): model, iter = self.widgets["seektreeview"].get_selection().get_selected() if iter == None: return self.lastSeekSelected = model.get_value(iter, 0) def _clear_messages (self): for message in self.messages.values(): message.dismiss() self.messages = {} def onPlayingGame (self): self._clear_messages() self.widgets["seekListContent"].set_sensitive(False) self.widgets["clearSeeksButton"].set_sensitive(False) self.store.clear() self.__updateActiveSeeksLabel() def onCurGameEnded (self): self.widgets["seekListContent"].set_sensitive(True) self.connection.glm.refreshSeeks() ######################################################################## # Initialize Seek Graph # ######################################################################## YMARKS = (800, 1600, 2400) YLOCATION = lambda y: min(y/3000.,3000) XMARKS = (5, 15) XLOCATION = lambda x: e**(-6.579/(x+1)) # This is used to convert increment time to minutes. With a GAME_LENGTH on # 40, a game on two minutes and twelve secconds will be placed at the same # X location as a game on 2+12*40/60 = 10 minutes GAME_LENGTH = 40 class SeekGraphSection (ParrentListSection): def __init__ (self, widgets, connection): ParrentListSection.__init__(self) self.widgets = widgets self.connection = connection self.graph = SpotGraph() for rating in YMARKS: self.graph.addYMark(YLOCATION(rating), str(rating)) for mins in XMARKS: self.graph.addXMark(XLOCATION(mins), str(mins) + _(" min")) self.widgets["graphDock"].add(self.graph) self.graph.show() self.graph.connect("spotClicked", self.onSpotClicked) self.connection.glm.connect("addSeek", lambda glm, seek: self.listPublisher.put((self.onSeekAdd, seek)) ) self.connection.glm.connect("removeSeek", lambda glm, gameno: self.listPublisher.put((self.onSeekRemove, gameno)) ) self.connection.glm.connect("clearSeeks", lambda glm: self.listPublisher.put((self.onSeekClear,)) ) self.connection.bm.connect("playGameCreated", lambda bm, game: self.listPublisher.put((self.onPlayingGame,)) ) self.connection.bm.connect("curGameEnded", lambda bm, game: self.listPublisher.put((self.onCurGameEnded,)) ) def onSpotClicked (self, graph, name): self.connection.bm.play(name) @classmethod def getSeekTooltipText (cls, player, rating, is_rated, is_manual, gametype, min, gain, rmin=0, rmax=9999): text = "%s" % player.name if int(rating) == 0: if not player.isGuest(): text += " (" + _("Unrated") + ")" else: text += " (%s)" % rating text += "%s" % player.display_titles(long=True) rated = _("Rated") if is_rated else _("Unrated") text += "\n%s %s" % (rated, gametype.display_text) text += "\n" + _("%(min)s min + %(sec)s sec") % {'min': min, 'sec': gain} rrtext = SeekChallengeSection.getRatingRangeDisplayText(rmin, rmax) if rrtext: text += "\n%s: %s" % (_("Opponent Rating"), rrtext) if is_manual: text += "\n%s" % _("Manual Accept") return text def onSeekAdd (self, seek): x = XLOCATION (float(seek["t"]) + float(seek["i"]) * GAME_LENGTH/60.) y = seek["rt"].isdigit() and YLOCATION(float(seek["rt"])) or 0 type = seek["r"] == "u" and 1 or 0 try: player = self.connection.players[FICSPlayer(seek["w"])] except KeyError: return is_rated = False if seek["r"] == "u" else True text = self.getSeekTooltipText(player, seek["rt"], is_rated, seek["manual"], seek["gametype"], seek["t"], seek["i"], rmin=seek["rmin"], rmax=seek["rmax"]) self.graph.addSpot(seek["gameno"], text, x, y, type) def onSeekRemove (self, gameno): self.graph.removeSpot(gameno) def onSeekClear (self): self.graph.clearSpots() def onPlayingGame (self): self.widgets["seekGraphContent"].set_sensitive(False) self.graph.clearSpots() def onCurGameEnded (self): self.widgets["seekGraphContent"].set_sensitive(True) ######################################################################## # Initialize Players List # ######################################################################## class PlayerTabSection (ParrentListSection): widgets = [] def __init__ (self, widgets, connection): ParrentListSection.__init__(self) PlayerTabSection.widgets = widgets self.connection = connection self.players = {} self.tv = widgets["playertreeview"] self.store = gtk.ListStore(FICSPlayer, gtk.gdk.Pixbuf, str, int, int, int, int, str) self.tv.set_model(gtk.TreeModelSort(self.store)) self.addColumns(self.tv, "FICSPlayer", "", _("Name"), _("Blitz"), _("Standard"), _("Lightning"), _("Wild"), _("Status"), hide=[0], pix=[1]) self.tv.get_column(0).set_sort_column_id(0) self.tv.get_model().set_sort_func(0, self.pixCompareFunction, 1) try: self.tv.set_search_position_func(self.lowLeftSearchPosFunc) except AttributeError: # Unknow signal name is raised by gtk < 2.10 pass connection.players.connect("FICSPlayerEntered", self.onPlayerAdded) connection.players.connect("FICSPlayerExited", self.onPlayerRemoved) widgets["private_chat_button"].connect("clicked", self.onPrivateChatClicked) widgets["private_chat_button"].set_sensitive(False) widgets["observe_button"].connect("clicked", self.onObserveClicked) widgets["observe_button"].set_sensitive(False) self.tv.get_selection().connect_after("changed", self.onSelectionChanged) self.onSelectionChanged(None) @glock.glocked def onPlayerAdded (self, players, player): if player in self.players: return ti = self.store.append([player, player.getIcon(), player.name + player.display_titles(), player.blitz, player.standard, player.lightning, player.wild, player.display_status]) self.players[player] = { "ti": ti } self.players[player]["status"] = player.connect( "notify::status", self.status_changed) self.players[player]["game"] = player.connect( "notify::game", self.status_changed) self.players[player]["titles"] = player.connect( "notify::titles", self.titles_changed) if player.game: self.players[player]["private"] = player.game.connect( "notify::private", self.private_changed, player) for rt in (TYPE_BLITZ, TYPE_STANDARD, TYPE_LIGHTNING, TYPE_WILD): self.players[player][rt] = player.ratings[rt].connect( "notify::elo", self.elo_changed, player) count = len(self.players) self.widgets["playersOnlineLabel"].set_text(_("Players: %d") % count) @glock.glocked def onPlayerRemoved (self, players, player): if player not in self.players: return if self.store.iter_is_valid(self.players[player]["ti"]): ti = self.players[player]["ti"] self.store.remove(ti) for key in ("status", "game", "titles"): if player.handler_is_connected(self.players[player][key]): player.disconnect(self.players[player][key]) if player.game and player.game.handler_is_connected( self.players[player]["private"]): player.game.disconnect(self.players[player]["private"]) for rt in (TYPE_BLITZ, TYPE_STANDARD, TYPE_LIGHTNING, TYPE_WILD): if player.ratings[rt].handler_is_connected( self.players[player][rt]): player.ratings[rt].disconnect(self.players[player][rt]) del self.players[player] count = len(self.players) self.widgets["playersOnlineLabel"].set_text(_("Players: %d") % count) @glock.glocked def status_changed (self, player, property): if player not in self.players: return if self.store.iter_is_valid(self.players[player]["ti"]): self.store.set(self.players[player]["ti"], 7, player.display_status) if player.status == IC_STATUS_PLAYING and player.game and \ "private" not in self.players[player]: self.players[player]["private"] = player.game.connect( "notify::private", self.private_changed, player) elif player.status != IC_STATUS_PLAYING and \ "private" in self.players[player]: game = player.game if game and game.handler_is_connected(self.players[player]["private"]): game.disconnect(self.players[player]["private"]) del self.players[player]["private"] if player == self.getSelectedPlayer(): self.onSelectionChanged(None) return False @glock.glocked def titles_changed (self, player, property): if player not in self.players: return if not self.store.iter_is_valid(self.players[player]["ti"]): return self.store.set(self.players[player]["ti"], 1, player.getIcon()) self.store.set(self.players[player]["ti"], 2, player.name + player.display_titles()) return False def private_changed (self, game, property, player): self.status_changed(player, property) self.onSelectionChanged(self.tv.get_selection()) return False @glock.glocked def elo_changed (self, rating, prop, player): if player not in self.players: return if not self.store.iter_is_valid(self.players[player]["ti"]): return ti = self.players[player]["ti"] self.store.set(ti, 1, player.getIcon()) if rating.type == TYPE_BLITZ: self.store.set(ti, 3, player.blitz) elif rating.type == TYPE_STANDARD: self.store.set(ti, 4, player.standard) elif rating.type == TYPE_LIGHTNING: self.store.set(ti, 5, player.lightning) elif rating.type == TYPE_WILD: self.store.set(ti, 6, player.wild) return False @classmethod def getSelectedPlayer (cls): model, iter = cls.widgets["playertreeview"].get_selection().get_selected() if iter == None: return None return model.get_value(iter, 0) def onPrivateChatClicked (self, button): player = self.getSelectedPlayer() if player is None: return for section in sections: if isinstance(section, ChatWindow): section.openChatWithPlayer(player.name) #TODO: isadmin og type def onObserveClicked (self, button): player = self.getSelectedPlayer() if player is not None and player.game is not None: self.connection.bm.observe(player.game) @glock.glocked def onSelectionChanged (self, selection): player = self.getSelectedPlayer() self.widgets["private_chat_button"].set_sensitive(player is not None) self.widgets["observe_button"].set_sensitive( player is not None and player.isObservable()) self.widgets["challengeButton"].set_sensitive( player is not None and player.isAvailableForGame()) ######################################################################## # Initialize Games List # ######################################################################## class GameTabSection (ParrentListSection): def __init__ (self, widgets, connection): ParrentListSection.__init__(self) self.widgets = widgets self.connection = connection self.games = {} self.recpix = load_icon(16, "media-record") self.clearpix = pixbuf_new_from_file(addDataPrefix("glade/board.png")) self.tv = self.widgets["gametreeview"] self.store = gtk.ListStore(FICSGame, gtk.gdk.Pixbuf, str, int, str, int, str, int) self.tv.set_model(gtk.TreeModelSort(self.store)) self.tv.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.addColumns ( self.tv, "FICSGame", "", _("White Player"), _("Rating"), _("Black Player"), _("Rating"), _("Game Type"), "Time", hide=[0,7], pix=[1] ) self.tv.get_column(0).set_sort_column_id(0) self.tv.get_model().set_sort_func(0, self.pixCompareFunction, 1) self.selection = self.tv.get_selection() self.selection.connect("changed", self.onSelectionChanged) self.onSelectionChanged(self.selection) def typeCompareFunction (treemodel, iter0, iter1): return cmp (treemodel.get_value(iter0, 7), treemodel.get_value(iter1, 7)) self.tv.get_model().set_sort_func(6, typeCompareFunction) try: self.tv.set_search_position_func(self.lowLeftSearchPosFunc) except AttributeError: # Unknow signal name is raised by gtk < 2.10 pass def searchCallback (model, column, key, iter): if model.get_value(iter, 2).lower().startswith(key) or \ model.get_value(iter, 4).lower().startswith(key): return False return True self.tv.set_search_equal_func (searchCallback) self.connection.games.connect("FICSGameCreated", lambda games, game: self.listPublisher.put((self.onGameAdd, game)) ) self.connection.games.connect("FICSGameEnded", lambda games, game: self.listPublisher.put((self.onGameRemove, game)) ) self.widgets["observeButton"].connect ("clicked", self.onObserveClicked) self.tv.connect("row-activated", self.onObserveClicked) self.connection.bm.connect("obsGameCreated", lambda bm, game: self.listPublisher.put((self.onGameObserved, game)) ) self.connection.bm.connect("obsGameUnobserved", lambda bm, game: self.listPublisher.put((self.onGameUnobserved, game)) ) def onSelectionChanged (self, selection): model, paths = selection.get_selected_rows() a_selected_game_is_observable = False for path in paths: rowiter = model.get_iter(path) game = model.get_value(rowiter, 0) if not game.private: a_selected_game_is_observable = True break self.widgets["observeButton"].set_sensitive(a_selected_game_is_observable) def _update_gamesrunning_label (self): count = len(self.games) self.widgets["gamesRunningLabel"].set_text(_("Games running: %d") % count) def onGameAdd (self, game): # log.debug("GameTabSection.onGameAdd: %s\n" % repr(game)) if game.min != None: length = game.min*60 + game.inc*40 elif game.game_type.rating_type == TYPE_LIGHTNING: length = 100 elif game.game_type.rating_type == TYPE_BLITZ: length = 9*60 elif game.game_type.rating_type == TYPE_STANDARD: length = 15*60 else: length = 0 ti = self.store.append ([game, self.clearpix, game.wplayer.name + game.wplayer.display_titles(), game.wplayer.getRatingForCurrentGame() or 0, game.bplayer.name + game.bplayer.display_titles(), game.bplayer.getRatingForCurrentGame() or 0, game.display_text, length]) self.games[game] = { "ti": ti } self.games[game]["private_cid"] = game.connect("notify::private", self.private_changed) self._update_gamesrunning_label() @glock.glocked def private_changed (self, game, property): if game in self.games and \ self.store.iter_is_valid(self.games[game]["ti"]): self.store.set(self.games[game]["ti"], 6, game.display_text) self.onSelectionChanged(self.tv.get_selection()) return False def onGameRemove (self, game): if game not in self.games: return if self.store.iter_is_valid(self.games[game]["ti"]): self.store.remove(self.games[game]["ti"]) if game.handler_is_connected(self.games[game]["private_cid"]): game.disconnect(self.games[game]["private_cid"]) del self.games[game] self._update_gamesrunning_label() def onObserveClicked (self, widget, *args): model, paths = self.tv.get_selection().get_selected_rows() for path in paths: rowiter = model.get_iter(path) game = model.get_value(rowiter, 0) self.connection.bm.observe(game) def onGameObserved (self, game): treeiter = self.games[game]["ti"] self.store.set_value(treeiter, 1, self.recpix) def onGameUnobserved (self, game): if game in self.games: treeiter = self.games[game]["ti"] self.store.set_value(treeiter, 1, self.clearpix) ######################################################################## # Initialize Adjourned List # ######################################################################## class AdjournedTabSection (ParrentListSection): def __init__ (self, widgets, connection, infobar): ParrentListSection.__init__(self) self.connection = connection self.widgets = widgets self.infobar = infobar self.games = {} self.messages = {} self.wpix = pixbuf_new_from_file(addDataPrefix("glade/white.png")) self.bpix = pixbuf_new_from_file(addDataPrefix("glade/black.png")) self.tv = widgets["adjournedtreeview"] self.store = gtk.ListStore(FICSAdjournedGame, gtk.gdk.Pixbuf, str, str, str, str, str) self.tv.set_model(gtk.TreeModelSort(self.store)) self.addColumns (self.tv, "FICSAdjournedGame", _("Your Color"), _("Opponent"), _("Is Online"), _("Time Control"), _("Game Type"), _("Date/Time"), hide=[0], pix=[1]) self.selection = self.tv.get_selection() self.selection.connect("changed", self.onSelectionChanged) self.onSelectionChanged(self.selection) self.connection.adm.connect("adjournedGameAdded", lambda adm, game: self.listPublisher.put((self.onAdjournedGameAdded, game)) ) self.connection.games.connect("FICSAdjournedGameRemoved", lambda games, game: self.listPublisher.put((self.onAdjournedGameRemoved, game)) ) widgets["resignButton"].connect("clicked", self.onResignButtonClicked) widgets["abortButton"].connect("clicked", self.onAbortButtonClicked) widgets["drawButton"].connect("clicked", self.onDrawButtonClicked) widgets["resumeButton"].connect("clicked", self.onResumeButtonClicked) widgets["previewButton"].connect("clicked", self.onPreviewButtonClicked) self.tv.connect("row-activated", lambda *args: self.onPreviewButtonClicked(None)) self.connection.adm.connect("adjournedGamePreview", lambda adm, game: self.listPublisher.put((self.onGamePreview, game))) self.connection.bm.connect("playGameCreated", self.onPlayGameCreated) def onSelectionChanged (self, selection): model, iter = selection.get_selected() a_row_is_selected = False if iter != None: a_row_is_selected = True for button in ("resignButton", "abortButton", "drawButton", "resumeButton", "previewButton"): self.widgets[button].set_sensitive(a_row_is_selected) @glock.glocked def onPlayGameCreated (self, bm, board): for message in self.messages.values(): message.dismiss() self.messages = {} return False def _update_infobarmessagebutton_sensitivity (self, message, player): button = message.buttons[0] if player.isAvailableForGame(): button.sensitive = True button.tooltip = "" else: button.sensitive = False button.tooltip = _("%s is %s") % \ (player.name, player.display_status.lower()) def _infobar_adjourned_message (self, game, player): if player not in self.messages: text = _(" with whom you have an adjourned <b>%s</b> <b>%s</b> " + \ "game is online.") % \ (game.display_timecontrol, game.game_type.display_text) content = self.get_infobarmessage_content(player, text, gametype=game.game_type) def callback (infobar, response): if response == gtk.RESPONSE_ACCEPT: print >> self.connection.client, "match %s" % player.name elif response == gtk.RESPONSE_HELP: self.connection.adm.queryMoves(game) del self.messages[player] message = InfoBarMessage(gtk.MESSAGE_QUESTION, content, callback) message.add_button(InfoBarMessageButton(_("Request Continuation"), gtk.RESPONSE_ACCEPT)) message.add_button(InfoBarMessageButton(_("Examine Adjourned Game"), gtk.RESPONSE_HELP)) message.add_button(InfoBarMessageButton(_("Do Nothing"), gtk.RESPONSE_NO)) self._update_infobarmessagebutton_sensitivity(message, player) self.messages[player] = message self.infobar.push_message(message) @glock.glocked def online_changed (self, player, property, game): log.debug("AdjournedTabSection.online_changed: %s %s\n" % \ (repr(player), repr(game))) if game in self.games and \ self.store.iter_is_valid(self.games[game]["ti"]): self.store.set(self.games[game]["ti"], 3, player.display_online) if player.online and player.adjournment: self._infobar_adjourned_message(game, player) elif not player.online and player in self.messages: self.messages[player].dismiss() # calling message.dismiss() might cause it to be removed from # self.messages in another callback, so we re-check if player in self.messages: del self.messages[player] return False @glock.glocked def status_changed (self, player, property, game): log.debug("AdjournedTabSection.status_changed: %s %s\n" % \ (repr(player), repr(game))) try: message = self.messages[player] except KeyError: return False self._update_infobarmessagebutton_sensitivity(message, player) return False def onAdjournedGameAdded (self, game): if game not in self.games: pix = (self.wpix, self.bpix)[game.our_color] ti = self.store.append([game, pix, game.opponent.name, game.opponent.display_online, game.display_timecontrol, game.game_type.display_text, game.display_time]) self.games[game] = {} self.games[game]["ti"] = ti self.games[game]["online_cid"] = game.opponent.connect( "notify::online", self.online_changed, game) self.games[game]["status_cid"] = game.opponent.connect( "notify::status", self.status_changed, game) if game.opponent.online: self._infobar_adjourned_message(game, game.opponent) return False def onAdjournedGameRemoved (self, game): if game in self.games: if self.store.iter_is_valid(self.games[game]["ti"]): self.store.remove(self.games[game]["ti"]) if game.opponent.handler_is_connected(self.games[game]["online_cid"]): game.opponent.disconnect(self.games[game]["online_cid"]) if game.opponent.handler_is_connected(self.games[game]["status_cid"]): game.opponent.disconnect(self.games[game]["status_cid"]) if game.opponent in self.messages: self.messages[game.opponent].dismiss() if game.opponent in self.messages: del self.messages[game.opponent] del self.games[game] return False def onResignButtonClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return game = model.get_value(iter, 0) self.connection.adm.resign(game) def onDrawButtonClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return game = model.get_value(iter, 0) self.connection.adm.draw(game) def onAbortButtonClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return game = model.get_value(iter, 0) self.connection.adm.abort(game) def onResumeButtonClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return game = model.get_value(iter, 0) self.connection.adm.resume(game) def onPreviewButtonClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return game = model.get_value(iter, 0) self.connection.adm.queryMoves(game) def onGamePreview (self, ficsgame): log.debug("ICLounge.onGamePreview: %s\n" % ficsgame) if ficsgame.board.wms == 0 and ficsgame.board.bms == 0: timemodel = None else: timemodel = TimeModel(ficsgame.board.wms/1000., ficsgame.inc, bsecs=ficsgame.board.bms/1000., minutes=ficsgame.min) gamemodel = ICGameModel(self.connection, ficsgame, timemodel) # The players need to start listening for moves IN this method if they # want to be noticed of all moves the FICS server sends us from now on. # Hence the lazy loading is skipped. wplayer, bplayer = ficsgame.wplayer, ficsgame.bplayer player0 = ICPlayer(gamemodel, wplayer.name, -1, WHITE, wplayer.long_name(game_type=ficsgame.game_type), icrating=wplayer.getRating(ficsgame.game_type.rating_type).elo) player1 = ICPlayer(gamemodel, bplayer.name, -1, BLACK, bplayer.long_name(game_type=ficsgame.game_type), icrating=bplayer.getRating(ficsgame.game_type.rating_type).elo) player0tup = (REMOTE, lambda:player0, (), wplayer.long_name()) player1tup = (REMOTE, lambda:player1, (), bplayer.long_name()) ionest.generalStart(gamemodel, player0tup, player1tup, (StringIO(ficsgame.board.pgn), pgn, 0, -1)) gamemodel.connect("game_started", lambda gamemodel: gamemodel.end(ADJOURNED, ficsgame.reason)) ############################################################################ # Initialize "Create Seek" and "Challenge" panels, and "Edit Seek:" dialog # ############################################################################ RATING_SLIDER_STEP = 25 class SeekChallengeSection (ParrentListSection): seekEditorWidgets = ( "untimedCheck", "minutesSpin", "gainSpin", "strengthCheck", "chainAlignment", "ratingCenterSlider", "toleranceSlider", "toleranceHBox", "nocolorRadio", "whitecolorRadio", "blackcolorRadio", # variantCombo has to come before other variant widgets so that # when the widget is loaded, variantRadio isn't selected by the callback, # overwriting the user's saved value for the variant radio buttons "variantCombo", "noVariantRadio", "variantRadio", "ratedGameCheck", "manualAcceptCheck" ) seekEditorWidgetDefaults = { "untimedCheck": [False, False, False], "minutesSpin": [15, 5, 2], "gainSpin": [10, 0, 1], "strengthCheck": [False, True, False], "chainAlignment": [True, True, True], "ratingCenterSlider": [40, 40, 40], "toleranceSlider": [8, 8, 8], "toleranceHBox": [False, False, False], "variantCombo": [RANDOMCHESS, FISCHERRANDOMCHESS, LOSERSCHESS], "noVariantRadio": [True, False, True], "variantRadio": [False, True, False], "nocolorRadio": [True, True, True], "whitecolorRadio": [False, False, False], "blackcolorRadio": [False, False, False], "ratedGameCheck": [False, True, True], "manualAcceptCheck": [False, False, False], } seekEditorWidgetGettersSetters = {} def __init__ (self, widgets, connection): ParrentListSection.__init__(self) self.widgets = widgets self.connection = connection self.finger = None conf.set("numberOfFingers", 0) glock.glock_connect(self.connection.fm, "fingeringFinished", lambda fm, finger: self.onFinger(fm, finger)) self.connection.fm.finger(self.connection.getUsername()) self.widgets["untimedCheck"].connect("toggled", self.onUntimedCheckToggled) self.widgets["minutesSpin"].connect("value-changed", self.onTimeSpinChanged) self.widgets["gainSpin"].connect("value-changed", self.onTimeSpinChanged) self.onTimeSpinChanged(self.widgets["minutesSpin"]) self.widgets["nocolorRadio"].connect("toggled", self.onColorRadioChanged) self.widgets["whitecolorRadio"].connect("toggled", self.onColorRadioChanged) self.widgets["blackcolorRadio"].connect("toggled", self.onColorRadioChanged) self.onColorRadioChanged(self.widgets["nocolorRadio"]) self.widgets["noVariantRadio"].connect("toggled", self.onVariantRadioChanged) self.widgets["variantRadio"].connect("toggled", self.onVariantRadioChanged) variantComboGetter, variantComboSetter = self.__initVariantCombo(self.widgets["variantCombo"]) self.seekEditorWidgetGettersSetters["variantCombo"] = (variantComboGetter, variantComboSetter) self.widgets["variantCombo"].connect("changed", self.onVariantComboChanged) self.widgets["editSeekDialog"].connect("delete_event", lambda *a: True) glock.glock_connect(self.connection, "disconnected", lambda c: self.widgets and self.widgets["editSeekDialog"].response(gtk.RESPONSE_CANCEL)) glock.glock_connect(self.connection, "disconnected", lambda c: self.widgets and self.widgets["challengeDialog"].response(gtk.RESPONSE_CANCEL)) self.widgets["strengthCheck"].connect("toggled", self.onStrengthCheckToggled) self.onStrengthCheckToggled(self.widgets["strengthCheck"]) self.widgets["ratingCenterSlider"].connect("value-changed", self.onRatingCenterSliderChanged) self.onRatingCenterSliderChanged(self.widgets["ratingCenterSlider"]) self.widgets["toleranceSlider"].connect("value-changed", self.onToleranceSliderChanged) self.onToleranceSliderChanged(self.widgets["toleranceSlider"]) self.widgets["toleranceButton"].connect("clicked", self.onToleranceButtonClicked) def toleranceHBoxGetter (widget): return self.widgets["toleranceHBox"].get_property("visible") def toleranceHBoxSetter (widget, visible): assert type(visible) is bool if visible: self.widgets["toleranceHBox"].show() else: self.widgets["toleranceHBox"].hide() self.seekEditorWidgetGettersSetters["toleranceHBox"] = (toleranceHBoxGetter, toleranceHBoxSetter) self.chainbox = ChainVBox() self.widgets["chainAlignment"].add(self.chainbox) def chainboxGetter (widget): return self.chainbox.active def chainboxSetter (widget, is_active): self.chainbox.active = is_active self.seekEditorWidgetGettersSetters["chainAlignment"] = (chainboxGetter, chainboxSetter) self.challengee = None self.in_challenge_mode = False self.seeknumber = 1 self.widgets["seekButton"].connect("clicked", self.onSeekButtonClicked) self.widgets["challengeButton"].connect("clicked", self.onChallengeButtonClicked) self.widgets["challengeDialog"].connect("delete-event", self.onChallengeDialogResponse) self.widgets["challengeDialog"].connect("response", self.onChallengeDialogResponse) self.widgets["editSeekDialog"].connect("response", self.onEditSeekDialogResponse) seekSelection = self.widgets["seektreeview"].get_selection() seekSelection.connect_after("changed", self.onSeekSelectionChanged) for widget in ("seek1Radio", "seek2Radio", "seek3Radio", "challenge1Radio", "challenge2Radio", "challenge3Radio"): uistuff.keep(self.widgets[widget], widget) self.lastdifference = 0 self.loading_seek_editor = False self.savedSeekRadioTexts = [ GAME_TYPES["blitz"].display_text ] * 3 for i in range(1,4): self.__loadSeekEditor(i) self.__writeSavedSeeks(i) self.widgets["seek%sRadioConfigButton" % i].connect( "clicked", self.onSeekRadioConfigButtonClicked, i) self.widgets["challenge%sRadioConfigButton" % i].connect( "clicked", self.onChallengeRadioConfigButtonClicked, i) if not self.connection.isRegistred(): self.chainbox.active = False self.widgets["chainAlignment"].set_sensitive(False) self.widgets["chainAlignment"].set_tooltip_text(_("The chain button is disabled because you are logged in as a guest. Guests can't establish ratings, and the chain button's state has no effect when there is no rating to which to tie \"Opponent Strength\" to")) def onSeekButtonClicked (self, button): if self.widgets["seek3Radio"].get_active(): self.__loadSeekEditor(3) elif self.widgets["seek2Radio"].get_active(): self.__loadSeekEditor(2) else: self.__loadSeekEditor(1) min, incr, gametype, ratingrange, color, rated, manual = self.__getSeekEditorDialogValues() self.connection.glm.seek(min, incr, gametype, rated, ratingrange, color, manual) def onChallengeButtonClicked (self, button): player = PlayerTabSection.getSelectedPlayer() if player is None: return self.challengee = player self.in_challenge_mode = True for i in range(1,4): self.__loadSeekEditor(i) self.__writeSavedSeeks(i) self.__updateRatedGameCheck() if self.widgets["seek3Radio"].get_active(): seeknumber = 3 elif self.widgets["seek2Radio"].get_active(): seeknumber = 2 else: seeknumber = 1 self.__updateSeekEditor(seeknumber, challengemode=True) self.widgets["challengeeNameLabel"].set_markup(player.getMarkup()) self.widgets["challengeeImage"].set_from_pixbuf(player.getIcon(size=32)) title = _("Challenge: ") + player.name self.widgets["challengeDialog"].set_title(title) self.widgets["challengeDialog"].present() def onChallengeDialogResponse (self, dialog, response): self.widgets["challengeDialog"].hide() if response is not 5: return True if self.widgets["challenge3Radio"].get_active(): self.__loadSeekEditor(3) elif self.widgets["challenge2Radio"].get_active(): self.__loadSeekEditor(2) else: self.__loadSeekEditor(1) min, incr, gametype, ratingrange, color, rated, manual = self.__getSeekEditorDialogValues() self.connection.om.challenge(self.challengee.name, gametype, min, incr, rated, color) def onSeekRadioConfigButtonClicked (self, configimage, seeknumber): self.__showSeekEditor(seeknumber) def onChallengeRadioConfigButtonClicked (self, configimage, seeknumber): self.__showSeekEditor(seeknumber, challengemode=True) def onEditSeekDialogResponse (self, dialog, response): self.widgets["editSeekDialog"].hide() if response != gtk.RESPONSE_OK: return self.__saveSeekEditor(self.seeknumber) self.__writeSavedSeeks(self.seeknumber) def __updateSeekEditor (self, seeknumber, challengemode=False): self.in_challenge_mode = challengemode self.seeknumber = seeknumber if not challengemode: self.widgets["strengthFrame"].set_sensitive(True) self.widgets["strengthFrame"].set_tooltip_text("") self.widgets["manualAcceptCheck"].set_sensitive(True) self.widgets["manualAcceptCheck"].set_tooltip_text("") else: self.widgets["strengthFrame"].set_sensitive(False) self.widgets["strengthFrame"].set_tooltip_text( _("This option is not applicable because you're challenging a player")) self.widgets["manualAcceptCheck"].set_sensitive(False) self.widgets["manualAcceptCheck"].set_tooltip_text( _("This option is not applicable because you're challenging a player")) self.widgets["chainAlignment"].show_all() self.__loadSeekEditor(seeknumber) self.widgets["seek%dRadio" % seeknumber].set_active(True) self.widgets["challenge%dRadio" % seeknumber].set_active(True) self.__updateYourRatingHBox() self.__updateRatingCenterInfoBox() self.__updateToleranceButton() self.__updateRatedGameCheck() self.onUntimedCheckToggled(self.widgets["untimedCheck"]) title = _("Edit Seek: ") + self.widgets["seek%dRadio" % seeknumber].get_label()[:-1] self.widgets["editSeekDialog"].set_title(title) def __showSeekEditor (self, seeknumber, challengemode=False): self.__updateSeekEditor(seeknumber, challengemode) self.widgets["editSeekDialog"].present() def onSeekSelectionChanged (self, selection): model, iter = selection.get_selected() a_seek_is_selected = False selection_is_challenge = False if iter != None: a_seek_is_selected = True gameno = model.get_value(iter, 0) if gameno.startswith("C"): selection_is_challenge = True self.widgets["acceptButton"].set_sensitive(a_seek_is_selected) self.widgets["declineButton"].set_sensitive(selection_is_challenge) #-------------------------------------------------------- Seek Editor @staticmethod def getRatingRangeDisplayText (rmin=0, rmax=9999): assert type(rmin) is type(int()) and rmin >= 0 and rmin <= 9999, rmin assert type(rmax) is type(int()) and rmax >= 0 and rmax <= 9999, rmax if rmin > 0: text = "%d" % rmin if rmax == 9999: text += "↑" else: text += "-%d" % rmax elif rmax != 9999: text = "%d↓" % rmax else: text = None return text def __writeSavedSeeks (self, seeknumber): """ Writes saved seek strings for both the Seek Panel and the Challenge Panel """ min, gain, gametype, ratingrange, color, rated, manual = \ self.__getSeekEditorDialogValues() self.savedSeekRadioTexts[seeknumber-1] = \ time_control_to_gametype(min, gain).display_text self.__writeSeekRadioLabels() seek = {} if gametype == GAME_TYPES["untimed"]: seek["time"] = gametype.display_text elif gain > 0: seek["time"] = _("%(minutes)d min + %(gain)d sec/move") % \ {'minutes' : min, 'gain' : gain} else: seek["time"] = _("%d min") % min if isinstance(gametype, VariantGameType): seek["variant"] = "%s" % gametype.display_text rrtext = self.getRatingRangeDisplayText(ratingrange[0], ratingrange[1]) if rrtext: seek["rating"] = rrtext if color == WHITE: seek["color"] = _("White") elif color == BLACK: seek["color"] = _("Black") if rated and gametype != GAME_TYPES["untimed"]: seek["rated"] = _("Rated") if manual: seek["manual"] = _("Manual") seek_ = [] challenge = [] challengee_is_guest = self.challengee and self.challengee.isGuest() for key in ("time", "variant", "rating", "color", "rated", "manual"): if key in seek: seek_.append(seek[key]) if key in ("time", "variant", "color") or \ (key == "rated" and not challengee_is_guest): challenge.append(seek[key]) seektext = ", ".join(seek_) challengetext = ", ".join(challenge) if seeknumber == 1: self.widgets["seek1RadioLabel"].set_text(seektext) self.widgets["challenge1RadioLabel"].set_text(challengetext) elif seeknumber == 2: self.widgets["seek2RadioLabel"].set_text(seektext) self.widgets["challenge2RadioLabel"].set_text(challengetext) else: self.widgets["seek3RadioLabel"].set_text(seektext) self.widgets["challenge3RadioLabel"].set_text(challengetext) def __loadSeekEditor (self, seeknumber): self.loading_seek_editor = True for widget in self.seekEditorWidgets: if widget in self.seekEditorWidgetGettersSetters: uistuff.loadDialogWidget(self.widgets[widget], widget, seeknumber, get_value_=self.seekEditorWidgetGettersSetters[widget][0], set_value_=self.seekEditorWidgetGettersSetters[widget][1], first_value=self.seekEditorWidgetDefaults[widget][seeknumber-1]) elif widget in self.seekEditorWidgetDefaults: uistuff.loadDialogWidget(self.widgets[widget], widget, seeknumber, first_value=self.seekEditorWidgetDefaults[widget][seeknumber-1]) else: uistuff.loadDialogWidget(self.widgets[widget], widget, seeknumber) self.lastdifference = conf.get("lastdifference-%d" % seeknumber, -1) self.loading_seek_editor = False def __saveSeekEditor (self, seeknumber): for widget in self.seekEditorWidgets: if widget in self.seekEditorWidgetGettersSetters: uistuff.saveDialogWidget(self.widgets[widget], widget, seeknumber, get_value_=self.seekEditorWidgetGettersSetters[widget][0]) else: uistuff.saveDialogWidget(self.widgets[widget], widget, seeknumber) conf.set("lastdifference-%d" % seeknumber, self.lastdifference) def __getSeekEditorDialogValues (self): if self.widgets["untimedCheck"].get_active(): min = 0 incr = 0 else: min = int(self.widgets["minutesSpin"].get_value()) incr = int(self.widgets["gainSpin"].get_value()) if self.widgets["strengthCheck"].get_active(): ratingrange = [0, 9999] else: center = int(self.widgets["ratingCenterSlider"].get_value()) * RATING_SLIDER_STEP tolerance = int(self.widgets["toleranceSlider"].get_value()) * RATING_SLIDER_STEP minrating = center - tolerance minrating = minrating > 0 and minrating or 0 maxrating = center + tolerance maxrating = maxrating >= 3000 and 9999 or maxrating ratingrange = [minrating, maxrating] if self.widgets["nocolorRadio"].get_active(): color = None elif self.widgets["whitecolorRadio"].get_active(): color = WHITE else: color = BLACK if self.widgets["noVariantRadio"].get_active() or \ self.widgets["untimedCheck"].get_active(): gametype = time_control_to_gametype(min, incr) else: variant_combo_getter = self.seekEditorWidgetGettersSetters["variantCombo"][0] variant = variant_combo_getter(self.widgets["variantCombo"]) gametype = VARIANT_GAME_TYPES[variant] rated = self.widgets["ratedGameCheck"].get_active() and \ not self.widgets["untimedCheck"].get_active() manual = self.widgets["manualAcceptCheck"].get_active() return min, incr, gametype, ratingrange, color, rated, manual def __writeSeekRadioLabels (self): gameTypes = { _("Untimed"): [0, 1], _("Standard"): [0, 1], _("Blitz"): [0, 1], _("Lightning"): [0, 1] } for i in range(3): gameTypes[self.savedSeekRadioTexts[i]][0] += 1 for i in range(3): if gameTypes[self.savedSeekRadioTexts[i]][0] > 1: labelText = "%s #%d:" % \ (self.savedSeekRadioTexts[i], gameTypes[self.savedSeekRadioTexts[i]][1]) self.widgets["seek%dRadio" % (i+1)].set_label(labelText) self.widgets["challenge%dRadio" % (i+1)].set_label(labelText) gameTypes[self.savedSeekRadioTexts[i]][1] += 1 else: self.widgets["seek%dRadio" % (i+1)].set_label(self.savedSeekRadioTexts[i]+":") self.widgets["challenge%dRadio" % (i+1)].set_label(self.savedSeekRadioTexts[i]+":") def __updateRatingRangeBox (self): center = int(self.widgets["ratingCenterSlider"].get_value()) * RATING_SLIDER_STEP tolerance = int(self.widgets["toleranceSlider"].get_value()) * RATING_SLIDER_STEP minRating = center - tolerance minRating = minRating > 0 and minRating or 0 maxRating = center + tolerance maxRating = maxRating >= 3000 and 9999 or maxRating self.widgets["ratingRangeMinLabel"].set_label("%d" % minRating) self.widgets["ratingRangeMaxLabel"].set_label("%d" % maxRating) for widgetName, rating in (("ratingRangeMinImage", minRating), ("ratingRangeMaxImage", maxRating)): pixbuf = FICSPlayer.getIconByRating(rating) self.widgets[widgetName].set_from_pixbuf(pixbuf) self.widgets["ratingRangeMinImage"].show() self.widgets["ratingRangeMinLabel"].show() self.widgets["dashLabel"].show() self.widgets["ratingRangeMaxImage"].show() self.widgets["ratingRangeMaxLabel"].show() if minRating == 0: self.widgets["ratingRangeMinImage"].hide() self.widgets["ratingRangeMinLabel"].hide() self.widgets["dashLabel"].hide() self.widgets["ratingRangeMaxLabel"].set_label("%d↓" % maxRating) if maxRating == 9999: self.widgets["ratingRangeMaxImage"].hide() self.widgets["ratingRangeMaxLabel"].hide() self.widgets["dashLabel"].hide() self.widgets["ratingRangeMinLabel"].set_label("%d↑" % minRating) if minRating == 0 and maxRating == 9999: self.widgets["ratingRangeMinLabel"].set_label(_("Any strength")) self.widgets["ratingRangeMinLabel"].show() def __getGameType (self): if self.widgets["untimedCheck"].get_active(): gametype = GAME_TYPES["untimed"] elif self.widgets["noVariantRadio"].get_active(): min = int(self.widgets["minutesSpin"].get_value()) gain = int(self.widgets["gainSpin"].get_value()) gametype = time_control_to_gametype(min, gain) else: variant_combo_getter = self.seekEditorWidgetGettersSetters["variantCombo"][0] variant = variant_combo_getter(self.widgets["variantCombo"]) gametype = VARIANT_GAME_TYPES[variant] return gametype def __updateYourRatingHBox (self): gametype = self.__getGameType() self.widgets["yourRatingNameLabel"].set_label("(" + gametype.display_text + ")") rating = self.__getRating(gametype.rating_type) if rating is None: self.widgets["yourRatingImage"].clear() self.widgets["yourRatingLabel"].set_label(_("Unrated")) return pixbuf = FICSPlayer.getIconByRating(rating) self.widgets["yourRatingImage"].set_from_pixbuf(pixbuf) self.widgets["yourRatingLabel"].set_label(str(rating)) center = int(self.widgets["ratingCenterSlider"].get_value()) * RATING_SLIDER_STEP rating = self.__clamp(rating) difference = rating - center if self.loading_seek_editor is False and self.chainbox.active and \ difference is not self.lastdifference: newcenter = rating - self.lastdifference self.widgets["ratingCenterSlider"].set_value(newcenter / RATING_SLIDER_STEP) else: self.lastdifference = difference def __clamp (self, rating): assert type(rating) is int mod = rating % RATING_SLIDER_STEP if mod > RATING_SLIDER_STEP / 2: return rating - mod + RATING_SLIDER_STEP else: return rating - mod def __updateRatedGameCheck (self): # on FICS, untimed games can't be rated, nor can games against a guest if not self.connection.isRegistred(): self.widgets["ratedGameCheck"].set_active(False) sensitive = False self.widgets["ratedGameCheck"].set_tooltip_text( _("You can't play rated games because you are logged in as a guest")) elif self.widgets["untimedCheck"].get_active() : sensitive = False self.widgets["ratedGameCheck"].set_tooltip_text( _("You can't play rated games because \"Untimed\" is checked, ") + _("and on FICS, untimed games can't be rated")) elif self.in_challenge_mode and self.challengee.isGuest(): sensitive = False self.widgets["ratedGameCheck"].set_tooltip_text( _("This option is not available because you're challenging a guest, ") + _("and guests can't play rated games")) else: sensitive = True self.widgets["ratedGameCheck"].set_tooltip_text("") self.widgets["ratedGameCheck"].set_sensitive(sensitive) def __initVariantCombo (self, combo): model = gtk.TreeStore(str) cellRenderer = gtk.CellRendererText() combo.clear() combo.pack_start(cellRenderer, True) combo.add_attribute(cellRenderer, 'text', 0) combo.set_model(model) groupNames = {VARIANTS_SHUFFLE: _("Shuffle"), VARIANTS_OTHER: _("Other")} ficsvariants = [v for k, v in variants.iteritems() if k in VARIANT_GAME_TYPES] groups = groupby(ficsvariants, attrgetter("variant_group")) pathToVariant = {} variantToPath = {} for i, (id, group) in enumerate(groups): iter = model.append(None, (groupNames[id],)) for variant in group: subiter = model.append(iter, (variant.name,)) path = model.get_path(subiter) pathToVariant[path] = variant.board.variant variantToPath[variant.board.variant] = path # this stops group names (eg "Shuffle") from being displayed in submenus def cellFunc (combo, cell, model, iter, data): isChildNode = not model.iter_has_child(iter) cell.set_property("sensitive", isChildNode) combo.set_cell_data_func(cellRenderer, cellFunc, None) def comboGetter (combo): path = model.get_path(combo.get_active_iter()) return pathToVariant[path] def comboSetter (combo, variant): assert variant in VARIANT_GAME_TYPES, \ "not a supported FICS variant: \"%s\"" % str(variant) combo.set_active_iter(model.get_iter(variantToPath[variant])) return comboGetter, comboSetter def __getRating (self, gametype): if self.finger is None: return None try: ratingobj = self.finger.getRating(type=gametype) rating = int(ratingobj.elo) except KeyError: # the user doesn't have a rating for this game type rating = None return rating def onFinger (self, fm, finger): if not finger.getName() == self.connection.getUsername(): return self.finger = finger numfingers = conf.get("numberOfFingers", 0) + 1 conf.set("numberOfFingers", numfingers) if conf.get("numberOfTimesLoggedInAsRegisteredUser", 0) is 1 and numfingers is 1: standard = self.__getRating(TYPE_STANDARD) blitz = self.__getRating(TYPE_BLITZ) lightning = self.__getRating(TYPE_LIGHTNING) if standard is not None: self.seekEditorWidgetDefaults["ratingCenterSlider"][0] = standard / RATING_SLIDER_STEP elif blitz is not None: self.seekEditorWidgetDefaults["ratingCenterSlider"][0] = blitz / RATING_SLIDER_STEP if blitz is not None: self.seekEditorWidgetDefaults["ratingCenterSlider"][1] = blitz / RATING_SLIDER_STEP if lightning is not None: self.seekEditorWidgetDefaults["ratingCenterSlider"][2] = lightning / RATING_SLIDER_STEP elif blitz is not None: self.seekEditorWidgetDefaults["ratingCenterSlider"][2] = blitz / RATING_SLIDER_STEP for i in range(1,4): self.__loadSeekEditor(i) self.__updateSeekEditor(i) self.__saveSeekEditor(i) self.__writeSavedSeeks(i) self.__updateYourRatingHBox() def onTimeSpinChanged (self, spin): minutes = self.widgets["minutesSpin"].get_value_as_int() gain = self.widgets["gainSpin"].get_value_as_int() name = time_control_to_gametype(minutes, gain).display_text self.widgets["timeControlNameLabel"].set_label("%s" % name) self.__updateYourRatingHBox() def onUntimedCheckToggled (self, check): is_untimed_game = check.get_active() self.widgets["timeControlConfigVBox"].set_sensitive(not is_untimed_game) # on FICS, untimed games can't be rated and can't be a chess variant self.widgets["variantFrame"].set_sensitive(not is_untimed_game) if is_untimed_game: self.widgets["variantFrame"].set_tooltip_text( _("You can't select a variant because \"Untimed\" is checked, ") + _("and on FICS, untimed games have to be normal chess rules")) else: self.widgets["variantFrame"].set_tooltip_text("") self.__updateRatedGameCheck() # sets sensitivity of widgets["ratedGameCheck"] self.__updateYourRatingHBox() def onStrengthCheckToggled (self, check): strengthsensitive = not check.get_active() self.widgets["strengthConfigVBox"].set_sensitive(strengthsensitive) def onRatingCenterSliderChanged (self, slider): center = int(self.widgets["ratingCenterSlider"].get_value()) * RATING_SLIDER_STEP pixbuf = FICSPlayer.getIconByRating(center) self.widgets["ratingCenterLabel"].set_label("%d" % (center)) self.widgets["ratingCenterImage"].set_from_pixbuf(pixbuf) self.__updateRatingRangeBox() rating = self.__getRating(self.__getGameType().rating_type) if rating is None: return rating = self.__clamp(rating) self.lastdifference = rating - center def __updateRatingCenterInfoBox (self): if self.widgets["toleranceHBox"].get_property("visible") == True: self.widgets["ratingCenterAlignment"].set_property("top-padding", 4) self.widgets["ratingCenterInfoHBox"].show() else: self.widgets["ratingCenterAlignment"].set_property("top-padding", 0) self.widgets["ratingCenterInfoHBox"].hide() def __updateToleranceButton (self): if self.widgets["toleranceHBox"].get_property("visible") == True: self.widgets["toleranceButton"].set_property("label", _("Hide")) else: self.widgets["toleranceButton"].set_property("label", _("Change Tolerance")) def onToleranceButtonClicked (self, button): if self.widgets["toleranceHBox"].get_property("visible") == True: self.widgets["toleranceHBox"].hide() else: self.widgets["toleranceHBox"].show() self.__updateToleranceButton() self.__updateRatingCenterInfoBox() def onToleranceSliderChanged (self, slider): tolerance = int(self.widgets["toleranceSlider"].get_value()) * RATING_SLIDER_STEP self.widgets["toleranceLabel"].set_label("±%d" % tolerance) self.__updateRatingRangeBox() def onColorRadioChanged (self, radio): if self.widgets["nocolorRadio"].get_active(): self.widgets["colorImage"].set_from_file(addDataPrefix("glade/piece-unknown.png")) self.widgets["colorImage"].set_sensitive(False) elif self.widgets["whitecolorRadio"].get_active(): self.widgets["colorImage"].set_from_file(addDataPrefix("glade/piece-white.png")) self.widgets["colorImage"].set_sensitive(True) elif self.widgets["blackcolorRadio"].get_active(): self.widgets["colorImage"].set_from_file(addDataPrefix("glade/piece-black.png")) self.widgets["colorImage"].set_sensitive(True) def onVariantRadioChanged (self, radio): self.__updateYourRatingHBox() def onVariantComboChanged (self, combo): self.widgets["variantRadio"].set_active(True) self.__updateYourRatingHBox() min, gain, gametype, ratingrange, color, rated, manual = \ self.__getSeekEditorDialogValues() self.widgets["variantCombo"].set_tooltip_text( variants[gametype.variant_type].__desc__) class ConsoleWindow: def __init__ (self, widgets, connection): pass ############################################################################ # Relay server messages to the user which aren't part of a game # ############################################################################ class Messages (Section): def __init__ (self, widgets, connection, infobar): self.connection = connection self.infobar = infobar self.messages = [] self.connection.bm.connect("tooManySeeks", self.tooManySeeks) self.connection.bm.connect("matchDeclined", self.matchDeclined) self.connection.bm.connect("playGameCreated", self.onPlayGameCreated) @glock.glocked def tooManySeeks (self, bm): label = gtk.Label(_("You may only have 3 outstanding seeks at the same time. If you want to add a new seek you must clear your currently active seeks. Clear your seeks?")) label.set_width_chars(70) label.set_line_wrap(True) def response_cb (infobar, response): if response == gtk.RESPONSE_YES: print >> self.connection.client, "unseek" message = InfoBarMessage(gtk.MESSAGE_QUESTION, label, response_cb) message.add_button(InfoBarMessageButton(gtk.STOCK_YES, gtk.RESPONSE_YES)) message.add_button(InfoBarMessageButton(gtk.STOCK_NO, gtk.RESPONSE_NO)) self.messages.append(message) self.infobar.push_message(message) @glock.glocked def onPlayGameCreated (self, bm, board): for message in self.messages: message.dismiss() self.messages = [] return False @glock.glocked def matchDeclined (self, bm, player): text = _(" has declined your offer for a match.") content = self.get_infobarmessage_content(player, text) message = InfoBarMessage(gtk.MESSAGE_INFO, content, None) message.add_button(InfoBarMessageButton(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL)) self.messages.append(message) self.infobar.push_message(message) ############################################################################ # Initialize connects for createBoard and createObsBoard # ############################################################################ class CreatedBoards (Section): def __init__ (self, widgets, connection): self.connection = connection self.connection.bm.connect("playGameCreated", self.onPlayGameCreated) self.connection.bm.connect("obsGameCreated", self.onObserveGameCreated) def onPlayGameCreated (self, bm, ficsgame): log.debug("ICLounge.onPlayGameCreated: %s\n" % ficsgame) if ficsgame.board.wms == 0 and ficsgame.board.bms == 0: timemodel = None else: timemodel = TimeModel (ficsgame.board.wms/1000., ficsgame.inc, bsecs=ficsgame.board.bms/1000., minutes=ficsgame.min) gamemodel = ICGameModel (self.connection, ficsgame, timemodel) gamemodel.connect("game_started", lambda gamemodel: self.connection.bm.onGameModelStarted(ficsgame.gameno)) wplayer, bplayer = ficsgame.wplayer, ficsgame.bplayer # We start if wplayer.name.lower() == self.connection.getUsername().lower(): player0tup = (LOCAL, Human, (WHITE, wplayer.long_name(), wplayer.name, wplayer.getRatingForCurrentGame()), wplayer.long_name()) player1tup = (REMOTE, ICPlayer, (gamemodel, bplayer.name, ficsgame.gameno, BLACK, bplayer.long_name(), bplayer.getRatingForCurrentGame()), bplayer.long_name()) # She starts else: player1tup = (LOCAL, Human, (BLACK, bplayer.long_name(), bplayer.name, bplayer.getRatingForCurrentGame()), bplayer.long_name()) # If the remote player is WHITE, we need to init her right now, so # we can catch fast made moves. Sorry lazy loading. player0 = ICPlayer(gamemodel, wplayer.name, ficsgame.gameno, WHITE, wplayer.long_name(), wplayer.getRatingForCurrentGame()) player0tup = (REMOTE, lambda:player0, (), wplayer.long_name()) if not ficsgame.board.fen: ionest.generalStart(gamemodel, player0tup, player1tup) else: ionest.generalStart(gamemodel, player0tup, player1tup, (StringIO(ficsgame.board.fen), fen, 0, -1)) def onObserveGameCreated (self, bm, ficsgame): log.debug("ICLounge.onObserveGameCreated: %s\n" % ficsgame) if ficsgame.board.wms == 0 and ficsgame.board.bms == 0: timemodel = None else: timemodel = TimeModel (ficsgame.board.wms/1000., ficsgame.inc, bsecs=ficsgame.board.bms/1000., minutes=ficsgame.min) gamemodel = ICGameModel (self.connection, ficsgame, timemodel) gamemodel.connect("game_started", lambda gamemodel: self.connection.bm.onGameModelStarted(ficsgame.gameno)) # The players need to start listening for moves IN this method if they # want to be noticed of all moves the FICS server sends us from now on wplayer, bplayer = ficsgame.wplayer, ficsgame.bplayer player0 = ICPlayer(gamemodel, wplayer.name, ficsgame.gameno, WHITE, wplayer.long_name(), wplayer.getRatingForCurrentGame()) player1 = ICPlayer(gamemodel, bplayer.name, ficsgame.gameno, BLACK, bplayer.long_name(), bplayer.getRatingForCurrentGame()) player0tup = (REMOTE, lambda:player0, (), wplayer.long_name()) player1tup = (REMOTE, lambda:player1, (), bplayer.long_name()) ionest.generalStart(gamemodel, player0tup, player1tup, (StringIO(ficsgame.board.pgn), pgn, 0, -1))
Python
from pychess import Variants from pychess.Utils.const import * # RatingType TYPE_BLITZ, TYPE_STANDARD, TYPE_LIGHTNING, TYPE_WILD, \ TYPE_BUGHOUSE, TYPE_CRAZYHOUSE, TYPE_SUICIDE, TYPE_LOSERS, TYPE_ATOMIC, \ TYPE_UNTIMED, TYPE_EXAMINED, TYPE_OTHER = range(12) class GameType (object): def __init__ (self, fics_name, short_fics_name, rating_type, display_text=None, variant_type=NORMALCHESS): self.fics_name = fics_name self.short_fics_name = short_fics_name self.rating_type = rating_type if display_text: self.display_text=display_text self.variant_type = variant_type @property def variant (self): return Variants.variants[self.variant_type] def __repr__ (self): s = "<GameType " s += "fics_name='%s', " % self.fics_name s += "short_fics_name='%s', " % self.short_fics_name s += "rating_type=%d, " % self.rating_type s += "variant_type=%d, " % self.variant_type s += "display_text='%s'>" % self.display_text return s class NormalGameType (GameType): def __init__ (self, fics_name, short_fics_name, rating_type, display_text): GameType.__init__(self, fics_name, short_fics_name, rating_type, display_text=display_text) class VariantGameType (GameType): def __init__ (self, fics_name, short_fics_name, rating_type, variant_type): GameType.__init__(self, fics_name, short_fics_name, rating_type, variant_type=variant_type) @property def display_text (self): assert self.variant_type != None return Variants.variants[self.variant_type].name @property def seek_text (self): return self.fics_name.replace("/", " ") class WildGameType (VariantGameType): _instances = [] def __init__ (self, fics_name, variant_type): VariantGameType.__init__(self, fics_name, "w", TYPE_WILD, variant_type=variant_type) WildGameType._instances.append(self) @classmethod def instances (cls): return cls._instances GAME_TYPES = { "blitz": NormalGameType("blitz", "b", TYPE_BLITZ, _("Blitz")), "standard": NormalGameType("standard", "s", TYPE_STANDARD, _("Standard")), "lightning": NormalGameType("lightning", "l", TYPE_LIGHTNING, _("Lightning")), "untimed": NormalGameType("untimed", "u", TYPE_UNTIMED, _("Untimed")), "examined": NormalGameType("examined", "e", TYPE_EXAMINED, _("Examined")), "nonstandard": NormalGameType("nonstandard", "n", TYPE_OTHER, _("Other")), "losers": VariantGameType("losers", "L", TYPE_LOSERS, LOSERSCHESS), "wild/fr": WildGameType("wild/fr", FISCHERRANDOMCHESS), "wild/2": WildGameType("wild/2", SHUFFLECHESS), "wild/3": WildGameType("wild/3", RANDOMCHESS), "wild/4": WildGameType("wild/4", ASYMMETRICRANDOMCHESS), "wild/5": WildGameType("wild/5", UPSIDEDOWNCHESS), "wild/8": WildGameType("wild/8", PAWNSPUSHEDCHESS), "wild/8a": WildGameType("wild/8a", PAWNSPASSEDCHESS) } # unsupported: # "bughouse": VariantGameType("bughouse", "B", TYPE_BUGHOUSE, BUGHOUSECHESS), # "crazyhouse": VariantGameType("crazyhouse", "z", TYPE_CRAZYHOUSE, CRAZYHOUSECHESS), # "suicide": VariantGameType("suicide", "S", TYPE_SUICIDE, SUICIDECHESS), # "atomic": VariantGameType("atomic", "x", TYPE_ATOMIC, ATOMICCHESS), VARIANT_GAME_TYPES = {} for key in GAME_TYPES: if isinstance(GAME_TYPES[key], VariantGameType): VARIANT_GAME_TYPES[GAME_TYPES[key].variant_type] = GAME_TYPES[key] # The following 3 GAME_TYPES_* data structures don't have any real entries # for the WildGameType's in GAME_TYPES above, and instead use # a dummy type for the all-encompassing "Wild" FICS rating for wild/* games GAME_TYPES_BY_SHORT_FICS_NAME = { "w": GameType("wild", "w", TYPE_WILD, display_text=_("Wild")) } for key in GAME_TYPES: if not isinstance(GAME_TYPES[key], WildGameType): GAME_TYPES_BY_SHORT_FICS_NAME[GAME_TYPES[key].short_fics_name] = \ GAME_TYPES[key] GAME_TYPES_BY_RATING_TYPE = {} for key in GAME_TYPES_BY_SHORT_FICS_NAME: GAME_TYPES_BY_RATING_TYPE[GAME_TYPES_BY_SHORT_FICS_NAME[key].rating_type] = \ GAME_TYPES_BY_SHORT_FICS_NAME[key] GAME_TYPES_BY_FICS_NAME = {} for key in GAME_TYPES_BY_SHORT_FICS_NAME: GAME_TYPES_BY_FICS_NAME[GAME_TYPES_BY_SHORT_FICS_NAME[key].fics_name] = \ GAME_TYPES_BY_SHORT_FICS_NAME[key] def type_to_display_text (typename): if "loaded from" in typename.lower(): typename = typename.split()[-1] if typename in GAME_TYPES: return GAME_TYPES[typename].display_text # Default solution for eco/A00 and a few others elif "/" in typename: a, b = typename.split("/") a = a[0].upper() + a[1:] b = b[0].upper() + b[1:] return a + " " + b else: # Otherwise forget about it return typename[0].upper() + typename[1:] def time_control_to_gametype (minutes, gain): assert type(minutes) == int and type(gain) == int assert minutes >= 0 and gain >= 0 gainminutes = gain > 0 and (gain*60)-1 or 0 if minutes is 0: return GAME_TYPES["untimed"] elif (minutes*60) + gainminutes >= (15*60): return GAME_TYPES["standard"] elif (minutes*60) + gainminutes >= (3*60): return GAME_TYPES["blitz"] else: return GAME_TYPES["lightning"] TYPE_ADMINISTRATOR, TYPE_BLINDFOLD, TYPE_COMPUTER, \ TYPE_TEAM, TYPE_UNREGISTERED, TYPE_CHESS_ADVISOR, \ TYPE_SERVICE_REPRESENTATIVE, TYPE_TOURNAMENT_DIRECTOR, TYPE_MAMER_MANAGER, \ TYPE_GRAND_MASTER, TYPE_INTERNATIONAL_MASTER, TYPE_FIDE_MASTER, \ TYPE_WOMAN_GRAND_MASTER, TYPE_WOMAN_INTERNATIONAL_MASTER, \ TYPE_DUMMY_ACCOUNT = range(15) TITLE_TYPE_DISPLAY_TEXTS = ( _("Administrator"), _("Blindfold Account"), _("Computer Account"), _("Team Account"), _("Unregistered User"), _("Chess Advisor"), _("Service Representative"), _("Tournament Director"), _("Mamer Manager"), _("Grand Master"), _("International Master"), _("FIDE Master"), _("Woman Grand Master"), _("Woman International Master"), _("Dummy Account"), ) TITLE_TYPE_DISPLAY_TEXTS_SHORT = ( _("*"), _("B"), _("C"), _("T"), _("U"), _("CA"), _("SR"), _("TD"), _("TM"), _("GM"), _("IM"), _("FM"), _("WGM"), _("WIM"), _("D") ) TITLES = { # From FICS 'help who' "*": TYPE_ADMINISTRATOR, "B": TYPE_BLINDFOLD, "C": TYPE_COMPUTER, "T": TYPE_TEAM, "U": TYPE_UNREGISTERED, "CA": TYPE_CHESS_ADVISOR, "SR": TYPE_SERVICE_REPRESENTATIVE, "TD": TYPE_TOURNAMENT_DIRECTOR, "TM": TYPE_MAMER_MANAGER, "GM": TYPE_GRAND_MASTER, "IM": TYPE_INTERNATIONAL_MASTER, "FM": TYPE_FIDE_MASTER, "WIM": TYPE_WOMAN_INTERNATIONAL_MASTER, "WGM": TYPE_WOMAN_GRAND_MASTER, "D": TYPE_DUMMY_ACCOUNT, } HEX_TO_TITLE = { 0x1 : TYPE_UNREGISTERED, 0x2 : TYPE_COMPUTER, 0x4 : TYPE_GRAND_MASTER, 0x8 : TYPE_INTERNATIONAL_MASTER, 0x10 : TYPE_FIDE_MASTER, 0x20 : TYPE_WOMAN_GRAND_MASTER, 0x40 : TYPE_WOMAN_INTERNATIONAL_MASTER, 0x80 : TYPE_FIDE_MASTER, }
Python
from pychess.Utils.const import * from pychess.Utils.Board import Board KNIGHTODDSSTART = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/R1BQKBNR w KQkq - 0 1" class KnightOddsBoard(Board): variant = KNIGHTODDSCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=KNIGHTODDSSTART) else: Board.__init__(self, setup=setup) class KnightOddsChess: __desc__ = _("One player starts with one less knight piece") name = _("Knight odds") cecp_name = "normal" board = KnightOddsBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_ODDS
Python
# Upside-down Chess from pychess.Utils.const import * from pychess.Utils.Board import Board UPSIDEDOWNSTART = "RNBQKBNR/PPPPPPPP/8/8/8/8/pppppppp/rnbqkbnr w - - 0 1" class UpsideDownBoard(Board): variant = UPSIDEDOWNCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=UPSIDEDOWNSTART) else: Board.__init__(self, setup=setup) class UpsideDownChess: __desc__ = _("FICS wild/5: http://www.freechess.org/Help/HelpFiles/wild.html\n" + "http://en.wikipedia.org/wiki/Chess_variant#Chess_with_different_starting_positions\n" + "Pawns start on their 7th rank rather than their 2nd rank!") name = _("Upside Down") cecp_name = "normal" board = UpsideDownBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_OTHER
Python
from pychess.Utils.const import * from pychess.Utils.Board import Board QUEENODDSSTART = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNB1KBNR w KQkq - 0 1" class QueenOddsBoard(Board): variant = QUEENODDSCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=QUEENODDSSTART) else: Board.__init__(self, setup=setup) class QueenOddsChess: __desc__ = _("One player starts with one less queen piece") name = _("Queen odds") cecp_name = "normal" board = QueenOddsBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_ODDS
Python
# Shuffle Chess import random from pychess.Utils.const import * from pychess.Utils.Board import Board class ShuffleBoard(Board): variant = SHUFFLECHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=self.shuffle_start()) else: Board.__init__(self, setup=setup) def shuffle_start(self): tmp = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'] random.shuffle(tmp) tmp = ''.join(tmp) tmp = tmp + '/pppppppp/8/8/8/8/PPPPPPPP/' + tmp.upper() + ' w - - 0 1' return tmp class ShuffleChess: __desc__ = _("xboard nocastle: http://tim-mann.org/xboard/engine-intf.html#8\n" + "FICS wild/2: http://www.freechess.org/Help/HelpFiles/wild.html\n" + "* Random arrangement of the pieces behind the pawns\n" + "* No castling\n" + "* Black's arrangement mirrors white's") name = _("Shuffle") cecp_name = "nocastle" board = ShuffleBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_SHUFFLE if __name__ == '__main__': Board = ShuffleBoard(True) for i in range(10): print Board.shuffle_start()
Python
# Pawns Passed Chess from pychess.Utils.const import * from pychess.Utils.Board import Board PAWNSPASSEDSTART = "rnbqkbnr/8/8/PPPPPPPP/pppppppp/8/8/RNBQKBNR w - - 0 1" class PawnsPassedBoard(Board): variant = PAWNSPASSEDCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=PAWNSPASSEDSTART) else: Board.__init__(self, setup=setup) class PawnsPassedChess: __desc__ = _("FICS wild/8a: http://www.freechess.org/Help/HelpFiles/wild.html\n" + "White pawns start on 5th rank and black pawns on the 4th rank") name = _("Pawns Passed") cecp_name = "normal" board = PawnsPassedBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_OTHER
Python
# AsymmetricRandom Chess import random from pychess.Utils.const import * from pychess.Utils.Board import Board class AsymmetricRandomBoard(Board): variant = ASYMMETRICRANDOMCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=self.asymmetricrandom_start()) else: Board.__init__(self, setup=setup) def asymmetricrandom_start(self): white = random.sample(('r', 'n', 'b', 'q')*16, 7) white.append('k') black = white[:] random.shuffle(white) random.shuffle(black) # balance the bishops (put them on equal numbers of dark and light squares) whitedarkbishops = 0 whitelightbishops = 0 for index, piece in enumerate(white): if piece == 'b': if index % 2 == 0: # even numbered square on the A rank are dark whitedarkbishops += 1 else: whitelightbishops += 1 blackdarkbishops = 0 blacklightbishops = 0 blackbishoprandomindexstack = [] for index, piece in enumerate(black): if piece == 'b': if index % 2 == 1: # odd numbered squares on the H rank are dark blackdarkbishops += 1 else: blacklightbishops += 1 blackbishoprandomindexstack.append(index) random.shuffle(blackbishoprandomindexstack) class RandomEnumeratePieces: def __init__ (self, pieces): self.pieces = pieces[:] self.randomindexstack = range(8) random.shuffle(self.randomindexstack) def __iter__ (self): return self def next(self): if not self.randomindexstack: raise StopIteration else: randomindex = self.randomindexstack.pop() return randomindex, self.pieces[randomindex] while (whitedarkbishops != blackdarkbishops) or \ (whitelightbishops != blacklightbishops): bishopindex = blackbishoprandomindexstack.pop() for index, piece in RandomEnumeratePieces(black): if piece != 'b': if ((blackdarkbishops > whitedarkbishops) and \ (bishopindex % 2 == 1) and (index % 2 == 0)): black[bishopindex] = piece black[index] = 'b' blacklightbishops += 1 blackdarkbishops = blackdarkbishops > 0 and (blackdarkbishops-1) or 0 break elif ((blacklightbishops > whitelightbishops) and \ (bishopindex % 2 == 0) and (index % 2 == 1)): black[bishopindex] = piece black[index] = 'b' blackdarkbishops += 1 blacklightbishops = blacklightbishops > 0 and (blacklightbishops-1) or 0 break tmp = ''.join(black) + '/pppppppp/8/8/8/8/PPPPPPPP/' + \ ''.join(white).upper() + ' w - - 0 1' return tmp class AsymmetricRandomChess: __desc__ = \ _("FICS wild/4: http://www.freechess.org/Help/HelpFiles/wild.html\n" + "* Randomly chosen pieces (two queens or three rooks possible)\n" + "* Exactly one king of each color\n" + "* Pieces placed randomly behind the pawns, SUBJECT TO THE CONSTRAINT THAT THE BISHOPS ARE BALANCED\n" + "* No castling\n" + "* Black's arrangement DOES NOT mirrors white's") name = _("Asymmetric Random") cecp_name = "unknown" board = AsymmetricRandomBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_SHUFFLE if __name__ == '__main__': Board = AsymmetricRandomBoard(True) for i in range(10): print Board.asymmetricrandom_start()
Python
from pychess.Utils.Board import Board class NormalChess: __desc__ = _("Classic chess rules\n" + "http://en.wikipedia.org/wiki/Chess") name = _("Normal") cecp_name = "normal" board = Board need_initial_board = False standard_rules = True
Python
# Random Chess import random from pychess.Utils.const import * from pychess.Utils.Board import Board class RandomBoard(Board): variant = RANDOMCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=self.random_start()) else: Board.__init__(self, setup=setup) def random_start(self): tmp = random.sample(('r', 'n', 'b', 'q')*16, 7) tmp.append('k') random.shuffle(tmp) tmp = ''.join(tmp) tmp = tmp + '/pppppppp/8/8/8/8/PPPPPPPP/' + tmp.upper() + ' w - - 0 1' return tmp class RandomChess: __desc__ = _("FICS wild/3: http://www.freechess.org/Help/HelpFiles/wild.html\n" + "* Randomly chosen pieces (two queens or three rooks possible)\n" + "* Exactly one king of each color\n" + "* Pieces placed randomly behind the pawns\n" + "* No castling\n" + "* Black's arrangement mirrors white's") name = _("Random") cecp_name = "unknown" board = RandomBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_SHUFFLE if __name__ == '__main__': Board = RandomBoard(True) for i in range(10): print Board.random_start()
Python
# Losers Chess from pychess.Utils.const import * from pychess.Utils.lutils.bitboard import bitLength from pychess.Utils.Board import Board class LosersBoard(Board): variant = LOSERSCHESS class LosersChess: __desc__ = _("FICS losers: http://www.freechess.org/Help/HelpFiles/losers_chess.html") name = _("Losers") cecp_name = "losers" board = LosersBoard need_initial_board = False standard_rules = False variant_group = VARIANTS_OTHER def testKingOnly(board): boards = board.boards[board.color] return bitLength(boards[PAWN]) + bitLength(boards[KNIGHT]) + \ bitLength(boards[BISHOP]) + bitLength(boards[ROOK]) + \ bitLength(boards[QUEEN]) == 0
Python
# Chess960 (Fischer Random Chess) import random from copy import copy from pychess.Utils.const import * from pychess.Utils.Cord import Cord from pychess.Utils.Board import Board from pychess.Utils.Piece import Piece from pychess.Utils.lutils.bitboard import * from pychess.Utils.lutils.attack import * from pychess.Utils.lutils.lmove import newMove, FLAG, PROMOTE_PIECE class FRCBoard(Board): variant = FISCHERRANDOMCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=self.shuffle_start()) else: Board.__init__(self, setup=setup) def simulateMove (self, board1, move): moved = [] new = [] dead = [] cord0, cord1 = move.cords moved.append( (self[cord0], cord0) ) if self[cord1]: if not move.flag in (QUEEN_CASTLE, KING_CASTLE): dead.append( self[cord1] ) if move.flag == QUEEN_CASTLE: if self.color == WHITE: r1 = self.board.ini_rooks[0][0] moved.append( (self[Cord(r1)], Cord(r1)) ) else: r8 = self.board.ini_rooks[1][0] moved.append( (self[Cord(r8)], Cord(r8)) ) elif move.flag == KING_CASTLE: if self.color == WHITE: r1 = self.board.ini_rooks[0][1] moved.append( (self[Cord(r1)], Cord(r1)) ) else: r8 = self.board.ini_rooks[1][1] moved.append( (self[Cord(r8)], Cord(r8)) ) elif move.flag in PROMOTIONS: newPiece = board1[cord1] moved.append( (newPiece, cord0) ) new.append( newPiece ) newPiece.opacity=1 dead.append( self[cord0] ) elif move.flag == ENPASSANT: if self.color == WHITE: dead.append( self[Cord(cord1.x, cord1.y-1)] ) else: dead.append( self[Cord(cord1.x, cord1.y+1)] ) return moved, new, dead def simulateUnmove (self, board1, move): moved = [] new = [] dead = [] cord0, cord1 = move.cords if not move.flag in (QUEEN_CASTLE, KING_CASTLE): moved.append( (self[cord1], cord1) ) if board1[cord1]: if not move.flag in (QUEEN_CASTLE, KING_CASTLE): dead.append( board1[cord1] ) if move.flag == QUEEN_CASTLE: if board1.color == WHITE: moved.append( (self[Cord(C1)], Cord(C1)) ) moved.append( (self[Cord(D1)], Cord(D1)) ) else: moved.append( (self[Cord(C8)], Cord(C8)) ) moved.append( (self[Cord(D8)], Cord(D8)) ) elif move.flag == KING_CASTLE: if board1.color == WHITE: moved.append( (self[Cord(F1)], Cord(F1)) ) moved.append( (self[Cord(G1)], Cord(G1)) ) else: moved.append( (self[Cord(F8)], Cord(F8)) ) moved.append( (self[Cord(G8)], Cord(G8)) ) elif move.flag in PROMOTIONS: newPiece = board1[cord0] moved.append( (newPiece, cord1) ) new.append( newPiece ) newPiece.opacity=1 dead.append( self[cord1] ) elif move.flag == ENPASSANT: if board1.color == WHITE: new.append( board1[Cord(cord1.x, cord1.y-1)] ) else: new.append( board1[Cord(cord1.x, cord1.y+1)] ) return moved, new, dead def move (self, move): assert self[move.cord0], "%s %s" % (move, self.asFen()) newBoard = self.clone() newBoard.board.applyMove (move.move) cord0, cord1 = move.cords flag = FLAG(move.move) # in frc there are unusual castling positions where # king will move on top of the castling rook, so... if flag in (KING_CASTLE, QUEEN_CASTLE): # don't put on the castling king yet king = newBoard[cord0] else: newBoard[cord1] = newBoard[cord0] newBoard[cord0] = None # move castling rook if self.color == WHITE: if flag == QUEEN_CASTLE: if self.board.ini_rooks[0][0] != D1: newBoard[Cord(D1)] = newBoard[Cord(self.board.ini_rooks[0][0])] newBoard[Cord(self.board.ini_rooks[0][0])] = None elif flag == KING_CASTLE: if self.board.ini_rooks[0][1] != F1: newBoard[Cord(F1)] = newBoard[Cord(self.board.ini_rooks[0][1])] newBoard[Cord(self.board.ini_rooks[0][1])] = None else: if flag == QUEEN_CASTLE: if self.board.ini_rooks[1][0] != D8: newBoard[Cord(D8)] = newBoard[Cord(self.board.ini_rooks[1][0])] newBoard[Cord(self.board.ini_rooks[1][0])] = None elif flag == KING_CASTLE: if self.board.ini_rooks[1][1] != F8: newBoard[Cord(F8)] = newBoard[Cord(self.board.ini_rooks[1][1])] newBoard[Cord(self.board.ini_rooks[1][1])] = None # put the castling king now if flag in (KING_CASTLE, QUEEN_CASTLE): if self.color == WHITE: if flag == QUEEN_CASTLE: newBoard[Cord(C1)] = king elif flag == KING_CASTLE: newBoard[Cord(G1)] = king else: if flag == QUEEN_CASTLE: newBoard[Cord(C8)] = king elif flag == KING_CASTLE: newBoard[Cord(G8)] = king if flag in PROMOTIONS: newBoard[cord1] = Piece(self.color, PROMOTE_PIECE(flag)) elif flag == ENPASSANT: newBoard[Cord(cord1.x, cord0.y)] = None return newBoard def shuffle_start(self): """ Create a random initial position. The king is placed somewhere between the two rooks. The bishops are placed on opposite-colored squares.""" positions = [1, 2, 3, 4, 5, 6, 7, 8] tmp = [''] * 8 castl = '' bishop = random.choice((1, 3, 5, 7)) tmp[bishop-1] = 'b' positions.remove(bishop) bishop = random.choice((2, 4, 6, 8)) tmp[bishop-1] = 'b' positions.remove(bishop) queen = random.choice(positions) tmp[queen-1] = 'q' positions.remove(queen) knight = random.choice(positions) tmp[knight-1] = 'n' positions.remove(knight) knight = random.choice(positions) tmp[knight-1] = 'n' positions.remove(knight) rook = positions[0] tmp[rook-1] = 'r' castl += reprFile[rook-1] king = positions[1] tmp[king-1] = 'k' rook = positions[2] tmp[rook-1] = 'r' castl += reprFile[rook-1] tmp = ''.join(tmp) tmp = tmp + '/pppppppp/8/8/8/8/PPPPPPPP/' + tmp.upper() + ' w ' + castl.upper() + castl +' - 0 1' #tmp = "rnqbbknr/pppppppp/8/8/8/8/PPPPPPPP/RNQBBKNR w AHah - 0 1" return tmp class FischerRandomChess: __desc__ = _("http://en.wikipedia.org/wiki/Chess960\n" + "FICS wild/fr: http://www.freechess.org/Help/HelpFiles/wild.html") name = _("Fischer Random") cecp_name = "fischerandom" board = FRCBoard need_initial_board = True standard_rules = False variant_group = VARIANTS_SHUFFLE def frc_castling_move(board, fcord, tcord, flag): if board.color == WHITE: if board.castling & W_OO and flag == KING_CASTLE and \ (tcord == G1 or tcord == board.ini_rooks[WHITE][1]): blocker = clearBit(board.blocker, board.ini_rooks[WHITE][1]) if fcord == B1 and not fromToRay[B1][G1] & blocker and \ not isAttacked (board, B1, BLACK) and \ not isAttacked (board, C1, BLACK) and \ not isAttacked (board, D1, BLACK) and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, F1, BLACK) and \ not isAttacked (board, G1, BLACK): return True if fcord == C1 and not fromToRay[C1][G1] & blocker and \ not isAttacked (board, C1, BLACK) and \ not isAttacked (board, D1, BLACK) and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, F1, BLACK) and \ not isAttacked (board, G1, BLACK): return True if fcord == D1 and not fromToRay[D1][G1] & blocker and \ not isAttacked (board, D1, BLACK) and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, F1, BLACK) and \ not isAttacked (board, G1, BLACK): return True if fcord == E1 and not fromToRay[E1][G1] & blocker and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, F1, BLACK) and \ not isAttacked (board, G1, BLACK): return True if fcord == F1 and not fromToRay[F1][G1] & blocker and \ not isAttacked (board, F1, BLACK) and \ not isAttacked (board, G1, BLACK): return True if fcord == G1 and board.arBoard[F1] == EMPTY and \ not isAttacked (board, G1, BLACK): return True if board.castling & W_OOO and flag == QUEEN_CASTLE and \ (tcord == C1 or tcord == board.ini_rooks[WHITE][0]): blocker = clearBit(board.blocker, board.ini_rooks[WHITE][0]) if fcord == G1 and not fromToRay[G1][C1] & blocker and \ not (board.ini_rooks[WHITE][0]==A1 and board.arBoard[B1] != EMPTY) and \ not isAttacked (board, C1, BLACK) and \ not isAttacked (board, D1, BLACK) and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, F1, BLACK) and \ not isAttacked (board, G1, BLACK): return True if fcord == F1 and not fromToRay[F1][C1] & blocker and \ not (board.ini_rooks[WHITE][0]==A1 and board.arBoard[B1] != EMPTY) and \ not isAttacked (board, C1, BLACK) and \ not isAttacked (board, D1, BLACK) and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, F1, BLACK): return True if fcord == E1 and not fromToRay[E1][C1] & blocker and \ not (board.ini_rooks[WHITE][0]==A1 and board.arBoard[B1] != EMPTY) and \ not isAttacked (board, C1, BLACK) and \ not isAttacked (board, D1, BLACK) and \ not isAttacked (board, E1, BLACK): return True if fcord == D1 and not fromToRay[D1][C1] & blocker and \ not (board.ini_rooks[WHITE][0]==A1 and board.arBoard[B1] != EMPTY) and \ not isAttacked (board, C1, BLACK) and \ not isAttacked (board, D1, BLACK): return True if fcord == C1 and \ board.arBoard[D1] == EMPTY and \ not (board.ini_rooks[WHITE][0]==A1 and board.arBoard[B1] != EMPTY) and \ not isAttacked (board, C1, BLACK): return True if fcord == B1 and \ board.arBoard[C1] == EMPTY and \ board.arBoard[D1] == EMPTY and \ not isAttacked (board, B1, BLACK) and \ not isAttacked (board, C1, BLACK): return True else: if board.castling & B_OO and flag == KING_CASTLE and \ (tcord == G8 or tcord == board.ini_rooks[BLACK][1]): blocker = clearBit(board.blocker, board.ini_rooks[BLACK][1]) if fcord == B8 and not fromToRay[B8][G8] & blocker and \ not isAttacked (board, B8, WHITE) and \ not isAttacked (board, C8, WHITE) and \ not isAttacked (board, D8, WHITE) and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, F8, WHITE) and \ not isAttacked (board, G8, WHITE): return True if fcord == C8 and not fromToRay[C8][G8] & blocker and \ not isAttacked (board, C8, WHITE) and \ not isAttacked (board, D8, WHITE) and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, F8, WHITE) and \ not isAttacked (board, G8, WHITE): return True if fcord == D8 and not fromToRay[D8][G8] & blocker and \ not isAttacked (board, D8, WHITE) and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, F8, WHITE) and \ not isAttacked (board, G8, WHITE): return True if fcord == E8 and not fromToRay[E8][G8] & blocker and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, F8, WHITE) and \ not isAttacked (board, G8, WHITE): return True if fcord == F8 and not fromToRay[F8][G8] & blocker and \ not isAttacked (board, F8, WHITE) and \ not isAttacked (board, G8, WHITE): return True if fcord == G8 and board.arBoard[F8] == EMPTY and \ not isAttacked (board, G8, WHITE): return True if board.castling & B_OOO and flag == QUEEN_CASTLE and \ (tcord == C8 or tcord == board.ini_rooks[BLACK][0]): blocker = clearBit(board.blocker, board.ini_rooks[BLACK][0]) if fcord == G8 and not fromToRay[G8][C8] & blocker and \ not (board.ini_rooks[BLACK][0]==A8 and board.arBoard[B8] != EMPTY) and \ not isAttacked (board, C8, WHITE) and \ not isAttacked (board, D8, WHITE) and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, F8, WHITE) and \ not isAttacked (board, G8, WHITE): return True if fcord == F8 and not fromToRay[F8][C8] & blocker and \ not (board.ini_rooks[BLACK][0]==A8 and board.arBoard[B8] != EMPTY) and \ not isAttacked (board, C8, WHITE) and \ not isAttacked (board, D8, WHITE) and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, F8, WHITE): return True if fcord == E8 and not fromToRay[E8][C8] & blocker and \ not (board.ini_rooks[BLACK][0]==A8 and board.arBoard[B8] != EMPTY) and \ not isAttacked (board, C8, WHITE) and \ not isAttacked (board, D8, WHITE) and \ not isAttacked (board, E8, WHITE): return True if fcord == D8 and not fromToRay[D8][C8] & blocker and \ not (board.ini_rooks[BLACK][0]==A8 and board.arBoard[B8] != EMPTY) and \ not isAttacked (board, C8, WHITE) and \ not isAttacked (board, D8, WHITE): return True if fcord == C8 and \ board.arBoard[D8] == EMPTY and \ not (board.ini_rooks[BLACK][0]==A8 and board.arBoard[B8] != EMPTY) and \ not isAttacked (board, C8, WHITE): return True if fcord == B8 and not fromToRay[B8][C8] & blocker and \ board.arBoard[C8] == EMPTY and \ board.arBoard[D8] == EMPTY and \ not isAttacked (board, B8, WHITE) and \ not isAttacked (board, C8, WHITE): return True return False if __name__ == '__main__': frcBoard = FRCBoard(True) for i in range(10): print frcBoard.shuffle_start()
Python
from pychess.Utils.const import * from normal import NormalChess from corner import CornerChess from shuffle import ShuffleChess from fischerandom import FischerRandomChess from randomchess import RandomChess from asymmetricrandom import AsymmetricRandomChess from upsidedown import UpsideDownChess from pawnspushed import PawnsPushedChess from pawnspassed import PawnsPassedChess from losers import LosersChess from pawnodds import PawnOddsChess from knightodds import KnightOddsChess from rookodds import RookOddsChess from queenodds import QueenOddsChess variants = {NORMALCHESS : NormalChess, CORNERCHESS : CornerChess, SHUFFLECHESS : ShuffleChess, FISCHERRANDOMCHESS : FischerRandomChess, RANDOMCHESS: RandomChess, ASYMMETRICRANDOMCHESS: AsymmetricRandomChess, UPSIDEDOWNCHESS : UpsideDownChess, PAWNSPUSHEDCHESS : PawnsPushedChess, PAWNSPASSEDCHESS : PawnsPassedChess, LOSERSCHESS : LosersChess, PAWNODDSCHESS : PawnOddsChess, KNIGHTODDSCHESS : KnightOddsChess, ROOKODDSCHESS : RookOddsChess, QUEENODDSCHESS : QueenOddsChess, }
Python
# Pawns Pushed Chess from pychess.Utils.const import * from pychess.Utils.Board import Board PAWNSPUSHEDSTART = "rnbqkbnr/8/8/pppppppp/PPPPPPPP/8/8/RNBQKBNR w - - 0 1" class PawnsPushedBoard(Board): variant = PAWNSPUSHEDCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=PAWNSPUSHEDSTART) else: Board.__init__(self, setup=setup) class PawnsPushedChess: __desc__ = _("FICS wild/8: http://www.freechess.org/Help/HelpFiles/wild.html\n" + "Pawns start on 4th and 5th ranks rather than 2nd and 7th") name = _("Pawns Pushed") cecp_name = "normal" board = PawnsPushedBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_OTHER
Python
from pychess.Utils.const import * from pychess.Utils.Board import Board PAWNODDSSTART = "rnbqkbnr/ppppp1pp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" class PawnOddsBoard(Board): variant = PAWNODDSCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=PAWNODDSSTART) else: Board.__init__(self, setup=setup) class PawnOddsChess: __desc__ = _("One player starts with one less pawn piece") name = _("Pawn odds") cecp_name = "normal" board = PawnOddsBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_ODDS
Python
from pychess.Utils.const import * from pychess.Utils.Board import Board ROOKODDSSTART = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/1NBQKBNR w Kkq - 0 1" class RookOddsBoard(Board): variant = ROOKODDSCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=ROOKODDSSTART) else: Board.__init__(self, setup=setup) class RookOddsChess: __desc__ = _("One player starts with one less rook piece") name = _("Rook odds") cecp_name = "normal" board = RookOddsBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_ODDS
Python
# Corner Chess import random from pychess.Utils.const import * from pychess.Utils.Board import Board class CornerBoard(Board): variant = CORNERCHESS def __init__ (self, setup=False): if setup is True: Board.__init__(self, setup=self.shuffle_start()) else: Board.__init__(self, setup=setup) def shuffle_start(self): b1 = b2 = 0 tmp = ['r', 'n', 'b', 'q', 'b', 'n', 'r'] while (b1%2 == b2%2): random.shuffle(tmp) b1 = tmp.index('b') b2 = tmp.index('b', b1+1) tmp = ''.join(tmp) tmp = 'k' + tmp + '/pppppppp/8/8/8/8/PPPPPPPP/' + tmp[::-1].upper() + 'K w - - 0 1' return tmp class CornerChess: __desc__ = \ _("http://brainking.com/en/GameRules?tp=2\n" + "* Placement of the pieces on the 1st and 8th row are randomized\n" + "* The king is in the right hand corner\n" + "* Bishops must start on opposite color squares\n" + "* Black's starting position is obtained by rotating white's position 180 degrees around the board's center\n" + "* No castling") name = _("Corner") cecp_name = "nocastle" board = CornerBoard need_initial_board = True standard_rules = True variant_group = VARIANTS_SHUFFLE if __name__ == '__main__': Board = CornerBoard(True) for i in range(10): print Board.shuffle_start()
Python
from Throbber import Throbber from pychess.Players.engineNest import discoverer from pychess.System import conf, uistuff from pychess.System.glock import glock_connect from pychess.System.prefix import addDataPrefix import gtk.glade import os uistuff.cacheGladefile("discovererDialog.glade") class DiscovererDialog: @classmethod def init (cls, discoverer): assert not hasattr(cls, "widgets"), "Show can only be called once" cls.widgets = uistuff.GladeWidgets("discovererDialog.glade") #======================================================================= # Clear glade defaults #======================================================================= for child in cls.widgets["enginesTable"].get_children(): cls.widgets["enginesTable"].remove(child) #======================================================================= # Connect us to the discoverer #======================================================================= glock_connect(discoverer, "discovering_started", cls._onDiscoveringStarted) glock_connect(discoverer, "engine_discovered", cls._onEngineDiscovered) glock_connect(discoverer, "all_engines_discovered", cls._onAllEnginesDiscovered) cls.finished = False @classmethod def show (cls, discoverer, mainwindow): if cls.finished: return #======================================================================= # Add throbber #======================================================================= throbber = Throbber(100, 100) throbber.set_size_request(100, 100) cls.widgets["throbberDock"].add(throbber) #======================================================================= # Show the window #======================================================================= cls.widgets["discovererDialog"].set_position(gtk.WIN_POS_CENTER_ON_PARENT) cls.widgets["discovererDialog"].set_modal(True) cls.widgets["discovererDialog"].set_transient_for(mainwindow) cls.widgets["discovererDialog"].show_all() @classmethod def _onDiscoveringStarted (cls, discoverer, binnames): #====================================================================== # Insert the names to be discovered #====================================================================== cls.nameToBar = {} for i, name in enumerate(binnames): label = gtk.Label(name+":") label.props.xalign = 1 cls.widgets["enginesTable"].attach(label, 0, 1, i, i+1) bar = gtk.ProgressBar() cls.widgets["enginesTable"].attach(bar, 1, 2, i, i+1) cls.nameToBar[name] = bar @classmethod def _onEngineDiscovered (cls, discoverer, binname, xmlenginevalue): bar = cls.nameToBar[binname] bar.props.fraction = 1 @classmethod def _onAllEnginesDiscovered (cls, discoverer): cls.finished = True cls.widgets["discovererDialog"].hide()
Python
import gtk, gobject import gamewidget firstRun = True def run(widgets): global firstRun if firstRun: initialize(widgets) firstRun = False widgets["player_info"].show_all() def initialize(widgets): def addColumns (treeview, *columns): model = gtk.ListStore(*((str,)*len(columns))) treeview.set_model(model) treeview.get_selection().set_mode(gtk.SELECTION_NONE) for i, name in enumerate(columns): crt = gtk.CellRendererText() column = gtk.TreeViewColumn(name, crt, text=i) treeview.append_column(column) addColumns(widgets["results_view"], "", "Games", "Won", "Drawn", "Lost", "Score") model = widgets["results_view"].get_model() model.append(("White", "67","28","24","15","59%")) model.append(("Black", "66","26","23","17","56%")) model.append(("Total", "133","54","47","32","58%")) addColumns(widgets["rating_view"], "Current", "Initial", "Lowest", "Highest", "Average") model = widgets["rating_view"].get_model() model.append(("1771","1734","1659","1791","1700")) widgets["history_view"].set_model(gtk.ListStore(object)) widgets["history_view"].get_selection().set_mode(gtk.SELECTION_NONE) widgets["history_view"].append_column(gtk.TreeViewColumn( "Player Rating History", HistoryCellRenderer(), data=0)) widgets["history_view"].get_model().append((1,)) def hide_window(button, *args): widgets["player_info"].hide() return True widgets["player_info"].connect("delete-event", hide_window) widgets["player_info_close_button"].connect("clicked", hide_window) class HistoryCellRenderer (gtk.GenericCellRenderer): __gproperties__ = { "data": (gobject.TYPE_PYOBJECT, "Data", "Data", gobject.PARAM_READWRITE), } def __init__(self): self.__gobject_init__() self.data = None def do_set_property(self, pspec, value): setattr(self, pspec.name, value) def do_get_property(self, pspec): return getattr(self, pspec.name) def on_render(self, window, widget, background_area, rect, expose_area, flags): if not self.data: return cairo = window.cairo_create() x,y,w,h = rect.x, rect.y, rect.width, rect.height cairo.rectangle(x+1,y+1,x+w-2,y+h-2) cairo.set_source_rgb(0.45,0.45,0.45) cairo.stroke() def on_get_size(self, widget, cell_area=None): return (0, 0, -1, 130)
Python
import gamewidget from pychess.System import glock from pychess.Utils.const import ACTION_MENU_ITEMS ################################################################################ # Main menubar MenuItem classes to keep track of menu widget states # ################################################################################ class GtkMenuItem (object): def __init__ (self, name, gamewidget, sensitive=False, label=None, tooltip=None): assert type(sensitive) is bool assert label is None or type(label) is str self.name = name self.gamewidget = gamewidget self._sensitive = sensitive self._label = label self._tooltip = tooltip @property def sensitive (self): return self._sensitive @sensitive.setter def sensitive (self, sensitive): assert type(sensitive) is bool self._sensitive = sensitive self._set_widget("sensitive", sensitive) @property def label (self): return self._label @label.setter def label (self, label): assert isinstance(label, str) or isinstance(label, unicode) self._label = label self._set_widget("label", label) @property def tooltip (self): return self._tooltip @tooltip.setter def tooltip (self, tooltip): assert isinstance(tooltip, str) or isinstance(tooltip, unicode) self._tooltip = tooltip self._set_widget("tooltip-text", tooltip) def _set_widget (self, property, value): if not self.gamewidget.isInFront(): return if gamewidget.widgets[self.name].get_property(property) != value: # log.debug("setting %s property %s to %s\n" % (self.name, property, str(value))) glock.acquire() try: gamewidget.widgets[self.name].set_property(property, value) finally: glock.release() def update (self): self._set_widget("sensitive", self._sensitive) if self._label is not None: self._set_widget("label", self._label) if self._tooltip is not None: self._set_widget("tooltip-text", self._tooltip) class GtkMenuToggleButton (GtkMenuItem): def __init__ (self, name, gamewidget, sensitive=False, active=False, label=None): assert type(active) is bool GtkMenuItem.__init__(self, name, gamewidget, sensitive, label) self._active = active @property def active (self): return self._active @active.setter def active (self, active): assert type(active) is bool self._active = active self._set_widget("active", active) def update (self): GtkMenuItem.update(self) self._set_widget("active", self._active) class MenuItemsDict (dict): """ Keeps track of menubar menuitem widgets that need to be managed on a game by game basis. Each menuitem writes through its respective widget state to the GUI if we are encapsulated in the gamewidget that's focused/infront """ VIEW_MENU_ITEMS = ("hint_mode", "spy_mode") class ReadOnlyDictException (Exception): pass def __init__ (self, gamewidget): dict.__init__(self) for item in ACTION_MENU_ITEMS: dict.__setitem__(self, item, GtkMenuItem(item, gamewidget)) for item in self.VIEW_MENU_ITEMS: dict.__setitem__(self, item, GtkMenuToggleButton(item, gamewidget)) gamewidget.connect("infront", self.on_gamewidget_infront) def __setitem__ (self, item, value): raise self.ReadOnlyDictException() def on_gamewidget_infront (self, gamewidget): for menuitem in self: self[menuitem].update()
Python
""" The task of this module, is to save, load and init new games """ from gettext import ngettext from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE from pychess import Savers from pychess.Players.engineNest import discoverer from pychess.Savers.ChessFile import LoadingError from pychess.Savers import * # This needs an import all not to break autoloading from pychess.System import conf from pychess.System.GtkWorker import GtkWorker from pychess.System.Log import log from pychess.System.protoopen import isWriteable from pychess.System.uistuff import GladeWidgets from pychess.Utils.const import * from pychess.widgets import gamenanny, gamewidget import gtk import os def generalStart (gamemodel, player0tup, player1tup, loaddata=None): """ The player tuples are: (The type af player in a System.const value, A callable creating the player, A list of arguments for the callable, A preliminary name for the player) If loaddata is specified, it should be a tuple of: (A text uri or fileobj, A Savers.something module with a load function capable of loading it, An int of the game in file you want to load, The position from where to start the game) """ log.debug("ionest.generalStart: %s\n %s\n %s\n" % (gamemodel, player0tup, player1tup)) worker = GtkWorker (lambda w: workfunc(w, gamemodel, player0tup, player1tup, loaddata)) def onPublished (worker, vallist): for val in vallist: # The worker will start by publishing (gmwidg, game) if type(val) == tuple: gmwidg, game = val gamewidget.attachGameWidget(gmwidg) gamenanny.nurseGame(gmwidg, game) handler.emit("gmwidg_created", gmwidg, game) # Then the worker will publish functions setting up widget stuff elif callable(val): val() worker.connect("published", onPublished) def onDone (worker, (gmwidg, game)): gmwidg.connect("close_clicked", closeGame, game) worker.__del__() worker.connect("done", onDone) worker.execute() def workfunc (worker, gamemodel, player0tup, player1tup, loaddata=None): log.debug("ionest.workfunc: %s\n %s\n %s\n" % (gamemodel, player0tup, player1tup)) gmwidg = gamewidget.GameWidget(gamemodel) # We want to show the game quickly, but the players take some time to start gmwidg.setTabText("%s %s %s %s" % (player0tup[3], _("vs"), player1tup[3], gamemodel.display_text)) worker.publish((gmwidg,gamemodel)) # Initing players players = [] for i, playertup in enumerate((player0tup, player1tup)): type, func, args, prename = playertup if type != LOCAL: players.append(func(*args)) #if type == ARTIFICIAL: # def readyformoves (player, color): # gmwidg.setTabText(gmwidg.display_text)) # players[i].connect("readyForMoves", readyformoves, i) else: # Until PyChess has a proper profiles system, as discussed on the # issue tracker, we need to give human players special treatment player = func(gmwidg, *args) players.append(player) # Connect to conf if i == 0 or (i == 1 and player0tup[0] != LOCAL): key = "firstName" alt = _("You") else: key = "secondName" alt = _("Guest") if prename == conf.get(key, alt): conf.notify_add(key, lambda *a:player.setName(conf.get(key,alt))) gamemodel.setPlayers(players) # Init analyze engines anaengines = list(discoverer.getAnalyzers()) specs = {} engine = discoverer.getEngineByMd5(conf.get("ana_combobox", 0)) if engine is None: engine = anaengines[0] if gamemodel.variant.board.variant in discoverer.getEngineVariants(engine) \ and conf.get("analyzer_check", True): hintanalyzer = discoverer.initAnalyzerEngine(engine, ANALYZING, gamemodel.variant) specs[HINT] = hintanalyzer log.debug("Hint Analyzer: %s\n" % repr(hintanalyzer)) engine = discoverer.getEngineByMd5(conf.get("inv_ana_combobox", 0)) if engine is None: engine = anaengines[0] if gamemodel.variant.board.variant in discoverer.getEngineVariants(engine) \ and conf.get("inv_analyzer_check", True): spyanalyzer = discoverer.initAnalyzerEngine(engine, INVERSE_ANALYZING, gamemodel.variant) specs[SPY] = spyanalyzer log.debug("Spy Analyzer: %s\n" % repr(spyanalyzer)) # Setting game gamemodel.setSpectators(specs) # Starting if loaddata: try: uri, loader, gameno, position = loaddata gamemodel.loadAndStart (uri, loader, gameno, position) except LoadingError, e: d = gtk.MessageDialog (type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_OK) d.set_markup ("<big><b>%s</b></big>" % e.args[0]) d.format_secondary_text (e.args[1] + "\n\n" + _("Correct the move, or start playing with what could be read")) d.connect("response", lambda d,a: d.hide()) worker.publish(d.show) else: if gamemodel.variant.need_initial_board: for player in gamemodel.players + gamemodel.spectators.values(): player.setOptionInitialBoard(gamemodel) gamemodel.start() log.debug("ionest.workfunc: returning gmwidg=%s\n gamemodel=%s\n" % \ (gmwidg, gamemodel)) return gmwidg, gamemodel ################################################################################ # Global Load and Save variables # ################################################################################ opendialog = None savedialog = None enddir = {} def getOpenAndSaveDialogs(): global opendialog, savedialog, enddir, savecombo, savers if not opendialog: types = [] savers = [getattr(Savers, s) for s in Savers.__all__] for saver in savers: for ending in saver.__endings__: enddir[ending] = saver types.append((saver.__label__, saver.__endings__)) opendialog = gtk.FileChooserDialog(_("Open Game"), None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT)) savedialog = gtk.FileChooserDialog(_("Save Game"), None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT)) savedialog.set_current_folder(os.environ["HOME"]) saveformats = gtk.ListStore(str, str) # All files filter star = gtk.FileFilter() star.set_name(_("All Files")) star.add_pattern("*") opendialog.add_filter(star) saveformats.append([_("Detect type automatically"), ""]) # All chess files filter all = gtk.FileFilter() all.set_name(_("All Chess Files")) opendialog.add_filter(all) opendialog.set_filter(all) # Specific filters and save formats default = 0 for i, (label, endings) in enumerate(types): endstr = "(%s)" % ", ".join(endings) f = gtk.FileFilter() f.set_name(label+" "+endstr) for ending in endings: f.add_pattern("*."+ending) all.add_pattern("*."+ending) opendialog.add_filter(f) saveformats.append([label, endstr]) if "pgn" in endstr: default = i + 1 # Add widgets to the savedialog savecombo = gtk.ComboBox() savecombo.set_model(saveformats) crt = gtk.CellRendererText() savecombo.pack_start(crt, True) savecombo.add_attribute(crt, 'text', 0) crt = gtk.CellRendererText() savecombo.pack_start(crt, False) savecombo.add_attribute(crt, 'text', 1) savecombo.set_active(default) savedialog.set_extra_widget(savecombo) return opendialog, savedialog, enddir, savecombo, savers ################################################################################ # Saving # ################################################################################ def saveGame (game): if not game.isChanged(): return if game.uri and isWriteable (game.uri): saveGameSimple (game.uri, game) else: return saveGameAs (game) def saveGameSimple (uri, game): ending = os.path.splitext(uri)[1] if not ending: return saver = enddir[ending[1:]] game.save(uri, saver, append=False) def saveGameAs (game): opendialog, savedialog, enddir, savecombo, savers = getOpenAndSaveDialogs() # Keep running the dialog until the user has canceled it or made an error # free operation while True: savedialog.set_current_name("%s %s %s" % (game.players[0], _("vs."), game.players[1])) res = savedialog.run() if res != gtk.RESPONSE_ACCEPT: break uri = savedialog.get_filename() ending = os.path.splitext(uri)[1] if ending.startswith("."): ending = ending[1:] append = False if savecombo.get_active() == 0: if not ending in enddir: d = gtk.MessageDialog( type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK) folder, file = os.path.split(uri) d.set_markup( _("<big><b>Unknown file type '%s'</b></big>") % ending) d.format_secondary_text(_("Was unable to save '%(uri)s' as PyChess doesn't know the format '%(ending)s'.") % { 'uri': uri, 'ending': ending}) d.run() d.hide() continue else: saver = enddir[ending] else: saver = savers[savecombo.get_active()-1] if not ending in enddir or not saver == enddir[ending]: uri += ".%s" % saver.__endings__[0] if os.path.isfile(uri) and not os.access (uri, os.W_OK): d = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK) d.set_markup(_("<big><b>Unable to save file '%s'</b></big>") % uri) d.format_secondary_text( _("You don't have the necessary rights to save the file.\n\ Please ensure that you have given the right path and try again.")) d.run() d.hide() continue if os.path.isfile(uri): d = gtk.MessageDialog(type=gtk.MESSAGE_QUESTION) d.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, _("_Replace"), gtk.RESPONSE_ACCEPT) if saver.__append__: d.add_buttons(gtk.STOCK_ADD, 1) d.set_title(_("File exists")) folder, file = os.path.split(uri) d.set_markup(_("<big><b>A file named '%s' already exists. Would you like to replace it?</b></big>") % file) d.format_secondary_text(_("The file already exists in '%s'. If you replace it, its content will be overwritten.") % folder) replaceRes = d.run() d.hide() if replaceRes == 1: append = True elif replaceRes == gtk.RESPONSE_CANCEL: continue else: print repr(uri) try: game.save(uri, saver, append) except IOError, e: d = gtk.MessageDialog(type=gtk.MESSAGE_ERROR) d.add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK) d.set_title(_("Could not save the file")) d.set_markup(_("<big><b>PyChess was not able to save the game</b></big>")) d.format_secondary_text(_("The error was: %s") % ", ".join(str(a) for a in e.args)) os.remove(uri) d.run() d.hide() continue break savedialog.hide() return res ################################################################################ # Closing # ################################################################################ def closeAllGames (pairs): changedPairs = [(gmwidg, game) for gmwidg, game in pairs if game.isChanged()] if len(changedPairs) == 0: response = gtk.RESPONSE_OK elif len(changedPairs) == 1: response = closeGame(*changedPairs[0]) else: widgets = GladeWidgets("saveGamesDialog.glade") dialog = widgets["saveGamesDialog"] heading = widgets["saveGamesDialogHeading"] saveLabel = widgets["saveGamesDialogSaveLabel"] treeview = widgets["saveGamesDialogTreeview"] heading.set_markup("<big><b>" + ngettext("There is %d game with unsaved moves.", "There are %d games with unsaved moves.", len(changedPairs)) % len(changedPairs) + " " + _("Save moves before closing?") + "</b></big>") liststore = gtk.ListStore(bool, str) treeview.set_model(liststore) renderer = gtk.CellRendererToggle() renderer.props.activatable = True treeview.append_column(gtk.TreeViewColumn("", renderer, active=0)) treeview.append_column(gtk.TreeViewColumn("", gtk.CellRendererText(), text=1)) for gmwidg, game in changedPairs: liststore.append((True, "%s %s %s" % (game.players[0], _("vs."), game.players[1]))) def callback (cell, path): if path: liststore[path][0] = not liststore[path][0] saves = len(tuple(row for row in liststore if row[0])) saveLabel.set_text(ngettext("_Save %d document", "_Save %d documents", saves) % saves) saveLabel.set_use_underline(True) renderer.connect("toggled", callback) callback(None, None) while True: response = dialog.run() if response == gtk.RESPONSE_YES: for i in xrange(len(liststore)-1, -1, -1): checked, name = liststore[i] if checked: gmwidg, game = changedPairs[i] if saveGame(game) == gtk.RESPONSE_ACCEPT: del pairs[i] liststore.remove(liststore.get_iter((i,))) game.end(ABORTED, ABORTED_AGREEMENT) gamewidget.delGameWidget(gmwidg) else: break else: break else: break dialog.destroy() if response not in (gtk.RESPONSE_DELETE_EVENT, gtk.RESPONSE_CANCEL): for gmwidg, game in pairs: game.end(ABORTED, ABORTED_AGREEMENT) game.terminate() return response def closeGame (gmwidg, game): if not game.isChanged(): response = gtk.RESPONSE_OK else: d = gtk.MessageDialog (type = gtk.MESSAGE_WARNING) d.add_button(_("Close _without Saving"), gtk.RESPONSE_OK) d.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) if game.uri: d.add_button(gtk.STOCK_SAVE, gtk.RESPONSE_YES) else: d.add_button(gtk.STOCK_SAVE_AS, gtk.RESPONSE_YES) gmwidg.bringToFront() d.set_markup(_("<b><big>Save the current game before you close it?</big></b>")) d.format_secondary_text (_( "It is not possible later to continue the game,\nif you don't save it.")) response = d.run() d.destroy() if response == gtk.RESPONSE_YES: # Test if cancel was pressed in the save-file-dialog if saveGame(game) != gtk.RESPONSE_ACCEPT: response = gtk.RESPONSE_CANCEL if response not in (gtk.RESPONSE_DELETE_EVENT, gtk.RESPONSE_CANCEL): if game.status in UNFINISHED_STATES: game.end(ABORTED, ABORTED_AGREEMENT) game.terminate() gamewidget.delGameWidget (gmwidg) return response ################################################################################ # Signal handler # ################################################################################ class Handler (GObject): """ The goal of this class, is to provide signal handling for the ionest module. Emit objects are gmwidg, gameobject """ __gsignals__ = { 'gmwidg_created': (SIGNAL_RUN_FIRST, TYPE_NONE, (object, object)) } def __init__ (self): GObject.__init__(self) handler = Handler()
Python
import time import gtk import gobject import pango import re from pychess.Utils.IconLoader import load_icon from pychess.System import uistuff from pychess.System.glock import glock_connect from pychess.widgets.ChatView import ChatView from pychess.widgets.pydock.PyDockTop import PyDockTop from pychess.widgets.pydock import NORTH, EAST, SOUTH, WEST, CENTER from pychess.ic.FICSObjects import FICSPlayer TYPE_PERSONAL, TYPE_CHANNEL = range(2) def get_playername (playername): m = re.match("(\w+)\W*", playername) return m.groups()[0] class BulletCellRenderer (gtk.GenericCellRenderer): __gproperties__ = { "color": (object, "Color", "Color", gobject.PARAM_READWRITE), } def __init__(self): self.__gobject_init__() self.color = None self.width = 16 self.height = 16 def do_set_property(self, pspec, value): setattr(self, pspec.name, value) def do_get_property(self, pspec): return getattr(self, pspec.name) def on_render(self, window, widget, bg_area, cell_area, expose_area, flags): if not self.color: return x, y = self.get_size(widget, cell_area)[:2] context = window.cairo_create() r,g,b = self.color context.set_source_rgb (r,g,b) context.rectangle (x, y, self.width, self.height) context.fill() context.set_line_width (1) context.set_source_rgba (0, 0, 0, 0.5) context.rectangle (x+0.5, y+0.5, self.width-1, self.height-1) context.stroke () context.set_line_width (1) context.set_source_rgba (1, 1, 1, 0.5) context.rectangle (x+1.5, y+1.5, self.width-3, self.height-3) context.stroke () def on_get_size(self, widget, cell_area=None): if cell_area: y = int(cell_area.height/2.-self.height/2.) + cell_area.y x = cell_area.x else: y = 0 x = 0 return (x+1, y+1, self.width+2, self.height+2) gobject.type_register(BulletCellRenderer) class TextImageTree (gtk.TreeView): """ Defines a tree with two columns. The first one has text. The seccond one a clickable stock_icon """ __gsignals__ = { 'activated' : (gobject.SIGNAL_RUN_FIRST, None, (str,str,int)), 'selected' : (gobject.SIGNAL_RUN_FIRST, None, (str,int)) } def __init__(self, icon_name): gtk.TreeView.__init__(self) self.id2iter = {} self.icon_name = icon_name self.props.model = gtk.ListStore(str,str,int) self.idSet = set() self.set_headers_visible(False) self.set_tooltip_column(1) self.set_search_column(1) # First column crt = gtk.CellRendererText() crt.props.ellipsize = pango.ELLIPSIZE_END self.leftcol = gtk.TreeViewColumn("", crt, text=1) self.leftcol.set_expand(True) self.append_column(self.leftcol) # Second column pixbuf = load_icon(16, icon_name) crp = gtk.CellRendererPixbuf() crp.props.pixbuf = pixbuf self.rightcol = gtk.TreeViewColumn("", crp) self.append_column(self.rightcol) # Mouse self.pressed = None self.stdcursor = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR) self.linkcursor = gtk.gdk.Cursor(gtk.gdk.HAND2) self.connect("button_press_event", self.button_press) self.connect("button_release_event", self.button_release) self.connect("motion_notify_event", self.motion_notify) self.connect("leave_notify_event", self.leave_notify) # Selection self.get_selection().connect("changed", self.selection_changed) def addRow (self, id, text, type): if id in self.id2iter: return iter = self.props.model.append([id, text, type]) self.id2iter[id] = iter self.idSet.add(id) def removeRow (self, id): try: iter = self.id2iter[id] except KeyError: return self.props.model.remove(iter) del self.id2iter[id] self.idSet.remove(id) def selectRow (self, id): iter = self.id2iter[id] self.get_selection().select_iter(iter) def __contains__ (self, id): return id in self.idSet def button_press (self, widget, event): path_col_pos = self.get_path_at_pos(int(event.x), int(event.y)) if path_col_pos and path_col_pos[1] == self.rightcol: self.pressed = path_col_pos[0] def button_release (self, widget, event): path_col_pos = self.get_path_at_pos(int(event.x), int(event.y)) if path_col_pos and path_col_pos[1] == self.rightcol: if self.pressed == path_col_pos[0]: iter = self.props.model.get_iter(self.pressed) id = self.props.model.get_value(iter, 0) text = self.props.model.get_value(iter, 1) type = self.props.model.get_value(iter, 2) self.emit("activated", id, text, type) self.pressed = None def motion_notify (self, widget, event): path_col_pos = self.get_path_at_pos(int(event.x), int(event.y)) if path_col_pos and path_col_pos[1] == self.rightcol: self.window.set_cursor(self.linkcursor) else: self.window.set_cursor(self.stdcursor) def leave_notify (self, widget, event): self.window.set_cursor(self.stdcursor) def selection_changed (self, selection): model, iter = selection.get_selected() if iter: id = model.get_value(iter, 0) type = model.get_value(iter, 2) self.emit("selected", id, type) class Panel: def start (self): pass def addItem (self, id, text, type, chatView): pass def removeItem (self, id): pass def selectItem (self, id): pass #=============================================================================== # Panels #=============================================================================== class ViewsPanel (gtk.Notebook, Panel): def __init__ (self, connection): gtk.Notebook.__init__(self) self.set_show_tabs(False) self.set_show_border(False) self.id2Widget = {} self.connection = connection label = gtk.Label() label.set_markup("<big>%s</big>" % _("You have opened no conversations yet")) label.props.xalign = .5 label.props.yalign = 0.381966011 label.props.justify = gtk.JUSTIFY_CENTER label.props.wrap = True label.props.width_request = 300 self.append_page(label, None) # When a person addresses us directly, ChannelsPanel will emit an # additem event and we add a new view. This however means that the first # message the user sends isn't registred by our privateMessage handler. # Therefore we save all messages sent by this hook, and when later we # add new items, we test if anything was already recieved self.messageBuffer = {} def globalPersonalMessage (cm, name, title, isadmin, text): if not name in self.messageBuffer: self.messageBuffer[name] = [] self.messageBuffer[name].append((title, isadmin, text)) self.connection.cm.connect("privateMessage", globalPersonalMessage) def addItem (self, id, name, type, chatView): chatView.connect("messageTyped", self.onMessageTyped, id, name, type) glock_connect(self.connection.cm, "channelMessage", self.onChannelMessage, id, chatView) glock_connect(self.connection.cm, "privateMessage", self.onPersonMessage, get_playername(name), chatView) if type == TYPE_CHANNEL: glock_connect(self.connection.cm, "channelLog", self.onChannelLog, id, chatView) self.connection.cm.getChannelLog(id) if not self.connection.cm.mayTellChannel(id): chatView.disable(_("Only registered users may talk to this channel")) elif type == TYPE_PERSONAL: if name in self.messageBuffer: for title, isadmin, messagetext in self.messageBuffer[name]: chatView.addMessage(name, messagetext) del self.messageBuffer[name] self.addPage(chatView, id) def removeItem (self, id): self.removePage(id) def selectItem (self, id): child = self.id2Widget[id] self.set_current_page(self.page_num(child)) def onChannelLog (self, cm, channel, time, handle, text, name_, chatView): if channel.lower() == name_.lower(): chatView.insertLogMessage(time, handle, text) def onMessageTyped (self, chatView, text, id, name, type): if type == TYPE_CHANNEL: self.connection.cm.tellChannel(id, text) elif type == TYPE_PERSONAL: self.connection.cm.tellPlayer(get_playername(name), text) chatView.addMessage(self.connection.getUsername(), text) def onPersonMessage (self, cm, name, title, isadmin, text, name_, chatView): if name.lower() == name_.lower(): chatView.addMessage(name, text) def onChannelMessage (self, cm, name, isadmin, isme, channel, text, name_, chatView): if channel.lower() == name_.lower() and not isme: chatView.addMessage(name, text) def addPage (self, widget, id): self.id2Widget[id] = widget self.append_page(widget) widget.show_all() def removePage (self, id): child = self.id2Widget.pop(id) self.remove_page(self.page_num(child)) class InfoPanel (gtk.Notebook, Panel): def __init__ (self, connection): gtk.Notebook.__init__(self) self.set_show_tabs(False) self.set_show_border(False) self.id2Widget = {} label = gtk.Label() label.set_markup("<big>%s</big>" % _("No conversation's selected")) label.props.xalign = .5 label.props.yalign = 0.381966011 label.props.justify = gtk.JUSTIFY_CENTER label.props.wrap = True label.props.width_request = 115 self.append_page(label, None) self.connection = connection def addItem (self, id, text, type, chatView): if type == TYPE_PERSONAL: infoItem = self.PlayerInfoItem(id, text, chatView, self.connection) elif type == TYPE_CHANNEL: infoItem = self.ChannelInfoItem(id, text, chatView, self.connection) self.addPage(infoItem, id) def removeItem (self, id): self.removePage(id) def selectItem (self, id): child = self.id2Widget[id] self.set_current_page(self.page_num(child)) def addPage (self, widget, id): self.id2Widget[id] = widget self.append_page(widget) widget.show_all() def removePage (self, id): child = self.id2Widget.pop(id) self.remove_page(self.page_num(child)) class PlayerInfoItem (gtk.Alignment): def __init__ (self, id, text, chatView, connection): gtk.Alignment.__init__(self, xscale=1, yscale=1) self.add(gtk.Label(_("Loading player data"))) playername = get_playername(text) self.fm = connection.fm self.handle_id = glock_connect(self.fm, "fingeringFinished", self.onFingeringFinished, playername) self.fm.finger(playername) def onFingeringFinished (self, fm, finger, playername): if not isinstance(self.get_child(), gtk.Label) or \ finger.getName().lower() != playername.lower(): return self.fm.disconnect(self.handle_id) label = gtk.Label() label.set_markup("<b>%s</b>" % playername) widget = gtk.Frame() widget.set_label_widget(label) widget.set_shadow_type(gtk.SHADOW_NONE) alignment = gtk.Alignment(0, 0, 1, 1) alignment.set_padding(3, 0, 12, 0) widget.add(alignment) store = gtk.ListStore(str,str) for i, note in enumerate(finger.getNotes()): if note: store.append([str(i+1),note]) tv = gtk.TreeView(store) tv.get_selection().set_mode(gtk.SELECTION_NONE) tv.set_headers_visible(False) tv.modify_base(gtk.STATE_NORMAL, self.get_style().bg[gtk.STATE_NORMAL].copy()) cell = gtk.CellRendererText() cell.props.cell_background_gdk = self.get_style().bg[gtk.STATE_ACTIVE].copy() cell.props.cell_background_set = True cell.props.yalign = 0 tv.append_column(gtk.TreeViewColumn("", cell, text=0)) cell = uistuff.appendAutowrapColumn(tv, 50, "Notes", text=1) cell.props.cell_background_gdk = self.get_style().bg[gtk.STATE_NORMAL].copy() cell.props.cell_background_set = True sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) sw.add(tv) alignment.add(sw) self.remove(self.get_child()) self.add(widget) widget.show_all() class ChannelInfoItem (gtk.Alignment): def __init__ (self, id, text, chatView, connection): gtk.Alignment.__init__(self, xscale=1, yscale=1) self.cm = connection.cm self.add(gtk.Label(_("Receiving list of players"))) chatView.connect("messageAdded", self.onMessageAdded) self.store = gtk.ListStore(object, # (r,g,b) Color tuple str, # name string bool # is separator ) self.handle_id = glock_connect(self.cm, "recievedNames", self.onNamesRecieved, id) self.cm.getPeopleInChannel(id) def onNamesRecieved (self, cm, channel, people, channel_): if not isinstance(self.get_child(), gtk.Label) or channel != channel_: return cm.disconnect(self.handle_id) sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) list = gtk.TreeView() list.set_headers_visible(False) list.set_tooltip_column(1) list.set_model(self.store) list.append_column(gtk.TreeViewColumn("", BulletCellRenderer(), color=0)) cell = gtk.CellRendererText() cell.props.ellipsize = pango.ELLIPSIZE_END list.append_column(gtk.TreeViewColumn("", cell, text=1)) list.fixed_height_mode = True self.separatorIter = self.store.append([(),"",True]) list.set_row_separator_func(lambda m,i: m.get_value(i, 2)) sw.add(list) self.store.connect("row-inserted", lambda w,p,i: list.queue_resize()) self.store.connect("row-deleted", lambda w,i: list.queue_resize()) # Add those names. If this is not the first namesRecieve, we only # add the new names noneed = set([name for color, name, isSeparator in self.store]) for name in people: if name in noneed: continue self.store.append([(1,1,1), name, False]) self.remove(self.get_child()) self.add(sw) self.show_all() def onMessageAdded (self, chatView, sender, text, color): iter = self.store.get_iter_first() # If the names list hasn't been retrieved yet, we have to skip this if not iter: return while self.store.get_path(iter) != self.store.get_path(self.separatorIter): person = self.store.get_value(iter, 1) # If the person is already in the area before the separator, we # don't have to do anything if person.lower() == sender.lower(): return iter = self.store.iter_next(iter) # Go to iter after separator iter = self.store.iter_next(iter) while iter and self.store.iter_is_valid(iter): person = self.store.get_value(iter, 1) if person.lower() == sender.lower(): self.store.set_value(iter, 0, color) self.store.move_before(iter, self.separatorIter) return iter = self.store.iter_next(iter) # If the person was not in the area under the separator of the # store, it must be a new person, who has joined the channel, and we # simply add him before the separator self.store.insert_before(self.separatorIter, [color, sender, False]) class ChannelsPanel (gtk.ScrolledWindow, Panel): __gsignals__ = { 'conversationAdded' : (gobject.SIGNAL_RUN_FIRST, None, (str,str,int)), 'conversationRemoved' : (gobject.SIGNAL_RUN_FIRST, None, (str,)), 'conversationSelected' : (gobject.SIGNAL_RUN_FIRST, None, (str,)) } def __init__ (self, connection): gtk.ScrolledWindow.__init__(self) self.connection = connection self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) vbox = gtk.VBox() self.add_with_viewport(vbox) self.child.set_shadow_type(gtk.SHADOW_NONE) self.joinedList = TextImageTree("gtk-remove") self.joinedList.connect("activated", self.onRemove) self.joinedList.connect("selected", self.onSelect) vbox.pack_start(self.joinedList) expander = gtk.Expander(_("More channels")) vbox.pack_start(expander, expand=False) self.channelsList = TextImageTree("gtk-add") self.channelsList.connect("activated", self.onAdd) self.channelsList.fixed_height_mode = True expander.add(self.channelsList) expander = gtk.Expander(_("More players")) vbox.pack_start(expander, expand=False) self.playersList = TextImageTree("gtk-add") self.playersList.connect("activated", self.onAdd) self.playersList.fixed_height_mode = True glock_connect(connection.cm, "privateMessage", self.onPersonMessage, after=True) expander.add(self.playersList) def start (self): for id, name in self.connection.cm.getChannels(): id = self.compileId(id, TYPE_CHANNEL) self.channelsList.addRow(id, str(id) + ": " + name, TYPE_CHANNEL) for id, name in self.connection.cm.getChannels(): if id in self.connection.cm.getJoinedChannels(): id = self.compileId(id, TYPE_CHANNEL) if id.isdigit(): self.onAdd(self.channelsList, id, str(id)+": "+name, TYPE_CHANNEL) else: self.onAdd(self.channelsList, id, name, TYPE_CHANNEL) for player in self.connection.players.values(): if player.online: id = self.compileId(player.name, TYPE_PERSONAL) self.playersList.addRow(id, player.name + player.display_titles(), TYPE_PERSONAL) self.connection.players.connect("FICSPlayerEntered", lambda players, player: self.playersList.addRow( self.compileId(player.name, TYPE_PERSONAL), player.name + player.display_titles(), TYPE_PERSONAL)) self.connection.players.connect("FICSPlayerExited", lambda players, player: self.playersList.removeRow( self.compileId(player.name, TYPE_PERSONAL))) def compileId (self, id, type): if type == TYPE_PERSONAL: id = "person" + id.lower() elif type == TYPE_CHANNEL: # FIXME: We can't really add stuff to the id, as panels use it to # identify the channel assert not id.startswith("person"), "Oops, this is a problem" return id def onAdd (self, list, id, text, type): if id in list: list.removeRow(id) self.joinedList.addRow(id, text, type) self.emit('conversationAdded', id, text, type) if type == TYPE_CHANNEL: self.connection.cm.joinChannel(id) self.joinedList.selectRow(id) def onRemove (self, joinedList, id, text, type): joinedList.removeRow(id) if type == TYPE_CHANNEL: self.channelsList.addRow(id, text, type) elif type == TYPE_PERSONAL: self.playersList.addRow(id, text, type) self.emit('conversationRemoved', id) if type == TYPE_CHANNEL: self.connection.cm.removeChannel(id) def onSelect (self, joinedList, id, type): self.emit('conversationSelected', id) def onPersonMessage (self, cm, name, title, isadmin, text): if not self.compileId(name, TYPE_PERSONAL) in self.joinedList: id = self.compileId(name, TYPE_PERSONAL) self.onAdd(self.playersList, id, name, TYPE_PERSONAL) #=============================================================================== # /Panels #=============================================================================== class ChatWindow: def __init__ (self, widgets, connection): self.connection = connection self.window = None widgets["show_chat_button"].connect("clicked", self.showChat) glock_connect(connection.cm, "privateMessage", self.onPersonMessage, after=False) glock_connect(connection, "disconnected", lambda c: self.window and self.window.hide()) self.viewspanel = ViewsPanel(self.connection) self.channelspanel = ChannelsPanel(self.connection) self.infopanel = InfoPanel(self.connection) self.panels = [self.viewspanel, self.channelspanel, self.infopanel] def showChat (self, *widget): if not self.window: self.initUi() self.window.show_all() def initUi (self): self.window = gtk.Window() self.window.set_border_width(12) self.window.set_icon_name("pychess") self.window.set_title("PyChess - Internet Chess Chat") self.window.connect("delete-event", lambda w,e: w.hide() or True) uistuff.keepWindowSize("chatwindow", self.window, defaultSize=(650,400)) dock = PyDockTop("icchat") dock.show() self.window.add(dock) leaf = dock.dock(self.viewspanel, CENTER, gtk.Label("chat"), "chat") leaf.setDockable(False) self.channelspanel.connect('conversationAdded', self.onConversationAdded) self.channelspanel.connect('conversationRemoved', self.onConversationRemoved) self.channelspanel.connect('conversationSelected', self.onConversationSelected) leaf.dock(self.channelspanel, WEST, gtk.Label(_("Conversations")), "conversations") leaf.dock(self.infopanel, EAST, gtk.Label(_("Conversation info")), "info") for panel in self.panels: panel.show_all() panel.start() def onConversationAdded (self, panel, id, text, type): chatView = ChatView() for panel in self.panels: panel.addItem(id, text, type, chatView) def onConversationRemoved (self, panel, id): for panel in self.panels: panel.removeItem(id) def onConversationSelected (self, panel, id): for panel in self.panels: panel.selectItem(id) def onPersonMessage (self, cm, name, title, isadmin, text): self.showChat() self.window.set_urgency_hint(True) def openChatWithPlayer (self, name): self.showChat() self.window.window.raise_() cm = self.connection.cm self.onPersonMessage(cm, name, "", False, "") self.channelspanel.onPersonMessage(cm, name, "", False, "") if __name__ == "__main__": import random class LM: def getPlayerlist(self): for i in range(10): chrs = map(chr,range(ord("a"),ord("z")+1)) yield "".join(random.sample(chrs, random.randrange(20))) def getChannels(self): return [(str(i),n) for i,n in enumerate(self.getPlayerlist())] def joinChannel (self, channel): pass def connect (self, *args): pass def getPeopleInChannel (self, name): pass def finger (self, name): pass def getJoinedChannels (self): return [] class Con: def __init__ (self): self.glm = LM() self.cm = LM() self.fm = LM() cw = ChatWindow({}, Con()) globals()["_"] = lambda x:x cw.showChat() cw.window.connect("delete-event", gtk.main_quit) gtk.main()
Python
import gtk from pychess.System import uistuff from pychess.System.prefix import addDataPrefix from pychess.Utils.Piece import Piece,QUEEN,ROOK,BISHOP,KNIGHT from pychess.Utils.const import WHITE,BLACK from PieceWidget import PieceWidget uistuff.cacheGladefile("promotion.glade") class PromotionDialog: def __init__(self): self.widgets = uistuff.GladeWidgets("promotion.glade") self.dialog = self.widgets["promotionDialog"] self.color = None self.widgets["knightDock"].add(PieceWidget(Piece(WHITE, KNIGHT))) self.widgets["knightDock"].child.show() self.widgets["bishopDock"].add(PieceWidget(Piece(WHITE, BISHOP))) self.widgets["bishopDock"].child.show() self.widgets["rookDock"].add(PieceWidget(Piece(WHITE, ROOK))) self.widgets["rookDock"].child.show() self.widgets["queenDock"].add(PieceWidget(Piece(WHITE, QUEEN))) self.widgets["queenDock"].child.show() def setColor(self, color): self.widgets["knightDock"].child.getPiece().color = color self.widgets["bishopDock"].child.getPiece().color = color self.widgets["rookDock"].child.getPiece().color = color self.widgets["queenDock"].child.getPiece().color = color def runAndHide(self, color): self.setColor(color) res = self.dialog.run() self.dialog.hide() if res != gtk.RESPONSE_DELETE_EVENT: return [QUEEN,ROOK,BISHOP,KNIGHT][int(res)] return res
Python
# -*- coding: UTF-8 -*- import os.path import time import codecs import gtk, pango, gobject from pychess.System import glock, uistuff from pychess.System.Log import log from pychess.System.Log import LOG_DEBUG, LOG_LOG, LOG_WARNING, LOG_ERROR from pychess.System.prefix import addDataPrefix def rawreplace(error): symbols = (ur"\x%02x" % ord(s) for s in error.object[error.start:error.end]) return u"".join(symbols), error.end codecs.register_error("rawreplace", rawreplace) class InformationWindow: @classmethod def _init (cls): cls.tagToIter = {} cls.tagToPage = {} cls.pathToPage = {} cls.tagToTime = {} cls.window = gtk.Window() cls.window.set_title(_("PyChess Information Window")) cls.window.set_border_width(12) cls.window.set_icon_name("pychess") uistuff.keepWindowSize("logdialog", cls.window, (640,480)) mainHBox = gtk.HBox() mainHBox.set_spacing(6) cls.window.add(mainHBox) sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) sw.set_shadow_type(gtk.SHADOW_IN) mainHBox.pack_start(sw, expand=False) cls.treeview = gtk.TreeView(gtk.TreeStore(str)) cls.treeview.append_column(gtk.TreeViewColumn("", gtk.CellRendererText(), text=0)) cls.treeview.set_headers_visible(False) cls.treeview.get_selection().set_mode(gtk.SELECTION_BROWSE) sw.add(cls.treeview) cls.pages = gtk.Notebook() cls.pages.set_show_tabs(False) cls.pages.set_show_border(False) mainHBox.pack_start(cls.pages) mainHBox.show_all() def selectionChanged (selection): treestore, iter = selection.get_selected() if iter: child = cls.pathToPage[treestore.get_path(iter)]["child"] cls.pages.set_current_page(cls.pages.page_num(child)) cls.treeview.get_selection().connect("changed", selectionChanged) @classmethod def show (cls): cls.window.show() @classmethod def hide (cls): cls.window.hide() @classmethod def newMessage (cls, tag, timestamp, message, importance): textview = cls._getPageFromTag(tag)["textview"] if not tag in cls.tagToTime or timestamp-cls.tagToTime[tag] >= 1: t = time.strftime("%H:%M:%S", time.localtime(timestamp)) textview.get_buffer().insert_with_tags_by_name( textview.get_buffer().get_end_iter(), "\n%s\n%s\n"%(t,"-"*60), str(LOG_LOG)) cls.tagToTime[tag] = timestamp if type(message) == str: message = unicode(message, "utf-8", 'rawreplace') textview.get_buffer().insert_with_tags_by_name( textview.get_buffer().get_end_iter(), message, str(importance)) @classmethod def _createPage (cls, parrentIter, tag): name = tag[-1] iter = cls.treeview.get_model().append(parrentIter, (name,)) cls.tagToIter[tag] = iter widgets = uistuff.GladeWidgets("findbar.glade") frame = widgets["frame"] frame.unparent() frame.show_all() uistuff.keepDown(widgets["scrolledwindow"]) textview = widgets["textview"] tb = textview.get_buffer() tb.create_tag(str(LOG_DEBUG), family='Monospace') tb.create_tag(str(LOG_LOG), family='Monospace', weight=pango.WEIGHT_BOLD) tb.create_tag(str(LOG_WARNING), family='Monospace', foreground="red") tb.create_tag(str(LOG_ERROR), family='Monospace', weight=pango.WEIGHT_BOLD, foreground="red") findbar = widgets["findbar"] findbar.hide() # Make searchEntry and "out of label" share height with the buttons widgets["prevButton"].connect("size-allocate", lambda w, alloc: widgets["searchEntry"].set_size_request(-1, alloc.height) or widgets["outofLabel"].set_size_request(-1, alloc.height-2)) # Make "out of label" more visually distinct uistuff.makeYellow(widgets["outofLabel"]) widgets["outofLabel"].hide() widgets["closeButton"].connect("clicked", lambda w: widgets["findbar"].hide()) # Connect showing/hiding of the findbar cls.window.connect("key-press-event", cls.onTextviewKeypress, widgets) widgets["findbar"].connect("key-press-event", cls.onFindbarKeypress) widgets["searchEntry"].connect("changed", cls.onSearchChanged, widgets) widgets["prevButton"].connect("clicked", lambda w: cls.searchJump(-1, widgets)) widgets["nextButton"].connect("clicked", lambda w: cls.searchJump(1, widgets)) cls.pages.append_page(frame) page = {"child": frame, "textview":textview} cls.tagToPage[tag] = page cls.pathToPage[cls.treeview.get_model().get_path(iter)] = page cls.treeview.expand_all() @classmethod def _getPageFromTag (cls, tag): if type(tag) == list: tag = tuple(tag) elif type(tag) != tuple: tag = (tag,) if tag in cls.tagToPage: return cls.tagToPage[tag] for i in xrange(len(tag)-1): subtag = tag[:-i-1] if subtag in cls.tagToIter: newtag = subtag+(tag[len(subtag)],) iter = cls.tagToIter[subtag] cls._createPage(iter, newtag) return cls._getPageFromTag(tag) cls._createPage(None, tag[:1]) return cls._getPageFromTag(tag) @classmethod def onSearchChanged (cls, searchEntry, widgets): pattern = searchEntry.get_text().lower() widgets["outofLabel"].props.visible = bool(pattern) if not pattern: return text = widgets["textview"].get_buffer().props.text.lower() widgets["outofLabel"].hits = [] widgets["outofLabel"].searchCurrent = -1 i = -len(pattern) while True: i = text.find(pattern, i+len(pattern)) if i != -1: widgets["outofLabel"].hits.append(i) else: break cls.searchJump(1, widgets) @classmethod def searchJump (cls, count, widgets): if not hasattr(widgets["outofLabel"], "hits"): return amount = len(widgets["outofLabel"].hits) if not amount: widgets["outofLabel"].set_text("0 %s 0" % _("of")) else: widgets["outofLabel"].searchCurrent += count current = widgets["outofLabel"].searchCurrent % amount widgets["outofLabel"].set_text("%d %s %d" % (current+1, _("of"), amount)) goto = widgets["outofLabel"].hits[current] iter0 = widgets["textview"].get_buffer().get_iter_at_offset(goto) length = len(widgets["searchEntry"].get_text()) iter1 = widgets["textview"].get_buffer().get_iter_at_offset(goto+length) widgets["textview"].get_buffer().select_range(iter0, iter1) widgets["textview"].scroll_to_iter(iter0, 0.2) @classmethod def onTextviewKeypress (cls, textview, event, widgets): if event.state & gtk.gdk.CONTROL_MASK: if event.keyval in (ord("f"), ord("F")): widgets["findbar"].props.visible = not widgets["findbar"].props.visible if widgets["findbar"].props.visible: signal = widgets["searchEntry"].connect_after("expose-event", lambda w,e: w.grab_focus() or widgets["searchEntry"].disconnect(signal)) @classmethod def onFindbarKeypress (cls, findbar, event): if gtk.gdk.keyval_name(event.keyval) == "Escape": findbar.props.visible = False uistuff.cacheGladefile("findbar.glade") ################################################################################ # Add early messages and connect for new # ################################################################################ InformationWindow._init() import gobject def addMessages2 (messages): gobject.idle_add(addMessages2, messages) def addMessages (messages): for task, timestamp, message, type in messages: InformationWindow.newMessage (task, timestamp, message, type) glock.acquire() try: addMessages(log.messages) log.messages = None finally: glock.release() log.connect ("logged", lambda log, messages: addMessages(messages)) ################################################################################ # External functions # ################################################################################ destroy_funcs = [] def add_destroy_notify (func): destroy_funcs.append(func) def _destroy_notify (widget, *args): [func() for func in destroy_funcs] return True InformationWindow.window.connect("delete-event", _destroy_notify) def show (): InformationWindow.show() def hide (): InformationWindow.hide() if __name__ == "__main__": show() InformationWindow.window.connect("delete-event", gtk.main_quit) gtk.main()
Python
# -*- coding: UTF-8 -*- import gtk, gtk.gdk from gobject import * import threading from pychess.System.prefix import addDataPrefix from pychess.System.Log import log from pychess.Utils.Cord import Cord from pychess.Utils.Move import Move from pychess.Utils.const import * from pychess.Utils.logic import validate from pychess.Utils.lutils import lmovegen from PromotionDialog import PromotionDialog from BoardView import BoardView, rect from BoardView import join class BoardControl (gtk.EventBox): __gsignals__ = { 'piece_moved' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object, int)), 'action' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object)) } def __init__(self, gamemodel, actionMenuItems): gtk.EventBox.__init__(self) self.promotionDialog = PromotionDialog() self.view = BoardView(gamemodel) self.add(self.view) self.actionMenuItems = actionMenuItems self.connections = {} for key, menuitem in self.actionMenuItems.iteritems(): if menuitem == None: print key self.connections[menuitem] = menuitem.connect("activate", self.actionActivate, key) self.view.connect("shown_changed", self.shown_changed) gamemodel.connect("moves_undoing", self.moves_undone) self.connect("button_press_event", self.button_press) self.connect("button_release_event", self.button_release) self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK|gtk.gdk.POINTER_MOTION_MASK) self.connect("motion_notify_event", self.motion_notify) self.connect("leave_notify_event", self.leave_notify) self.selected_last = None self.stateLock = threading.Lock() self.normalState = NormalState(self) self.selectedState = SelectedState(self) self.activeState = ActiveState(self) self.lockedState = LockedState(self) self.lockedSelectedState = LockedSelectedState(self) self.lockedActiveState = LockedActiveState(self) self.currentState = self.lockedState self.lockedPly = self.view.shown self.possibleBoards = { self.lockedPly : self._genPossibleBoards(self.lockedPly) } self.allowPremove = False def onGameStart (gamemodel): for player in gamemodel.players: if player.__type__ == LOCAL: self.allowPremove = True gamemodel.connect("game_started", onGameStart) def __del__ (self): for menu, conid in self.connections.iteritems(): menu.disconnect(conid) self.connections = {} def emit_move_signal (self, cord0, cord1): color = self.view.model.boards[-1].color board = self.view.model.getBoardAtPly(self.view.shown) # Ask player for which piece to promote into. If this move does not # include a promotion, QUEEN will be sent as a dummy value, but not used promotion = QUEEN if board[cord0].sign == PAWN and cord1.y in (0,7): res = self.promotionDialog.runAndHide(color) if res != gtk.RESPONSE_DELETE_EVENT: promotion = res else: # Put back pawn moved be d'n'd self.view.runAnimation(redrawMisc = False) return move = Move(cord0, cord1, self.view.model.boards[-1], promotion) self.emit("piece_moved", move, color) def actionActivate (self, widget, key): """ Put actions from a menu or similar """ if key == "call_flag": self.emit("action", FLAG_CALL, None) elif key == "abort": self.emit("action", ABORT_OFFER, None) elif key == "adjourn": self.emit("action", ADJOURN_OFFER, None) elif key == "draw": self.emit("action", DRAW_OFFER, None) elif key == "resign": self.emit("action", RESIGNATION, None) elif key == "ask_to_move": self.emit("action", HURRY_ACTION, None) elif key == "undo1": curColor = self.view.model.variations[0][-1].color curPlayer = self.view.model.players[curColor] if curPlayer.__type__ == LOCAL and self.view.model.ply > 1: self.emit("action", TAKEBACK_OFFER, self.view.model.ply-2) else: self.emit("action", TAKEBACK_OFFER, self.view.model.ply-1) elif key == "pause1": self.emit("action", PAUSE_OFFER, None) elif key == "resume1": self.emit("action", RESUME_OFFER, None) def shown_changed (self, view, shown): self.lockedPly = self.view.shown self.possibleBoards[self.lockedPly] = self._genPossibleBoards(self.lockedPly) if self.view.shown-2 in self.possibleBoards: del self.possibleBoards[self.view.shown-2] def moves_undone (self, gamemodel, moves): self.stateLock.acquire() try: self.view.selected = None self.view.active = None self.view.hover = None self.view.draggedPiece = None self.view.startAnimation() self.currentState = self.lockedState finally: self.stateLock.release() def setLocked (self, locked): self.stateLock.acquire() try: if locked: if self.view.model.status != RUNNING: self.view.selected = None self.view.active = None self.view.hover = None self.view.draggedPiece = None self.view.startAnimation() self.currentState = self.lockedState else: if self.currentState == self.lockedSelectedState: self.currentState = self.selectedState elif self.currentState == self.lockedActiveState: self.currentState = self.activeState else: self.currentState = self.normalState finally: self.stateLock.release() def setStateSelected (self): self.stateLock.acquire() try: if self.currentState in (self.lockedState, self.lockedSelectedState, self.lockedActiveState): self.currentState = self.lockedSelectedState else: self.currentState = self.selectedState finally: self.stateLock.release() def setStateActive (self): self.stateLock.acquire() try: if self.currentState in (self.lockedState, self.lockedSelectedState, self.lockedActiveState): self.currentState = self.lockedActiveState else: self.currentState = self.activeState finally: self.stateLock.release() def setStateNormal (self): self.stateLock.acquire() try: if self.currentState in (self.lockedState, self.lockedSelectedState, self.lockedActiveState): self.currentState = self.lockedState else: self.currentState = self.normalState finally: self.stateLock.release() def button_press (self, widget, event): return self.currentState.press(event.x, event.y) def button_release (self, widget, event): return self.currentState.release(event.x, event.y) def motion_notify (self, widget, event): return self.currentState.motion(event.x, event.y) def leave_notify (self, widget, event): return self.currentState.leave(event.x, event.y) def _genPossibleBoards(self, ply): possibleBoards = [] curboard = self.view.model.getBoardAtPly(ply) for lmove in lmovegen.genAllMoves(curboard.board): move = Move(lmove) board = curboard.move(move) possibleBoards.append(board) return possibleBoards class BoardState: def __init__ (self, board): self.parent = board self.view = board.view self.lastMotionCord = None def getBoard (self): return self.view.model.getBoardAtPly(self.view.shown) def validate (self, cord0, cord1): assert cord0 != None and cord1 != None, "cord0: " + str(cord0) + ", cord1: " + str(cord1) if self.getBoard()[cord0] == None: return False return validate(self.getBoard(), Move(cord0, cord1, self.getBoard())) def transPoint (self, x, y): if not self.view.square: return None xc, yc, square, s = self.view.square x, y = self.view.invmatrix.transform_point(x,y) y -= yc; x -= xc y /= float(s) x /= float(s) return x, 8-y def point2Cord (self, x, y): if not self.view.square: return None point = self.transPoint(x, y) if not 0 <= int(point[0]) <= 7 or not 0 <= int(point[1]) <= 7: return None return Cord(int(point[0]), int(point[1])) def isSelectable (self, cord): # Simple isSelectable method, disabling selecting cords out of bound etc if not cord: return False if not 0 <= cord.x <= 7 or not 0 <= cord.y <= 7: return False if self.view.model.status != RUNNING: return False if self.view.shown != self.view.model.ply: return False return True def press (self, x, y): pass def release (self, x, y): pass def motion (self, x, y): cord = self.point2Cord(x, y) if self.lastMotionCord == cord: return self.lastMotionCord = cord if cord and self.isSelectable(cord): self.view.hover = cord else: self.view.hover = None def leave (self, x, y): a = self.parent.get_allocation() if not (0 <= x < a.width and 0 <= y < a.height): self.view.hover = None class LockedBoardState (BoardState): def __init__ (self, board): BoardState.__init__(self, board) def isAPotentiallyLegalNextMove (self, cord0, cord1): """ Determines whether the given move is at all legally possible as the next move after the player who's turn it is makes their move Note: This doesn't always return the correct value, such as when BoardControl.setLocked() has been called and we've begun a drag, but view.shown and BoardControl.lockedPly haven't been updated yet """ if cord0 == None or cord1 == None: return False if not self.parent.lockedPly in self.parent.possibleBoards: return False for board in self.parent.possibleBoards[self.parent.lockedPly]: if not board[cord0]: return False if validate(board, Move(cord0, cord1, board)): return True return False class NormalState (BoardState): def isSelectable (self, cord): if not BoardState.isSelectable(self, cord): return False # We don't want empty cords if self.getBoard()[cord] == None: return False # We should not be able to select an opponent piece if self.getBoard()[cord].color != self.getBoard().color: return False return True def press (self, x, y): self.parent.grab_focus() cord = self.point2Cord(x,y) if self.isSelectable(cord): self.view.draggedPiece = self.getBoard()[cord] self.view.active = cord self.parent.setStateActive() class ActiveState (BoardState): def isSelectable (self, cord): if not BoardState.isSelectable(self, cord): return False return self.validate(self.view.active, cord) def release (self, x, y): cord = self.point2Cord(x,y) if not cord: self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() # When in the mixed active/selected state elif self.view.selected: # Move when releasing on a good cord if self.validate(self.view.selected, cord): self.parent.setStateNormal() # It is important to emit_move_signal after setting state # as listeners of the function probably will lock the board self.view.draggedPiece = None self.parent.emit_move_signal(self.view.selected, cord) self.view.selected = None self.view.active = None elif cord == self.view.active == self.view.selected == self.parent.selected_last: # user clicked (press+release) same piece twice, so unselect it self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() else: # leave last selected piece selected self.view.active = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateSelected() # If dragged and released on a possible cord elif self.validate(self.view.active, cord): self.parent.setStateNormal() self.view.draggedPiece = None self.parent.emit_move_signal(self.view.active, cord) self.view.active = None # Select last piece user tried to move or that was selected elif self.view.active or self.view.selected: self.view.selected = self.view.active if self.view.active else self.view.selected self.view.active = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateSelected() # Send back, if dragging to a not possible cord else: self.view.active = None # Send the piece back to its original cord self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() self.parent.selected_last = self.view.selected def motion (self, x, y): if not self.getBoard()[self.view.active]: return BoardState.motion(self, x, y) fcord = self.view.active piece = self.getBoard()[fcord] if piece.color != self.getBoard().color: return if not self.view.square: return xc, yc, square, s = self.view.square co, si = self.view.matrix[0], self.view.matrix[1] point = self.transPoint(x-s*(co+si)/2., y+s*(co-si)/2.) if not point: return x, y = point if piece.x != x or piece.y != y: if piece.x: paintBox = self.view.cord2RectRelative(piece.x, piece.y) else: paintBox = self.view.cord2RectRelative(self.view.active) paintBox = join(paintBox, self.view.cord2RectRelative(x, y)) piece.x = x piece.y = y self.view.redraw_canvas(rect(paintBox), queue=True) class SelectedState (BoardState): def isSelectable (self, cord): if not BoardState.isSelectable(self, cord): return False # Select another piece if self.getBoard()[cord] != None and \ self.getBoard()[cord].color == self.getBoard().color: return True return self.validate(self.view.selected, cord) def press (self, x, y): cord = self.point2Cord(x,y) # Unselecting by pressing the selected cord, or marking the cord to be # moved to. We don't unset self.view.selected, so ActiveState can handle # things correctly if self.isSelectable(cord): if self.view.selected and self.view.selected != cord and \ self.getBoard()[cord] != None and \ self.getBoard()[cord].color == self.getBoard().color and \ not self.validate(self.view.selected, cord): # corner case encountered: # user clicked (press+release) a piece, then clicked (no release yet) # a different piece and dragged it somewhere else. Since # ActiveState.release() will use self.view.selected as the source piece # rather than self.view.active, we need to update it here self.view.selected = cord # re-select new cord self.view.draggedPiece = self.getBoard()[cord] self.view.active = cord self.parent.setStateActive() else: # Unselecting by pressing an inactive cord self.view.selected = None self.parent.setStateNormal() class LockedState (LockedBoardState): def isSelectable (self, cord): if not BoardState.isSelectable(self, cord): return False # Don't allow premove if neither player is human if not self.parent.allowPremove: return False # We don't want empty cords if self.getBoard()[cord] == None: return False # We should not be able to select an opponent piece if self.getBoard()[cord].color == self.getBoard().color: return False return True def press (self, x, y): self.parent.grab_focus() cord = self.point2Cord(x,y) if self.isSelectable(cord): self.view.draggedPiece = self.getBoard()[cord] self.view.active = cord self.parent.setStateActive() class LockedActiveState (LockedBoardState): def isSelectable (self, cord): if not BoardState.isSelectable(self, cord): return False return self.isAPotentiallyLegalNextMove(self.view.active, cord) def release (self, x, y): cord = self.point2Cord(x,y) if cord == self.view.active == self.view.selected == self.parent.selected_last: # user clicked (press+release) same piece twice, so unselect it self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() elif self.view.active or self.view.selected: # Select last piece user tried to move or that was selected self.view.selected = self.view.active if self.view.active else self.view.selected self.view.active = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateSelected() else: self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() self.parent.selected_last = self.view.selected def motion (self, x, y): if not self.getBoard()[self.view.active]: return BoardState.motion(self, x, y) fcord = self.view.active piece = self.getBoard()[fcord] if piece.color == self.getBoard().color: return if not self.view.square: return xc, yc, square, s = self.view.square co, si = self.view.matrix[0], self.view.matrix[1] point = self.transPoint(x-s*(co+si)/2., y+s*(co-si)/2.) if not point: return x, y = point if piece.x != x or piece.y != y: if piece.x: paintBox = self.view.cord2RectRelative(piece.x, piece.y) else: paintBox = self.view.cord2RectRelative(self.view.active) paintBox = join(paintBox, self.view.cord2RectRelative(x, y)) piece.x = x piece.y = y self.view.redraw_canvas(rect(paintBox), queue=True) class LockedSelectedState (LockedBoardState): def isSelectable (self, cord): if not BoardState.isSelectable(self, cord): return False # Select another piece if self.getBoard()[cord] != None and \ self.getBoard()[cord].color != self.getBoard().color: return True return False def motion (self, x, y): cord = self.point2Cord(x, y) if self.lastMotionCord == cord: self.view.hover = cord return self.lastMotionCord = cord if cord and self.isAPotentiallyLegalNextMove(self.view.selected, cord): self.view.hover = cord else: self.view.hover = None def press (self, x, y): cord = self.point2Cord(x,y) # Unselecting by pressing the selected cord, or marking the cord to be # moved to. We don't unset self.view.selected, so ActiveState can handle # things correctly if self.isSelectable(cord): if self.view.selected and self.view.selected != cord and \ self.getBoard()[cord] != None and \ self.getBoard()[cord].color != self.getBoard().color and \ not self.isAPotentiallyLegalNextMove(self.view.selected, cord): # corner-case encountered (see comment in SelectedState.press) self.view.selected = cord # re-select new cord self.view.draggedPiece = self.getBoard()[cord] self.view.active = cord self.parent.setStateActive() else: # Unselecting by pressing an inactive cord self.view.selected = None self.parent.setStateNormal()
Python
# -*- coding: UTF-8 -*- import sys from math import floor, ceil, pi from time import time, sleep from threading import Lock, RLock import gtk, gtk.gdk, cairo from gobject import * import pango from pychess.System import glock, conf, gstreamer from pychess.System.glock import glock_connect, glock_connect_after from pychess.System.repeat import repeat, repeat_sleep from pychess.gfx.Pieces import drawPiece from pychess.Utils.Piece import Piece from pychess.Utils.Cord import Cord from pychess.Utils.Move import Move from pychess.Utils.GameModel import GameModel from pychess.Utils.const import * from pychess.Variants.fischerandom import FischerRandomChess import preferencesDialog def intersects (r0, r1): w0 = r0.width + r0.x h0 = r0.height + r0.y w1 = r1.width + r1.x h1 = r1.height + r1.y return (w1 < r1.x or w1 > r0.x) and \ (h1 < r1.y or h1 > r0.y) and \ (w0 < r0.x or w0 > r1.x) and \ (h0 < r0.y or h0 > r1.y) def contains (r0, r1): w0 = r0.width + r0.x h0 = r0.height + r0.y w1 = r1.width + r1.x h1 = r1.height + r1.y return r0.x <= r1.x and w0 >= w1 and \ r0.y <= r1.y and h0 >= h1 def join (r0, r1): """ Take (x, y, w, [h]) squares """ if not r0: return r1 if not r1: return r0 if not r0 and not r1: return None if len(r0) == 3: r0 = (r0[0], r0[1], r0[2], r0[2]) if len(r1) == 3: r1 = (r1[0], r1[1], r1[2], r1[2]) x1 = min(r0[0], r1[0]) x2 = max(r0[0]+r0[2], r1[0]+r1[2]) y1 = min(r0[1], r1[1]) y2 = max(r0[1]+r0[3], r1[1]+r1[3]) return (x1, y1, x2 - x1, y2 - y1) def rect (r): x, y = [int(floor(v)) for v in r[:2]] w = int(ceil(r[2])) if len(r) == 4: h = int(ceil(r[3])) else: h = w return gtk.gdk.Rectangle (x, y, w, h) def matrixAround (rotatedMatrix, anchorX, anchorY): co = rotatedMatrix[0] si = rotatedMatrix[1] aysi = anchorY*si axsi = anchorX*si ayco = anchorY*(1-co) axco = anchorX*(1-co) matrix = cairo.Matrix(co, si, -si, co, axco+aysi, ayco-axsi) invmatrix = cairo.Matrix(co, -si, si, co, axco-aysi, ayco+axsi) return matrix, invmatrix ANIMATION_TIME = 0.5 # If this is true, the board is scaled so that everything fits inside the window # even if the board is rotated 45 degrees SCALE_ROTATED_BOARD = False CORD_PADDING = 1.5 class BoardView (gtk.DrawingArea): __gsignals__ = { 'shown_changed' : (SIGNAL_RUN_FIRST, TYPE_NONE, (int,)) } def __init__(self, gamemodel=None): gtk.DrawingArea.__init__(self) if gamemodel == None: gamemodel = GameModel() self.model = gamemodel glock_connect(self.model, "game_started", self.game_started) glock_connect_after(self.model, "game_started", self.game_started_after) glock_connect_after(self.model, "game_changed", self.game_changed) glock_connect_after(self.model, "moves_undoing", self.moves_undoing) glock_connect_after(self.model, "game_loading", self.game_loading) glock_connect_after(self.model, "game_loaded", self.game_loaded) glock_connect_after(self.model, "game_ended", self.game_ended) self.connect("expose_event", self.expose) self.connect_after("realize", self.on_realized) conf.notify_add("showCords", self.on_show_cords) conf.notify_add("faceToFace", self.on_face_to_face) self.set_size_request(350,350) self.animationStart = time() self.lastShown = None self.deadlist = [] self.autoUpdateShown = True self.padding = 0 # Set to self.pad when setcords is active self.square = 0, 0, 8, 1 # An object global variable with the current # board size self.pad = 0.13 # Padding applied only when setcords is active self._selected = None self._hover = None self._active = None self._redarrow = None self._greenarrow = None self._bluearrow = None self._shown = self.model.ply self._showCords = False self.showCords = conf.get("showCords", False) self._showEnpassant = False self.lastMove = None self.matrix = cairo.Matrix() self.matrixPi = cairo.Matrix.init_rotate(pi) self.cordMatricesState = (0, 0) self._rotation = 0 self.drawcount = 0 self.drawtime = 0 self.gotStarted = False self.animationLock = RLock() self.rotationLock = Lock() self.draggedPiece = None # a piece being dragged by the user def game_started_after (self, model): self.emit("shown_changed", self.shown) def game_started (self, model): if conf.get("noAnimation", False): self.gotStarted = True self.redraw_canvas() else: if model.moves: self.lastMove = model.moves[-1] self.animationLock.acquire() try: for row in self.model.boards[-1].data: for piece in row: if piece: piece.opacity = 0 finally: self.animationLock.release() self.gotStarted = True self.startAnimation() def game_changed (self, model): # Play sounds if self.model.players and self.model.status != WAITING_TO_START: move = model.moves[-1] if move.is_capture(model.boards[-2]): sound = "aPlayerCaptures" else: sound = "aPlayerMoves" if model.boards[-1].board.isChecked(): sound = "aPlayerChecks" if model.players[0].__type__ == REMOTE and \ model.players[1].__type__ == REMOTE: sound = "observedMoves" preferencesDialog.SoundTab.playAction(sound) # Auto updating self.shown can be disabled. Useful for loading games. # If we are not at the latest game we are probably browsing the history, # and we won't like auto updating. if self.autoUpdateShown and self.shown+1 >= model.ply: self.shown = model.ply # Rotate board if conf.get("autoRotate", True): if self.model.players and self.model.curplayer.__type__ == LOCAL: self.rotation = self.model.boards[-1].color * pi def moves_undoing (self, model, moves): if model.boards == model.variations[0]: self.shown = model.ply-moves else: # Go back to the mainline to let animation system work board = model.getBoardAtPly(self.shown) while board not in model.variations[0]: board = model.boards[board.ply-model.lowply-1] self.shown = board.ply self.model.boards = self.model.variations[0] self.shown = model.ply-moves def game_loading (self, model, uri): self.autoUpdateShown = False def game_loaded (self, model, uri): self.autoUpdateShown = True self._shown = model.ply def game_ended (self, model, reason): self.redraw_canvas() if self.model.players: sound = False if model.status == DRAW: sound = "gameIsDrawn" elif model.status == WHITEWON: if model.players[0].__type__ == LOCAL: sound = "gameIsWon" elif model.players[1].__type__ == LOCAL: sound = "gameIsLost" elif model.status == BLACKWON: if model.players[1].__type__ == LOCAL: sound = "gameIsWon" elif model.players[0].__type__ == LOCAL: sound = "gameIsLost" elif model.status in (ABORTED, KILLED): sound = "gameIsLost" if model.status in (DRAW, WHITEWON, BLACKWON, KILLED, ABORTED) and \ model.players[0].__type__ == REMOTE and \ model.players[1].__type__ == REMOTE: sound = "oberservedEnds" # This should never be false, unless status is set to UNKNOWN or # something strange if sound: preferencesDialog.SoundTab.playAction(sound) def on_show_cords (self, *args): self.showCords = conf.get("showCords", False) def on_face_to_face (self, *args): self.redraw_canvas() ############################### # Animation # ############################### def paintBoxAround(self, move): paintBox = self.cord2RectRelative(move.cord0) paintBox = join(paintBox, self.cord2RectRelative(move.cord1)) if move.flag in (KING_CASTLE, QUEEN_CASTLE): y = move.cord0.cy color = (y == 1) rsqs = self.model.boards[-1].board.ini_rooks[color] if move.flag == KING_CASTLE: paintBox = join(paintBox, self.cord2RectRelative(Cord(rsqs[1]))) paintBox = join(paintBox, self.cord2RectRelative(Cord("f" + y))) paintBox = join(paintBox, self.cord2RectRelative(Cord("g" + y))) else: paintBox = join(paintBox, self.cord2RectRelative(Cord(rsqs[0]))) paintBox = join(paintBox, self.cord2RectRelative(Cord("c" + y))) paintBox = join(paintBox, self.cord2RectRelative(Cord("d" + y))) return paintBox def _get_shown(self): return self._shown def _set_shown(self, shown): # We don't do anything if we are already showing the right ply if shown == self._shown: return # This would cause IndexErrors later if not self.model.lowply <= shown <= self.model.ply: return # If there is only one board, we don't do any animation, but simply # redraw the entire board. Same if we are at first draw. if len(self.model.boards) == 1 or self.shown < self.model.lowply: self._shown = shown if shown > self.model.lowply: self.lastMove = self.model.getMoveAtPly(shown-1) self.emit("shown_changed", self.shown) self.redraw_canvas() return step = shown > self.shown and 1 or -1 self.animationLock.acquire() try: deadset = set() for i in xrange(self.shown, shown, step): board = self.model.getBoardAtPly(i) board1 = self.model.getBoardAtPly(i + step) if step == 1: move = self.model.getMoveAtPly(i) moved, new, dead = board.simulateMove(board1, move) else: move = self.model.getMoveAtPly(i-1) moved, new, dead = board.simulateUnmove(board1, move) # We need to ensure, that the piece coordinate is saved in the # piece for piece, cord0 in moved: # Test if the piece already has a realcoord (has been dragged) if piece.x == None: # We don't want newly restored pieces to flew from their # deadspot to their old position, as it doesn't work # vice versa if piece.opacity == 1: piece.x = cord0.x piece.y = cord0.y for piece in dead: deadset.add(piece) # Reset the location of the piece to avoid a small visual # jump, when it is at some other time waken to life. piece.x = None piece.y = None for piece in new: piece.opacity = 0 finally: self.animationLock.release() self.deadlist = [] for y, row in enumerate(self.model.getBoardAtPly(self.shown).data): for x, piece in enumerate(row): if piece in deadset: self.deadlist.append((piece,x,y)) self._shown = shown self.emit("shown_changed", self.shown) self.animationStart = time() if self.lastMove: paintBox = self.paintBoxAround(self.lastMove) self.lastMove = None self.redraw_canvas(rect(paintBox)) if self.shown > self.model.lowply: self.lastMove = self.model.getMoveAtPly(self.shown-1) else: self.lastMove = None # Back to the main line if needed... stayInVariation = True if self.model.boards != self.model.variations[0]: if self.model.isMainlineBoard(self.shown): self.model.boards = self.model.variations[0] stayInVariation = False self.runAnimation(redrawMisc=stayInVariation) repeat(self.runAnimation) shown = property(_get_shown, _set_shown) def runAnimation (self, redrawMisc=False): """ The animationsystem in pychess is very loosely inspired by the one of chessmonk. The idea is, that every piece has a place in an array (the board.data one) for where to be drawn. If a piece is to be animated, it can set its x and y properties, to some cord (or part cord like 0.42 for 42% right to file 0). Each time runAnimation is run, it will set those x and y properties a little closer to the location in the array. When it has reached its final location, x and y will be set to None. _set_shown, which starts the animation, also sets a timestamp for the acceleration to work properply. """ self.animationLock.acquire() try: paintBox = None mod = min(1, (time()-self.animationStart)/ANIMATION_TIME) board = self.model.getBoardAtPly(self.shown) for y, row in enumerate(board.data): for x, piece in enumerate(row): if not piece: continue if piece == self.draggedPiece: continue if piece.x != None: if not conf.get("noAnimation", False): if piece.piece == KNIGHT: #print mod, x, piece.x newx = piece.x + (x-piece.x)*mod**(1.5) newy = piece.y + (y-piece.y)*mod else: newx = piece.x + (x-piece.x)*mod newy = piece.y + (y-piece.y)*mod else: newx, newy = x, y paintBox = join(paintBox, self.cord2RectRelative(piece.x, piece.y)) paintBox = join(paintBox, self.cord2RectRelative(newx, newy)) if (newx <= x <= piece.x or newx >= x >= piece.x) and \ (newy <= y <= piece.y or newy >= y >= piece.y) or \ abs(newx-x) < 0.005 and abs(newy-y) < 0.005: piece.x = None piece.y = None else: piece.x = newx piece.y = newy if piece.opacity < 1: if piece.x != None: px = piece.x py = piece.y else: px = x py = y if paintBox: paintBox = join(paintBox,self.cord2RectRelative(px, py)) else: paintBox = self.cord2RectRelative(px, py) if not conf.get("noAnimation", False): newOp = piece.opacity + (1-piece.opacity)*mod else: newOp = 1 if newOp >= 1 >= piece.opacity or abs(1-newOp) < 0.005: piece.opacity = 1 else: piece.opacity = newOp for i, (piece, x, y) in enumerate(self.deadlist): if not paintBox: paintBox = self.cord2RectRelative(x, y) else: paintBox = join(paintBox, self.cord2RectRelative(x, y)) if not conf.get("noAnimation", False): newOp = piece.opacity + (0-piece.opacity)*mod else: newOp = 0 if newOp <= 0 <= piece.opacity or abs(0-newOp) < 0.005: del self.deadlist[i] else: piece.opacity = newOp finally: self.animationLock.release() if redrawMisc: for cord in (self.selected, self.hover, self.active): if cord: paintBox = join(paintBox, self.cord2RectRelative(cord)) for arrow in (self.redarrow, self.greenarrow, self.bluearrow): if arrow: paintBox = join(paintBox, self.cord2RectRelative(arrow[0])) paintBox = join(paintBox, self.cord2RectRelative(arrow[1])) if self.lastMove: paintBox = join(paintBox, self.paintBoxAround(self.lastMove)) if paintBox: self.redraw_canvas(rect(paintBox)) return paintBox and True or False def startAnimation (self): self.animationStart = time() self.runAnimation(redrawMisc = True) repeat(self.runAnimation) ############################# # Drawing # ############################# def on_realized (self, widget): p = (1-self.padding) alloc = self.get_allocation() square = float(min(alloc.width, alloc.height))*p xc = alloc.width/2. - square/2 yc = alloc.height/2. - square/2 s = square/8 self.square = (xc, yc, square, s) def expose(self, widget, event): context = widget.window.cairo_create() #r = (event.area.x, event.area.y, event.area.width, event.area.height) #context.rectangle(r[0]-.5, r[1]-.5, r[2]+1, r[3]+1) #context.clip() if False: import profile profile.runctx("self.draw(context, event.area)", locals(), globals(), "/tmp/pychessprofile") from pstats import Stats s = Stats("/tmp/pychessprofile") s.sort_stats('cumulative') s.print_stats() else: self.drawcount += 1 start = time() self.animationLock.acquire() self.draw(context, event.area) self.animationLock.release() self.drawtime += time() - start #if self.drawcount % 100 == 0: # print "Average FPS: %0.3f - %d / %d" % \ # (self.drawcount/self.drawtime, self.drawcount, self.drawtime) return False ############################################################################ # drawing functions # ############################################################################ ############################### # redraw_canvas # ############################### def redraw_canvas(self, r=None, queue=False): if self.window: glock.acquire() try: if self.window: if not r: alloc = self.get_allocation() r = gtk.gdk.Rectangle(0, 0, alloc.width, alloc.height) assert type(r[2]) == int if queue: self.queue_draw_area(r.x, r.y, r.width, r.height) else: self.window.invalidate_rect(r, True) self.window.process_updates(True) finally: glock.release() ############################### # draw # ############################### def draw (self, context, r): #context.set_antialias (cairo.ANTIALIAS_NONE) if self.shown < self.model.lowply: print "exiting cause to lowlpy", self.shown, self.model.lowply return alloc = self.get_allocation() self.matrix, self.invmatrix = matrixAround( self.matrix, alloc.width/2., alloc.height/2.) cos_, sin_ = self.matrix[0], self.matrix[1] context.transform(self.matrix) square = float(min(alloc.width, alloc.height))*(1-self.padding) if SCALE_ROTATED_BOARD: square /= abs(cos_)+abs(sin_) xc = alloc.width/2. - square/2 yc = alloc.height/2. - square/2 s = square/8 self.square = (xc, yc, square, s) self.drawBoard (context, r) if min(alloc.width, alloc.height) > 32: self.drawCords (context, r) if self.gotStarted: self.drawSpecial (context, r) self.drawEnpassant (context, r) self.drawArrows (context) self.animationLock.acquire() try: self.drawPieces (context, r) finally: self.animationLock.release() self.drawLastMove (context, r) if self.model.status == KILLED: self.drawCross (context, r) # Unselect to mark redrawn areas - for debugging purposes #context.transform(self.invmatrix) #context.rectangle(r.x,r.y,r.width,r.height) #dc = self.drawcount*50 #dc = dc % 1536 #c = dc % 256 / 255. #if dc < 256: # context.set_source_rgb(1,c,0) #elif dc < 512: # context.set_source_rgb(1-c,1,0) #elif dc < 768: # context.set_source_rgb(0,1,c) #elif dc < 1024: # context.set_source_rgb(0,1-c,1) #elif dc < 1280: # context.set_source_rgb(c,0,1) #elif dc < 1536: # context.set_source_rgb(1,0,1-c) #context.stroke() ############################### # drawCords # ############################### def drawCords (self, context, r): thickness = 0.01 signsize = 0.04 if not self.showCords: return xc, yc, square, s = self.square if contains(rect((xc, yc, square)), r): return t = thickness*square ss = signsize*square context.rectangle(xc-t*1.5,yc-t*1.5,square+t*3,square+t*3) context.set_source_color(self.get_style().dark[gtk.STATE_NORMAL]) context.set_line_width(t) context.set_line_join(gtk.gdk.JOIN_ROUND) context.stroke() pangoScale = float(pango.SCALE) def paint (inv): for n in xrange(8): rank = inv and n+1 or 8-n layout = self.create_pango_layout("%d" % rank) layout.set_font_description( pango.FontDescription("bold %d" % ss)) w = layout.get_extents()[1][2]/pangoScale h = layout.get_extents()[0][3]/pangoScale # Draw left side context.move_to(xc-t*2.5-w, s*n+yc+h/2+t) context.show_layout(layout) # Draw right side #context.move_to(xc+square+t*2.5, s*n+yc+h/2+t) #context.show_layout(layout) file = inv and 8-n or n+1 layout = self.create_pango_layout(chr(file+ord("A")-1)) layout.set_font_description( pango.FontDescription("bold %d" % ss)) w = layout.get_pixel_size()[0] h = layout.get_pixel_size()[1] y = layout.get_extents()[1][1]/pangoScale # Draw top #context.move_to(xc+s*n+s/2.-w/2., yc-h-t*1.5) #context.show_layout(layout) # Draw bottom context.move_to(xc+s*n+s/2.-w/2., yc+square+t*1.5+abs(y)) context.show_layout(layout) matrix, invmatrix = matrixAround( self.matrixPi, xc+square/2., yc+square/2.) paint(False) context.transform(matrix) paint(True) context.transform(invmatrix) ############################### # drawBoard # ############################### def drawBoard(self, context, r): xc, yc, square, s = self.square for x in xrange(8): for y in xrange(8): if x % 2 + y % 2 == 1: bounding = self.cord2RectRelative((xc+x*s,yc+y*s,s)) if intersects(rect(bounding), r): context.rectangle(xc+x*s,yc+y*s,s,s) context.set_source_color(self.get_style().dark[gtk.STATE_NORMAL]) context.fill() ############################### # drawPieces # ############################### def getCordMatrices (self, x, y, inv=False): xc, yc, square, s = self.square square_, rot_ = self.cordMatricesState if square != self.square or rot_ != self.rotation: self.cordMatrices = [None] * 64 self.cordMatricesState = (self.square, self.rotation) c = x * 8 + y if type(c) == int and self.cordMatrices[c]: matrices = self.cordMatrices[c] else: cx, cy = self.cord2Point(x,y) matrices = matrixAround(self.matrix, cx+s/2., cy+s/2.) matrices += (cx, cy) if type(c) == int: self.cordMatrices[c] = matrices return matrices def __drawPiece(self, context, piece, x, y): xc, yc, square, s = self.square if not conf.get("faceToFace", False): matrix, invmatrix, cx, cy = self.getCordMatrices(x, y) else: cx, cy = self.cord2Point(x,y) if piece.color == BLACK: matrix, invmatrix = matrixAround((-1,0), cx+s/2., cy+s/2.) else: matrix = invmatrix = cairo.Matrix(1,0,0,1,0,0) context.transform(invmatrix) drawPiece( piece, context, cx+CORD_PADDING, cy+CORD_PADDING, s-CORD_PADDING*2) context.transform(matrix) def drawPieces(self, context, r): pieces = self.model.getBoardAtPly(self.shown) xc, yc, square, s = self.square parseC = lambda c: (c.red/65535., c.green/65535., c.blue/65535.) fgN = parseC(self.get_style().fg[gtk.STATE_NORMAL]) fgS = fgN fgA = parseC(self.get_style().fg[gtk.STATE_ACTIVE]) fgP = parseC(self.get_style().fg[gtk.STATE_PRELIGHT]) # As default we use normal foreground for selected cords, as it looks # less confusing. However for some themes, the normal foreground is so # similar to the selected background, that we have to use the selected # foreground. bgSl = parseC(self.get_style().bg[gtk.STATE_SELECTED]) bgSd = parseC(self.get_style().dark[gtk.STATE_SELECTED]) if min((fgN[0]-bgSl[0])**2+(fgN[1]-bgSl[1])**2+(fgN[2]-bgSl[2])**2, (fgN[0]-bgSd[0])**2+(fgN[1]-bgSd[1])**2+(fgN[2]-bgSd[2])**2) < 0.2: fgS = parseC(self.get_style().fg[gtk.STATE_SELECTED]) # Draw dying pieces (Found in self.deadlist) for piece, x, y in self.deadlist: context.set_source_rgba(fgN[0],fgN[1],fgN[2],piece.opacity) self.__drawPiece(context, piece, x, y) # Draw pieces reincarnating (With opacity < 1) for y, row in enumerate(pieces.data): for x, piece in enumerate(row): if not piece or piece.opacity == 1: continue if piece.x: x, y = piece.x, piece.y context.set_source_rgba(fgN[0],fgN[1],fgN[2],piece.opacity) self.__drawPiece(context, piece, x, y) # Draw standing pieces (Only those who intersect drawn area) for y, row in enumerate(pieces.data): for x, piece in enumerate(row): if not piece or piece.x != None or piece.opacity < 1: continue if not intersects(rect(self.cord2RectRelative(x,y)), r): continue if Cord(x,y) == self.selected: context.set_source_rgb(*fgS) elif Cord(x,y) == self.active: context.set_source_rgb(*fgA) elif Cord(x,y) == self.hover: context.set_source_rgb(*fgP) else: context.set_source_rgb(*fgN) self.__drawPiece(context, piece, x, y) context.set_source_rgb(*fgP) # Draw moving or dragged pieces (Those with piece.x and piece.y != None) for y, row in enumerate(pieces.data): for x, piece in enumerate(row): if not piece or piece.x == None or piece.opacity < 1: continue self.__drawPiece(context, piece, piece.x, piece.y) ############################### # drawSpecial # ############################### def drawSpecial (self, context, redrawn): used = [] for cord, state in ((self.active, gtk.STATE_ACTIVE), (self.selected, gtk.STATE_SELECTED), (self.hover, gtk.STATE_PRELIGHT)): if not cord: continue if cord in used: continue # Ensure that same cord, if having multiple "tasks", doesn't get # painted more than once used.append(cord) bounding = self.cord2RectRelative(cord) if not intersects(rect(bounding), redrawn): continue xc, yc, square, s = self.square x, y = self.cord2Point(cord) context.rectangle(x, y, s, s) if self.isLight(cord): style = self.get_style().bg else: style = self.get_style().dark context.set_source_color(style[state]) context.fill() ############################### # drawLastMove # ############################### def drawLastMove (self, context, redrawn): if not self.lastMove: return if self.shown <= self.model.lowply: return show_board = self.model.getBoardAtPly(self.shown) last_board = self.model.getBoardAtPly(self.shown - 1) capture = self.lastMove.is_capture(last_board) wh = 0.27 # Width of marker p0 = 0.155 # Padding on last cord p1 = 0.085 # Padding on current cord sw = 0.02 # Stroke width xc, yc, square, s = self.square context.save() context.set_line_width(sw*s) d0 = {-1:1-p0,1:p0} d1 = {-1:1-p1,1:p1} ms = ((1,1),(-1,1),(-1,-1),(1,-1)) light_yellow = (.929, .831, 0, 0.8) dark_yellow = (.769, .627, 0, 0.5) light_orange = (.961, .475, 0, 0.8) dark_orange = (.808, .361, 0, 0.5) if self.lastMove.flag in (KING_CASTLE, QUEEN_CASTLE): ksq0 = last_board.board.kings[last_board.color] ksq1 = show_board.board.kings[last_board.color] if self.lastMove.flag == KING_CASTLE: rsq0 = show_board.board.ini_rooks[last_board.color][1] rsq1 = ksq1 - 1 else: rsq0 = show_board.board.ini_rooks[last_board.color][0] rsq1 = ksq1 + 1 cord_pairs = [ [Cord(ksq0), Cord(ksq1)], [Cord(rsq0), Cord(rsq1)] ] else: cord_pairs = [ [self.lastMove.cord0, self.lastMove.cord1] ] for [cord0, cord1] in cord_pairs: rel = self.cord2RectRelative(cord0) if intersects(rect(rel), redrawn): r = self.cord2Rect(cord0) for m in ms: context.move_to( r[0]+(d0[m[0]]+wh*m[0])*r[2], r[1]+(d0[m[1]]+wh*m[1])*r[2]) context.rel_line_to( 0, -wh*r[2]*m[1]) context.rel_curve_to( 0, wh*r[2]*m[1]/2.0, -wh*r[2]*m[0]/2.0, wh*r[2]*m[1], -wh*r[2]*m[0], wh*r[2]*m[1]) context.close_path() context.set_source_rgba(*light_yellow) context.fill_preserve() context.set_source_rgba(*dark_yellow) context.stroke() rel = self.cord2RectRelative(cord1) if intersects(rect(rel), redrawn): r = self.cord2Rect(cord1) for m in ms: context.move_to( r[0]+d1[m[0]]*r[2], r[1]+d1[m[1]]*r[2]) context.rel_line_to( wh*r[2]*m[0], 0) context.rel_curve_to( -wh*r[2]*m[0]/2.0, 0, -wh*r[2]*m[0], wh*r[2]*m[1]/2.0, -wh*r[2]*m[0], wh*r[2]*m[1]) context.close_path() if capture: context.set_source_rgba(*light_orange) context.fill_preserve() context.set_source_rgba(*dark_orange) context.stroke() else: context.set_source_rgba(*light_yellow) context.fill_preserve() context.set_source_rgba(*dark_yellow) context.stroke() ############################### # drawArrows # ############################### def __drawArrow (self, context, cords, aw, ahw, ahh, asw, fillc, strkc): context.save() lvx = cords[1].x-cords[0].x lvy = cords[0].y-cords[1].y l = float((lvx**2+lvy**2)**.5) vx = lvx/l vy = lvy/l v1x = -vy v1y = vx r = self.cord2Rect(cords[0]) px = r[0]+r[2]/2.0 py = r[1]+r[2]/2.0 ax = v1x*r[2]*aw/2 ay = v1y*r[2]*aw/2 context.move_to(px+ax, py+ay) p1x = px+(lvx-vx*ahh)*r[2] p1y = py+(lvy-vy*ahh)*r[2] context.line_to(p1x+ax, p1y+ay) lax = v1x*r[2]*ahw/2 lay = v1y*r[2]*ahw/2 context.line_to(p1x+lax, p1y+lay) context.line_to(px+lvx*r[2], py+lvy*r[2]) context.line_to(p1x-lax, p1y-lay) context.line_to(p1x-ax, p1y-ay) context.line_to(px-ax, py-ay) context.close_path() context.set_source_rgba(*fillc) context.fill_preserve() context.set_line_join(gtk.gdk.JOIN_ROUND) context.set_line_width(asw*r[2]) context.set_source_rgba(*strkc) context.stroke() context.restore() def drawArrows (self, context): # TODO: Only redraw when intersecting with the redrawn area aw = 0.3 # Arrow width ahw = 0.72 # Arrow head width ahh = 0.64 # Arrow head height asw = 0.08 # Arrow stroke width if self.bluearrow: self.__drawArrow(context, self.bluearrow, aw, ahw, ahh, asw, (.447,.624,.812,0.9), (.204,.396,.643,1)) if self.shown != self.model.ply or \ self.model.boards != self.model.variations[0]: return if self.greenarrow: self.__drawArrow(context, self.greenarrow, aw, ahw, ahh, asw, (.54,.886,.2,0.9), (.306,.604,.024,1)) if self.redarrow: self.__drawArrow(context, self.redarrow, aw, ahw, ahh, asw, (.937,.16,.16,0.9), (.643,0,0,1)) ############################### # drawEnpassant # ############################### def drawEnpassant (self, context, redrawn): if not self.showEnpassant: return enpassant = self.model.boards[-1].enpassant if not enpassant: return context.set_source_rgb(0, 0, 0) xc, yc, square, s = self.square x, y = self.cord2Point(enpassant) if not intersects(rect((x, y, s, s)), redrawn): return x, y = self.cord2Point(enpassant) cr = context cr.set_font_size(s/2.) fascent, fdescent, fheight, fxadvance, fyadvance = cr.font_extents() chars = "en" xbearing, ybearing, width, height, xadvance, yadvance = \ cr.text_extents(chars) cr.move_to(x + s / 2. - xbearing - width / 2.-1, s / 2. + y - fdescent + fheight / 2.) cr.show_text(chars) ############################### # drawCross # ############################### def drawCross (self, context, redrawn): xc, yc, square, s = self.square context.move_to(xc, yc) context.rel_line_to(square, square) context.move_to(xc+square, yc) context.rel_line_to(-square, square) context.set_line_cap(cairo.LINE_CAP_SQUARE) context.set_source_rgba(0,0,0,0.65) context.set_line_width(s) context.stroke_preserve() context.set_source_rgba(1,0,0,0.8) context.set_line_width(s/2.) context.stroke() ############################################################################ # Attributes # ############################################################################ ############################### # Cord vars # ############################### def _set_selected (self, cord): self._active = None if self._selected == cord: return if self._selected: r = rect(self.cord2RectRelative(self._selected)) if cord: r = r.union(rect(self.cord2RectRelative(cord))) elif cord: r = rect(self.cord2RectRelative(cord)) self._selected = cord self.redraw_canvas(r) def _get_selected (self): return self._selected selected = property(_get_selected, _set_selected) def _set_hover (self, cord): if self._hover == cord: return if self._hover: r = rect(self.cord2RectRelative(self._hover)) if cord: r = r.union(rect(self.cord2RectRelative(cord))) elif cord: r = rect(self.cord2RectRelative(cord)) self._hover = cord self.redraw_canvas(r) def _get_hover (self): return self._hover hover = property(_get_hover, _set_hover) def _set_active (self, cord): if self._active == cord: return if self._active: r = rect(self.cord2RectRelative(self._active)) if cord: r = r.union(rect(self.cord2RectRelative(cord))) elif cord: r = rect(self.cord2RectRelative(cord)) self._active = cord self.redraw_canvas(r) def _get_active (self): return self._active active = property(_get_active, _set_active) ################################ # Arrow vars # ################################ def _set_redarrow (self, cords): if cords == self._redarrow: return paintCords = [] if cords: paintCords += cords if self._redarrow: paintCords += self._redarrow r = rect(self.cord2RectRelative(paintCords[0])) for cord in paintCords[1:]: r = r.union(rect(self.cord2RectRelative(cord))) self._redarrow = cords self.redraw_canvas(r) def _get_redarrow (self): return self._redarrow redarrow = property(_get_redarrow, _set_redarrow) def _set_greenarrow (self, cords): if cords == self._greenarrow: return paintCords = [] if cords: paintCords += cords if self._greenarrow: paintCords += self._greenarrow r = rect(self.cord2RectRelative(paintCords[0])) for cord in paintCords[1:]: r = r.union(rect(self.cord2RectRelative(cord))) self._greenarrow = cords self.redraw_canvas(r) def _get_greenarrow (self): return self._greenarrow greenarrow = property(_get_greenarrow, _set_greenarrow) def _set_bluearrow (self, cords): if cords == self._bluearrow: return paintCords = [] if cords: paintCords += cords if self._bluearrow: paintCords += self._bluearrow r = rect(self.cord2RectRelative(paintCords[0])) for cord in paintCords[1:]: r = r.union(rect(self.cord2RectRelative(cord))) self._bluearrow = cords self.redraw_canvas(r) def _get_bluearrow (self): return self._bluearrow bluearrow = property(_get_bluearrow, _set_bluearrow) ################################ # Other vars # ################################ def _set_rotation (self, radians): if not conf.get("fullAnimation", True): glock.acquire() try: self._rotation = radians self.nextRotation = radians self.matrix = cairo.Matrix.init_rotate(radians) self.redraw_canvas() finally: glock.release() else: if hasattr(self, "nextRotation") and \ self.nextRotation != self.rotation: return self.nextRotation = radians oldr = self.rotation start = time() def callback (): glock.acquire() try: amount = (time()-start)/ANIMATION_TIME if amount > 1: amount = 1 next = False else: next = True self._rotation = new = oldr + amount*(radians-oldr) self.matrix = cairo.Matrix.init_rotate(new) self.redraw_canvas() finally: glock.release() return next repeat(callback) def _get_rotation (self): return self._rotation rotation = property(_get_rotation, _set_rotation) def _set_showCords (self, showCords): if not showCords: self.padding = 0 else: self.padding = self.pad self._showCords = showCords self.redraw_canvas() def _get_showCords (self): return self._showCords showCords = property(_get_showCords, _set_showCords) def _set_showEnpassant (self, showEnpassant): if self._showEnpassant == showEnpassant: return if self.model: enpascord = self.model.boards[-1].enpassant if enpascord: r = rect(self.cord2RectRelative(enpascord)) self.redraw_canvas(r) self._showEnpassant = showEnpassant def _get_showEnpassant (self): return self._showEnpassant showEnpassant = property(_get_showEnpassant, _set_showEnpassant) ########################### # Other # ########################### def cord2Rect (self, cord, y=None): if y == None: x, y = cord.x, cord.y else: x = cord xc, yc, square, s = self.square r = (xc+x*s, yc+(7-y)*s, s) return r def cord2Point (self, cord, y=None): r = self.cord2Rect(cord, y) return r[:2] def cord2RectRelative (self, cord, y=None): """ Like cord2Rect, but gives you bounding rect in case board is beeing Rotated """ if type(cord) == tuple: cx, cy, s = cord else: cx, cy, s = self.cord2Rect(cord, y) x0, y0 = self.matrix.transform_point(cx, cy) x1, y1 = self.matrix.transform_point(cx+s, cy) x2, y2 = self.matrix.transform_point(cx, cy+s) x3, y3 = self.matrix.transform_point(cx+s, cy+s) x = min(x0, x1, x2, x3) y = min(y0, y1, y2, y3) s = max(y0, y1, y2, y3) - y return (x, y, s) def isLight (self, cord): x, y = cord.cords return x % 2 + y % 2 == 1 def runWhenReady (self, func, *args): """ As some pieces of pychess are quite eager to set the attributes of BoardView, we can't always be sure, that BoardView has been painted once before, and therefore self.sqaure has been set. This might be doable in a smarter way... """ def do2(): if not self.square: sleep(0.01) return True func(*args) repeat(do2) def showFirst (self): self.shown = self.model.lowply def showPrevious (self): if self.shown > self.model.lowply: self.shown -= 1 def showNext (self): if self.shown < self.model.ply: self.shown += 1 def showLast (self): self.shown = self.model.ply
Python
""" This module handles the tabbed layout in PyChess """ from BoardControl import BoardControl from ChessClock import ChessClock from MenuItemsDict import MenuItemsDict from pychess.System import glock, conf, prefix from pychess.System.Log import log from pychess.System.glock import glock_connect from pychess.System.prefix import addUserConfigPrefix from pychess.System.uistuff import makeYellow from pychess.Utils.GameModel import GameModel from pychess.Utils.IconLoader import load_icon from pychess.Utils.const import * from pychess.Utils.logic import playerHasMatingMaterial, isClaimableDraw from pychess.ic.ICGameModel import ICGameModel from pydock.PyDockTop import PyDockTop from pydock.__init__ import CENTER, EAST, SOUTH import cStringIO import gtk import gobject import imp import os import traceback ################################################################################ # Initialize modul constants, and a few worker functions # ################################################################################ def createAlignment (top, right, bottom, left): align = gtk.Alignment(.5, .5, 1, 1) align.set_property("top-padding", top) align.set_property("right-padding", right) align.set_property("bottom-padding", bottom) align.set_property("left-padding", left) return align def cleanNotebook (): notebook = gtk.Notebook() notebook.set_show_tabs(False) notebook.set_show_border(False) return notebook def createImage (pixbuf): image = gtk.Image() image.set_from_pixbuf(pixbuf) return image light_on = load_icon(16, "stock_3d-light-on", "weather-clear") light_off = load_icon(16, "stock_3d-light-off", "weather-clear-night") gtk_close = load_icon(16, "gtk-close") media_previous = load_icon(16, "gtk-media-previous-ltr") media_rewind = load_icon(16, "gtk-media-rewind-ltr") media_forward = load_icon(16, "gtk-media-forward-ltr") media_next = load_icon(16, "gtk-media-next-ltr") path = prefix.addDataPrefix("sidepanel") postfix = "Panel.py" files = [f[:-3] for f in os.listdir(path) if f.endswith(postfix)] sidePanels = [imp.load_module(f, *imp.find_module(f, [path])) for f in files] pref_sidePanels = [] for panel in sidePanels: if conf.get(panel.__name__, True): pref_sidePanels.append(panel) ################################################################################ # Initialize module variables # ################################################################################ widgets = None def setWidgets (w): global widgets widgets = w def getWidgets (): return widgets key2gmwidg = {} notebooks = {"board": cleanNotebook(), "statusbar": cleanNotebook(), "messageArea": cleanNotebook()} for panel in sidePanels: notebooks[panel.__name__] = cleanNotebook() docks = {"board": (gtk.Label("Board"), notebooks["board"])} ################################################################################ # The holder class for tab releated widgets # ################################################################################ class GameWidget (gobject.GObject): __gsignals__ = { 'close_clicked': (gobject.SIGNAL_RUN_FIRST, None, ()), 'infront': (gobject.SIGNAL_RUN_FIRST, None, ()), 'title_changed': (gobject.SIGNAL_RUN_FIRST, None, ()), 'closed': (gobject.SIGNAL_RUN_FIRST, None, ()), } def __init__ (self, gamemodel): gobject.GObject.__init__(self) self.gamemodel = gamemodel tabcontent = self.initTabcontents() boardvbox, board, messageSock = self.initBoardAndClock(gamemodel) statusbar, stat_hbox = self.initStatusbar(board) self.tabcontent = tabcontent self.board = board self.statusbar = statusbar self.messageSock = messageSock self.notebookKey = gtk.Label(); self.notebookKey.set_size_request(0,0) self.boardvbox = boardvbox self.stat_hbox = stat_hbox self.menuitems = MenuItemsDict(self) gamemodel.connect("game_started", self.game_started) gamemodel.connect("game_ended", self.game_ended) gamemodel.connect("game_changed", self.game_changed) gamemodel.connect("game_paused", self.game_paused) gamemodel.connect("game_resumed", self.game_resumed) gamemodel.connect("moves_undone", self.moves_undone) gamemodel.connect("game_unended", self.game_unended) gamemodel.connect("players_changed", self.players_changed) self.players_changed(gamemodel) if gamemodel.timemodel: gamemodel.timemodel.connect("zero_reached", self.zero_reached) # Some stuff in the sidepanels .load functions might change UI, so we # need glock # TODO: Really? glock.acquire() try: self.panels = [panel.Sidepanel().load(self) for panel in sidePanels] finally: glock.release() def __del__ (self): self.board.__del__() def _update_menu_abort (self): if self.gamemodel.isObservationGame(): self.menuitems["abort"].sensitive = False elif isinstance(self.gamemodel, ICGameModel) \ and self.gamemodel.status in UNFINISHED_STATES: if self.gamemodel.ply < 2: self.menuitems["abort"].label = _("Abort") self.menuitems["abort"].tooltip = \ _("This game can be automatically aborted without rating loss because there has not yet been two moves made") else: self.menuitems["abort"].label = _("Offer Abort") self.menuitems["abort"].tooltip = \ _("Your opponent must agree to abort the game because there has been two or more moves made") self.menuitems["abort"].sensitive = True else: self.menuitems["abort"].sensitive = False self.menuitems["abort"].tooltip = "" def _update_menu_adjourn (self): self.menuitems["adjourn"].sensitive = \ isinstance(self.gamemodel, ICGameModel) and \ self.gamemodel.status in UNFINISHED_STATES and \ not self.gamemodel.isObservationGame() and \ not self.gamemodel.hasGuestPlayers() if isinstance(self.gamemodel, ICGameModel) and \ self.gamemodel.status in UNFINISHED_STATES and \ not self.gamemodel.isObservationGame() and \ self.gamemodel.hasGuestPlayers(): self.menuitems["adjourn"].tooltip = \ _("This game can not be adjourned because one or both players are guests") else: self.menuitems["adjourn"].tooltip = "" def _update_menu_draw (self): self.menuitems["draw"].sensitive = self.gamemodel.status in UNFINISHED_STATES \ and not self.gamemodel.isObservationGame() def can_win (color): if self.gamemodel.timemodel: return playerHasMatingMaterial(self.gamemodel.boards[-1], color) and \ self.gamemodel.timemodel.getPlayerTime(color) > 0 else: return playerHasMatingMaterial(self.gamemodel.boards[-1], color) if isClaimableDraw(self.gamemodel.boards[-1]) or not \ (can_win(self.gamemodel.players[0].color) or \ can_win(self.gamemodel.players[1].color)): self.menuitems["draw"].label = _("Claim Draw") def _update_menu_resign (self): self.menuitems["resign"].sensitive = self.gamemodel.status in UNFINISHED_STATES \ and not self.gamemodel.isObservationGame() def _update_menu_pause_and_resume (self): self.menuitems["pause1"].sensitive = self.gamemodel.status == RUNNING \ and not self.gamemodel.isObservationGame() self.menuitems["resume1"].sensitive = self.gamemodel.status == PAUSED \ and not self.gamemodel.isObservationGame() # TODO: if IC game is over and opponent is available, enable Resume def _update_menu_undo (self): if self.gamemodel.isObservationGame(): self.menuitems["undo1"].sensitive = False elif isinstance(self.gamemodel, ICGameModel): if self.gamemodel.status in UNFINISHED_STATES and self.gamemodel.ply > 0: self.menuitems["undo1"].sensitive = True else: self.menuitems["undo1"].sensitive = False elif self.gamemodel.ply > 0 \ and self.gamemodel.status in UNDOABLE_STATES + (RUNNING,): self.menuitems["undo1"].sensitive = True else: self.menuitems["undo1"].sensitive = False def _update_menu_ask_to_move (self): if self.gamemodel.isObservationGame(): self.menuitems["ask_to_move"].sensitive = False elif isinstance(self.gamemodel, ICGameModel): self.menuitems["ask_to_move"].sensitive = False elif self.gamemodel.waitingplayer.__type__ == LOCAL \ and self.gamemodel.status in UNFINISHED_STATES \ and self.gamemodel.status != PAUSED: self.menuitems["ask_to_move"].sensitive = True else: self.menuitems["ask_to_move"].sensitive = False def game_started (self, gamemodel): self._update_menu_abort() self._update_menu_adjourn() self._update_menu_draw() self._update_menu_pause_and_resume() self._update_menu_resign() self._update_menu_undo() self._update_menu_ask_to_move() activate_hint = False activate_spy = False if HINT in gamemodel.spectators and not \ (isinstance(self.gamemodel, ICGameModel) and self.gamemodel.isObservationGame() is False): activate_hint = True if SPY in gamemodel.spectators and not \ (isinstance(self.gamemodel, ICGameModel) and self.gamemodel.isObservationGame() is False): activate_spy = True self.menuitems["hint_mode"].active = activate_hint self.menuitems["hint_mode"].sensitive = HINT in gamemodel.spectators self.menuitems["spy_mode"].active = activate_spy self.menuitems["spy_mode"].sensitive = SPY in gamemodel.spectators def game_ended (self, gamemodel, reason): for item in self.menuitems: self.menuitems[item].sensitive = False self._update_menu_undo() def game_changed (self, gamemodel): self._update_menu_abort() self._update_menu_ask_to_move() self._update_menu_draw() self._update_menu_pause_and_resume() self._update_menu_undo() def game_paused (self, gamemodel): self._update_menu_pause_and_resume() self._update_menu_undo() self._update_menu_ask_to_move() def game_resumed (self, gamemodel): self._update_menu_pause_and_resume() self._update_menu_undo() self._update_menu_ask_to_move() def moves_undone (self, gamemodel, moves): self.game_changed(gamemodel) def game_unended (self, gamemodel): self.game_started(gamemodel) def players_changed (self, gamemodel): for player in gamemodel.players: self.name_changed(player) # Notice that this may connect the same player many times. In # normal use that shouldn't be a problem. glock_connect(player, "name_changed", self.name_changed) @property def display_text (self): vs = " " + _("vs") + " " if isinstance(self.gamemodel, ICGameModel): ficsgame = self.gamemodel.ficsgame t = vs.join((ficsgame.wplayer.long_name(game_type=ficsgame.game_type), ficsgame.bplayer.long_name(game_type=ficsgame.game_type))) else: t = vs.join(map(repr, self.gamemodel.players)) if self.gamemodel.display_text != "": t += " " + self.gamemodel.display_text return t def name_changed (self, player): newText = self.display_text if newText != self.getTabText(): self.setTabText(newText) def zero_reached (self, timemodel, color): if self.gamemodel.status not in UNFINISHED_STATES: return if self.gamemodel.players[0].__type__ == LOCAL \ and self.gamemodel.players[1].__type__ == LOCAL: self.menuitems["call_flag"].sensitive = True return for player in self.gamemodel.players: opplayercolor = BLACK if player == self.gamemodel.players[WHITE] else WHITE if player.__type__ == LOCAL and opplayercolor == color: log.debug("gamewidget.zero_reached: LOCAL player=%s, color=%s\n" % \ (repr(player), str(color))) self.menuitems["call_flag"].sensitive = True break def initTabcontents(self): tabcontent = createAlignment(gtk.Notebook().props.tab_vborder,0,0,0) hbox = gtk.HBox() hbox.set_spacing(4) hbox.pack_start(createImage(light_off), expand=False) close_button = gtk.Button() close_button.set_property("can-focus", False) close_button.add(createImage(gtk_close)) close_button.set_relief(gtk.RELIEF_NONE) close_button.set_size_request(20, 18) close_button.connect("clicked", lambda w: self.emit("close_clicked")) hbox.pack_end(close_button, expand=False) label = gtk.Label("") label.set_alignment(0,.7) hbox.pack_end(label) tabcontent.add(hbox) tabcontent.show_all() # Gtk doesn't show tab labels when the rest is return tabcontent def initBoardAndClock(self, gamemodel): boardvbox = gtk.VBox() boardvbox.set_spacing(2) messageSock = createAlignment(0,0,0,0) makeYellow(messageSock) if gamemodel.timemodel: ccalign = createAlignment(0, 0, 0, 0) cclock = ChessClock() cclock.setModel(gamemodel.timemodel) ccalign.add(cclock) ccalign.set_size_request(-1, 32) boardvbox.pack_start(ccalign, expand=False) actionMenuDic = {} for item in ACTION_MENU_ITEMS: actionMenuDic[item] = widgets[item] board = BoardControl(gamemodel, actionMenuDic) boardvbox.pack_start(board) return boardvbox, board, messageSock def initStatusbar(self, board): def tip (widget, x, y, keyboard_mode, tooltip, text): l = gtk.Label(text) tooltip.set_custom(l) l.show() return True stat_hbox = gtk.HBox() page_vbox = gtk.VBox() page_vbox.set_spacing(1) sep = gtk.HSeparator() sep.set_size_request(-1, 2) page_hbox = gtk.HBox() startbut = gtk.Button() startbut.add(createImage(media_previous)) startbut.set_relief(gtk.RELIEF_NONE) startbut.props.has_tooltip = True startbut.connect("query-tooltip", tip, _("Jump to initial position")) backbut = gtk.Button() backbut.add(createImage(media_rewind)) backbut.set_relief(gtk.RELIEF_NONE) backbut.props.has_tooltip = True backbut.connect("query-tooltip", tip, _("Step back one move")) forwbut = gtk.Button() forwbut.add(createImage(media_forward)) forwbut.set_relief(gtk.RELIEF_NONE) forwbut.props.has_tooltip = True forwbut.connect("query-tooltip", tip, _("Step forward one move")) endbut = gtk.Button() endbut.add(createImage(media_next)) endbut.set_relief(gtk.RELIEF_NONE) endbut.props.has_tooltip = True endbut.connect("query-tooltip", tip, _("Jump to latest position")) startbut.connect("clicked", lambda w: board.view.showFirst()) backbut.connect("clicked", lambda w: board.view.showPrevious()) forwbut.connect("clicked", lambda w: board.view.showNext()) endbut.connect("clicked", lambda w: board.view.showLast()) page_hbox.pack_start(startbut) page_hbox.pack_start(backbut) page_hbox.pack_start(forwbut) page_hbox.pack_start(endbut) page_vbox.pack_start(sep) page_vbox.pack_start(page_hbox) statusbar = gtk.Statusbar() stat_hbox.pack_start(page_vbox, expand=False) stat_hbox.pack_start(statusbar) return statusbar, stat_hbox def setLocked (self, locked): """ Makes the board insensitive and turns off the tab ready indicator """ log.debug("GameWidget.setLocked: %s locked=%s\n" % (self.gamemodel.players, str(locked))) self.board.setLocked(locked) if not self.tabcontent.get_children(): return if len(self.tabcontent.child.get_children()) < 2: log.warn("GameWidget.setLocked: Not removing last tabcontent child\n") return self.tabcontent.child.remove(self.tabcontent.child.get_children()[0]) if not locked: self.tabcontent.child.pack_start(createImage(light_on), expand=False) else: self.tabcontent.child.pack_start(createImage(light_off), expand=False) self.tabcontent.show_all() log.debug("GameWidget.setLocked: %s: returning\n" % self.gamemodel.players) def setTabText (self, text): self.tabcontent.child.get_children()[1].set_text(text) self.emit('title_changed') def getTabText (self): return self.tabcontent.child.get_children()[1].get_text() def status (self, message): glock.acquire() try: self.statusbar.pop(0) if message: self.statusbar.push(0, message) finally: glock.release() def bringToFront (self): getheadbook().set_current_page(self.getPageNumber()) def isInFront(self): if not getheadbook(): return False return getheadbook().get_current_page() == self.getPageNumber() def getPageNumber (self): return getheadbook().page_num(self.notebookKey) def showMessage (self, messageDialog, vertical=False): if self.messageSock.child: self.messageSock.remove(self.messageSock.child) message = messageDialog.child.get_children()[0] hbuttonbox = messageDialog.child.get_children()[-1] if vertical: buttonbox = gtk.VButtonBox() buttonbox.props.layout_style = gtk.BUTTONBOX_SPREAD for button in hbuttonbox.get_children(): hbuttonbox.remove(button) buttonbox.add(button) else: messageDialog.child.remove(hbuttonbox) buttonbox = hbuttonbox buttonbox.props.layout_style = gtk.BUTTONBOX_SPREAD messageDialog.child.remove(message) texts = message.get_children()[1] message.set_child_packing(texts, False, False, 0, gtk.PACK_START) text1, text2 = texts.get_children() text1.props.yalign = 1 text2.props.yalign = 0 texts.set_child_packing(text1, True, True, 0, gtk.PACK_START) texts.set_child_packing(text2, True, True, 0, gtk.PACK_START) texts.set_spacing(3) message.pack_end(buttonbox, True, True) if self.messageSock.child: self.messageSock.remove(self.messageSock.child) self.messageSock.add(message) self.messageSock.show_all() if self == cur_gmwidg(): notebooks["messageArea"].show() def hideMessage (self): self.messageSock.hide() if self == cur_gmwidg(): notebooks["messageArea"].hide() ################################################################################ # Main handling of gamewidgets # ################################################################################ def splitit(widget): if not hasattr(widget, 'get_children'): return for child in widget.get_children(): splitit(child) widget.remove(child) def delGameWidget (gmwidg): """ Remove the widget from the GUI after the game has been terminated """ gmwidg.emit("closed") del key2gmwidg[gmwidg.notebookKey] pageNum = gmwidg.getPageNumber() headbook = getheadbook() headbook.remove_page(pageNum) for notebook in notebooks.values(): notebook.remove_page(pageNum) if headbook.get_n_pages() == 1 and conf.get("hideTabs", False): show_tabs(False) if headbook.get_n_pages() == 0: mainvbox = widgets["mainvbox"] centerVBox = mainvbox.get_children()[2] for child in centerVBox.get_children(): centerVBox.remove(child) mainvbox.remove(centerVBox) mainvbox.remove(mainvbox.get_children()[1]) mainvbox.pack_end(background) background.show() gmwidg.__del__() def _ensureReadForGameWidgets (): mainvbox = widgets["mainvbox"] if len(mainvbox.get_children()) == 3: return global background background = widgets["mainvbox"].get_children()[1] mainvbox.remove(background) # Initing headbook align = createAlignment (4, 4, 0, 4) align.set_property("yscale", 0) headbook = gtk.Notebook() headbook.set_scrollable(True) headbook.props.tab_vborder = 0 align.add(headbook) mainvbox.pack_start(align, expand=False) show_tabs(not conf.get("hideTabs", False)) # Initing center centerVBox = gtk.VBox() # The message area centerVBox.pack_start(notebooks["messageArea"], expand=False) def callback (notebook, gpointer, page_num): notebook.props.visible = notebook.get_nth_page(page_num).child.props.visible notebooks["messageArea"].connect("switch-page", callback) # The dock global dock, dockAlign dock = PyDockTop("main") dockAlign = createAlignment(4,4,0,4) dockAlign.add(dock) centerVBox.pack_start(dockAlign) dockAlign.show() dock.show() dockLocation = addUserConfigPrefix("pydock.xml") for panel in sidePanels: hbox = gtk.HBox() pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(panel.__icon__, 16, 16) icon = gtk.image_new_from_pixbuf(pixbuf) label = gtk.Label(panel.__title__) label.set_size_request(0, 0) label.set_alignment(0, 1) hbox.pack_start(icon, expand=False, fill=False) hbox.pack_start(label, expand=True, fill=True) hbox.set_spacing(2) hbox.show_all() def cb (widget, x, y, keyboard_mode, tooltip, title, desc, filename): table = gtk.Table(2,2) table.set_row_spacings(2) table.set_col_spacings(6) table.set_border_width(4) pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename, 56, 56) image = gtk.image_new_from_pixbuf(pixbuf) image.set_alignment(0, 0) table.attach(image, 0,1,0,2) titleLabel = gtk.Label() titleLabel.set_markup("<b>%s</b>" % title) titleLabel.set_alignment(0, 0) table.attach(titleLabel, 1,2,0,1) descLabel = gtk.Label(desc) descLabel.props.wrap = True table.attach(descLabel, 1,2,1,2) tooltip.set_custom(table) table.show_all() return True hbox.props.has_tooltip = True hbox.connect("query-tooltip", cb, panel.__title__, panel.__desc__, panel.__icon__) docks[panel.__name__] = (hbox, notebooks[panel.__name__]) if os.path.isfile(dockLocation): try: dock.loadFromXML(dockLocation, docks) except Exception, e: stringio = cStringIO.StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error("Dock loading error: %s\n%s" % (e, error)) md = gtk.MessageDialog(widgets["window1"], type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE) md.set_markup(_("<b><big>PyChess was unable to load your panel settings</big></b>")) md.format_secondary_text(_("Your panel settings have been reset. If this problem repeats, you should report it to the developers")) md.run() md.hide() os.remove(dockLocation) for title, panel in docks.values(): title.unparent() panel.unparent() if not os.path.isfile(dockLocation): leaf = dock.dock(docks["board"][1], CENTER, gtk.Label(docks["board"][0]), "board") docks["board"][1].show_all() leaf.setDockable(False) # NE leaf = leaf.dock(docks["annotationPanel"][1], EAST, docks["annotationPanel"][0], "annotationPanel") conf.set("historyPanel", True) leaf = leaf.dock(docks["historyPanel"][1], CENTER, docks["historyPanel"][0], "historyPanel") conf.set("historyPanel", True) leaf = leaf.dock(docks["scorePanel"][1], CENTER, docks["scorePanel"][0], "scorePanel") conf.set("scorePanel", True) # SE leaf = leaf.dock(docks["bookPanel"][1], SOUTH, docks["bookPanel"][0], "bookPanel") conf.set("bookPanel", True) leaf = leaf.dock(docks["commentPanel"][1], CENTER, docks["commentPanel"][0], "commentPanel") conf.set("commentPanel", True) leaf = leaf.dock(docks["chatPanel"][1], CENTER, docks["chatPanel"][0], "chatPanel") conf.set("chatPanel", True) def unrealize (dock): # unhide the panel before saving so its configuration is saved correctly notebooks["board"].get_parent().get_parent().zoomDown() dock.saveToXML(dockLocation) dock.__del__() dock.connect("unrealize", unrealize) # The status bar notebooks["statusbar"].set_border_width(4) centerVBox.pack_start(notebooks["statusbar"], expand=False) mainvbox.pack_start(centerVBox) centerVBox.show_all() mainvbox.show() # Connecting headbook to other notebooks def callback (notebook, gpointer, page_num): for notebook in notebooks.values(): notebook.set_current_page(page_num) headbook.connect("switch-page", callback) if hasattr(headbook, "set_tab_reorderable"): def page_reordered (widget, child, new_num, headbook): old_num = notebooks["board"].page_num(key2gmwidg[child].boardvbox) if old_num == -1: log.error('Games and labels are out of sync!') else: for notebook in notebooks.values(): notebook.reorder_child(notebook.get_nth_page(old_num), new_num) headbook.connect("page-reordered", page_reordered, headbook) def attachGameWidget (gmwidg): _ensureReadForGameWidgets() headbook = getheadbook() key2gmwidg[gmwidg.notebookKey] = gmwidg headbook.append_page(gmwidg.notebookKey, gmwidg.tabcontent) gmwidg.notebookKey.show_all() headbook.set_tab_label_packing(gmwidg.notebookKey, True, True, gtk.PACK_START) if hasattr(headbook, "set_tab_reorderable"): headbook.set_tab_reorderable (gmwidg.notebookKey, True) def callback (notebook, gpointer, page_num, gmwidg): if notebook.get_nth_page(page_num) == gmwidg.notebookKey: gmwidg.emit("infront") headbook.connect_after("switch-page", callback, gmwidg) gmwidg.emit("infront") messageSockAlign = createAlignment(4,4,0,4) messageSockAlign.show() messageSockAlign.add(gmwidg.messageSock) notebooks["messageArea"].append_page(messageSockAlign) notebooks["board"].append_page(gmwidg.boardvbox) gmwidg.boardvbox.show_all() for panel, instance in zip(sidePanels, gmwidg.panels): notebooks[panel.__name__].append_page(instance) instance.show_all() notebooks["statusbar"].append_page(gmwidg.stat_hbox) gmwidg.stat_hbox.show_all() # We should always show tabs if more than one exists if headbook.get_n_pages() == 2: show_tabs(True) headbook.set_current_page(-1) if headbook.get_n_pages() == 1 and not widgets["show_sidepanels"].get_active(): zoomToBoard(True) def cur_gmwidg (): headbook = getheadbook() if headbook == None: return None notebookKey = headbook.get_nth_page(headbook.get_current_page()) return key2gmwidg[notebookKey] def getheadbook (): if len(widgets["mainvbox"].get_children()) == 2: # If the headbook hasn't been added yet return None return widgets["mainvbox"].get_children()[1].child def zoomToBoard (viewZoomed): if not notebooks["board"].get_parent(): return if viewZoomed: notebooks["board"].get_parent().get_parent().zoomUp() else: notebooks["board"].get_parent().get_parent().zoomDown() def show_tabs (show): if show: widgets["mainvbox"].get_children()[1].show_all() else: widgets["mainvbox"].get_children()[1].hide() def tabsCallback (none): head = getheadbook() if not head: return if head.get_n_pages() == 1: show_tabs(not conf.get("hideTabs", False)) conf.notify_add("hideTabs", tabsCallback) ################################################################################ # Handling of the special sidepanels-design-gamewidget used in preferences # ################################################################################ designGW = None def showDesignGW(): global designGW if not designGW: designGW = GameWidget(GameModel()) if isDesignGWShown(): return getWidgets()["show_sidepanels"].set_active(True) getWidgets()["show_sidepanels"].set_sensitive(False) attachGameWidget(designGW) def hideDesignGW(): if isDesignGWShown(): delGameWidget(designGW) getWidgets()["show_sidepanels"].set_sensitive(True) def isDesignGWShown(): return designGW in key2gmwidg.values()
Python
import pygtk pygtk.require("2.0") import gtk from gobject import * from pychess.System.Log import log from pychess.Utils.IconLoader import load_icon class ToggleComboBox (gtk.ToggleButton): __gsignals__ = {'changed' : (SIGNAL_RUN_FIRST, TYPE_NONE, (TYPE_INT,))} def __init__ (self): gtk.ToggleButton.__init__(self) self.set_relief(gtk.RELIEF_NONE) self.label = label = gtk.Label() label.set_alignment(0, 0.5) self.hbox = hbox = gtk.HBox() self.image = gtk.Image() hbox.pack_start(self.image, False, False) hbox.pack_start(label) arrow = gtk.Arrow (gtk.ARROW_DOWN, gtk.SHADOW_OUT); hbox.pack_start(arrow, False, False) self.add(hbox) self.show_all() self.connect("button_press_event", self.button_press) self.connect("key_press_event", self.key_press) self.connect("scroll_event", self.scroll_event) self.menu = menu = gtk.Menu() deactivate = lambda w: self.set_active(False) menu.connect("deactivate", deactivate) menu.attach_to_widget(self, None) self.markup = "", "" self._active = -1 self._items = [] def _get_active(self): return self._active def _set_active(self, active): if type(active) != int: raise TypeError if active == self._active: return if active >= len(self._items): log.warn("Tried to set combobox to %d, but it has only got %d items" % (active, len(self._items))) return oldactive = self._active # take care the case when last used engine was uninstalled self._active = (active < len(self._items) and [active] or [1])[0] self.emit("changed", oldactive) text, icon = self._items[self._active] self.label.set_markup (self.markup[0] + text + self.markup[1]) if icon != None: self.hbox.set_spacing(6) self.image.set_from_pixbuf(icon) else: self.hbox.set_spacing(0) self.image.clear() active = property(_get_active, _set_active) def setMarkup(self, start, end): self.markup = (start, end) text = self._items[self.active][0] self.label.set_markup (self.markup[0] + text + self.markup[1]) def getMarkup(self): return self.markup def addItem (self, text, stock=None): if stock == None: item = gtk.MenuItem(text) else: item = gtk.MenuItem() label = gtk.Label(text) label.props.xalign = 0 if type(stock) == str: stock = load_icon(12, stock) image = gtk.Image() image.set_from_pixbuf(stock) hbox = gtk.HBox() hbox.set_spacing(6) hbox.pack_start(image, expand=False, fill=False) hbox.add(label) item.add(hbox) hbox.show_all() item.connect("activate", self.menu_item_activate, len(self._items)) self.menu.append(item) self._items += [(text, stock)] item.show() if self.active < 0: self.active = 0 def menuPos (self, menu): x, y = self.window.get_origin() x += self.get_allocation().x y += self.get_allocation().y + self.get_allocation().height return (x,y,False) def scroll_event (self, widget, event): if event.direction == gtk.gdk.SCROLL_UP: if self.active > 0: self.active -= 1 else: if self.active < len(self._items)-1: self.active += 1 def button_press (self, widget, event): width = self.allocation.width self.menu.set_size_request(-1,-1) ownWidth = self.menu.size_request()[0] self.menu.set_size_request(max(width,ownWidth),-1) self.set_active(True) self.menu.popup(None,None, self.menuPos, 1, event.time) from gtk.gdk import keyval_from_name keys = map(keyval_from_name,("space", "KP_Space", "Return", "KP_Enter")) def key_press (self, widget, event): if not event.keyval in self.keys: return self.set_active(True) self.menu.popup(None,None, self.menuPos, 1, event.time) return True def menu_item_activate (self, widget, index): self.active = index
Python
# -*- coding: UTF-8 -*- from math import ceil, pi, cos, sin import cairo, gtk, pango from gtk import gdk from pychess.System import glock from pychess.System.repeat import repeat_sleep from pychess.Utils.const import WHITE, BLACK class ChessClock (gtk.DrawingArea): def __init__(self): gtk.DrawingArea.__init__(self) self.connect("expose_event", self.expose) self.names = [_("White"),_("Black")] self.model = None #self.thread = None def expose(self, widget, event): context = widget.window.cairo_create() context.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) context.clip() self.draw(context) return False def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] if not self.model: return # Draw graphical Clock. Should this be moved to preferences? drawClock = True rect = self.get_allocation() context.rectangle( rect.width/2. * self.model.movingColor, 0, rect.width/2., rect.height) context.set_source_color(self.dark) context.fill_preserve() context.new_path() time0 = self.names[0], self.formatedCache[WHITE] layout0 = self.create_pango_layout(" %s: %s " % (time0)) layout0.set_font_description(pango.FontDescription("Sans Serif 17")) time1 = self.names[1], self.formatedCache[BLACK] layout1 = self.create_pango_layout(" %s: %s " % (time1)) layout1.set_font_description(pango.FontDescription("Sans Serif 17")) w = max(layout1.get_pixel_size()[0], layout0.get_pixel_size()[0])*2 self.set_size_request(w+rect.height+7, -1) pangoScale = float(pango.SCALE) # Analog clock code. def paintClock (player): cy = rect.height/2. cx = cy + rect.width/2.*player + 1 r = rect.height/2.-3.5 context.arc(cx,cy, r-1, 0, 2*pi) linear = cairo.LinearGradient(cx-r*2, cy-r*2, cx+r*2, cy+r*2) linear.add_color_stop_rgba(0, 1, 1, 1, 0.3) linear.add_color_stop_rgba(1, 0, 0, 0, 0.3) #context.set_source_rgba( 0, 0, 0, .3) context.set_source(linear) context.fill() linear = cairo.LinearGradient(cx-r, cy-r, cx+r, cy+r) linear.add_color_stop_rgba(0, 0, 0, 0, 0.5) linear.add_color_stop_rgba(1, 1, 1, 1, 0.5) context.arc(cx,cy, r, 0, 2*pi) context.set_source(linear) context.set_line_width(2.5) context.stroke() starttime = float(self.model.getInitialTime()) or 1 used = self.model.getPlayerTime(player) / starttime if used > 0: if used > 0: context.arc(cx,cy, r-.8, -(used+0.25)*2*pi, -0.5*pi) context.line_to(cx,cy) context.close_path() elif used == 0: context.arc(cx,cy, r-.8, -0.5*pi, 1.5*pi) context.line_to(cx,cy) radial = cairo.RadialGradient(cx,cy, 3, cx,cy,r) if player == 0: #radial.add_color_stop_rgb(0, .73, .74, .71) radial.add_color_stop_rgb(0, .93, .93, .92) radial.add_color_stop_rgb(1, 1, 1, 1) else: #radial.add_color_stop_rgb(0, .53, .54, .52) radial.add_color_stop_rgb(0, .18, .20, .21) radial.add_color_stop_rgb(1, 0, 0, 0) context.set_source(radial) context.fill() x = cx - cos((used-0.25)*2*pi)*(r-1) y = cy + sin((used-0.25)*2*pi)*(r-1) context.move_to(cx,cy-r+1) context.line_to(cx,cy) context.line_to(x,y) context.set_line_width(0.2) if player == 0: context.set_source_rgb(0,0,0) else: context.set_source_rgb(1,1,1) context.stroke() if drawClock: paintClock (WHITE) if (self.model.movingColor or WHITE) == WHITE: context.set_source_color(self.light) else: context.set_source_color(self.dark) y = rect.height/2. - layout0.get_extents()[0][3]/pangoScale/2 \ - layout0.get_extents()[0][1]/pangoScale context.move_to(rect.height-7,y) context.show_layout(layout0) if drawClock: paintClock (BLACK) if self.model.movingColor == BLACK: context.set_source_color(self.light) else: context.set_source_color(self.dark) y = rect.height/2. - layout1.get_extents()[0][3]/pangoScale/2 \ - layout1.get_extents()[0][1]/pangoScale context.move_to(rect.width/2. + rect.height-7, y) context.show_layout(layout1) def redraw_canvas(self): if self.window: glock.acquire() try: if self.window: a = self.get_allocation() rect = gdk.Rectangle(0, 0, a.width, a.height) self.window.invalidate_rect(rect, True) self.window.process_updates(True) finally: glock.release() def setModel (self, model): self.model = model if model != None: self.model.connect("time_changed", self.time_changed) self.model.connect("player_changed", self.player_changed) self.formatedCache = [self.formatTime ( self.model.getPlayerTime (self.model.movingColor or WHITE))] * 2 repeat_sleep(self.update, 0.1) else: self.formatedCache = None def time_changed (self, model): self.update() def player_changed (self, model): self.redraw_canvas() def update(self): wt = self.formatTime (self.model.getPlayerTime(WHITE)) bt = self.formatTime (self.model.getPlayerTime(BLACK)) if self.formatedCache != [wt, bt]: self.formatedCache = [wt, bt] self.redraw_canvas() return not self.model.ended def formatTime(self, seconds): if not -10 <= seconds <= 10: seconds = ceil(seconds) minus = seconds < 0 and "-" or "" if minus: seconds = -seconds h = int(seconds / 3600) m = int(seconds % 3600 / 60) s = seconds % 60 if h: return minus+"%d:%02d:%02d" % (h,m,s) elif not m and s < 10: return minus+"%.1f" % s else: return minus+"%d:%02d" % (m,s)
Python
import gtk import cairo from pychess.gfx.Pieces import drawPiece class PieceWidget (gtk.DrawingArea): def __init__(self, piece): gtk.DrawingArea.__init__(self) self.connect("expose_event", self.expose) self.piece = piece def setPiece(self, piece): self.piece = piece def getPiece(self): return self.piece def expose(self, widget, event): context = widget.window.cairo_create() rect = self.get_allocation() s = min(rect.width, rect.height) x = (rect.width-s) / 2.0 y = (rect.height-s) / 2.0 drawPiece(self.piece, context, x, y, s)
Python
import cairo import gtk from gtk import gdk from gobject import SIGNAL_RUN_FIRST, TYPE_NONE from pychess.System.prefix import addDataPrefix from pychess.System import glock from BorderBox import BorderBox class ChainVBox (gtk.VBox): """ Inspired by the GIMP chainbutton widget """ __gsignals__ = { 'clicked' : (SIGNAL_RUN_FIRST, TYPE_NONE, ()) } def __init__ (self): gtk.VBox.__init__(self) chainline = ChainLine(CHAIN_TOP) self.pack_start(chainline) self.button = gtk.Button() self.pack_start(self.button, expand=False) chainline = ChainLine(CHAIN_BOTTOM) self.pack_start(chainline) self.image = gtk.Image() self.image.set_from_file(addDataPrefix("glade/stock-vchain-24.png")) self.button.set_image(self.image) self.button.set_relief(gtk.RELIEF_NONE) self.button.set_property("yalign", 0) self._active = True self.button.connect("clicked", self.onClicked) def getActive (self): return self._active def setActive (self, active): assert type(active) is bool self._active = active if self._active is True: self.image.set_from_file(addDataPrefix("glade/stock-vchain-24.png")) else: self.image.set_from_file(addDataPrefix("glade/stock-vchain-broken-24.png")) active = property(getActive, setActive) def onClicked (self, button): if self._active is False: self.image.set_from_file(addDataPrefix("glade/stock-vchain-24.png")) self._active = True else: self.image.set_from_file(addDataPrefix("glade/stock-vchain-broken-24.png")) self._active = False self.emit("clicked") CHAIN_TOP, CHAIN_BOTTOM = range(2) SHORT_LINE = 2 LONG_LINE = 8 class ChainLine (gtk.Alignment): """ The ChainLine's are the little right-angle lines above and below the chain button that visually connect the ChainButton to the widgets who's values are "chained" together by the ChainButton being active """ def __init__ (self, position): gtk.Alignment.__init__(self) self.position = position self.connect_after("size-allocate", self.onSizeAllocate) self.connect_after("expose-event", self.onExpose) self.set_flags(gtk.NO_WINDOW) self.set_size_request(10,10) self.lastRectangle = None def onSizeAllocate(self, widget, requisition): if self.window: glock.acquire() try: a = self.get_allocation() rect = gdk.Rectangle(a.x, a.y, a.width, a.height) unionrect = self.lastRectangle.union(rect) if self.lastRectangle != None else rect self.window.invalidate_rect(unionrect, True) self.window.process_updates(True) self.lastRectangle = rect finally: glock.release() def onExpose (self, widget, event): context = widget.window.cairo_create() context.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) context.clip() self.draw(context) return False ### ### the original gtk.Style.paint_polygon() way to draw, like The GIMP does it ### # def draw (self, widget, event): # a = self.get_allocation() ## print a.x, a.y, a.width, a.height # points = [None, None, None] # points[0] = (a.x + a.width/2 - SHORT_LINE, a.y + a.height/2) # points[1] = (points[0][0] + SHORT_LINE, points[0][1]) # points[2] = (points[1][0], self.position == CHAIN_TOP and a.y+a.height-1 or a.y) # if self.position == CHAIN_BOTTOM: # t = points[0] # points[0] = points[2] # points[2] = t ## print points # self.points = points # # style = widget.get_style() # style.paint_polygon(widget.get_parent_window(), # gtk.STATE_NORMAL, # gtk.SHADOW_ETCHED_OUT, # event.area, # widget, # "chainbutton", # points, # False) def __toAHalf (self, number): """ To draw thin straight lines in cairo that aren't blurry, you have to adjust the endpoints by 0.5: http://www.cairographics.org/FAQ/#sharp_lines """ return int(number) + 0.5 def draw (self, context): r = self.get_allocation() x = r.x y = r.y width = r.width - 1 height = r.height context.set_source_rgb(.2, .2, .2) # context.rectangle(0, 0, width, height) # context.fill() context.move_to(self.__toAHalf(x+width/2.)-LONG_LINE, self.__toAHalf(y+height/2.)) context.line_to(self.__toAHalf(x+width/2.), self.__toAHalf(y+height/2.)) if self.position == CHAIN_TOP: context.line_to(self.__toAHalf(x+width/2.), self.__toAHalf(float(y+height))) else: context.line_to(self.__toAHalf(x+width/2.), self.__toAHalf(y+0.)) context.set_line_width(1.0) context.set_line_cap(cairo.LINE_CAP_ROUND) context.set_line_join(cairo.LINE_JOIN_ROUND) context.stroke() def __str__ (self): a = self.get_allocation() s = "ChainLine(%s, %s, %s, %s" % (a.x, a.y, a.width, a.height) if self.points != None: points = [] for a in self.points: points.append("(%s, %s)" % (a[0], a[1])) s += ", (" + ", ".join(points) + ")" s += (self.position == CHAIN_TOP and ", CHAIN_TOP" or ", CHAIN_BOTTOM") return s + ")" if __name__ == "__main__": win = gtk.Window() chainvbox = ChainVBox() label = gtk.Label("Locked") adjustment = gtk.Adjustment(value=10, upper=100, lower=0, step_incr=1) spinbutton1 = gtk.SpinButton(adjustment=adjustment) adjustment = gtk.Adjustment(value=0, upper=100, lower=0, step_incr=1) spinbutton2 = gtk.SpinButton(adjustment=adjustment) table = gtk.Table(rows=3,columns=2) # table.attach(label,0,2,0,1) # table.attach(chainvbox,1,2,1,3) # table.attach(spinbutton1,0,1,1,2) # table.attach(spinbutton2,0,1,2,3) table.attach(label,0,2,0,1,xoptions=gtk.SHRINK) table.attach(chainvbox,1,2,1,3,xoptions=gtk.SHRINK) table.attach(spinbutton1,0,1,1,2,xoptions=gtk.SHRINK) table.attach(spinbutton2,0,1,2,3,xoptions=gtk.SHRINK) table.set_row_spacings(2) def onChainBoxClicked (*whatever): if chainvbox.active == False: label.set_label("Unlocked") else: label.set_label("Locked") chainvbox.connect("clicked", onChainBoxClicked) bb = BorderBox(widget=table) win.add(bb) # win.resize(150,100) win.connect("delete-event", gtk.main_quit) win.show_all() gtk.main()
Python
import sys, os import gtk from pychess.System.prefix import addDataPrefix from pychess.System import conf, gstreamer, uistuff from pychess.Players.engineNest import discoverer from pychess.Utils.const import * from pychess.Utils.IconLoader import load_icon firstRun = True def run(widgets): global firstRun if firstRun: initialize(widgets) firstRun = False widgets["preferences"].show() def initialize(widgets): GeneralTab(widgets) EngineTab(widgets) SoundTab(widgets) PanelTab(widgets) def delete_event (widget, *args): widgets["preferences"].hide() return True widgets["preferences"].connect("delete-event", delete_event) widgets["preferences_close_button"].connect("clicked", delete_event) widgets["preferences"].connect("key-press-event", lambda w,e: delete_event(w) if e.keyval == gtk.keysyms.Escape else None) ################################################################################ # General initing # ################################################################################ class GeneralTab: def __init__ (self, widgets): conf.set("firstName", conf.get("firstName", conf.username)) conf.set("secondName", conf.get("secondName", _("Guest"))) # Give to uistuff.keeper for key in ("firstName", "secondName", "hideTabs", "autoRotate", "faceToFace", "showCords", "figuresInNotation", "autoCallFlag", "fullAnimation", "moveAnimation", "noAnimation"): uistuff.keep(widgets[key], key) ################################################################################ # Engine initing # ################################################################################ class EngineTab: def __init__ (self, widgets): # Put engines in trees and combos engines = discoverer.getEngines() allstore = gtk.ListStore(gtk.gdk.Pixbuf, str) for engine in engines.values(): c = discoverer.getCountry(engine) if c: flag = addDataPrefix("flags/%s.png" % c) if not c or not os.path.isfile(flag): flag = addDataPrefix("flags/unknown.png") flag_icon = gtk.gdk.pixbuf_new_from_file(flag) allstore.append((flag_icon, discoverer.getName(engine))) tv = widgets["engines_treeview"] tv.set_model(allstore) tv.append_column(gtk.TreeViewColumn( _("Flag"), gtk.CellRendererPixbuf(), pixbuf=0)) tv.append_column(gtk.TreeViewColumn( _("Name"), gtk.CellRendererText(), text=1)) analyzers = list(discoverer.getAnalyzers()) ana_data = [] invana_data = [] for engine in analyzers: name = discoverer.getName(engine) c = discoverer.getCountry(engine) if c: flag = addDataPrefix("flags/%s.png" % c) if not c or not os.path.isfile(flag): flag = addDataPrefix("flags/unknown.png") flag_icon = gtk.gdk.pixbuf_new_from_file(flag) ana_data.append((flag_icon, name)) invana_data.append((flag_icon, name)) uistuff.createCombo(widgets["ana_combobox"], ana_data) uistuff.createCombo(widgets["inv_ana_combobox"], invana_data) # Save, load and make analyze combos active conf.set("ana_combobox", conf.get("ana_combobox", 0)) conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", 0)) def on_analyzer_check_toggled (check): widgets["analyzers_vbox"].set_sensitive(check.get_active()) widgets["hint_mode"].set_active(check.get_active()) from pychess.Main import gameDic if gameDic: widgets["hint_mode"].set_sensitive(check.get_active()) widgets["analyzer_check"].connect("toggled", on_analyzer_check_toggled) uistuff.keep(widgets["analyzer_check"], "analyzer_check") def on_invanalyzer_check_toggled (check): widgets["inv_analyzers_vbox"].set_sensitive(check.get_active()) widgets["spy_mode"].set_active(check.get_active()) from pychess.Main import gameDic if gameDic: widgets["spy_mode"].set_sensitive(check.get_active()) widgets["inv_analyzer_check"].connect("toggled", on_invanalyzer_check_toggled) uistuff.keep(widgets["inv_analyzer_check"], "inv_analyzer_check") # Put options in trees in add/edit dialog #======================================================================= # tv = widgets["optionview"] # tv.append_column(gtk.TreeViewColumn( # "Option", gtk.CellRendererText(), text=0)) # tv.append_column(gtk.TreeViewColumn( # "Value", gtk.CellRendererText(), text=1)) # # def edit (button): # # iter = widgets["engines_treeview"].get_selection().get_selected()[1] # if iter: row = allstore.get_path(iter)[0] # else: return # # engine = discoverer.getEngineN(row) # optionstags = engine.getElementsByTagName("options") # if not optionstags: # widgets["engine_options_expander"].hide() # else: # widgets["engine_options_expander"].show() # widgets["engine_options_expander"].set_expanded(False) # # optionsstore = gtk.ListStore(str, str) # tv = widgets["optionview"] # tv.set_model(optionsstore) # # for option in optionstags[0].childNodes: # if option.nodeType != option.ELEMENT_NODE: continue # optionsstore.append( [option.getAttribute("name"), # option.getAttribute("default")] ) # # widgets["engine_path_chooser"].set_title(_("Locate Engine")) # widgets["engine_path_chooser"].set_uri("file:///usr/bin/gnuchess") # # dialog = widgets["addconfig_engine"] # answer = dialog.run() # dialog.hide() # widgets["edit_engine_button"].connect("clicked", edit) #======================================================================= #widgets["remove_engine_button"].connect("clicked", remove) #widgets["add_engine_button"].connect("clicked", add) # Give widgets to kepper for combo in ("ana_combobox", "inv_ana_combobox"): def get_value (combobox): engine = list(discoverer.getAnalyzers())[combobox.get_active()] if engine.find('md5') != None: return engine.find('md5').text.strip() def set_value (combobox, value): engine = discoverer.getEngineByMd5(value) if engine is None: combobox.set_active(0) else: try: index = list(discoverer.getAnalyzers()).index(engine) except ValueError: index = 0 combobox.set_active(index) uistuff.keep (widgets[combo], combo, get_value, set_value) # Init info box uistuff.makeYellow(widgets["analyzer_pref_infobox"]) widgets["analyzer_pref_infobox"].hide() def updatePrefInfobox (widget, *args): widgets["analyzer_pref_infobox"].show() widgets["ana_combobox"].connect("changed", updatePrefInfobox) widgets["analyzer_check"].connect("toggled", updatePrefInfobox) widgets["inv_ana_combobox"].connect("changed", updatePrefInfobox) widgets["inv_analyzer_check"].connect("toggled", updatePrefInfobox) widgets["preferences"].connect("hide", lambda *a: widgets["analyzer_pref_infobox"].hide()) ################################################################################ # Sound initing # ################################################################################ # Setup default sounds for i in xrange(9): if not conf.hasKey("soundcombo%d" % i): conf.set("soundcombo%d" % i, SOUND_URI) if not conf.hasKey("sounduri0"): conf.set("sounduri0", "file://"+addDataPrefix("sounds/move1.ogg")) if not conf.hasKey("sounduri1"): conf.set("sounduri1", "file://"+addDataPrefix("sounds/check1.ogg")) if not conf.hasKey("sounduri2"): conf.set("sounduri2", "file://"+addDataPrefix("sounds/capture1.ogg")) if not conf.hasKey("sounduri3"): conf.set("sounduri3", "file://"+addDataPrefix("sounds/start1.ogg")) if not conf.hasKey("sounduri4"): conf.set("sounduri4", "file://"+addDataPrefix("sounds/win1.ogg")) if not conf.hasKey("sounduri5"): conf.set("sounduri5", "file://"+addDataPrefix("sounds/lose1.ogg")) if not conf.hasKey("sounduri6"): conf.set("sounduri6", "file://"+addDataPrefix("sounds/draw1.ogg")) if not conf.hasKey("sounduri7"): conf.set("sounduri7", "file://"+addDataPrefix("sounds/obs_mov.ogg")) if not conf.hasKey("sounduri8"): conf.set("sounduri8", "file://"+addDataPrefix("sounds/obs_end.ogg")) class SoundTab: SOUND_DIRS = (addDataPrefix("sounds"), "/usr/share/sounds", "/usr/local/share/sounds", os.environ["HOME"]) COUNT_OF_SOUNDS = 9 actionToKeyNo = { "aPlayerMoves": 0, "aPlayerChecks": 1, "aPlayerCaptures": 2, "gameIsSetup": 3, "gameIsWon": 4, "gameIsLost": 5, "gameIsDrawn": 6, "observedMoves": 7, "oberservedEnds": 8 } _player = None @classmethod def getPlayer (cls): if not cls._player: cls._player = gstreamer.Player() return cls._player @classmethod def playAction (cls, action): if not conf.get("useSounds", True): return if type(action) == str: no = cls.actionToKeyNo[action] else: no = action typ = conf.get("soundcombo%d" % no, SOUND_MUTE) if typ == SOUND_BEEP: sys.stdout.write("\a") sys.stdout.flush() elif typ == SOUND_URI: uri = conf.get("sounduri%d" % no, "") if not os.path.isfile(uri[7:]): conf.set("soundcombo%d" % no, SOUND_MUTE) return cls.getPlayer().play(uri) def __init__ (self, widgets): # Init open dialog opendialog = gtk.FileChooserDialog ( _("Open Sound File"), None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT)) for dir in self.SOUND_DIRS: if os.path.isdir(dir): opendialog.set_current_folder(dir) break soundfilter = gtk.FileFilter() soundfilter.add_custom(soundfilter.get_needed(), lambda data: data[3] and data[3].startswith("audio/")) opendialog.add_filter(soundfilter) opendialog.set_filter(soundfilter) # Get combo icons icons = ((_("No sound"), "audio-volume-muted", "audio-volume-muted"), (_("Beep"), "stock_bell", "audio-x-generic"), (_("Select sound file..."), "gtk-open", "document-open")) items = [] for level, stock, altstock in icons: image = load_icon(16, stock, altstock) items += [(image, level)] audioIco = load_icon(16, "audio-x-generic") # Set-up combos def callback (combobox, index): if combobox.get_active() == SOUND_SELECT: if opendialog.run() == gtk.RESPONSE_ACCEPT: uri = opendialog.get_uri() model = combobox.get_model() conf.set("sounduri%d"%index, uri) label = os.path.split(uri)[1] if len(model) == 3: model.append([audioIco, label]) else: model.set(model.get_iter((3,)), 1, label) combobox.set_active(3) else: combobox.set_active(conf.get("soundcombo%d"%index,SOUND_MUTE)) opendialog.hide() for i in xrange(self.COUNT_OF_SOUNDS): combo = widgets["soundcombo%d"%i] uistuff.createCombo (combo, items) combo.set_active(0) combo.connect("changed", callback, i) label = widgets["soundlabel%d"%i] label.props.mnemonic_widget = combo uri = conf.get("sounduri%d"%i,"") if os.path.isfile(uri[7:]): model = combo.get_model() model.append([audioIco, os.path.split(uri)[1]]) combo.set_active(3) for i in xrange(self.COUNT_OF_SOUNDS): if conf.get("soundcombo%d"%i, SOUND_MUTE) == SOUND_URI and \ not os.path.isfile(conf.get("sounduri%d"%i,"")[7:]): conf.set("soundcombo%d"%i, SOUND_MUTE) uistuff.keep(widgets["soundcombo%d"%i], "soundcombo%d"%i) #widgets["soundcombo%d"%i].set_active(conf.get("soundcombo%d"%i, SOUND_MUTE)) # Init play button def playCallback (button, index): SoundTab.playAction(index) for i in range (self.COUNT_OF_SOUNDS): button = widgets["soundbutton%d"%i] button.connect("clicked", playCallback, i) # Init 'use sound" checkbutton def checkCallBack (*args): checkbox = widgets["useSounds"] widgets["frame23"].set_property("sensitive", checkbox.get_active()) conf.notify_add("useSounds", checkCallBack) widgets["useSounds"].set_active(True) uistuff.keep(widgets["useSounds"], "useSounds") checkCallBack() def soundError (player, gstmessage): widgets["useSounds"].set_sensitive(False) widgets["useSounds"].set_active(False) self.getPlayer().connect("error", soundError) ################################################################################ # Panel initing # ################################################################################ class PanelTab: def __init__ (self, widgets): # Put panels in trees self.widgets = widgets from pychess.widgets.gamewidget import sidePanels store = gtk.ListStore(bool, gtk.gdk.Pixbuf, str, object) for panel in sidePanels: checked = conf.get(panel.__name__, False) panel_icon = gtk.gdk.pixbuf_new_from_file_at_size(panel.__icon__, 32, 32) text = "<b>%s</b>\n%s" % (panel.__title__, panel.__desc__) store.append((checked, panel_icon, text, panel)) self.tv = widgets["treeview1"] self.tv.set_model(store) self.widgets['panel_about_button'].connect('clicked', self.panel_about) self.widgets['panel_enable_button'].connect('toggled', self.panel_toggled) self.tv.get_selection().connect('changed', self.selection_changed) pixbuf = gtk.CellRendererPixbuf() pixbuf.props.yalign = 0 pixbuf.props.ypad = 3 pixbuf.props.xpad = 3 self.tv.append_column(gtk.TreeViewColumn("Icon", pixbuf, pixbuf=1, sensitive=0)) uistuff.appendAutowrapColumn(self.tv, 200, "Name", markup=2, sensitive=0) widgets['notebook1'].connect("switch-page", self.__on_switch_page) widgets["preferences"].connect("show", self.__on_show_window) widgets["preferences"].connect("hide", self.__on_hide_window) def selection_changed(self, treeselection): store, iter = self.tv.get_selection().get_selected() self.widgets['panel_enable_button'].set_sensitive(bool(iter)) self.widgets['panel_about_button'].set_sensitive(bool(iter)) if iter: active = self.tv.get_model().get(iter, 0)[0] self.widgets['panel_enable_button'].set_active(active) def panel_about(self, button): store, iter = self.tv.get_selection().get_selected() assert iter # The button should only be clickable when we have a selection path = store.get_path(iter) panel = store[path][3] d = gtk.MessageDialog (type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_CLOSE) d.set_markup ("<big><b>%s</b></big>" % panel.__title__) text = panel.__about__ if hasattr(panel, '__about__') else _('Undescribed panel') d.format_secondary_text (text) d.run() d.hide() def panel_toggled(self, button): store, iter = self.tv.get_selection().get_selected() assert iter # The button should only be clickable when we have a selection path = store.get_path(iter) active = button.get_active() if store[path][0] == active: return store[path][0] = active self.__set_panel_active(store[path][3], active) def __set_panel_active(self, panel, active): name = panel.__name__ from pychess.widgets.gamewidget import notebooks, docks from pychess.widgets.pydock import EAST if active: conf.set(name, True) leaf = notebooks["board"].get_parent().get_parent() leaf.dock(docks[name][1], EAST, docks[name][0], name) else: conf.set(name, False) try: notebooks[name].get_parent().get_parent().undock(notebooks[name]) except AttributeError: # A new panel appeared in the panels directory conf.set(name, True) leaf = notebooks["board"].get_parent().get_parent() leaf.dock(docks[name][1], EAST, docks[name][0], name) def showit(self): from pychess.widgets.gamewidget import showDesignGW showDesignGW() def hideit(self): from pychess.widgets.gamewidget import hideDesignGW hideDesignGW() def __on_switch_page(self, notebook, page, page_num): if notebook.get_nth_page(page_num) == self.widgets['sidepanels']: self.showit() else: self.hideit() def __on_show_window(self, widget): notebook = self.widgets['notebook1'] page_num = notebook.get_current_page() if notebook.get_nth_page(page_num) == self.widgets['sidepanels']: self.showit() def __on_hide_window(self, widget): self.hideit()
Python
from os import path import gtk import cairo from pychess.System.prefix import addDataPrefix, addUserCachePrefix CLEARPATH = addDataPrefix("glade/clear.png") surface = None def giveBackground (widget): widget.connect("expose_event", expose) widget.connect("style-set", newtheme) def expose (widget, event): cr = widget.window.cairo_create() cr.rectangle (event.area.x, event.area.y, event.area.width, event.area.height) if not surface: newtheme(widget, None) cr.set_source_surface(surface, 0, 0) pattern = cr.get_source() pattern.set_extend(cairo.EXTEND_REPEAT) cr.fill() def newtheme (widget, oldstyle): global surface lnewcolor = widget.get_style().bg[gtk.STATE_NORMAL] dnewcolor = widget.get_style().dark[gtk.STATE_NORMAL] if oldstyle: loldcolor = oldstyle.bg[gtk.STATE_NORMAL] doldcolor = oldstyle.dark[gtk.STATE_NORMAL] if lnewcolor.red == loldcolor.red and \ lnewcolor.green == loldcolor.green and \ lnewcolor.blue == loldcolor.blue and \ dnewcolor.red == doldcolor.red and \ dnewcolor.green == doldcolor.green and \ dnewcolor.blue == doldcolor.blue: return colors = [ lnewcolor.red/256, lnewcolor.green/256, lnewcolor.blue/256, dnewcolor.red/256, dnewcolor.green/256, dnewcolor.blue/256 ] # Check if a cache has been saved temppng = addUserCachePrefix("temp.png") if path.isfile(temppng): f = open(temppng, "rb") # Check if the cache was made while using the same theme if [ord(c) for c in f.read(6)] == colors: surface = cairo.ImageSurface.create_from_png(f) return # Get mostly transparant shadowy image imgsurface = cairo.ImageSurface.create_from_png(CLEARPATH) AVGALPHA = 108/255. surface = cairo.ImageSurface(cairo.FORMAT_RGB24, imgsurface.get_width(), imgsurface.get_height()) ctx = cairo.Context (surface) if lnewcolor.blue-dnewcolor.blue > 0: a = dnewcolor.red/(3*(lnewcolor.blue-dnewcolor.blue)*(1-AVGALPHA)) ctx.set_source_rgb( lnewcolor.red/65535./2 + dnewcolor.red/65535.*a/2, lnewcolor.green/65535./2 + dnewcolor.green/65535.*a/2, lnewcolor.blue/65535./2 + dnewcolor.blue/65535.*a/2) ctx.paint() ctx.set_source_surface(imgsurface, 0, 0) ctx.paint_with_alpha(.8) # Save a cache for later use. Save 'newcolor' in the frist three pixels # to check for theme changes between two instances f = open(temppng, "wb") for color in colors: f.write(chr(color)) surface.write_to_png(f)
Python
import gobject import gtk class InfoBarMessageButton (gobject.GObject): def __init__(self, text, response_id, sensitive=True, tooltip=""): gobject.GObject.__init__(self) self.text = text self.response_id = response_id self.sensitive = sensitive self.tooltip = tooltip self._sensitive_cid = None self._tooltip_cid = None self._button = None def get_sensitive (self): return self._sensitive def set_sensitive (self, sensitive): self._sensitive = sensitive sensitive = gobject.property(get_sensitive, set_sensitive) def get_tooltip (self): return self._tooltip def set_tooltip (self, tooltip): self._tooltip = tooltip tooltip = gobject.property(get_tooltip, set_tooltip) class InfoBarMessage (gobject.GObject): __gsignals__ = { "dismissed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), } def __init__ (self, message_type, content, callback): gobject.GObject.__init__(self) self.type = message_type container = gtk.HBox() container.pack_start(content, expand=False, fill=False) self.content = container self.callback = callback self.buttons = [] self._dismissed_cid = None def add_button (self, button): """ All buttons must be added before doing InfoBar.push_message() """ if not isinstance(button, InfoBarMessageButton): raise TypeError("Not an InfoBarMessageButton: %s" % repr(button)) self.buttons.append(button) def dismiss (self): self.emit("dismissed") class InfoBar (gtk.InfoBar): """ This is a gtk.InfoBar which manages messages pushed onto it via push_message() like a stack. If/when the current message at the top of the stack is responded to or dismissed by the user, the next message in the stack waiting for a response is displayed. Messages that aren't applicable anymore can be removed from anywhere in the InfoBar message stack by calling message.dismiss() """ def __init__ (self, *args): gtk.InfoBar.__init__(self, *args) self.messages = [] self.response_cid = None self.connect_after("response", self._response_cb) def _remove_message (self, message): if message.handler_is_connected(message._dismissed_cid): message.disconnect(message._dismissed_cid) message._dismissed_cid = None for button in message.buttons: if button.handler_is_connected(button._sensitive_cid): button.disconnect(button._sensitive_cid) button._sensitive_cid = None if button.handler_is_connected(button._tooltip_cid): button.disconnect(button._tooltip_cid) button._tooltip_cid = None def _message_dismissed_cb (self, message): try: shown_message = self.messages[-1] except IndexError: shown_message = None if message == shown_message: self.response(gtk.RESPONSE_CANCEL) else: self._remove_message(message) self.messages.remove(message) return False def _button_sensitive_cb (self, button, property, message): try: shown_message = self.messages[-1] except IndexError: return if message == shown_message: self.set_response_sensitive(button.response_id, button.sensitive) return False def _button_tooltip_cb (self, button, property, message): try: shown_message = self.messages[-1] except IndexError: return if message == shown_message and button._button is not None: button._button.set_property("tooltip-text", button.tooltip) return False def _response_cb (self, infobar, response): try: shown_message = self.messages.pop() except IndexError: pass else: self._unload_message(shown_message) self._remove_message(shown_message) try: cur_message = self.messages[-1] except IndexError: self.hide() else: self._load_message(cur_message) return False def _unload_message (self, message): if self.response_cid is not None and \ self.handler_is_connected(self.response_cid): self.disconnect(self.response_cid) self.response_cid = None for button in message.buttons: button._button = None def _load_message (self, message): for container in (self.get_action_area(), self.get_content_area()): for widget in container: container.remove(widget) self.set_message_type(message.type) self.get_content_area().add(message.content) for button in message.buttons: button._button = self.add_button(button.text, button.response_id) button._sensitive_cid = button.connect( "notify::sensitive", self._button_sensitive_cb, message) button._tooltip_cid = button.connect( "notify::tooltip", self._button_tooltip_cb, message) self._button_sensitive_cb(button, None, message) self._button_tooltip_cb(button, None, message) if message.callback: self.response_cid = self.connect("response", message.callback) def push_message (self, message): if not isinstance(message, InfoBarMessage): raise TypeError("Not of type InfoBarMessage: %s" % repr(message)) try: shown_message = self.messages[-1] except IndexError: pass else: self._unload_message(shown_message) self.messages.append(message) self._load_message(message) message._dismissed_cid = message.connect("dismissed", self._message_dismissed_cb) self.show_all()
Python
import gtk class BorderBox (gtk.Alignment): def __init__ (self, widget=None, top=False, right=False, bottom=False, left=False): gtk.Alignment.__init__(self, 0, 0, 1, 1) self.connect("expose-event", self._onExpose) if widget: self.add(widget) self.__top = top self.__right = right self.__bottom = bottom self.__left = left self._updateBorders() def _onExpose(self, area, event): context = self.window.cairo_create() color = self.get_style().dark[gtk.STATE_NORMAL] context.set_source_rgb(color.red/65535., color.green/65535., color.blue/65535.) r = self.get_allocation() x = r.x + .5 y = r.y + .5 width = r.width - 1 height = r.height - 1 if self.top: context.move_to(x, y) context.line_to(x+width, y) if self.right: context.move_to(x+width, y) context.line_to(x+width, y+height) if self.bottom: context.move_to(x+width, y+height) context.line_to(x, y+height) if self.left: context.move_to(x, y+height) context.line_to(x, y) context.set_line_width(1) context.stroke() def _updateBorders (self): self.set_padding(self.top and 1 or 0, self.bottom and 1 or 0, self.right and 1 or 0, self.left and 1 or 0) def isTop(self): return self.__top def isRight(self): return self.__right def isBottom(self): return self.__bottom def isLeft(self): return self.__left def setTop(self, value): self.__top = value self._updateBorders() def setRight(self, value): self.__right = value self._updateBorders() def setBottom(self, value): self.__bottom = value self._updateBorders() def setLeft(self, value): self.__left = value self._updateBorders() top = property(isTop, setTop, None, None) right = property(isRight, setRight, None, None) bottom = property(isBottom, setBottom, None, None) left = property(isLeft, setLeft, None, None)
Python
import gtk, gtk.gdk from gobject import * from math import floor from BoardView import BoardView from pychess.Utils.const import * from pychess.Utils.Cord import Cord ALL = 0 class SetupBoard (gtk.EventBox): __gsignals__ = { 'cord_clicked' : (SIGNAL_RUN_FIRST, TYPE_NONE, (TYPE_PYOBJECT,)), } def __init__(self): gtk.EventBox.__init__(self) self.view = BoardView() self.add(self.view) self.view.showEnpassant = True self.connect("button_press_event", self.button_press) self.connect("button_release_event", self.button_release) self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK|gtk.gdk.POINTER_MOTION_MASK) self.connect("motion_notify_event", self.motion_notify) self.connect("leave_notify_event", self.leave_notify) self.brush = None # Selection and stuff # def setBrush (self, brush): self.brush = brush def getBrush (self): return self.brush def transPoint (self, x, y): if not self.view.square: return None xc, yc, square, s = self.view.square y -= yc; x -= xc y /= float(s) x /= float(s) if self.view.fromWhite: y = 8 - y else: x = 8 - x return x, y def point2Cord (self, x, y): if not self.view.square: return None point = self.transPoint(x, y) x = floor(point[0]) if self.view.fromWhite: y = floor(point[1]) else: y = floor(point[1]) if not (0 <= x <= 7 and 0 <= y <= 7): return None return Cord(x, y) def button_press (self, widget, event): self.grab_focus() cord = self.point2Cord (event.x, event.y) if self.legalCords == ALL or cord in self.legalCords: self.view.active = cord else: self.view.active = None def button_release (self, widget, event): cord = self.point2Cord (event.x, event.y) if cord == self.view.active: self.emit('cord_clicked', cord) self.view.active = None def motion_notify (self, widget, event): cord = self.point2Cord (event.x, event.y) if cord == None: return if self.legalCords == ALL or cord in self.legalCords: self.view.hover = cord else: self.view.hover = None def leave_notify (self, widget, event): a = self.get_allocation() if not (0 <= event.x < a.width and 0 <= event.y < a.height): self.view.hover = None
Python
import gtk.glade, os from pychess.System import conf from pychess.System import uistuff from pychess.System.prefix import addDataPrefix from random import randrange uistuff.cacheGladefile("tipoftheday.glade") class TipOfTheDay: @classmethod def _init (cls): cls.widgets = uistuff.GladeWidgets("tipoftheday.glade") uistuff.keepWindowSize("tipoftheday", cls.widgets["window1"], (320,240), uistuff.POSITION_CENTER) cls.widgets["checkbutton1"].set_active(conf.get("show_tip_at_startup", False)) cls.widgets["checkbutton1"].connect("toggled", lambda w: conf.set("show_tip_at_startup", w.get_active())) cls.widgets["close_button"].connect("clicked", lambda w: cls.widgets["window1"].emit("delete-event", None)) cls.widgets["window1"].connect("delete_event", lambda w, a: cls.widgets["window1"].hide()) cls.widgets["back_button"].connect("clicked", lambda w: cls.set_currentIndex(cls.currentIndex-1)) cls.widgets["forward_button"].connect("clicked", lambda w: cls.set_currentIndex(cls.currentIndex+1)) cls.currentIndex = 0 @classmethod def show (cls): if not hasattr(cls, "widgets"): cls._init() cls.set_currentIndex(randrange(len(tips))) cls.widgets["window1"].show() @classmethod def set_currentIndex (cls, value): if len(tips) == 0: return if value < 0: value = len(tips)-1 elif value >= len(tips): value = 0 cls.currentIndex = value cls.widgets["tipfield"].set_markup(tips[value]) tips = ( _("You can start a new game by <b>Game</b> > <b>New Game</b>, in New Game window do you can choose <b>Players</b>, <b>Time Control</b> and <b>Chess Variants</b>."), _("You can choose from 8 different difficulties to play against the computer."), _("Chess Variants are like the pieces of the last line will be placed on the board."), _("To save a game <b>Game</b> > <b>Save Game As</b>, give the filename and choose where you want to be saved. At the bottom choose extension type of the file, and <b>Save</b>."), _("Do you know that you can call flag when the clock is with you, <b>Actions</b> > <b>Call Flag</b>."), _("Pressing <b>Ctrl+Z</b> to offer opponent the possible rollback moves."), _("To play on <b>Fullscreen mode</b>, just type <b>F11</b>. Coming back, F11 again."), _("<b>Hint mode</b> analyzing your game, enable this type <b>Ctrl+H</b>."), _("<b>Spy mode</b> analyzing the oponnent game, enable this type <b>Ctrl+Y</b>."), _("You can play chess listening to the sounds of the game, for that, <b>Settings</b> > <b>Preferences</b> > <b>Sound tab</b>, enable <b>Use sounds in PyChess</b> and choose your preferred sounds."), _("Do you know that you can help translate Pychess in your language, <b>Help</b> > <b>Translate Pychess</b>."), _("Do you know that it is possible to finish a chess game in just 2 turns?"), _("Do you know that the number of possible chess games exceeds the number of atoms in the Universe?"), )
Python
import math ceil = lambda f: int(math.ceil(f)) from gobject import * import gtk import cairo import pango line = 10 curve = 60 dotSmall = 14 dotLarge = 24 lineprc = 1/7. hpadding = 5 vpadding = 3 class SpotGraph (gtk.EventBox): __gsignals__ = { 'spotClicked' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)) } def __init__ (self): gtk.EventBox.__init__(self) self.connect("expose_event", self.expose) self.typeColors = [[[85, 152, 215], [59, 106, 151]], [[115, 210, 22], [78, 154, 6]]] for type in self.typeColors: for color in type: color[0] = color[0]/255. color[1] = color[1]/255. color[2] = color[2]/255. self.add_events( gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK ) self.connect("button_press_event", self.button_press) self.connect("button_release_event", self.button_release) self.connect("motion_notify_event", self.motion_notify) self.connect("leave_notify_event", self.motion_notify) self.connect("size-allocate", self.size_allocate) self.cords = [] self.hovered = None self.pressed = False self.spots = {} self.spotQueue = [] # For spots added prior to widget allocation self.xmarks = [] self.ymarks = [] self.set_visible_window(False) ############################################################################ # Drawing # ############################################################################ def redraw_canvas(self, rect=None): if self.window: if not rect: alloc = self.get_allocation() rect = (0, 0, alloc.width, alloc.height) rect = gtk.gdk.Rectangle(*map(int,rect)) self.window.invalidate_rect(rect, True) self.window.process_updates(True) def expose(self, widget, event): context = widget.window.cairo_create() self.draw(context, event.area) return False def draw (self, context, r): alloc = self.get_allocation() width = alloc.width height = alloc.height #------------------------------------------------------ Paint side ruler context.move_to(alloc.x+line, alloc.y+line) context.rel_line_to(0, height-line*2-curve) context.rel_curve_to(0, curve, 0, curve, curve, curve) context.rel_line_to(width-line*2-curve, 0) context.set_line_width(line) context.set_line_cap(cairo.LINE_CAP_ROUND) state = self.state == gtk.STATE_NORMAL and gtk.STATE_PRELIGHT or self.state context.set_source_color(self.get_style().dark[state]) context.stroke() #------------------------------------------------ Paint horizontal marks for x, title in self.xmarks: context.set_source_color(self.get_style().fg[self.state]) context.set_font_size(12) x, y = self.prcToPix (x, 1) context.move_to (x+line/2., y-line/2.) context.rotate(-math.pi/2) context.show_text(title) context.rotate(math.pi/2) context.set_source_color(self.get_style().bg[self.state]) context.move_to (x-line/2., y) context.rel_curve_to (6, 0, 6, line, 6, line) context.rel_curve_to (0, -line, 6, -line, 6, -line) context.close_path() context.fill() #-------------------------------------------------- Paint vertical marks for y, title in self.ymarks: context.set_source_color(self.get_style().fg[self.state]) context.set_font_size(12) x, y = self.prcToPix (0, y) context.move_to (x+line/2., y+line/2.) context.show_text(title) context.set_source_color(self.get_style().bg[self.state]) context.move_to (x, y-line/2.) context.rel_curve_to (0, 6, -line, 6, -line, 6) context.rel_curve_to (line, 0, line, 6, line, 6) context.close_path() context.fill() #----------------------------------------------------------- Paint spots context.set_line_width(dotSmall*lineprc) for x, y, type, name, text in self.spots.values(): context.set_source_rgb(*self.typeColors[type][0]) if self.hovered and name == self.hovered[3]: continue x, y = self.prcToPix (x, y) context.arc(x, y, dotSmall/(1+lineprc)/2., 0, 2 * math.pi) context.fill_preserve() context.set_source_rgb(*self.typeColors[type][1]) context.stroke() #--------------------------------------------------- Paint hovered spots context.set_line_width(dotLarge*lineprc) if self.hovered: x, y, type, name, text = self.hovered x, y = self.prcToPix (x, y) if not self.pressed: context.set_source_rgb(*self.typeColors[type][0]) else: context.set_source_rgb(*self.typeColors[type][1]) context.arc(x, y, dotLarge/(1+lineprc)/2., 0, 2 * math.pi) context.fill_preserve() context.set_source_rgb(*self.typeColors[type][1]) context.stroke() x, y, width, height = self.getTextBounds(self.hovered) self.get_style().paint_flat_box (self.window, gtk.STATE_NORMAL, gtk.SHADOW_NONE, r, self, "tooltip", int(x-hpadding), int(y-vpadding), ceil(width+hpadding*2), ceil(height+vpadding*2)) context.move_to(x, y) context.set_source_color(self.get_style().fg[self.state]) context.show_layout(self.create_pango_layout(text)) ############################################################################ # Events # ############################################################################ def button_press (self, widget, event): alloc = self.get_allocation() self.cords = [event.x+alloc.x, event.y+alloc.y] self.pressed = True if self.hovered: self.redraw_canvas(self.getBounds(self.hovered)) def button_release (self, widget, event): alloc = self.get_allocation() self.cords = [event.x+alloc.x, event.y+alloc.y] self.pressed = False if self.hovered: self.redraw_canvas(self.getBounds(self.hovered)) if self.pointIsOnSpot (event.x+alloc.x, event.y+alloc.y, self.hovered): self.emit("spotClicked", self.hovered[3]) def motion_notify (self, widget, event): alloc = self.get_allocation() self.cords = [event.x+alloc.x, event.y+alloc.y] spot = self.getSpotAtPoint (*self.cords) if self.hovered and spot == self.hovered: return if self.hovered: bounds = self.getBounds(self.hovered) self.hovered = None self.redraw_canvas(bounds) if spot: self.hovered = spot self.redraw_canvas(self.getBounds(self.hovered)) def size_allocate (self, widget, allocation): assert self.get_allocation().width > 1 for spot in self.spotQueue: self.addSpot(*spot) del self.spotQueue[:] ############################################################################ # Interaction # ############################################################################ def addSpot (self, name, text, x0, y0, type=0): """ x and y are in % from 0 to 1 """ assert type in range(len(self.typeColors)) if self.get_allocation().width <= 1: self.spotQueue.append((name, text, x0, y0, type)) return x1, y1 = self.getNearestFreeNeighbourHexigon(x0, 1-y0) spot = (x1, y1, type, name, text) self.spots[name] = spot if not self.hovered and self.cords and \ self.pointIsOnSpot (self.cords[0], self.cords[1], spot): self.hovered = spot self.redraw_canvas(self.getBounds(spot)) def removeSpot (self, name): if not name in self.spots: return spot = self.spots.pop(name) bounds = self.getBounds(spot) if spot == self.hovered: self.hovered = None self.redraw_canvas(bounds) def clearSpots (self): self.hovered = None self.spots.clear() self.redraw_canvas() self.redraw_canvas() def addXMark (self, x, title): self.xmarks.append( (x, title) ) def addYMark (self, y, title): self.ymarks.append( (1-y, title) ) ############################################################################ # Internal stuff # ############################################################################ def getTextBounds (self, spot): x, y, type, name, text = spot x, y = self.prcToPix (x, y) alloc = self.get_allocation() width = alloc.width height = alloc.height extends = self.create_pango_layout(text).get_extents() scale = float(pango.SCALE) x_bearing, y_bearing, twidth, theight = [e/scale for e in extends[1]] tx = x - x_bearing + dotLarge/2. ty = y - y_bearing - theight - dotLarge/2. if tx + twidth > width and x - x_bearing - twidth - dotLarge/2. > alloc.x: tx = x - x_bearing - twidth - dotLarge/2. if ty < alloc.y: ty = y - y_bearing + dotLarge/2. return (tx, ty, twidth, theight) def join (self, r0, r1): x1 = min(r0[0], r1[0]) x2 = max(r0[0]+r0[2], r1[0]+r1[2]) y1 = min(r0[1], r1[1]) y2 = max(r0[1]+r0[3], r1[1]+r1[3]) return (x1, y1, x2 - x1, y2 - y1) def getBounds (self, spot): x, y, type, name, text = spot x, y = self.prcToPix (x, y) if spot == self.hovered: size = dotLarge else: size = dotSmall bounds = (x-size/2.-1, y-size/2.-1, size+2, size+2) if spot == self.hovered: x, y, w, h = self.getTextBounds(spot) tbounds = (x-hpadding, y-vpadding, w+hpadding*2+1, h+vpadding*2+1) return self.join(bounds, tbounds) return bounds def getNearestFreeNeighbourHexigon (self, xorg, yorg): """ This method performs an hexigon search for an empty place to put a new dot. """ x, y = self.prcToPix (xorg, yorg) # Start by testing current spot if self.isEmpty (x, y): return xorg, yorg directions = [(math.cos((i+2)*math.pi/3), math.sin((i+2)*math.pi/3)) for i in xrange(6)] level = 1 while True: x += dotSmall for dx, dy in directions: for i in xrange(level): if self.isEmpty (x, y): return self.pixToPrc (x, y) x += dx*dotSmall y += dy*dotSmall level += 1 def getNearestFreeNeighbourArchi (self, xorg, yorg): """ This method performs an archimedes-spircal search for an empty place to put a new dot. http://en.wikipedia.org/wiki/Archimedean_spiral """ xorg, yorg = self.prcToPix (xorg, yorg) # Start by testing current spot if self.isEmpty (xorg, yorg): return self.pixToPrc (xorg, yorg) r = 0 while True: # This is an approx to the equation # cos((r-s)/(2pi)) = (r^2+s^2-1)/(2*r*s) # which gives the next point on the spiral 1 away. r = (4*math.pi**3*r + r**2 + math.sqrt(16*math.pi**6 + 8*math.pi**3*r + r**4)) / (4*math.pi**3 + 2*r) x = r*math.cos(r)/(4*math.pi)*dotSmall + xorg y = r*math.sin(r)/(4*math.pi)*dotSmall + yorg if self.isEmpty (x, y): return self.pixToPrc (x, y) def getNearestFreeNeighbourSquare (self, xorg, yorg): """ This method performs a spircal search for an empty square to put a new dot. """ up = 2 right = 1 down = 1 left = 2 x, y = self.prcToPix (xorg, yorg) # Start by testing current spot if self.isEmpty (x, y): return self.pixToPrc (x, y) while True: for i in range(right): x += dotSmall if self.isEmpty (x, y): return self.pixToPrc (x, y) for i in range(down): y += dotSmall if self.isEmpty (x, y): return self.pixToPrc (x, y) for i in range(left): x -= dotSmall if self.isEmpty (x, y): return self.pixToPrc (x, y) for i in range(up): y -= dotSmall if self.isEmpty (x, y): return self.pixToPrc (x, y) # Grow spiral bounds right += 2 down += 2 left += 2 up += 2 def isEmpty (self, x0, y0): """ Returns true if a spot placed on (x, y) is inside the graph and not intersecting with other spots. x and y should be in pixels, not percent """ # Make sure spiral search don't put dots outside the graph x, y = self.prcToPix(0,0) w, h = self.prcToPix(1,1) if not x <= x0 <= w or not y <= y0 <= h: return False # Tests if the spot intersects any other spots for x1, y1, type, name, text in self.spots.values(): x1, y1 = self.prcToPix(x1, y1) if (x1-x0)**2 + (y1-y0)**2 < dotSmall**2 - 0.1: return False return True def pointIsOnSpot (self, x0, y0, spot): """ Returns true if (x, y) is inside the spot 'spot'. The size of the spot is determined based on its hoverness. x and y should be in pixels, not percent """ if spot == self.hovered: size = dotLarge else: size = dotSmall x1, y1, type, name, text = spot x1, y1 = self.prcToPix(x1, y1) if (x1-x0)**2 + (y1-y0)**2 <= (size/2.)**2: return True return False def getSpotAtPoint (self, x, y): """ Returns the spot embrace (x, y) if any. Otherwise it returns None. x and y should be in pixels, not percent """ if self.hovered and self.pointIsOnSpot(x, y, self.hovered): return self.hovered for spot in self.spots.values(): if spot == self.hovered: continue if self.pointIsOnSpot(x, y, spot): return spot return None def prcToPix (self, x, y): """ Translates from 0-1 cords to real world cords """ alloc = self.get_allocation() return x*(alloc.width - line*1.5-dotLarge*0.5) + line*1.5 + alloc.x, \ y*(alloc.height - line*1.5-dotLarge*0.5) + dotLarge*0.5 + alloc.y def pixToPrc (self, x, y): """ Translates from real world cords to 0-1 cords """ alloc = self.get_allocation() return (x - line*1.5 - alloc.x)/(alloc.width - line*1.5-dotLarge*0.5), \ (y - dotLarge*0.5 - alloc.y)/(alloc.height - line*1.5-dotLarge*0.5) if __name__ == "__main__": w = gtk.Window() nb = gtk.Notebook() w.add(nb) vb = gtk.VBox() nb.append_page(vb) sg = SpotGraph() sg.addXMark(.5, "Center") sg.addYMark(.5, "Center") vb.pack_start(sg) button = gtk.Button("New Spot") def callback (button): if not hasattr(button, "nextnum"): button.nextnum = 0 else: button.nextnum += 1 sg.addSpot(str(button.nextnum), "Blablabla", 1, 1, 0) button.connect("clicked", callback) vb.pack_start(button, expand=False) w.connect("delete-event", gtk.main_quit) w.show_all() w.resize(400,400) gtk.main()
Python
# -*- coding: UTF-8 -*- import os import gtk, gtk.glade, gobject from pychess.Utils.const import reprResult, BLACK, FEN_EMPTY from pychess.Utils.Board import Board from pychess.System.uistuff import GladeWidgets from pychess.System.protoopen import protoopen, splitUri from pychess.widgets.BoardView import BoardView from pychess.Savers.ChessFile import LoadingError def ellipsize (string, maxlen): if len(string) <= maxlen or maxlen < 4: return string return string[:maxlen-1] + "…" class BoardPreview: def __init__ (self, widgets, fcbutton, opendialog, enddir): self.position = 0 self.gameno = 0 self.filename = None self.chessfile = None self.widgets = widgets self.fcbutton = fcbutton self.enddir = enddir # Treeview self.list = self.widgets["gamesTree"] self.list.set_model(gtk.ListStore(str, str,str,str)) # GTK_SELECTION_BROWSE - exactly one item is always selected self.list.get_selection().set_mode(gtk.SELECTION_BROWSE) self.list.get_selection().connect_after( 'changed', self.on_selection_changed) # Add columns renderer = gtk.CellRendererText() renderer.set_property("xalign",0) self.list.append_column(gtk.TreeViewColumn(None, renderer, text=0)) self.list.append_column(gtk.TreeViewColumn(None, renderer, text=1)) self.list.append_column(gtk.TreeViewColumn(None, renderer, text=2)) renderer = gtk.CellRendererText() renderer.set_property("xalign",1) self.list.append_column(gtk.TreeViewColumn(None, renderer, text=3)) # Connect buttons self.widgets["first_button"].connect("clicked", self.on_first_button) self.widgets["back_button"].connect("clicked", self.on_back_button) self.widgets["forward_button"].connect("clicked", self.on_forward_button) self.widgets["last_button"].connect("clicked", self.on_last_button) # Add the board self.boardview = BoardView() self.boardview.set_size_request(170,170) self.widgets["boardPreviewDock"].add(self.boardview) self.boardview.show() self.gamemodel = self.boardview.model self.boardview.gotStarted = True # Connect label showing possition self.boardview.connect('shown_changed', self.shown_changed) self.boardview.autoUpdateShown = False # Add the filechooserbutton self.widgets["fileChooserDock"].add(fcbutton) # Connect doubleclicking a file to on_file_activated fcbutton.connect("file-activated", self.on_file_activated) # Connect the openbutton in the dialog to on_file_activated openbut = opendialog.get_children()[0].get_children()[1].get_children()[0] openbut.connect("clicked", self.on_file_activated) # The first time the button is opened, the player has just opened # his/her file, before we connected the dialog. if self._retrieve_filename(): self.on_file_activated(fcbutton) def on_file_activated (self, *args): filename = self._retrieve_filename() if filename: if filename == self.get_filename(): return self.set_filename(filename) elif self.get_filename(): filename = self.get_filename() else: return if os.path.isdir(filename): return ending = filename[filename.rfind(".")+1:] loader = self.enddir[ending] self.chessfile = chessfile = loader.load(protoopen(filename)) self.list.get_model().clear() for gameno in range(len(chessfile)): names = chessfile.get_player_names (gameno) names = [ellipsize (name, 9) for name in names] result = reprResult[chessfile.get_result (gameno)] result = result.replace("1/2","½") self.list.get_model().append (["%s." % (gameno+1)]+names+[result]) self.lastSel = -1 # The row that was last selected self.list.set_cursor((0,)) def on_selection_changed (self, selection): iter = selection.get_selected()[1] if iter == None: self.gamemodel.boards = [Board(FEN_EMPTY)] del self.gamemodel.moves[:] self.boardview.shown = 0 self.boardview.redraw_canvas() return sel = self.list.get_model().get_path(iter)[0] if sel == self.lastSel: return self.lastSel = sel self.boardview.animationLock.acquire() try: try: self.chessfile.loadToModel(sel, -1, self.gamemodel, False) except LoadingError, e: #TODO: Pressent this a little nicer print e self.boardview.lastMove = None self.boardview._shown = self.gamemodel.lowply last = self.gamemodel.ply finally: self.boardview.animationLock.release() self.boardview.redraw_canvas() self.boardview.shown = last self.shown_changed(self.boardview, last) def on_first_button (self, button): self.boardview.showFirst() def on_back_button (self, button): self.boardview.showPrevious() def on_forward_button (self, button): self.boardview.showNext() def on_last_button (self, button): self.boardview.showLast() def shown_changed (self, boardView, shown): pos = "%d." % (shown/2+1) if shown & 1: pos += ".." self.widgets["posLabel"].set_text(pos) def set_filename (self, filename): asPath = splitUri(filename)[-1] if os.path.isfile(asPath): self.fcbutton.show() if filename != self._retrieve_filename(): self.fcbutton.set_filename(os.path.abspath(asPath)) else: self.fcbutton.set_uri("") self.fcbutton.hide() self.filename = filename def get_filename (self): return self.filename def is_empty (self): return not self.chessfile or not len(self.chessfile) def _retrieve_filename (self): #if self.fcbutton.get_filename(): # return self.fcbutton.get_filename() if self.fcbutton.get_preview_filename(): return self.fcbutton.get_preview_filename() elif self.fcbutton.get_uri(): return self.fcbutton.get_uri()[7:] def get_position (self): return self.boardview.shown def get_gameno (self): iter = self.list.get_selection().get_selected()[1] if iter == None: return -1 return self.list.get_model().get_path(iter)[0]
Python
import gtk class ImageMenu(gtk.EventBox): def __init__ (self, image, child): gtk.EventBox.__init__(self) self.add(image) self.subwindow = gtk.Window() self.subwindow.set_decorated(False) self.subwindow.set_resizable(False) self.subwindow.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG) self.subwindow.add(child) self.subwindow.connect_after("expose-event", self.__sub_onExpose) self.subwindow.connect("button_press_event", self.__sub_onPress) self.subwindow.connect("motion_notify_event", self.__sub_onMotion) self.subwindow.connect("leave_notify_event", self.__sub_onMotion) self.subwindow.connect("delete-event", self.__sub_onDelete) self.subwindow.connect("focus-out-event", self.__sub_onFocusOut) child.show_all() self.setOpen(False) self.connect("button_press_event", self.__onPress) def setOpen (self, isopen): self.isopen = isopen if isopen: topwindow = self.get_parent() while not isinstance(topwindow, gtk.Window): topwindow = topwindow.get_parent() x, y = topwindow.window.get_position() x += self.get_allocation().x + self.get_allocation().width y += self.get_allocation().y self.subwindow.move(x, y) self.subwindow.props.visible = isopen self.set_state(self.isopen and gtk.STATE_SELECTED or gtk.STATE_NORMAL) def __onPress (self, self_, event): if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS: self.setOpen(not self.isopen) def __sub_setGrabbed (self, grabbed): if grabbed and not gtk.gdk.pointer_is_grabbed(): gtk.gdk.pointer_grab(self.subwindow.window, event_mask = gtk.gdk.LEAVE_NOTIFY_MASK| gtk.gdk.POINTER_MOTION_MASK| gtk.gdk.BUTTON_PRESS_MASK) gtk.gdk.keyboard_grab(self.subwindow.window) elif gtk.gdk.pointer_is_grabbed(): gtk.gdk.pointer_ungrab() gtk.gdk.keyboard_ungrab() def __sub_onMotion (self, subwindow, event): a = subwindow.get_allocation() self.__sub_setGrabbed(not (0 <= event.x < a.width and 0 <= event.y < a.height)) def __sub_onPress (self, subwindow, event): a = subwindow.get_allocation() if not (0 <= event.x < a.width and 0 <= event.y < a.height): gtk.gdk.pointer_ungrab(event.time) self.setOpen(False) def __sub_onExpose (self, subwindow, event): a = subwindow.get_allocation() context = subwindow.window.cairo_create() context.set_line_width(2) context.rectangle (a.x, a.y, a.width, a.height) context.set_source_color(self.get_style().dark[gtk.STATE_NORMAL]) context.stroke() self.__sub_setGrabbed(self.isopen) def __sub_onDelete (self, subwindow, event): self.setOpen(False) return True def __sub_onFocusOut (self, subwindow, event): self.setOpen(False) def switchWithImage (image, dialog): parent = image.get_parent() parent.remove(image) imageMenu = ImageMenu(image, dialog) parent.add(imageMenu) imageMenu.show() if __name__ == "__main__": win = gtk.Window() vbox = gtk.VBox() vbox.add(gtk.Label("Her er der en kat")) image = gtk.image_new_from_icon_name("gtk-properties", gtk.ICON_SIZE_BUTTON) vbox.add(image) vbox.add(gtk.Label("Her er der ikke en kat")) win.add(vbox) table = gtk.Table(2, 2) table.attach(gtk.Label("Minutes:"), 0, 1, 0, 1) spin1 = gtk.SpinButton(gtk.Adjustment(0,0,100,1)) table.attach(spin1, 1, 2, 0, 1) table.attach(gtk.Label("Gain:"), 0, 1, 1, 2) spin2 = gtk.SpinButton(gtk.Adjustment(0,0,100,1)) table.attach(spin2, 1, 2, 1, 2) table.set_border_width(6) switchWithImage(image, table) def onValueChanged (spin): print spin.get_value() spin1.connect("value-changed", onValueChanged) spin2.connect("value-changed", onValueChanged) win.show_all() win.connect("delete-event", gtk.main_quit) gtk.main()
Python
import gamewidget firstRun = True def run(widgets, gameDic): global firstRun if firstRun: initialize(widgets, gameDic) firstRun = False widgets["game_info"].show() def initialize(widgets, gameDic): gamemodel = gameDic[gamewidget.cur_gmwidg()] widgets["event_entry"].set_text(gamemodel.tags["Event"]) widgets["site_entry"].set_text(gamemodel.tags["Site"]) widgets["round_spinbutton"].set_value(float(gamemodel.tags["Round"])) # Notice: GtkCalender month goes from 0 to 11, but gamemodel goes from # 1 to 12 widgets["game_info_calendar"].clear_marks() widgets["game_info_calendar"].select_month( gamemodel.tags["Month"]-1, gamemodel.tags["Year"]) widgets["game_info_calendar"].select_day(gamemodel.tags["Day"]) def hide_window(button, *args): widgets["game_info"].hide() return True def accept_new_properties(button, *args): gamemodel = gameDic[gamewidget.cur_gmwidg()] gamemodel.tags["Event"] = widgets["event_entry"].get_text() gamemodel.tags["Site"] = widgets["site_entry"].get_text() gamemodel.tags["Round"] = int(widgets["round_spinbutton"].get_value()) gamemodel.tags["Year"] = widgets["game_info_calendar"].get_date()[0] gamemodel.tags["Month"] = widgets["game_info_calendar"].get_date()[1] + 1 gamemodel.tags["Day"] = widgets["game_info_calendar"].get_date()[2] widgets["game_info"].hide() return True widgets["game_info"].connect("delete-event", hide_window) widgets["game_info_cancel_button"].connect("clicked", hide_window) widgets["game_info_ok_button"].connect("clicked", accept_new_properties)
Python
import gtk import pango import math import random from gtk.gdk import pixbuf_new_from_file from pychess.Players.Human import Human from pychess.Players.engineNest import discoverer from pychess.System import uistuff, conf from pychess.System.glock import glock_connect_after from pychess.System.prefix import addDataPrefix from pychess.Utils.GameModel import GameModel from pychess.Utils.IconLoader import load_icon from pychess.Utils.TimeModel import TimeModel from pychess.Utils.const import LOCAL, ARTIFICIAL, WHITE, BLACK, NORMALCHESS from pychess.Variants import variants from pychess.ic import ICLogon from pychess.widgets import ionest, newGameDialog from Background import giveBackground from ToggleComboBox import ToggleComboBox class TaskerManager (gtk.Table): def __init__ (self): gtk.Table.__init__(self) self.border = 20 giveBackground(self) self.connect("expose_event", self.expose) #self.set_homogeneous(True) def expose (self, widget, event): cr = widget.window.cairo_create() for widget in self.widgets: x = widget.get_allocation().x y = widget.get_allocation().y width = widget.get_allocation().width height = widget.get_allocation().height cr.move_to (x-self.border, y) cr.curve_to (x-self.border, y-self.border/2., x-self.border/2., y-self.border, x, y-self.border) cr.line_to (x+width, y-self.border) cr.curve_to (x+width+self.border/2., y-self.border, x+width+self.border, y-self.border/2., x+width+self.border, y) cr.line_to (x+width+self.border, y+height) cr.curve_to (x+width+self.border, y+height+self.border/2., x+width+self.border/2., y+height+self.border, x+width, y+height+self.border) cr.line_to (x, y+height+self.border) cr.curve_to (x-self.border/2., y+height+self.border, x-self.border, y+height+self.border/2., x-self.border, y+height) cr.set_source_color(self.get_style().bg[gtk.STATE_NORMAL]) cr.fill() cr.rectangle (x-self.border, y+height-30, width+self.border*2, 30) cr.set_source_color(self.get_style().dark[gtk.STATE_NORMAL]) cr.fill() def calcSpacings (self, n): """ Will yield ranges like ((.50,.50),) ((.66,.33), (.33,.66)) ((.75,.25), (.50,.50), (.25,.75)) ((.80,.20), (.60,.40), (.40,.60), (.20,.80)) Used to create the centering in the table """ first = next = (n)/float(n+1) for i in range(n): yield (next, 1-next) next = first-(1-next) def packTaskers (self, *widgets): self.widgets = widgets for widget in widgets: widget.connect("size-allocate", lambda *a: self.window.invalidate_rect(self.get_allocation(), False)) root = math.sqrt(len(widgets)) # Calculate number of rows rows = int(math.ceil(root)) # Calculate number of filled out rows rrows = int(math.floor(root)) # Calculate number of cols in filled out rows cols = int(math.ceil( len(widgets)/float(rows) )) # Calculate spacings vspac = [s[0] for s in self.calcSpacings(rows)] hspac = [s[0] for s in self.calcSpacings(cols)] # Clear and set up new size for child in self.get_children(): self.remove(child) self.props.n_columns = cols self.props.n_rows = rows # Add filled out rows for row in range(rrows): for col in range(cols): widget = widgets[row*cols + col] alignment = gtk.Alignment(hspac[col], vspac[row]) alignment.add(widget) self.attach(alignment, col, col+1, row, row+1) # Add last row if rows > rrows: lastrow = gtk.HBox() # Calculate number of widgets in last row numw = len(widgets) - cols*rrows hspac = [s[0] for s in self.calcSpacings(numw)] for col, widget in enumerate(widgets[-numw:]): alignment = gtk.Alignment(hspac[col], vspac[-1]) alignment.add(widget) alignment.set_padding(self.border, self.border, self.border, self.border) lastrow.pack_start(alignment) self.attach(lastrow, 0, cols, rrows, rrows+1) class NewGameTasker (gtk.Alignment): def __init__ (self): gtk.Alignment.__init__(self,0,0,0,0) self.widgets = widgets = uistuff.GladeWidgets("taskers.glade") tasker = widgets["newGameTasker"] tasker.unparent() self.add(tasker) combo = ToggleComboBox() combo.addItem(_("White"), pixbuf_new_from_file(addDataPrefix("glade/white.png"))) combo.addItem(_("Black"), pixbuf_new_from_file(addDataPrefix("glade/black.png"))) combo.addItem(_("Random"), pixbuf_new_from_file(addDataPrefix("glade/random.png"))) combo.setMarkup("<b>", "</b>") widgets["colorDock"].add(combo) uistuff.keep(combo, "newgametasker_colorcombo") widgets['yourColorLabel'].set_mnemonic_widget(combo) # We need to wait until after engines have been discovered, to init the # playerCombos. We use connect_after to make sure, that newGameDialog # has also had time to init the constants we share with them. self.playerCombo = ToggleComboBox() widgets["opponentDock"].add(self.playerCombo) glock_connect_after(discoverer, "all_engines_discovered", self.__initPlayerCombo, widgets) widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo) def on_skill_changed (scale): pix = newGameDialog.skillToIconLarge[int(scale.get_value())] widgets["skillImage"].set_from_pixbuf(pix) widgets["skillSlider"].connect("value-changed", on_skill_changed) on_skill_changed(widgets["skillSlider"]) widgets["startButton"].connect("clicked", self.startClicked) self.widgets["opendialog1"].connect("clicked", self.openDialogClicked) def __initPlayerCombo (self, discoverer, widgets): combo = self.playerCombo for image, name in newGameDialog.smallPlayerItems[0]: combo.addItem(name, image) combo.label.set_ellipsize(pango.ELLIPSIZE_MIDDLE) combo.setMarkup("<b>", "</b>") combo.active = 1 uistuff.keep(self.playerCombo, "newgametasker_playercombo") def on_playerCombobox_changed (widget, event): widgets["skillSlider"].props.visible = widget.active > 0 combo.connect("changed", on_playerCombobox_changed) uistuff.keep(widgets["skillSlider"], "taskerSkillSlider") widgets["skillSlider"].set_no_show_all(True) on_playerCombobox_changed(self.playerCombo, None) def openDialogClicked (self, button): newGameDialog.NewGameMode.run() def startClicked (self, button): color = self.widgets["colorDock"].child.active if color == 2: color = random.choice([WHITE, BLACK]) opponent = self.widgets["opponentDock"].child.active difficulty = int(self.widgets["skillSlider"].get_value()) gamemodel = GameModel(TimeModel(5*60, 0)) name = conf.get("firstName", _("You")) player0tup = (LOCAL, Human, (color, name), name) if opponent == 0: name = conf.get("secondName", _("Guest")) player1tup = (LOCAL, Human, (1-color, name), name) else: engine = discoverer.getEngineN (opponent-1) name = discoverer.getName(engine) player1tup = (ARTIFICIAL, discoverer.initPlayerEngine, (engine, 1-color, difficulty, variants[NORMALCHESS], 5*60, 0), name) if color == WHITE: ionest.generalStart(gamemodel, player0tup, player1tup) else: ionest.generalStart(gamemodel, player1tup, player0tup) big_start = load_icon(48, "stock_init", "gnome-globe", "applications-internet") class InternetGameTasker (gtk.Alignment): def __init__ (self): gtk.Alignment.__init__(self,0,0,0,0) self.widgets = uistuff.GladeWidgets("taskers.glade") tasker = self.widgets["internetGameTasker"] tasker.unparent() self.add(tasker) def asGuestCallback (checkbutton): for widget in (self.widgets["usernameLabel"], self.widgets["usernameEntry"], self.widgets["passwordLabel"], self.widgets["passwordEntry"]): widget.set_sensitive(not checkbutton.get_active()) self.widgets["asGuestCheck"].connect("toggled", asGuestCallback) uistuff.keep(self.widgets["asGuestCheck"], "asGuestCheck") uistuff.keep(self.widgets["usernameEntry"], "usernameEntry") uistuff.keep(self.widgets["passwordEntry"], "passwordEntry") self.widgets["connectButton"].connect("clicked", self.connectClicked) self.widgets["opendialog2"].connect("clicked", self.openDialogClicked) self.widgets["startIcon"].set_from_pixbuf(big_start) def openDialogClicked (self, button): ICLogon.run() def connectClicked (self, button): asGuest = self.widgets["asGuestCheck"].get_active() username = self.widgets["usernameEntry"].get_text() password = self.widgets["passwordEntry"].get_text() ICLogon.run() if not ICLogon.dialog.connection: ICLogon.dialog.widgets["logOnAsGuest"].set_active(asGuest) ICLogon.dialog.widgets["nameEntry"].set_text(username) ICLogon.dialog.widgets["passEntry"].set_text(password) ICLogon.dialog.widgets["connectButton"].clicked()
Python
import sys import time import math import gtk import gobject import cairo if sys.platform == 'win32': from pychess.System.WinRsvg import rsvg else: import rsvg from pychess.System.uistuff import addDataPrefix from pychess.System.repeat import repeat_sleep from pychess.System import glock MAX_FPS = 20 RAD_PS = 2*math.pi class Throbber (gtk.DrawingArea): def __init__(self, width, height): gtk.DrawingArea.__init__(self) self.connect("expose_event", self.__expose) self.surface = self.__loadSvg(addDataPrefix("glade/throbber.svg"), width, height) self.width = width self.height = height self.started = False repeat_sleep(self.redraw, 1./MAX_FPS) def __expose(self, widget, event): context = widget.window.cairo_create() if not self.started: self.started = time.time() ds = time.time() - self.started r = -RAD_PS * ds matrix = cairo.Matrix() matrix.translate(self.width/2, self.height/2) matrix.rotate(int(r/(2*math.pi)*12)/12.*2*math.pi) matrix.translate(-self.width/2, -self.height/2) context.transform(matrix) context.set_source_surface(self.surface, 0, 0) context.paint() def redraw (self): if self.window: glock.acquire() try: if self.window: a = self.get_allocation() rect = gtk.gdk.Rectangle(0, 0, a.width, a.height) self.window.invalidate_rect(rect, True) self.window.process_updates(True) return True finally: glock.release() def __loadSvg (self, path, width, height): svg = rsvg.Handle(path) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) context.set_operator(cairo.OPERATOR_SOURCE) if svg.props.width != width or svg.props.height != height: context.scale(width/float(svg.props.width), height/float(svg.props.height)) svg.render_cairo(context) return surface
Python
import os.path import gettext import locale from cStringIO import StringIO from operator import attrgetter from itertools import groupby import gtk from cairo import ImageSurface try: from gtksourceview import SourceBuffer from gtksourceview import SourceView from gtksourceview import SourceLanguagesManager as LanguageManager except ImportError: from gtksourceview2 import Buffer as SourceBuffer from gtksourceview2 import View as SourceView from gtksourceview2 import LanguageManager from pychess.Utils.IconLoader import load_icon from pychess.Utils.GameModel import GameModel from pychess.Utils.TimeModel import TimeModel from pychess.Utils.const import * from pychess.Utils.repr import localReprSign from pychess.System import uistuff from pychess.System.Log import log from pychess.System import conf from pychess.System.prefix import getDataPrefix, isInstalled, addDataPrefix from pychess.Players.engineNest import discoverer from pychess.Players.Human import Human from pychess.widgets import BoardPreview from pychess.widgets import ionest from pychess.widgets import ImageMenu from pychess.Savers import pgn from pychess.Variants import variants from pychess.Variants.normal import NormalChess #=============================================================================== # We init most dialog icons global to make them accessibly to the # Background.Taskers so they have a similar look. #=============================================================================== big_time = load_icon(48, "stock_alarm", "appointment-soon") big_people = load_icon(48, "stock_people", "system-users") iwheels = load_icon(24, "gtk-execute") ipeople = load_icon(24, "stock_people", "system-users") inotebook = load_icon(24, "stock_notebook", "computer") speople = load_icon(16, "stock_people", "system-users") snotebook = load_icon(16, "stock_notebook", "computer") skillToIcon = { 1: load_icon(16, "weather-clear"), 2: load_icon(16, "weather-few-clouds"), 3: load_icon(16, "weather-few-clouds"), 4: load_icon(16, "weather-overcast"), 5: load_icon(16, "weather-overcast"), 6: load_icon(16, "weather-showers"), 7: load_icon(16, "weather-showers"), 8: load_icon(16, "weather-storm"), } # Used by TaskerManager. Put here to help synchronization skillToIconLarge = { 1: load_icon(48, "weather-clear"), 2: load_icon(48, "weather-few-clouds"), 3: load_icon(48, "weather-few-clouds"), 4: load_icon(48, "weather-overcast"), 5: load_icon(48, "weather-overcast"), 6: load_icon(48, "weather-showers"), 7: load_icon(48, "weather-showers"), 8: load_icon(48, "weather-storm"), } playerItems = [] smallPlayerItems = [] def createPlayerUIGlobals (discoverer): global playerItems global smallPlayerItems for variantClass in variants.values(): playerItems += [ [(ipeople, _("Human Being"))] ] smallPlayerItems += [ [(speople, _("Human Being"))] ] for engine in discoverer.getEngines().values(): name = discoverer.getName(engine) c = discoverer.getCountry(engine) path = addDataPrefix("flags/%s.png" % c) if c and os.path.isfile(path): flag_icon = gtk.gdk.pixbuf_new_from_file(path) else: flag_icon = inotebook for variant in discoverer.getEngineVariants(engine): playerItems[variant] += [(flag_icon, name)] smallPlayerItems[variant] += [(snotebook, name)] discoverer.connect("all_engines_discovered", createPlayerUIGlobals) #=============================================================================== # GameInitializationMode is the super class of new game dialogs. Dialogs include # the standard new game dialog, the load file dialog and the enter notation # dialog. #=============================================================================== class _GameInitializationMode: @classmethod def _ensureReady (cls): if not hasattr(_GameInitializationMode, "superhasRunInit"): _GameInitializationMode._init() _GameInitializationMode.superhasRunInit = True if not hasattr(cls, "hasRunInit"): cls._init() cls.hasRunInit = True @classmethod def _init (cls): cls.widgets = uistuff.GladeWidgets ("newInOut.glade") uistuff.createCombo(cls.widgets["whitePlayerCombobox"], (i[:2] for i in playerItems[0])) uistuff.createCombo(cls.widgets["blackPlayerCombobox"], (i[:2] for i in playerItems[0])) cls.widgets["playersIcon"].set_from_pixbuf(big_people) cls.widgets["timeIcon"].set_from_pixbuf(big_time) def on_playerCombobox_changed (widget, skillHbox): skillHbox.props.visible = widget.get_active() > 0 cls.widgets["whitePlayerCombobox"].connect( "changed", on_playerCombobox_changed, cls.widgets["skillHbox1"]) cls.widgets["blackPlayerCombobox"].connect( "changed", on_playerCombobox_changed, cls.widgets["skillHbox2"]) cls.widgets["whitePlayerCombobox"].set_active(0) cls.widgets["blackPlayerCombobox"].set_active(1) def on_skill_changed (scale, image): image.set_from_pixbuf(skillToIcon[int(scale.get_value())]) cls.widgets["skillSlider1"].connect("value-changed", on_skill_changed, cls.widgets["skillIcon1"]) cls.widgets["skillSlider2"].connect("value-changed", on_skill_changed, cls.widgets["skillIcon2"]) cls.widgets["skillSlider1"].set_value(3) cls.widgets["skillSlider2"].set_value(3) cls.__initTimeRadio(_("Blitz"), "ngblitz", cls.widgets["blitzRadio"], cls.widgets["configImageBlitz"], 5, 0) cls.__initTimeRadio(_("Rapid"), "ngrapid", cls.widgets["rapidRadio"], cls.widgets["configImageRapid"], 15, 5) cls.__initTimeRadio(_("Normal"), "ngnormal", cls.widgets["normalRadio"], cls.widgets["configImageNormal"], 40, 15) cls.__initVariantRadio("ngvariant1", cls.widgets["playVariant1Radio"], cls.widgets["configImageVariant1"], FISCHERRANDOMCHESS) cls.__initVariantRadio("ngvariant2", cls.widgets["playVariant2Radio"], cls.widgets["configImageVariant2"], LOSERSCHESS) def updateCombos(*args): if cls.widgets["playNormalRadio"].get_active(): variant = NORMALCHESS elif cls.widgets["playVariant1Radio"].get_active(): variant = conf.get("ngvariant1", FISCHERRANDOMCHESS) else: variant = conf.get("ngvariant2", LOSERSCHESS) variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS) cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__) variant2 = conf.get("ngvariant2", LOSERSCHESS) cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__) uistuff.updateCombo(cls.widgets["blackPlayerCombobox"], playerItems[variant]) uistuff.updateCombo(cls.widgets["whitePlayerCombobox"], playerItems[variant]) conf.notify_add("ngvariant1", updateCombos) conf.notify_add("ngvariant2", updateCombos) cls.widgets["playNormalRadio"].connect("toggled", updateCombos) cls.widgets["playNormalRadio"].set_tooltip_text(variants[NORMALCHESS].__desc__) cls.widgets["playVariant1Radio"].connect("toggled", updateCombos) variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS) cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__) cls.widgets["playVariant2Radio"].connect("toggled", updateCombos) variant2 = conf.get("ngvariant2", LOSERSCHESS) cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__) # The "variant" has to come before players, because the engine positions # in the user comboboxes can be different in different variants for key in ("whitePlayerCombobox", "blackPlayerCombobox", "skillSlider1", "skillSlider2", "notimeRadio", "blitzRadio", "rapidRadio", "normalRadio", "playNormalRadio", "playVariant1Radio", "playVariant2Radio"): uistuff.keep(cls.widgets[key], key) # We don't want the dialog to deallocate when closed. Rather we hide # it on respond cls.widgets["newgamedialog"].connect("delete_event", lambda *a: True) @classmethod def __initTimeRadio (cls, name, id, radiobutton, configImage, defmin, defgain): minSpin = gtk.SpinButton(gtk.Adjustment(1,1,240,1)) gainSpin = gtk.SpinButton(gtk.Adjustment(0,-60,60,1)) cls.widgets["%s min" % id] = minSpin cls.widgets["%s gain" % id] = gainSpin uistuff.keep(minSpin, "%s min" % id, first_value=defmin) uistuff.keep(gainSpin, "%s gain" % id, first_value=defgain) table = gtk.Table(2, 2) table.props.row_spacing = 3 table.props.column_spacing = 12 label = gtk.Label(_("Minutes:")) label.props.xalign = 0 table.attach(label, 0, 1, 0, 1) table.attach(minSpin, 1, 2, 0, 1) label = gtk.Label(_("Gain:")) label.props.xalign = 0 table.attach(label, 0, 1, 1, 2) table.attach(gainSpin, 1, 2, 1, 2) alignment = gtk.Alignment(1,1,1,1) alignment.set_padding(6,6,12,12) alignment.add(table) ImageMenu.switchWithImage(configImage, alignment) def updateString (spin): minutes = minSpin.get_value_as_int() gain = gainSpin.get_value_as_int() if gain > 0: radiobutton.set_label(_("%(name)s %(minutes)d min + %(gain)d sec/move") % { 'name': name, 'minutes': minutes, 'gain': gain}) elif gain < 0: radiobutton.set_label(_("%(name)s %(minutes)d min %(gain)d sec/move") % { 'name': name, 'minutes': minutes, 'gain': gain}) else: radiobutton.set_label(_("%(name)s %(minutes)d min") % { 'name': name, 'minutes': minutes}) minSpin.connect("value-changed", updateString) gainSpin.connect("value-changed", updateString) updateString(None) @classmethod def __initVariantRadio (cls, confid, radiobutton, configImage, default): model = gtk.TreeStore(str) treeview = gtk.TreeView(model) treeview.set_headers_visible(False) treeview.append_column(gtk.TreeViewColumn(None, gtk.CellRendererText(), text=0)) alignment = gtk.Alignment(1,1,1,1) alignment.set_padding(6,6,12,12) alignment.add(treeview) ImageMenu.switchWithImage(configImage, alignment) groupNames = {VARIANTS_BLINDFOLD: _("Blindfold"), VARIANTS_ODDS: _("Odds"), VARIANTS_SHUFFLE: _("Shuffle"), VARIANTS_OTHER: _("Other")} specialVariants = [v for v in variants.values() if v != NormalChess] groups = groupby(specialVariants, attrgetter("variant_group")) pathToVariant = {} variantToPath = {} for i, (id, group) in enumerate(groups): iter = model.append(None, (groupNames[id],)) for variant in group: subiter = model.append(iter, (variant.name,)) path = model.get_path(subiter) pathToVariant[path] = variant.board.variant variantToPath[variant.board.variant] = path treeview.expand_row((i,), True) selection = treeview.get_selection() selection.set_mode(gtk.SELECTION_BROWSE) selection.set_select_function(lambda path: len(path) > 1) selection.select_path(variantToPath[conf.get(confid, default)]) def callback (selection): model, iter = selection.get_selected() if iter: radiobutton.set_label("%s" % model.get(iter, 0) + _(" chess")) path = model.get_path(iter) variant = pathToVariant[path] conf.set(confid, variant) selection.connect("changed", callback) callback(selection) @classmethod def _generalRun (cls, callback): def onResponse(dialog, res): cls.widgets["newgamedialog"].hide() cls.widgets["newgamedialog"].disconnect(handlerId) if res != gtk.RESPONSE_OK: return # Find variant if cls.widgets["playNormalRadio"].get_active(): variant_index = NORMALCHESS elif cls.widgets["playVariant1Radio"].get_active(): variant_index = conf.get("ngvariant1", FISCHERRANDOMCHESS) else: variant_index = conf.get("ngvariant2", LOSERSCHESS) variant = variants[variant_index] # Find time if cls.widgets["notimeRadio"].get_active(): secs = 0 incr = 0 elif cls.widgets["blitzRadio"].get_active(): secs = cls.widgets["ngblitz min"].get_value_as_int()*60 incr = cls.widgets["ngblitz gain"].get_value_as_int() elif cls.widgets["rapidRadio"].get_active(): secs = cls.widgets["ngrapid min"].get_value_as_int()*60 incr = cls.widgets["ngrapid gain"].get_value_as_int() elif cls.widgets["normalRadio"].get_active(): secs = cls.widgets["ngnormal min"].get_value_as_int()*60 incr = cls.widgets["ngnormal gain"].get_value_as_int() # Find players player0 = cls.widgets["whitePlayerCombobox"].get_active() player0 = playerItems[0].index(playerItems[variant_index][player0]) diffi0 = int(cls.widgets["skillSlider1"].get_value()) player1 = cls.widgets["blackPlayerCombobox"].get_active() player1 = playerItems[0].index(playerItems[variant_index][player1]) diffi1 = int(cls.widgets["skillSlider2"].get_value()) # Prepare players for ionest playertups = [] for i, playerno, diffi, color in ((0, player0, diffi0, WHITE), (1, player1, diffi1, BLACK)): if playerno > 0: engine = discoverer.getEngineN (playerno-1) name = discoverer.getName(engine) playertups.append((ARTIFICIAL, discoverer.initPlayerEngine, (engine, color, diffi, variant, secs, incr), name)) else: if not playertups or playertups[0][0] != LOCAL: name = conf.get("firstName", _("You")) else: name = conf.get("secondName", _("Guest")) playertups.append((LOCAL, Human, (color, name), name)) if secs > 0: timemodel = TimeModel (secs, incr) else: timemodel = None gamemodel = GameModel (timemodel, variant) callback(gamemodel, playertups[0], playertups[1]) handlerId = cls.widgets["newgamedialog"].connect("response", onResponse) cls.widgets["newgamedialog"].show() @classmethod def _hideOthers (cls): for extension in ("loadsidepanel", "enterGameNotationSidePanel", "enterGameNotationSidePanel"): cls.widgets[extension].hide() ################################################################################ # NewGameMode # ################################################################################ class NewGameMode (_GameInitializationMode): @classmethod def _init (cls): # We have to override this, so the GameInitializationMode init method # isn't called twice pass @classmethod def run (cls): cls._ensureReady() if cls.widgets["newgamedialog"].props.visible: cls.widgets["newgamedialog"].present() return cls._hideOthers() cls.widgets["newgamedialog"].set_title(_("New Game")) cls._generalRun(ionest.generalStart) ################################################################################ # LoadFileExtension # ################################################################################ class LoadFileExtension (_GameInitializationMode): @classmethod def _init (cls): opendialog, savedialog, enddir, savecombo, savers = ionest.getOpenAndSaveDialogs() cls.filechooserbutton = gtk.FileChooserButton(opendialog) cls.loadSidePanel = BoardPreview.BoardPreview(cls.widgets, cls.filechooserbutton, opendialog, enddir) @classmethod def run (cls, uri=None): cls._ensureReady() if cls.widgets["newgamedialog"].props.visible: cls.widgets["newgamedialog"].present() return if not uri: res = ionest.opendialog.run() ionest.opendialog.hide() if res != gtk.RESPONSE_ACCEPT: return else: if not uri[uri.rfind(".")+1:] in ionest.enddir: log.log("Ignoring strange file: %s" % uri) return cls.loadSidePanel.set_filename(uri) cls.filechooserbutton.emit("file-activated") cls._hideOthers() cls.widgets["newgamedialog"].set_title(_("Open Game")) cls.widgets["loadsidepanel"].show() def _callback (gamemodel, p0, p1): if not cls.loadSidePanel.is_empty(): uri = cls.loadSidePanel.get_filename() loader = ionest.enddir[uri[uri.rfind(".")+1:]] position = cls.loadSidePanel.get_position() gameno = cls.loadSidePanel.get_gameno() ionest.generalStart(gamemodel, p0, p1, (uri, loader, gameno, position)) else: ionest.generalStart(gamemodel, p0, p1) cls._generalRun(_callback) ################################################################################ # EnterNotationExtension # ################################################################################ class EnterNotationExtension (_GameInitializationMode): @classmethod 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 = SourceBuffer() sourceview = SourceView(cls.sourcebuffer) 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.WRAP_WORD) man = 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.warn("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.warn("Unable to load pgn syntax-highlighting.") cls.sourcebuffer.set_highlight(True) @classmethod def run (cls): cls._ensureReady() if cls.widgets["newgamedialog"].props.visible: cls.widgets["newgamedialog"].present() return cls._hideOthers() cls.widgets["newgamedialog"].set_title(_("Enter Game")) cls.widgets["enterGameNotationSidePanel"].show() def _callback (gamemodel, p0, p1): text = cls.sourcebuffer.get_text( cls.sourcebuffer.get_start_iter(), cls.sourcebuffer.get_end_iter()) # Test if the ImageButton has two layers and is set on the local language if len(cls.ib.surfaces) == 2 and cls.ib.current == 0: # 2 step used to avoid backtranslating # (local and english piece letters can overlap) for i, sign in enumerate(localReprSign[1:]): if sign.strip(): text = text.replace(sign, FAN_PIECES[0][i+1]) for i, sign in enumerate(FAN_PIECES[0][1:7]): text = text.replace(sign, reprSign[i+1]) text = str(text) ionest.generalStart(gamemodel, p0, p1, (StringIO(text), pgn, 0, -1)) cls._generalRun(_callback) class ImageButton(gtk.DrawingArea): def __init__ (self, imagePaths): gtk.DrawingArea.__init__(self) self.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.BUTTON_PRESS_MASK) self.connect("expose-event", self.draw) self.connect("button_press_event", self.buttonPress) self.surfaces = [ImageSurface.create_from_png(path) for path in imagePaths] self.current = 0 width, height = self.surfaces[0].get_width(), self.surfaces[0].get_height() self.size = gtk.gdk.Rectangle(0, 0, width, height) self.set_size_request(width, height) def draw (self, self_, event): context = self.window.cairo_create() context.rectangle (event.area.x, event.area.y, event.area.width, event.area.height) context.set_source_surface(self.surfaces[self.current], 0, 0) context.fill() def buttonPress (self, self_, event): if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS: self.current = (self.current + 1) % len(self.surfaces) self.window.invalidate_rect(self.size, True) self.window.process_updates(True) def createRematch (gamemodel): """ If gamemodel contains only LOCAL or ARTIFICIAL players, this starts a new game, based on the info in gamemodel """ if gamemodel.timemodel: secs = gamemodel.timemodel.intervals[0][WHITE] gain = gamemodel.timemodel.gain newgamemodel = GameModel(TimeModel(secs, gain), gamemodel.variant) else: secs = 0 gain = 0 newgamemodel = GameModel(variant=gamemodel.variant) wp = gamemodel.players[WHITE] bp = gamemodel.players[BLACK] if wp.__type__ == LOCAL: player1tup = (wp.__type__, wp.__class__, (BLACK, repr(wp)), repr(wp)) if bp.__type__ == LOCAL: player0tup = (bp.__type__, bp.__class__, (WHITE, repr(wp)), repr(bp)) else: binname = bp.engine.path.split("/")[-1] if binname == "python": binname = bp.engine.args[1].split("/")[-1] xmlengine = discoverer.getEngines()[binname] player0tup = (ARTIFICIAL, discoverer.initPlayerEngine, (xmlengine, WHITE, bp.strength, gamemodel.variant, secs, gain), repr(bp)) else: player0tup = (bp.__type__, bp.__class__, (WHITE, ""), repr(bp)) binname = wp.engine.path.split("/")[-1] if binname == "python": binname = wp.engine.args[1].split("/")[-1] xmlengine = discoverer.getEngines()[binname] player1tup = (ARTIFICIAL, discoverer.initPlayerEngine, (xmlengine, BLACK, wp.strength, gamemodel.variant, secs, gain), repr(wp)) ionest.generalStart(newgamemodel, player0tup, player1tup)
Python
from time import strftime, gmtime, localtime import random import gtk from gtk.gdk import keyval_from_name import pango import gobject from pychess.System import uistuff from BorderBox import BorderBox class ChatView (gtk.VPaned): __gsignals__ = { 'messageAdded' : (gobject.SIGNAL_RUN_FIRST, None, (str,str,object)), 'messageTyped' : (gobject.SIGNAL_RUN_FIRST, None, (str,)) } def __init__ (self): gtk.VPaned.__init__(self) # States for the color generator self.colors = {} self.startpoint = random.random() # Inits the read view self.readView = gtk.TextView() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sw.set_shadow_type(gtk.SHADOW_NONE) uistuff.keepDown(sw) sw.add(self.readView) self.readView.set_editable(False) self.readView.props.wrap_mode = gtk.WRAP_WORD self.readView.props.pixels_below_lines = 1 self.readView.props.pixels_above_lines = 2 self.readView.props.left_margin = 2 #self.readView.get_buffer().create_tag("log", # foreground = self.readView.get_style().fg[gtk.STATE_INSENSITIVE]) self.pack1(BorderBox(sw,bottom=True), resize=True, shrink=True) # Create a 'log mark' in the beginning of the text buffer. Because we # query the log asynchronously and in chunks, we can use this to insert # it correctly after previous log messages, but before the new messages. start = self.readView.get_buffer().get_start_iter() self.readView.get_buffer().create_mark("logMark", start) # Inits the write view self.writeView = gtk.TextView() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sw.set_shadow_type(gtk.SHADOW_NONE) sw.add(self.writeView) self.writeView.props.wrap_mode = gtk.WRAP_WORD self.writeView.props.pixels_below_lines = 1 self.writeView.props.pixels_above_lines = 2 self.writeView.props.left_margin = 2 self.pack2(BorderBox(sw,top=True), resize=True, shrink=True) # Forces are reasonable position for the panner. def callback (widget, event): widget.disconnect(handle_id) allocation = widget.get_allocation() self.set_position(int(max(0.79*allocation.height, allocation.height-60))) handle_id = self.connect("expose-event", callback) self.writeView.connect("key-press-event", self.onKeyPress) def _ensureColor(self, pref): """ Ensures that the tags for pref_normal and pref_bold are set in the text buffer """ tb = self.readView.get_buffer() if not pref in self.colors: color = uistuff.genColor(len(self.colors) + 1, self.startpoint) self.colors[pref] = color color = [int(c * 255) for c in color] color = "#" + "".join([hex(v)[2:].zfill(2) for v in color]) tb.create_tag(pref + "_normal", foreground=color) tb.create_tag(pref + "_bold", foreground=color, weight=pango.WEIGHT_BOLD) def clear (self): self.writeView.get_buffer().props.text = "" self.readView.get_buffer().props.text = "" tagtable = self.readView.get_buffer().get_tag_table() for i in xrange(len(self.colors)): tagtable.remove("%d_normal" % i) tagtable.remove("%d_bold" % i) self.colors.clear() def __addMessage (self, iter, time, sender, text): pref = sender.lower() tb = self.readView.get_buffer() # Calculate a color for the sender self._ensureColor(pref) # Insert time, name and text with different stylesd tb.insert_with_tags_by_name(iter, "(%s) "%time, pref+"_normal") tb.insert_with_tags_by_name(iter, sender+": ", pref+"_bold") tb.insert(iter, text) # This is used to buzz the user and add senders to a list of active participants self.emit("messageAdded", sender, text, self.colors[pref]) def insertLogMessage (self, timestamp, sender, text): """ Takes a list of (timestamp, sender, text) pairs, and inserts them in the beginning of the document. All text will be in a gray color """ tb = self.readView.get_buffer() iter = tb.get_iter_at_mark(tb.get_mark("logMark")) time = strftime("%H:%M:%S", localtime(timestamp)) self.__addMessage(iter, time, sender, text) tb.insert(iter, "\n") def addMessage (self, sender, text): tb = self.readView.get_buffer() iter = tb.get_end_iter() # Messages have linebreak before the text. This is opposite to log # messages if tb.props.text: tb.insert(iter, "\n") self.__addMessage(iter, strftime("%H:%M:%S"), sender, text) def disable (self, message): """ Sets the write field insensitive, in cases where the channel is read only. Use the message to give the user a propriate exlpanation """ self.writeView.set_sensitive(False) self.writeView.props.buffer.set_text(message) def enable (self): self.writeView.props.buffer.set_text("") self.writeView.set_sensitive(True) def onKeyPress (self, widget, event): if event.keyval in map(keyval_from_name,("Return", "KP_Enter")): if not event.state & gtk.gdk.CONTROL_MASK: buffer = self.writeView.get_buffer() self.emit("messageTyped", buffer.props.text) buffer.props.text = "" return True
Python
import gtk, cairo from math import ceil as fceil ceil = lambda f: int(fceil(f)) from __init__ import NORTH, EAST, SOUTH, WEST, CENTER from OverlayWindow import OverlayWindow class HighlightArea (OverlayWindow): """ An entirely blue widget """ def __init__ (self, parent): OverlayWindow.__init__(self, parent) self.myparent = parent self.connect_after("expose-event", self.__onExpose) def showAt (self, position): alloc = self.myparent.get_allocation() if position == NORTH: x, y = 0, 0 width, height = alloc.width, alloc.height*0.381966011 elif position == EAST: x, y = alloc.width*0.618033989, 0 width, height = alloc.width*0.381966011, alloc.height elif position == SOUTH: x, y = 0, alloc.height*0.618033989 width, height = alloc.width, alloc.height*0.381966011 elif position == WEST: x, y = 0, 0 width, height = alloc.width*0.381966011, alloc.height elif position == CENTER: x, y = 0, 0 width, height = alloc.width, alloc.height x, y = self.translateCoords(int(x), int(y)) self.move(x, y) self.resize(ceil(width), ceil(height)) self.show() def __onExpose (self, self_, event): context = self.window.cairo_create() context.rectangle(event.area) if self.is_composited(): color = self.get_style().light[gtk.STATE_SELECTED] context.set_operator(cairo.OPERATOR_CLEAR) context.set_source_rgba(0,0,0,0.0) context.fill_preserve () context.set_operator(cairo.OPERATOR_OVER) context.set_source_rgba(color.red/65535., color.green/65535., color.blue/65535., 0.5) context.fill() else: context.set_source_color(self.get_style().light[gtk.STATE_SELECTED]) context.set_operator(cairo.OPERATOR_OVER) context.fill()
Python
import os import re import sys import gtk import cairo if sys.platform == 'win32': from pychess.System.WinRsvg import rsvg else: import rsvg class OverlayWindow (gtk.Window): """ This class knows about being an overlaywindow and some svg stuff """ cache = {} # Class global self.cache for svgPath:rsvg and (svgPath,w,h):surface def __init__ (self, parent): gtk.Window.__init__(self, gtk.WINDOW_POPUP) colormap = self.get_screen().get_rgba_colormap() if colormap: self.set_colormap(colormap) self.myparent = parent #=========================================================================== # The overlay stuff #=========================================================================== def paintTransparent (self, cairoContext): if self.is_composited(): cairoContext.set_operator(cairo.OPERATOR_CLEAR) cairoContext.set_source_rgba(0,0,0,0) cairoContext.paint() cairoContext.set_operator(cairo.OPERATOR_OVER) def digAHole (self, svgShape, width, height): # Create a bitmap and clear it mask = gtk.gdk.Pixmap(None, width, height, 1) mcontext = mask.cairo_create() mcontext.set_source_rgb(0, 0, 0) mcontext.set_operator(cairo.OPERATOR_DEST_OUT) mcontext.paint() # Paint our shape surface = self.getSurfaceFromSvg(svgShape, width, height) mcontext.set_operator(cairo.OPERATOR_OVER) mcontext.set_source_surface(surface, 0, 0) mcontext.paint() # Apply it only if aren't composited, in which case we only need input # masking if self.is_composited(): self.window.input_shape_combine_mask(mask, 0, 0) else: self.window.shape_combine_mask(mask, 0, 0) def translateCoords (self, x, y): x1, y1 = self.myparent.window.get_position() x += x1 + self.myparent.get_allocation().x y += y1 + self.myparent.get_allocation().y return x, y #=========================================================================== # The SVG stuff #=========================================================================== def getSurfaceFromSvg (self, svgPath, width, height): path = os.path.abspath(svgPath) if (path, width, height) in self.cache: return self.cache[(path, width, height)] else: if path in self.cache: svg = self.cache[path] else: svg = self.__loadNativeColoredSvg(path) self.cache[path] = svg surface = self.__svgToSurface(svg, width, height) self.cache[(path, width, height)] = surface return surface def getSizeOfSvg (self, svgPath): path = os.path.abspath(svgPath) if not path in self.cache: svg = self.__loadNativeColoredSvg(path) self.cache[path] = svg svg = self.cache[path] return (svg.props.width, svg.props.height) def __loadNativeColoredSvg (self, svgPath): def colorToHex (color, state): color = getattr(self.myparent.get_style(), color)[state] pixels = (color.red, color.green, color.blue) return "#"+"".join(hex(c/256)[2:].zfill(2) for c in pixels) TEMP_PATH = "/tmp/pychess_theamed.svg" colorDic = {"#18b0ff": colorToHex("light", gtk.STATE_SELECTED), "#575757": colorToHex("text_aa", gtk.STATE_PRELIGHT), "#e3ddd4": colorToHex("bg", gtk.STATE_NORMAL), "#d4cec5": colorToHex("bg", gtk.STATE_INSENSITIVE), "#ffffff": colorToHex("base", gtk.STATE_NORMAL), "#000000": colorToHex("fg", gtk.STATE_NORMAL)} data = file(svgPath).read() data = re.sub("|".join(colorDic.keys()), lambda m: m.group() in colorDic and colorDic[m.group()] or m.group(), data) f = file(TEMP_PATH, "w") f.write(data) f.close() svg = rsvg.Handle(TEMP_PATH) os.remove(TEMP_PATH) return svg def __svgToSurface (self, svg, width, height): assert type(width) == int surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) context.set_operator(cairo.OPERATOR_SOURCE) if svg.props.width != width or svg.props.height != height: context.scale(width/float(svg.props.width), height/float(svg.props.height)) svg.render_cairo(context) return surface def __onStyleSet (self, self_, oldstyle): self.cache.clear()
Python
from math import ceil as float_ceil ceil = lambda f: int(float_ceil(f)) import gtk, cairo import gobject from OverlayWindow import OverlayWindow POSITIONS_COUNT = 5 NORTH, EAST, SOUTH, WEST, CENTER = range(POSITIONS_COUNT) DX_DY = ((0,-1), (1,0), (0,1), (-1,0), (0,0)) PADDING_X = 0.2 # Amount of button width PADDING_Y = 0.4 # Amount of button height class StarArrowButton (OverlayWindow): __gsignals__ = { 'dropped' : (gobject.SIGNAL_RUN_FIRST, None, (int, object)), 'hovered' : (gobject.SIGNAL_RUN_FIRST, None, (int, object)), 'left' : (gobject.SIGNAL_RUN_FIRST, None, ()), } def __init__ (self, parent, northSvg, eastSvg, southSvg, westSvg, centerSvg, bgSvg): OverlayWindow.__init__(self, parent) self.myparent = parent self.svgs = (northSvg, eastSvg, southSvg, westSvg, centerSvg) self.bgSvg = bgSvg self.size = () self.connect_after("expose-event", self.__onExposeEvent) self.currentHovered = -1 targets = [("GTK_NOTEBOOK_TAB", gtk.TARGET_SAME_APP, 0xbadbeef)] self.drag_dest_set(gtk.DEST_DEFAULT_DROP | gtk.DEST_DEFAULT_MOTION, targets, gtk.gdk.ACTION_MOVE) self.drag_dest_set_track_motion(True) self.connect("drag-motion", self.__onDragMotion) self.connect("drag-leave", self.__onDragLeave) self.connect("drag-drop", self.__onDragDrop) self.myparentAlloc = None self.myparentPos = None self.hasHole = False self.size = () def _calcSize (self): parentAlloc = self.myparent.get_allocation() if self.myparentAlloc == None or \ parentAlloc.width != self.myparentAlloc.width or \ parentAlloc.height != self.myparentAlloc.height: starWidth, starHeight = self.getSizeOfSvg(self.bgSvg) scale = min(1, parentAlloc.width / float(starWidth), parentAlloc.height / float(starHeight)) self.size = map(int, (starWidth*scale, starHeight*scale)) self.resize(self.size[0], self.size[1]) if self.window: self.hasHole = True self.digAHole(self.bgSvg, self.size[0], self.size[1]) elif not self.hasHole: self.hasHole = True self.digAHole(self.bgSvg, self.size[0], self.size[1]) if self.myparent.window: x, y = self.translateCoords(int(parentAlloc.width/2. - self.size[0]/2.), int(parentAlloc.height/2. - self.size[1]/2.)) if (x,y) != self.get_position(): self.move(x, y) self.myparentPos = self.myparent.window.get_position() self.myparentAlloc = parentAlloc def __onExposeEvent (self, self_, event): self._calcSize() context = self.window.cairo_create() self.paintTransparent(context) surface = self.getSurfaceFromSvg(self.bgSvg, self.size[0], self.size[1]) context.set_source_surface(surface, 0, 0) context.paint() for position in range(POSITIONS_COUNT): rect = self.__getButtonRectangle(position) context = self.window.cairo_create() surface = self.getSurfaceFromSvg(self.svgs[position], rect.width, rect.height) context.set_source_surface(surface, rect.x, rect.y) context.paint() def __getButtonRectangle (self, position): starWidth, starHeight = self.getSizeOfSvg(self.bgSvg) buttonWidth, buttonHeight = self.getSizeOfSvg(self.svgs[position]) buttonWidth = buttonWidth * self.size[0]/float(starWidth) buttonHeight = buttonHeight * self.size[1]/float(starHeight) dx, dy = DX_DY[position] x = ceil(dx*(1+PADDING_X)*buttonWidth - buttonWidth/2. + self.size[0]/2.) y = ceil(dy*(1+PADDING_Y)*buttonHeight - buttonHeight/2. + self.size[1]/2.) return gtk.gdk.Rectangle(x, y, ceil(buttonWidth), ceil(buttonHeight)) def __getButtonAtPoint (self, x, y): for position in xrange(POSITIONS_COUNT): region = gtk.gdk.region_rectangle(self.__getButtonRectangle(position)) if region.point_in(x, y): return position return -1 def __onDragMotion (self, arrow, context, x, y, timestamp): position = self.__getButtonAtPoint(x, y) if self.currentHovered != position: self.currentHovered = position if position > -1: self.emit("hovered", position, context.get_source_widget()) else: self.emit("left") if position > -1: context.drag_status (gtk.gdk.ACTION_MOVE, timestamp) return True context.drag_status (gtk.gdk.ACTION_DEFAULT, timestamp) def __onDragLeave (self, arrow, context, timestamp): if self.currentHovered != -1: self.currentHovered = -1 self.emit("left") def __onDragDrop (self, arrow, context, x, y, timestamp): position = self.__getButtonAtPoint(x, y) if position > -1: self.emit("dropped", position, context.get_source_widget()) context.finish(True, True, timestamp) return True if __name__ == "__main__": w = gtk.Window() w.connect("delete-event", gtk.main_quit) sab = StarArrowButton(w, "/home/thomas/Programmering/workspace/pychess/glade/dock_top.svg", "/home/thomas/Programmering/workspace/pychess/glade/dock_right.svg", "/home/thomas/Programmering/workspace/pychess/glade/dock_bottom.svg", "/home/thomas/Programmering/workspace/pychess/glade/dock_left.svg", "/home/thomas/Programmering/workspace/pychess/glade/dock_center.svg", "/home/thomas/Programmering/workspace/pychess/glade/dock_star.svg") def on_expose (widget, event): cr = widget.window.cairo_create() cx = cy = 100 r = 50 cr.arc(cx, cy, r-1, 0, 2*math.pi) cr.set_source_rgba(1.0, 0.0, 0.0, 1.0) cr.set_operator(cairo.OPERATOR_OVER) cr.fill() #w.connect("e) w.show_all() sab.show_all() gtk.main() #if __name__ != "__main__": # w = gtk.Window() # w.connect("delete-event", gtk.main_quit) # hbox = gtk.HBox() # # l = gtk.Layout() # l.set_size_request(200,200) # sab = StarArrowButton("/home/thomas/Programmering/workspace/pychess/glade/dock_top.svg", # "/home/thomas/Programmering/workspace/pychess/glade/dock_right.svg", # "/home/thomas/Programmering/workspace/pychess/glade/dock_bottom.svg", # "/home/thomas/Programmering/workspace/pychess/glade/dock_left.svg", # "/home/thomas/Programmering/workspace/pychess/glade/dock_center.svg", # "/home/thomas/Programmering/workspace/pychess/glade/dock_star.svg") # sab.set_size_request(200,200) # l.put(sab, 0, 0) # hbox.add(l) # def handle (*args): # sab.showAt(l, CENTER) # l.connect("button-press-event", handle) # # nb = gtk.Notebook() # label = gtk.Label("hi") # nb.append_page(label) # nb.set_tab_detachable(label, True) # hbox.add(nb) # w.add(hbox) # w.show_all() # gtk.main()
Python