/usr/share/pyshared/pychess/ic/ICLounge.py is in pychess 0.12~beta3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 | # -*- 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.ConsoleWindow import ConsoleWindow
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, connection, helperconn, host):
GObject.__init__(self)
self.connection = connection
self.helperconn = helperconn
self.host = host
self.need_who = True
self.need_games = True
self.widgets = 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(self.widgets, self.connection),
UserInfoSection(self.widgets, self.connection, self.host),
NewsSection(self.widgets, self.connection),
SeekTabSection(self.widgets, self.connection, self.infobar),
SeekGraphSection(self.widgets, self.connection),
PlayerTabSection(self.widgets, self.connection),
GameTabSection(self.widgets, self.connection),
AdjournedTabSection(self.widgets, self.connection, self.infobar),
ChatWindow(self.widgets, self.connection),
ConsoleWindow(self.widgets, self.connection),
SeekChallengeSection(self.widgets, self.connection),
# This is not really a section. It handles server messages which
# don't correspond to a running game
Messages(self.widgets, self.connection, 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(self.widgets, self.connection)
)
self.widgets['notebook'].connect("switch-page", self.onSwitchPage)
def onSwitchPage(self, notebook, page, page_num):
# We don't want to slow down the login process, so load
# all players and all games just on first time when needed
#b: blitz l: lightning u: untimed e: examined game
#s: standard w: wild x: atomic z: crazyhouse
#B: Bughouse L: losers S: Suicide
if notebook.get_nth_page(page_num) == self.widgets['playersListContent']:
if self.need_who:
# New ivar pin
# http://www.freechess.org/Help/HelpFiles/new_features.html
self.helperconn.client.run_command("who IsblwzL")
self.need_who = False
if notebook.get_nth_page(page_num) == self.widgets['gamesListContent']:
if self.need_games:
self.helperconn.client.run_command("games /sblwzL")
self.need_games = False
@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
if self.helperconn != None:
self.helperconn.close()
self.helperconn = 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"])
#widgets["show_console_button"].hide()
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, host):
self.widgets = widgets
self.connection = connection
self.host = host
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(self.host)
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
player = self.connection.players.get(FICSPlayer(seek["w"]))
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")
player = self.connection.players.get(FICSPlayer(match["w"]))
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>%(time)s</b> " + \
"<b>%(gametype)s</b> game.") % {"time": time, "gametype": match["gametype"].display_text}
else:
text = _(" challenges you to a <b>%(time)s</b> %(rated)s <b>%(gametype)s</b> game.") \
% {"time": time, "rated": rated.lower(), "gametype": 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):
self.connection.client.run_command("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.refresh_seeks()
########################################################################
# 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
player = self.connection.players.get(FICSPlayer(seek["w"]))
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, int, str, str)
self.tv.set_model(gtk.TreeModelSort(self.store))
self.addColumns(self.tv, "FICSPlayer", "", _("Name"), _("Blitz"),
_("Standard"), _("Lightning"), _("Crazyhouse"), _("Wild"), _("Status"), "tooltip", hide=[0,6,7,9],
pix=[1])
self.tv.set_tooltip_column(9,)
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)
@classmethod
def getPlayerTooltipText (cls, player):
text = "%s" % player.name
text += "%s" % player.display_titles(long=True)
if player.blitz:
text += "\n%s: %s" % (_("Blitz"), player.blitz)
if player.standard:
text += "\n%s: %s" % (_("Standard"), player.standard)
if player.lightning:
text += "\n%s: %s" % (_("Lightning"), player.lightning)
if player.crazyhouse:
text += "\n%s: %s" % (_("Crazyhouse"), player.crazyhouse)
if player.wild:
text += "\n%s: %s" % (_("Wild"), player.wild)
text += "\n%s" % player.display_status
return text
@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.crazyhouse, player.wild, player.display_status,
self.getPlayerTooltipText(player)])
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_CRAZYHOUSE, 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 "private" in self.players[player] 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_CRAZYHOUSE, 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"], 8, player.display_status)
self.store.set(self.players[player]["ti"], 9,
self.getPlayerTooltipText(player))
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())
self.store.set(self.players[player]["ti"], 9,
self.getPlayerTooltipText(player))
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())
self.store.set(self.players[player]["ti"], 9,
self.getPlayerTooltipText(player))
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_CRAZYHOUSE:
self.store.set(ti, 6, player.crazyhouse)
elif rating.type == TYPE_WILD:
self.store.set(ti, 7, 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):
'''When the player selects a player from the player list, update the clickability of our buttons.'''
player = self.getSelectedPlayer()
user_name = self.connection.getUsername()
self.widgets["private_chat_button"].set_sensitive(player is not None)
self.widgets["observe_button"].set_sensitive(
player is not None and player.isObservable()\
and user_name not in (player.game.wplayer.name, player.game.bplayer.name))
self.widgets["challengeButton"].set_sensitive(
player is not None and player.isAvailableForGame() and player.name!=user_name)
########################################################################
# 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 and game.supported:
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):
if game in self.games:
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 = _("%(player)s is %(status)s") % \
{"player": player.name, "status": 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>%(timecontrol)s</b> <b>%(gametype)s</b> " + \
"game is online.") % \
{"timecontrol": game.display_timecontrol, "gametype": 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:
self.connection.client.run_command("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 and
v.board.variant not in UNSUPPORTED]
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__)
############################################################################
# Relay server messages which aren't part of a game to the user #
############################################################################
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:
self.connection.client.run_command("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))
|