Example #1
0
    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()
Example #2
0
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)
Example #3
0
    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()
Example #4
0
    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)
Example #5
0
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)
Example #6
0
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)