def paste(gamemodel): output = StringIO() text = pgn.save(output, gamemodel) values = {'apikey': APIKEY, 'pgn': text, "name": "PyChess", 'sandbox': 'false'} data = urlencode(values).encode('utf-8') req = Request(URL, data) try: response = urlopen(req, timeout=10) except URLError as err: if hasattr(err, 'reason'): print('We failed to reach the server.') print('Reason: ', err.reason) elif hasattr(err, 'code'): print('The server couldn\'t fulfill the request.') print('Error code: ', err.code) else: ID = response.read() link = "http://www.chesspastebin.com/?p=%s" % int(ID) clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_text(link, -1) #print(text) #print(clipboard.wait_for_text()) msg_dialog = Gtk.MessageDialog(type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK) msg = _( "Game shared at ") + '<a href="%s">chesspastebin.com</a>' % link msg_dialog.set_markup(msg) msg_dialog.format_secondary_text(_("(Link is available on clipboard.)")) msg_dialog.connect("response", lambda msg_dialog, a: msg_dialog.hide()) msg_dialog.show()
def saveGamePGN(self, game): if conf.get("saveOwnGames", False) and not game.hasLocalPlayer(): return True filename = conf.get("autoSaveFormat", "pychess") filename = filename.replace("#n1", game.tags["White"]) filename = filename.replace("#n2", game.tags["Black"]) filename = filename.replace("#y", "%s" % game.tags["Year"]) filename = filename.replace("#m", "%s" % game.tags["Month"]) filename = filename.replace("#d", "%s" % game.tags["Day"]) pgn_path = conf.get("autoSavePath", os.path.expanduser("~")) + \ "/" + filename + ".pgn" append = True try: if not os.path.isfile(pgn_path): # create new file with open(pgn_path, "w"): pass base_offset = os.path.getsize(pgn_path) # save to .sqlite database_path = os.path.splitext(pgn_path)[0] + '.sqlite' database.save(database_path, game, base_offset) # save to .scout from pychess.Savers.pgn import scoutfish_path if scoutfish_path is not None: pgn_text = pgn.save(StringIO(), game) tmp = tempfile.NamedTemporaryFile(mode="w", delete=False) pgnfile = tmp.name with tmp.file as f: f.write(pgn_text) # create new .scout from pgnfile we are importing args = [scoutfish_path, "make", pgnfile, "%s" % base_offset] output = subprocess.check_output(args, stderr=subprocess.STDOUT) # append it to our existing one if output.decode().find(u"Processing...done") > 0: old_scout = os.path.splitext(pgn_path)[0] + '.scout' new_scout = os.path.splitext(pgnfile)[0] + '.scout' with open(old_scout, "ab") as file1, open(new_scout, "rb") as file2: file1.write(file2.read()) # TODO: do we realy want to update .bin ? It can be huge/slow! # save to .pgn game.save(pgn_path, pgn, append) return True except IOError: return False
def _validate(gamemodel): try: text, loadType = _get_text() chessfile = loadType.load(StringIO(text)) chessfile.loadToModel(0, -1, model=gamemodel) gamemodel.status = WAITING_TO_START return True except LoadingError as e: d = Gtk.MessageDialog(type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK, message_format=e.args[0]) d.format_secondary_text(e.args[1]) d.connect("response", lambda d, a: d.hide()) d.show() return False
def run(self): log.debug("GameModel.run: Starting. self=%s" % self) # Avoid racecondition when self.start is called while we are in # self.end if self.status != WAITING_TO_START: return if not self.isLocalGame(): self.timemodel.handle_gain = False self.status = RUNNING for player in self.players + list(self.spectators.values()): player.start() log.debug("GameModel.run: emitting 'game_started' self=%s" % self) self.emit("game_started") # Let GameModel end() itself on games started with loadAndStart() self.checkStatus() self.curColor = self.boards[-1].color while self.status in (PAUSED, RUNNING, DRAW, WHITEWON, BLACKWON): curPlayer = self.players[self.curColor] if self.timed: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: updating %s's time" % ( id(self), str(self.players), str(self.ply), str(curPlayer))) curPlayer.updateTime( self.timemodel.getPlayerTime(self.curColor), self.timemodel.getPlayerTime(1 - self.curColor)) try: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: calling %s.makeMove()" % ( id(self), str(self.players), self.ply, str(curPlayer))) if self.ply > self.lowply: move = curPlayer.makeMove(self.boards[-1], self.moves[-1], self.boards[-2]) else: move = curPlayer.makeMove(self.boards[-1], None, None) log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: got move=%s from %s" % ( id(self), str(self.players), self.ply, move, str(curPlayer))) except PlayerIsDead as e: if self.status in (WAITING_TO_START, PAUSED, RUNNING): stringio = StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error( "GameModel.run: A Player died: player=%s error=%s\n%s" % (curPlayer, error, e)) if self.curColor == WHITE: self.kill(WHITE_ENGINE_DIED) else: self.kill(BLACK_ENGINE_DIED) break except InvalidMove as e: if self.curColor == WHITE: self.end(BLACKWON, WON_ADJUDICATION) else: self.end(WHITEWON, WON_ADJUDICATION) break except TurnInterrupt: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: TurnInterrupt" % ( id(self), str(self.players), self.ply)) self.curColor = self.boards[-1].color continue log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: acquiring self.applyingMoveLock" % ( id(self), str(self.players), self.ply)) assert isinstance(move, Move), "%s" % repr(move) self.applyingMoveLock.acquire() try: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: applying move=%s" % ( id(self), str(self.players), self.ply, str(move))) self.needsSave = True newBoard = self.boards[-1].move(move) newBoard.board.prev = self.boards[-1].board # Variation on next move can exist from the hint panel... if self.boards[-1].board.next is not None: newBoard.board.children = self.boards[ -1].board.next.children self.boards = self.variations[0] self.boards[-1].board.next = newBoard.board self.boards.append(newBoard) self.moves.append(move) if self.timed: self.timemodel.tap() if not self.terminated: self.emit("game_changed", self.ply) for spectator in self.spectators.values(): if spectator.board == self.boards[-2]: spectator.putMove(self.boards[-1], self.moves[-1], self.boards[-2]) self.setOpening() self.checkStatus() self.curColor = 1 - self.curColor finally: log.debug("GameModel.run: releasing self.applyingMoveLock") self.applyingMoveLock.release()
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") % \ (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: # LectureBot allways uses gameno 1 for many games in one lecture # 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" % \ (id(self), str(self.players))) if self.timed: log.debug("ICGameModel.onBoardUpdate: id=%d self.players=%s: updating timemodel" % \ (id(self), str(self.players))) # If game end coming from helper connection before last move made # we have to tap() ourselves if self.status in (DRAW, WHITEWON, BLACKWON): if self.timemodel.ply < ply: self.timemodel.paused = False self.timemodel.tap() self.timemodel.paused = True self.timemodel.updatePlayer(WHITE, wms / 1000.) self.timemodel.updatePlayer(BLACK, bms / 1000.) if lastmove is None: if bname != self.tags["Black"]: self.tags["Black"] = self.players[ BLACK].name = self.ficsplayers[BLACK].name = bname self.emit("players_changed") if wname != self.tags["White"]: self.tags["White"] = self.players[ WHITE].name = self.ficsplayers[WHITE].name = wname self.emit("players_changed") if self.boards[-1].asFen() != fen: self.status = RUNNING self.loadAndStart(StringIO(fen), fen_loader, 0, -1, first_time=False) self.emit("game_started") curPlayer = self.players[self.curColor] curPlayer.resetPosition() elif ply < self.ply: log.debug("ICGameModel.onBoardUpdate: id=%d self.players=%s \ self.ply=%d ply=%d: TAKEBACK" % \ (id(self), str(self.players), self.ply, ply)) for offer in list(self.offers.keys()): 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] # In some cases (like lost on time) the last move is resent # or we just observing an examined game if self.reason != WON_CALLFLAG: if len(self.moves) >= self.ply - ply: self.undoMoves(self.ply - ply) else: self.status = RUNNING self.loadAndStart(StringIO(fen), fen_loader, 0, -1, first_time=False) self.emit("game_started") curPlayer = self.players[self.curColor] curPlayer.resetPosition() elif ply > self.ply + 1: self.status = RUNNING self.loadAndStart(StringIO(fen), fen_loader, 0, -1, first_time=False) self.emit("game_started") curPlayer = self.players[self.curColor] curPlayer.resetPosition()
def _ensureReadForGameWidgets(): mainvbox = widgets["mainvbox"] if len(mainvbox.get_children()) == 3: return global background, notebooks notebooks = get_clean_notebooks(mainvbox) 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) align.add(headbook) mainvbox.pack_start(align, False, True, 0) show_tabs(not conf.get("hideTabs", False)) # Initing center centerVBox = Gtk.VBox() # The dock global dock, dockAlign dock = PyDockTop("main") dockAlign = createAlignment(4, 4, 0, 4) dockAlign.add(dock) centerVBox.pack_start(dockAlign, True, True, 0) dockAlign.show() dock.show() for panel in sidePanels: hbox = Gtk.HBox() pixbuf = get_pixbuf(panel.__icon__, 16) icon = Gtk.Image.new_from_pixbuf(pixbuf) label = Gtk.Label(label=panel.__title__) label.set_size_request(0, 0) label.set_alignment(0, 1) hbox.pack_start(icon, False, False, 0) hbox.pack_start(label, True, True, 0) 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 = get_pixbuf(filename, 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(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 as e: stringio = StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error("Dock loading error: %s\n%s" % (e, error)) msg_dia = Gtk.MessageDialog(widgets["window1"], type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.CLOSE) msg_dia.set_markup( _("<b><big>PyChess was unable to load your panel settings</big></b>" )) msg_dia.format_secondary_text( _("Your panel settings have been reset. If this problem repeats, \ you should report it to the developers")) msg_dia.run() msg_dia.hide() os.remove(dockLocation) for title, panel in docks.values(): title.unparent() panel.unparent() if not os.path.isfile(dockLocation): leaf = dock.dock(docks["board"][1], CENTER, Gtk.Label(label=docks["board"][0]), "board") docks["board"][1].show_all() leaf.setDockable(False) # S epanel = leaf.dock(docks["bookPanel"][1], SOUTH, docks["bookPanel"][0], "bookPanel") epanel.default_item_height = 45 epanel = epanel.dock(docks["engineOutputPanel"][1], CENTER, docks["engineOutputPanel"][0], "engineOutputPanel") # NE leaf = leaf.dock(docks["annotationPanel"][1], EAST, docks["annotationPanel"][0], "annotationPanel") leaf = leaf.dock(docks["historyPanel"][1], CENTER, docks["historyPanel"][0], "historyPanel") leaf = leaf.dock(docks["scorePanel"][1], CENTER, docks["scorePanel"][0], "scorePanel") # SE leaf = leaf.dock(docks["chatPanel"][1], SOUTH, docks["chatPanel"][0], "chatPanel") leaf = leaf.dock(docks["commentPanel"][1], CENTER, docks["commentPanel"][0], "commentPanel") def unrealize(dock, notebooks): # 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, notebooks) hbox = Gtk.HBox() # Buttons notebooks["buttons"].set_border_width(4) hbox.pack_start(notebooks["buttons"], False, True, 0) # The message area # TODO: If you try to fix this first read issue #958 and 1018 align = createAlignment(0, 0, 0, 0) # sw = Gtk.ScrolledWindow() # port = Gtk.Viewport() # port.add(notebooks["messageArea"]) # sw.add(port) # align.add(sw) align.add(notebooks["messageArea"]) hbox.pack_start(align, True, True, 0) def ma_switch_page(notebook, gpointer, page_num): notebook.props.visible = notebook.get_nth_page(page_num).\ get_child().props.visible notebooks["messageArea"].connect("switch-page", ma_switch_page) centerVBox.pack_start(hbox, False, True, 0) mainvbox.pack_start(centerVBox, True, True, 0) centerVBox.show_all() mainvbox.show() # Connecting headbook to other notebooks def hb_switch_page(notebook, gpointer, page_num): for notebook in notebooks.values(): notebook.set_current_page(page_num) # log.debug("HB_switch ficsgame no. %s , %s " % (key2gmwidg[getheadbook().\ # get_nth_page(page_num)].gamemodel.ficsgame.gameno,str(page_num))) gmwidg = key2gmwidg[getheadbook().get_nth_page(page_num)] if isinstance(gmwidg.gamemodel, ICGameModel): primary = "primary " + str(gmwidg.gamemodel.ficsgame.gameno) gmwidg.gamemodel.connection.client.run_command(primary) headbook.connect("switch-page", hb_switch_page) if hasattr(headbook, "set_tab_reorderable"): def page_reordered(widget, child, new_num, headbook): old_num = 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 copy_fen(self): output = StringIO() clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_text( fen.save(output, self.gamemodel, self.board.view.shown), -1)
def copy_pgn(self): output = StringIO() clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_text(pgn.save(output, self.gamemodel), -1)
def _callback(gamemodel, p0, p1): text, loadType = _get_text() ionest.generalStart(gamemodel, p0, p1, (StringIO(text), loadType, 0, -1))
def _callback(gamemodel, p0, p1): text = cls.get_fen() ionest.generalStart(gamemodel, p0, p1, (StringIO(text), fen, 0, -1))
def init_layout(self): perspective_widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) perspective_manager.set_perspective_widget("database", perspective_widget) self.gamelist = GameList(database.load(None)) self.switcher_panel = SwitcherPanel(self.gamelist) self.opening_tree_panel = OpeningTreePanel(self.gamelist) self.filter_panel = FilterPanel(self.gamelist) self.preview_panel = PreviewPanel(self.gamelist) self.progressbar0 = Gtk.ProgressBar(show_text=True) self.progressbar = Gtk.ProgressBar(show_text=True) self.progress_dialog = Gtk.Dialog("Import", None, 0, ( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)) self.progress_dialog.get_content_area().pack_start(self.progressbar0, True, True, 0) self.progress_dialog.get_content_area().pack_start(self.progressbar, True, True, 0) self.progress_dialog.get_content_area().show_all() perspective = perspective_manager.get_perspective("database") self.dock = PyDockTop("database", perspective) align = Gtk.Alignment() align.show() align.add(self.dock) self.dock.show() perspective_widget.pack_start(align, True, True, 0) dockLocation = addUserConfigPrefix("pydock-database.xml") docks = { "gamelist": (Gtk.Label(label="gamelist"), self.gamelist.box), "switcher": (dock_panel_tab(_("Database switcher"), "", addDataPrefix("glade/panel_docker.svg")), self.switcher_panel.alignment), "openingtree": (dock_panel_tab(_("Opening tree"), "", addDataPrefix("glade/panel_docker.svg")), self.opening_tree_panel.box), "filter": (dock_panel_tab(_("Filter"), "", addDataPrefix("glade/panel_docker.svg")), self.filter_panel.box), "preview": (dock_panel_tab(_("Preview"), "", addDataPrefix("glade/panel_docker.svg")), self.preview_panel.box), } if os.path.isfile(dockLocation): try: self.dock.loadFromXML(dockLocation, docks) except Exception as e: stringio = StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error("Dock loading error: %s\n%s" % (e, error)) msg_dia = Gtk.MessageDialog(None, type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.CLOSE) msg_dia.set_markup(_( "<b><big>PyChess was unable to load your panel settings</big></b>")) msg_dia.format_secondary_text(_( "Your panel settings have been reset. If this problem repeats, \ you should report it to the developers")) msg_dia.run() msg_dia.hide() os.remove(dockLocation) for title, panel in docks.values(): title.unparent() panel.unparent() if not os.path.isfile(dockLocation): leaf = self.dock.dock(docks["gamelist"][1], CENTER, docks["gamelist"][0], "gamelist") leaf.setDockable(False) leaf.dock(docks["switcher"][1], NORTH, docks["switcher"][0], "switcher") leaf = leaf.dock(docks["filter"][1], EAST, docks["filter"][0], "filter") leaf = leaf.dock(docks["openingtree"][1], SOUTH, docks["openingtree"][0], "openingtree") leaf.dock(docks["preview"][1], SOUTH, docks["preview"][0], "preview") def unrealize(dock): dock.saveToXML(dockLocation) dock._del() self.dock.connect("unrealize", unrealize) self.dock.show_all() perspective_widget.show_all() perspective_manager.set_perspective_toolbuttons("database", [self.import_button, self.close_button]) self.switcher_panel.connect("chessfile_switched", self.on_chessfile_switched)
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) align.add(headbook) mainvbox.pack_start(align, False, True, 0) show_tabs(not conf.get("hideTabs", False)) # Initing center centerVBox = Gtk.VBox() # The dock global dock, dockAlign dock = PyDockTop("main") dockAlign = createAlignment(4, 4, 0, 4) dockAlign.add(dock) centerVBox.pack_start(dockAlign, True, True, 0) dockAlign.show() dock.show() for panel in sidePanels: hbox = Gtk.HBox() pixbuf = get_pixbuf(panel.__icon__, 16) icon = Gtk.Image.new_from_pixbuf(pixbuf) label = Gtk.Label(label=panel.__title__) label.set_size_request(0, 0) label.set_alignment(0, 1) hbox.pack_start(icon, False, False, 0) hbox.pack_start(label, True, True, 0) 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 = get_pixbuf(filename, 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(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 as e: stringio = StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error("Dock loading error: %s\n%s" % (e, error)) msg_dia = Gtk.MessageDialog(widgets["window1"], type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.CLOSE) msg_dia.set_markup(_( "<b><big>PyChess was unable to load your panel settings</big></b>")) msg_dia.format_secondary_text(_( "Your panel settings have been reset. If this problem repeats, \ you should report it to the developers")) msg_dia.run() msg_dia.hide() os.remove(dockLocation) for title, panel in docks.values(): title.unparent() panel.unparent() if not os.path.isfile(dockLocation): leaf = dock.dock(docks["board"][1], CENTER, Gtk.Label(label=docks["board"][0]), "board") docks["board"][1].show_all() leaf.setDockable(False) # S epanel = leaf.dock(docks["bookPanel"][1], SOUTH, docks["bookPanel"][0], "bookPanel") epanel.default_item_height = 45 epanel = epanel.dock(docks["engineOutputPanel"][1], CENTER, docks["engineOutputPanel"][0], "engineOutputPanel") # NE leaf = leaf.dock(docks["annotationPanel"][1], EAST, docks["annotationPanel"][0], "annotationPanel") leaf = leaf.dock(docks["historyPanel"][1], CENTER, docks["historyPanel"][0], "historyPanel") leaf = leaf.dock(docks["scorePanel"][1], CENTER, docks["scorePanel"][0], "scorePanel") # SE leaf = leaf.dock(docks["chatPanel"][1], SOUTH, docks["chatPanel"][0], "chatPanel") leaf = leaf.dock(docks["commentPanel"][1], CENTER, docks["commentPanel"][0], "commentPanel") 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) hbox = Gtk.HBox() # The status bar notebooks["statusbar"].set_border_width(4) hbox.pack_start(notebooks["statusbar"], False, True, 0) # The message area # TODO: If you try to fix this first read issue #958 and 1018 align = createAlignment(0, 0, 0, 0) # sw = Gtk.ScrolledWindow() # port = Gtk.Viewport() # port.add(notebooks["messageArea"]) # sw.add(port) # align.add(sw) align.add(notebooks["messageArea"]) hbox.pack_start(align, True, True, 0) def ma_switch_page(notebook, gpointer, page_num): notebook.props.visible = notebook.get_nth_page(page_num).\ get_child().props.visible notebooks["messageArea"].connect("switch-page", ma_switch_page) centerVBox.pack_start(hbox, False, True, 0) mainvbox.pack_start(centerVBox, True, True, 0) centerVBox.show_all() mainvbox.show() # Connecting headbook to other notebooks def hb_switch_page(notebook, gpointer, page_num): for notebook in notebooks.values(): notebook.set_current_page(page_num) # log.debug("HB_switch ficsgame no. %s , %s " % (key2gmwidg[getheadbook().\ # get_nth_page(page_num)].gamemodel.ficsgame.gameno,str(page_num))) gmwidg = key2gmwidg[getheadbook().get_nth_page(page_num)] if isinstance(gmwidg.gamemodel, ICGameModel): primary = "primary " + str(gmwidg.gamemodel.ficsgame.gameno) gmwidg.gamemodel.connection.client.run_command(primary) headbook.connect("switch-page", hb_switch_page) if hasattr(headbook, "set_tab_reorderable"): def page_reordered(widget, child, new_num, headbook): old_num = 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 __repr__(self): return self.name pgnfile0 = pgnload(open('gamefiles/annotated.pgn')) pgnfile1 = pgnload( StringIO(""" [Event "win"] [Result "1-0"] 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 [Event "draw"] [Result "1/2-1/2"] 1. d4 d5 2. Nf3 Nf6 [Event "win"] [Result "1-0"] 1. c4 c5 2. Nf3 Nf6 [Event "win"] [Result "0-1"] 1. c4 c5 2. Nc3 Nf6 """)) GAME_COUNT = len(pgnfile1.games) BITBOARD_COUNT = (1, 3, 3, 4) class DbTestCase(unittest.TestCase): def setUp(self):
def _ensureReadForGameWidgets(): if len(key2gmwidg) > 0: return global notebooks perspective_widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) perspective_manager.set_perspective_widget("games", perspective_widget) perspective = perspective_manager.get_perspective("games") notebooks = get_clean_notebooks(perspective.widget) # Initing headbook align = createAlignment(4, 4, 0, 4) align.set_property("yscale", 0) headbook = Gtk.Notebook() headbook.set_name("headbook") headbook.set_scrollable(True) align.add(headbook) perspective_widget.pack_start(align, False, True, 0) show_tabs(not conf.get("hideTabs", False)) # Initing center centerVBox = Gtk.VBox() # The dock global dock, dockAlign dock = PyDockTop("main", perspective) dockAlign = createAlignment(4, 4, 0, 4) dockAlign.add(dock) centerVBox.pack_start(dockAlign, True, True, 0) dockAlign.show() dock.show() for panel in sidePanels: box = dock_panel_tab(panel.__title__, panel.__desc__, panel.__icon__) docks[panel.__name__] = (box, notebooks[panel.__name__]) if os.path.isfile(dockLocation): try: dock.loadFromXML(dockLocation, docks) except Exception as e: stringio = StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error("Dock loading error: %s\n%s" % (e, error)) msg_dia = Gtk.MessageDialog(widgets["window1"], type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.CLOSE) msg_dia.set_markup( _("<b><big>PyChess was unable to load your panel settings</big></b>" )) msg_dia.format_secondary_text( _("Your panel settings have been reset. If this problem repeats, \ you should report it to the developers")) msg_dia.run() msg_dia.hide() os.remove(dockLocation) for title, panel in docks.values(): title.unparent() panel.unparent() if not os.path.isfile(dockLocation): leaf = dock.dock(docks["board"][1], CENTER, Gtk.Label(label=docks["board"][0]), "board") docks["board"][1].show_all() leaf.setDockable(False) # S epanel = leaf.dock(docks["bookPanel"][1], SOUTH, docks["bookPanel"][0], "bookPanel") epanel.default_item_height = 45 epanel = epanel.dock(docks["engineOutputPanel"][1], CENTER, docks["engineOutputPanel"][0], "engineOutputPanel") # NE leaf = leaf.dock(docks["annotationPanel"][1], EAST, docks["annotationPanel"][0], "annotationPanel") leaf = leaf.dock(docks["historyPanel"][1], CENTER, docks["historyPanel"][0], "historyPanel") leaf = leaf.dock(docks["scorePanel"][1], CENTER, docks["scorePanel"][0], "scorePanel") # SE leaf = leaf.dock(docks["chatPanel"][1], SOUTH, docks["chatPanel"][0], "chatPanel") leaf = leaf.dock(docks["commentPanel"][1], CENTER, docks["commentPanel"][0], "commentPanel") def unrealize(dock, notebooks): # 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, notebooks) hbox = Gtk.HBox() # Buttons notebooks["buttons"].set_border_width(4) hbox.pack_start(notebooks["buttons"], False, True, 0) # The message area # TODO: If you try to fix this first read issue #958 and 1018 align = createAlignment(0, 0, 0, 0) # sw = Gtk.ScrolledWindow() # port = Gtk.Viewport() # port.add(notebooks["messageArea"]) # sw.add(port) # align.add(sw) align.add(notebooks["messageArea"]) hbox.pack_start(align, True, True, 0) def ma_switch_page(notebook, gpointer, page_num): notebook.props.visible = notebook.get_nth_page(page_num).\ get_child().props.visible notebooks["messageArea"].connect("switch-page", ma_switch_page) centerVBox.pack_start(hbox, False, True, 0) perspective_widget.pack_start(centerVBox, True, True, 0) centerVBox.show_all() perspective_widget.show_all() # Connecting headbook to other notebooks def hb_switch_page(notebook, gpointer, page_num): for notebook in notebooks.values(): notebook.set_current_page(page_num) gmwidg = key2gmwidg[getheadbook().get_nth_page(page_num)] if isinstance(gmwidg.gamemodel, ICGameModel): primary = "primary " + str(gmwidg.gamemodel.ficsgame.gameno) gmwidg.gamemodel.connection.client.run_command(primary) headbook.connect("switch-page", hb_switch_page) if hasattr(headbook, "set_tab_reorderable"): def page_reordered(widget, child, new_num, headbook): old_num = 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)
pgnfile0 = pgnload(open('gamefiles/annotated.pgn')) pgnfile1 = pgnload( StringIO(""" [Event "win"] [Result "1-0"] [WhiteElo "2700"] [BlackElo "1700"] 1. e4 e5 2. Nf3 Nf6 [Event "draw"] [Result "1/2-1/2"] [WhiteElo "2726"] [BlackElo "1726"] 1. e4 d5 2. Nf3 Nf6 [Event "win"] [Result "1-0"] [WhiteElo "2710"] [BlackElo "1710"] 1. e4 c5 2. Nf3 Nf6 [Event "win"] [Result "0-1"] 1. e4 c5 2. Nc3 Nf6 """)) GAME_COUNT = len(pgnfile1.games) BITBOARD_COUNT = (0, 1, 3, 4, 4)