コード例 #1
0
    def _init(cls):
        def callback(widget, allocation):
            cls.widgets["setupPositionFrame"].set_size_request(
                523, allocation.height - 4)

        cls.widgets["setupPositionSidePanel"].connect_after(
            "size-allocate", callback)

        cls.castl = set()

        cls.white = Gtk.Image.new_from_pixbuf(get_pixbuf("glade/white.png"))
        cls.black = Gtk.Image.new_from_pixbuf(get_pixbuf("glade/black.png"))
        cls.widgets["side_button"].set_image(cls.white)

        cls.widgets["side_button"].connect("toggled", cls.side_button_toggled)
        cls.widgets["moveno_spin"].connect("value-changed",
                                           cls.moveno_spin_changed)
        cls.widgets["fifty_spin"].connect("value-changed",
                                          cls.fifty_spin_changed)
        cls.widgets["woo"].connect("toggled", cls.castl_toggled, "K")
        cls.widgets["wooo"].connect("toggled", cls.castl_toggled, "Q")
        cls.widgets["boo"].connect("toggled", cls.castl_toggled, "k")
        cls.widgets["booo"].connect("toggled", cls.castl_toggled, "q")

        ep_store = Gtk.ListStore(str)
        ep_store.append(["-"])
        for f in reprFile:
            ep_store.append([f])
        cls.widgets["ep_combo"].set_model(ep_store)
        renderer_text = Gtk.CellRendererText()
        cls.widgets["ep_combo"].pack_start(renderer_text, True)
        cls.widgets["ep_combo"].add_attribute(renderer_text, "text", 0)
        cls.widgets["ep_combo"].set_active(0)
        cls.widgets["ep_combo"].connect("changed", cls.ep_combo_changed)
コード例 #2
0
ファイル: newGameDialog.py プロジェクト: jcoffee/pychess
    def _init (cls):
        def callback (widget, allocation):
            cls.widgets["setupPositionFrame"].set_size_request(
                    523, allocation.height-4)
        cls.widgets["setupPositionSidePanel"].connect_after("size-allocate", callback)

        cls.castl = set()

        cls.white = Gtk.Image.new_from_pixbuf(get_pixbuf("glade/white.png"))
        cls.black = Gtk.Image.new_from_pixbuf(get_pixbuf("glade/black.png"))
        cls.widgets["side_button"].set_image(cls.white)

        cls.widgets["side_button"].connect("toggled", cls.side_button_toggled)
        cls.widgets["moveno_spin"].connect("value-changed", cls.moveno_spin_changed)
        cls.widgets["fifty_spin"].connect("value-changed", cls.fifty_spin_changed)
        cls.widgets["woo"].connect("toggled", cls.castl_toggled, "K")
        cls.widgets["wooo"].connect("toggled", cls.castl_toggled, "Q")
        cls.widgets["boo"].connect("toggled", cls.castl_toggled, "k")
        cls.widgets["booo"].connect("toggled", cls.castl_toggled, "q")

        ep_store = Gtk.ListStore(str)
        ep_store.append(["-"])
        for f in reprFile:
            ep_store.append([f])
        epcombo = cls.widgets["ep_combo"]
        epcombo.set_name("ep_combo")
        epcombo.set_model(ep_store)
        renderer_text = Gtk.CellRendererText()
        cls.widgets["ep_combo"].pack_start(renderer_text, True)
        cls.widgets["ep_combo"].add_attribute(renderer_text, "text", 0)
        cls.widgets["ep_combo"].set_active(0)
        cls.widgets["ep_combo"].connect("changed", cls.ep_combo_changed)
コード例 #3
0
    def addPerspectives(self):
        perspective_manager.set_widgets(self.widgets)
        for persp in (Welcome, Games, FICS, Database, Learn):
            perspective = persp()
            perspective_manager.add_perspective(perspective)
            perspective.create_toolbuttons()

            if persp == Database:
                perspective.connect("chessfile_opened",
                                    self.on_chessfile_opened)
            elif persp == Games:
                perspective.connect("gmwidg_created", self.on_gmwidg_created)

        newimage = get_pixbuf("glade/new24.png")
        new_button = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(newimage))
        new_button.set_tooltip_text(_("New Game"))
        new_button.connect("clicked",
                           self.glade_handlers.on_new_game1_activate)
        perspective_manager.toolbar.insert(new_button, 0)

        openimage = get_pixbuf("glade/open24.png")
        open_button = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(openimage))
        open_button.set_tooltip_text(_("Open Game"))
        open_button.connect("clicked",
                            self.glade_handlers.on_load_game1_activate)
        perspective_manager.toolbar.insert(open_button, 1)
コード例 #4
0
ファイル: newGameDialog.py プロジェクト: judoaseeta/pychess
def createPlayerUIGlobals(discoverer):
    global playerItems
    global analyzerItems
    global allEngineItems

    playerItems = []
    analyzerItems = []
    allEngineItems = []

    for variantClass in variants.values():
        playerItems += [[(ipeople, _("Human Being"))]]
    for engine in discoverer.getEngines():
        name = engine["name"]
        c = discoverer.getCountry(engine)
        path = addDataPrefix("flags/%s.png" % c)

        if c and os.path.isfile(path):
            flag_icon = get_pixbuf(path)
        else:
            path = addDataPrefix("flags/unknown.png")
            flag_icon = get_pixbuf(path)

        allEngineItems.append((flag_icon, name))

        for variant in discoverer.getEngineVariants(engine):
            playerItems[variant] += [(flag_icon, name)]

        if discoverer.is_analyzer(engine):
            analyzerItems.append((flag_icon, name))
コード例 #5
0
ファイル: newGameDialog.py プロジェクト: leogregianin/pychess
def createPlayerUIGlobals(discoverer):
    global playerItems
    global analyzerItems
    global allEngineItems

    playerItems = []
    analyzerItems = []
    allEngineItems = []

    for variantClass in variants.values():
        playerItems += [[(ipeople, _("Human Being"))]]
    for engine in discoverer.getEngines():
        name = engine["name"]
        c = discoverer.getCountry(engine)
        path = addDataPrefix("flags/%s.png" % c)

        if c and os.path.isfile(path):
            flag_icon = get_pixbuf(path)
        else:
            path = addDataPrefix("flags/unknown.png")
            flag_icon = get_pixbuf(path)

        allEngineItems.append((flag_icon, name))

        for variant in discoverer.getEngineVariants(engine):
            playerItems[variant] += [(flag_icon, name)]

        if discoverer.is_analyzer(engine):
            analyzerItems.append((flag_icon, name))
コード例 #6
0
ファイル: TaskerManager.py プロジェクト: ZeepXanflorp/pychess
    def __init__(self):
        #GObject.GObject.__init__(self,0,0,0,0)
        GObject.GObject.__init__(self)
        self.widgets = widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        combo = ToggleComboBox()
        combo.addItem(_("White"), get_pixbuf("glade/white.png"))
        combo.addItem(_("Black"), get_pixbuf("glade/black.png"))
        combo.addItem(_("Random"), get_pixbuf("glade/random.png"))
        combo.setMarkup("<b>", "</b>")
        widgets["colorDock"].add(combo)
        uistuff.keep(combo, "newgametasker_colorcombo")
        widgets['yourColorLabel'].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = ToggleComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
            widgets["skillImage"].set_from_pixbuf(pix)

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #7
0
ファイル: TaskerManager.py プロジェクト: vaj25/pychess
    def __init__(self):
        #GObject.GObject.__init__(self,0,0,0,0)
        GObject.GObject.__init__(self)
        self.widgets = widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        combo = ToggleComboBox()
        combo.addItem(_("White"), get_pixbuf("glade/white.png"))
        combo.addItem(_("Black"), get_pixbuf("glade/black.png"))
        combo.addItem(_("Random"), get_pixbuf("glade/random.png"))
        combo.setMarkup("<b>", "</b>")
        widgets["colorDock"].add(combo)
        uistuff.keep(combo, "newgametasker_colorcombo")
        widgets['yourColorLabel'].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = ToggleComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
            widgets["skillImage"].set_from_pixbuf(pix)

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #8
0
ファイル: FICSObjects.py プロジェクト: zennsocial/pychess
 def getIconByRating(cls, rating, size=16):
     assert isinstance(rating, int), "rating not an int: %s" % str(rating)
     if rating >= 1900:
         return get_pixbuf("glade/16x16/weather-storm.png")
     elif rating >= 1600:
         return get_pixbuf("glade/16x16/weather-showers.png")
     elif rating >= 1300:
         return get_pixbuf("glade/16x16/weather-overcast.png")
     elif rating >= 1000:
         return get_pixbuf("glade/16x16/weather-few-clouds.png")
     else:
         return get_pixbuf("glade/16x16/weather-clear.png")
コード例 #9
0
ファイル: FICSObjects.py プロジェクト: teacoffee2017/pychess
 def getIconByRating(cls, rating, size=16):
     assert isinstance(rating, int), "rating not an int: %s" % str(rating)
     if rating >= 1900:
         return get_pixbuf("glade/16x16/weather-storm.png")
     elif rating >= 1600:
         return get_pixbuf("glade/16x16/weather-showers.png")
     elif rating >= 1300:
         return get_pixbuf("glade/16x16/weather-overcast.png")
     elif rating >= 1000:
         return get_pixbuf("glade/16x16/weather-few-clouds.png")
     else:
         return get_pixbuf("glade/16x16/weather-clear.png")
コード例 #10
0
ファイル: enginesDialog.py プロジェクト: ypeng22/pychess
def run(widgets):
    global firstRun, engine_dialog
    if firstRun:
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not (iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"],
                            name="engine_country_combo",
                            ellipsize_mode=Pango.EllipsizeMode.END)
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        engine_dialog = EnginesDialog(widgets)

        def cancel_event(widget, with_confirmation, *args):
            # Confirm if the changes need to be saved
            modified = discoverer.hasChanged()
            if modified and with_confirmation:
                dialog = Gtk.MessageDialog(mainwindow(),
                                           type=Gtk.MessageType.QUESTION,
                                           buttons=Gtk.ButtonsType.YES_NO)
                dialog.set_markup(
                    _("You have unsaved changes. Do you want to save before leaving?"
                      ))
                response = dialog.run()
                dialog.destroy()
                # if response == Gtk.ResponseType.CANCEL:
                #    return False
                if response == Gtk.ResponseType.NO:
                    discoverer.restore()
                if response == Gtk.ResponseType.YES:
                    discoverer.save()

            # Close the window
            widgets["manage_engines_dialog"].hide()
            return True

        def save_event(widget, *args):
            discoverer.save()
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", cancel_event,
                                                 True)
        widgets["engine_cancel_button"].connect("clicked", cancel_event, False)
        widgets["engine_save_button"].connect("clicked", save_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event", lambda w, e: cancel_event(w, True)
            if e.keyval == Gdk.KEY_Escape else None)

    discoverer.backup()
    engine_dialog.widgets["enginebook"].set_current_page(0)
    widgets["manage_engines_dialog"].show()
    if not firstRun:
        engine_dialog.update_store()
    firstRun = False
コード例 #11
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = tasker_widgets
        tasker = self.widgets["databaseTasker"]
        tasker.unparent()
        self.add(tasker)

        startButton = self.widgets["openButton"]
        startButton.set_name("openButton")

        liststore = Gtk.ListStore(str, str)

        self.recent_combo = self.widgets["recent_combo"]
        self.recent_combo.set_model(liststore)
        renderer_text = Gtk.CellRendererText()
        renderer_text.set_property("width-chars", 30)
        renderer_text.set_property("ellipsize", Pango.EllipsizeMode.END)
        self.recent_combo.pack_start(renderer_text, True)
        self.recent_combo.add_attribute(renderer_text, "text", 1)

        self.on_recent_menu_changed(recent_manager, liststore)
        recent_manager.connect("changed", self.on_recent_menu_changed,
                               liststore)

        openimage = get_pixbuf("glade/open48.png")
        self.widgets["openImage"].set_from_pixbuf(openimage)

        self.widgets["opendialog3"].connect("clicked", self.openDialogClicked)
        self.widgets["openButton"].connect("clicked", self.openClicked)
コード例 #12
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = tasker_widgets
        tasker = self.widgets["internetGameTasker"]
        tasker.unparent()
        self.add(tasker)

        if ICLogon.dialog is None:
            ICLogon.dialog = ICLogon.ICLogon()

        liststore = Gtk.ListStore(str)
        liststore.append(["FICS"])
        liststore.append(["ICC"])
        self.ics_combo = self.widgets["ics_combo"]
        self.ics_combo.set_model(liststore)
        renderer_text = Gtk.CellRendererText()
        self.ics_combo.pack_start(renderer_text, True)
        self.ics_combo.add_attribute(renderer_text, "text", 0)
        self.ics_combo.connect("changed", ICLogon.dialog.on_ics_combo_changed)
        self.ics_combo.set_active(conf.get("ics_combo"))

        self.widgets["connectButton"].connect("clicked", self.connectClicked)
        self.widgets["opendialog2"].connect("clicked", self.openDialogClicked)

        big_start = get_pixbuf("glade/internet.png")
        self.widgets["startIcon"].set_from_pixbuf(big_start)

        uistuff.keep(self.widgets["ics_combo"], "ics_combo")
        uistuff.keep(self.widgets["autoLogin"], "autoLogin")
コード例 #13
0
ファイル: __init__.py プロジェクト: bboutkov/pychess
def dock_panel_tab(title, desc, icon):
    box = Gtk.Box()
    pixbuf = get_pixbuf(icon, 16)
    image = Gtk.Image.new_from_pixbuf(pixbuf)
    label = Gtk.Label(label=title)
    label.set_size_request(0, 0)
    label.set_alignment(0, 1)
    box.pack_start(image, False, False, 0)
    box.pack_start(label, True, True, 0)
    box.set_spacing(2)
    box.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

    box.props.has_tooltip = True
    box.connect("query-tooltip", cb, title, desc, icon)
    return box
コード例 #14
0
ファイル: __init__.py プロジェクト: bigbaer/pychess
def dock_panel_tab(title, desc, icon):
    box = Gtk.Box()
    pixbuf = get_pixbuf(icon, 16)
    image = Gtk.Image.new_from_pixbuf(pixbuf)
    label = Gtk.Label(label=title)
    label.set_size_request(0, 0)
    label.set_alignment(0, 1)
    box.pack_start(image, False, False, 0)
    box.pack_start(label, True, True, 0)
    box.set_spacing(2)
    box.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

    box.props.has_tooltip = True
    box.connect("query-tooltip", cb, title, desc, icon)
    return box
コード例 #15
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = widgets = tasker_widgets
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        startButton = self.widgets["startButton"]
        startButton.set_name("startButton")
        combo = Gtk.ComboBox()
        uistuff.createCombo(
            combo,
            [
                (get_pixbuf("glade/white.png"), _("White")),
                (get_pixbuf("glade/black.png"), _("Black")),
                (get_pixbuf("glade/random.png"), _("Random")),
            ],
        )
        widgets["colorDock"].add(combo)
        if combo.get_active() < 0:
            combo.set_active(0)
        widgets["yourColorLabel"].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = Gtk.ComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets["opponentLabel"].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            # Just to make sphinx happy...
            try:
                pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
                widgets["skillImage"].set_from_pixbuf(pix)
            except TypeError:
                pass

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #16
0
    def __init__(self, widgets):
        self.themes = self.discover_themes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run create_theme_preview.sh !"
                )
                break

        iconView = widgets["pieceTheme"]
        iconView.set_model(store)
        iconView.set_pixbuf_column(0)
        iconView.set_text_column(1)

        #############################################
        # Hack to fix spacing problem in iconview
        # http://stackoverflow.com/questions/14090094/what-causes-the-different-display-behaviour-for-a-gtkiconview-between-different
        def keep_size(crt, *args):
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt, crp = iconView.get_cells()
        crt_notify = crt.connect('notify', keep_size)

        #############################################

        def _get_active(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                i = indices[0]
                theme = model[i][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _set_active(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _get_active,
                     _set_active, "Chessicons")
コード例 #17
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.widgets = widgets = uistuff.GladeWidgets("taskers.glade")
        tasker = widgets["newGameTasker"]
        tasker.unparent()
        self.add(tasker)

        startButton = self.widgets["startButton"]
        startButton.set_name("startButton")
        combo = Gtk.ComboBox()
        uistuff.createCombo(combo, [
            (get_pixbuf("glade/white.png"), _("White")),
            (get_pixbuf("glade/black.png"), _("Black")),
            (get_pixbuf("glade/random.png"), _("Random"))])
        widgets["colorDock"].add(combo)
        if combo.get_active() < 0:
            combo.set_active(0)
        uistuff.keep(combo, "newgametasker_colorcombo")
        widgets['yourColorLabel'].set_mnemonic_widget(combo)

        # We need to wait until after engines have been discovered, to init the
        # playerCombos. We use connect_after to make sure, that newGameDialog
        # has also had time to init the constants we share with them.
        self.playerCombo = Gtk.ComboBox()
        widgets["opponentDock"].add(self.playerCombo)
        discoverer.connect_after("all_engines_discovered",
                                 self.__initPlayerCombo, widgets)
        widgets['opponentLabel'].set_mnemonic_widget(self.playerCombo)

        def on_skill_changed(scale):
            # Just to make sphinx happy...
            try:
                pix = newGameDialog.skillToIconLarge[int(scale.get_value())]
                widgets["skillImage"].set_from_pixbuf(pix)
            except TypeError:
                pass

        widgets["skillSlider"].connect("value-changed", on_skill_changed)
        on_skill_changed(widgets["skillSlider"])

        widgets["startButton"].connect("clicked", self.startClicked)
        self.widgets["opendialog1"].connect("clicked", self.openDialogClicked)
コード例 #18
0
    def __init__ (self, widgets):
        self.themes = self.discover_themes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)
        
        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)
        
            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print("WARNING: No piece theme preview icons found. Please run create_theme_preview.sh !")
                break

        iconView = widgets["pieceTheme"]
        iconView.set_model(store)
        iconView.set_pixbuf_column(0)
        iconView.set_text_column(1)
        
        #############################################
        # Hack to fix spacing problem in iconview
        # http://stackoverflow.com/questions/14090094/what-causes-the-different-display-behaviour-for-a-gtkiconview-between-different
        def keep_size(crt, *args):
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt, crp = iconView.get_cells()
        crt_notify = crt.connect('notify', keep_size)
        #############################################

        def _get_active(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()
            
            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")
            
            indices = selected[0].get_indices()
            if indices:
                i = indices[0]
                theme = model[i][1]
                Pieces.set_piece_theme(theme)
                return theme
        
        def _set_active(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index,))
                
        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _get_active,
                     _set_active, "Chessicons")
コード例 #19
0
ファイル: enginesDialog.py プロジェクト: leogregianin/pychess
def run(widgets):
    global firstRun, engine_dialog
    if firstRun:
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not(iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"], name="engine_country_combo",
                            ellipsize_mode=Pango.EllipsizeMode.END)
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        engine_dialog = EnginesDialog(widgets)

        def cancel_event(widget, with_confirmation, *args):
            # Confirm if the changes need to be saved
            modified = discoverer.hasChanged()
            if modified and with_confirmation:
                dialog = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO)
                dialog.set_markup(_("You have unsaved changes. Do you want to save before leaving?"))
                response = dialog.run()
                dialog.destroy()
                # if response == Gtk.ResponseType.CANCEL:
                #    return False
                if response == Gtk.ResponseType.NO:
                    discoverer.restore()
                if response == Gtk.ResponseType.YES:
                    discoverer.save()

            # Close the window
            widgets["manage_engines_dialog"].hide()
            return True

        def save_event(widget, *args):
            discoverer.save()
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", cancel_event, True)
        widgets["engine_cancel_button"].connect("clicked", cancel_event, False)
        widgets["engine_save_button"].connect("clicked", save_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event",
            lambda w, e: cancel_event(w, True) if e.keyval == Gdk.KEY_Escape else None)

    discoverer.backup()
    engine_dialog.widgets["enginebook"].set_current_page(0)
    widgets["manage_engines_dialog"].show()
    if not firstRun:
        engine_dialog.update_store()
    firstRun = False
コード例 #20
0
def dock_panel_tab(title, desc, icon, button=None):
    box = Gtk.Box()
    pixbuf = get_pixbuf(icon, 16)
    image = Gtk.Image.new_from_pixbuf(pixbuf)
    label = Gtk.Label(label=title)
    box.set_tooltip_text(desc)
    box.pack_start(image, False, True, 0)
    box.pack_start(label, False, True, 0)
    if button is not None:
        box.pack_start(button, False, True, 0)

    box.set_spacing(2)
    box.show_all()

    return box
コード例 #21
0
ファイル: preferencesDialog.py プロジェクト: ypeng22/pychess
    def __init__(self, widgets):
        # Put panels in trees
        self.widgets = widgets
        persp = perspective_manager.get_perspective("games")
        sidePanels = persp.sidePanels
        dockLocation = persp.dockLocation

        saved_panels = []
        xmlOK = os.path.isfile(dockLocation)
        if xmlOK:
            doc = minidom.parse(dockLocation)
            for elem in doc.getElementsByTagName("panel"):
                saved_panels.append(elem.getAttribute("id"))

        store = Gtk.ListStore(bool, GdkPixbuf.Pixbuf, str, object)
        for panel in sidePanels:
            checked = True if not xmlOK else panel.__name__ in saved_panels
            panel_icon = get_pixbuf(panel.__icon__, 32)
            text = "<b>%s</b>\n%s" % (panel.__title__, panel.__desc__)
            store.append((checked, panel_icon, text, panel))

        self.tv = widgets["panels_treeview"]
        self.tv.set_model(store)

        self.widgets['panel_about_button'].connect('clicked', self.panel_about)
        self.widgets['panel_enable_button'].connect('toggled',
                                                    self.panel_toggled)
        self.tv.get_selection().connect('changed', self.selection_changed)

        pixbuf = Gtk.CellRendererPixbuf()
        pixbuf.props.yalign = 0
        pixbuf.props.ypad = 3
        pixbuf.props.xpad = 3
        self.tv.append_column(Gtk.TreeViewColumn("Icon",
                                                 pixbuf,
                                                 pixbuf=1,
                                                 sensitive=0))

        uistuff.appendAutowrapColumn(self.tv, "Name", markup=2, sensitive=0)

        widgets['preferences_notebook'].connect("switch-page", self.__on_switch_page)
        widgets["preferences_dialog"].connect("show", self.__on_show_window)
        widgets["preferences_dialog"].connect("hide", self.__on_hide_window)
コード例 #22
0
    def __init__(self, widgets):
        # Put panels in trees
        self.widgets = widgets
        persp = perspective_manager.get_perspective("games")
        sidePanels = persp.sidePanels
        dockLocation = persp.dockLocation

        saved_panels = []
        xmlOK = os.path.isfile(dockLocation)
        if xmlOK:
            doc = minidom.parse(dockLocation)
            for elem in doc.getElementsByTagName("panel"):
                saved_panels.append(elem.getAttribute("id"))

        store = Gtk.ListStore(bool, GdkPixbuf.Pixbuf, str, object)
        for panel in sidePanels:
            checked = True if not xmlOK else panel.__name__ in saved_panels
            panel_icon = get_pixbuf(panel.__icon__, 32)
            text = "<b>%s</b>\n%s" % (panel.__title__, panel.__desc__)
            store.append((checked, panel_icon, text, panel))

        self.tv = widgets["panels_treeview"]
        self.tv.set_model(store)

        self.widgets['panel_about_button'].connect('clicked', self.panel_about)
        self.widgets['panel_enable_button'].connect('toggled',
                                                    self.panel_toggled)
        self.tv.get_selection().connect('changed', self.selection_changed)

        pixbuf = Gtk.CellRendererPixbuf()
        pixbuf.props.yalign = 0
        pixbuf.props.ypad = 3
        pixbuf.props.xpad = 3
        self.tv.append_column(Gtk.TreeViewColumn("Icon",
                                                 pixbuf,
                                                 pixbuf=1,
                                                 sensitive=0))

        uistuff.appendAutowrapColumn(self.tv, "Name", markup=2, sensitive=0)

        widgets['preferences_notebook'].connect("switch-page", self.__on_switch_page)
        widgets["preferences_dialog"].connect("show", self.__on_show_window)
        widgets["preferences_dialog"].connect("hide", self.__on_hide_window)
コード例 #23
0
ファイル: enginesDialog.py プロジェクト: leogregianin/pychess
        def country_changed(widget):
            if self.cur_engine is not None and not self.selection:
                engine = discoverer.getEngineByName(self.cur_engine)
                old_country = discoverer.getCountry(engine)
                new_country = ISO3166_LIST[widget.get_active()].iso2
                if old_country != new_country:
                    engine["country"] = new_country

                    # Refresh the flag in the tree view
                    path = addDataPrefix("flags/%s.png" % new_country)
                    if not os.path.isfile(path):
                        path = addDataPrefix("flags/unknown.png")
                    item = self.tv.get_selection().get_selected()
                    if item is not None:
                        model, ts_iter = item
                        model[ts_iter][0] = get_pixbuf(path)

                        # Notify playerCombos in NewGameTasker
                        discoverer.emit("all_engines_discovered")
コード例 #24
0
 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
コード例 #25
0
ファイル: gamewidget.py プロジェクト: CarbonFixer/pychess
 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
コード例 #26
0
ファイル: enginesDialog.py プロジェクト: ypeng22/pychess
        def country_changed(widget):
            if self.cur_engine is not None and not self.selection:
                engine = discoverer.getEngineByName(self.cur_engine)
                old_country = discoverer.getCountry(engine)
                new_country = ISO3166_LIST[widget.get_active()].iso2
                if old_country != new_country:
                    engine["country"] = new_country

                    # Refresh the flag in the tree view
                    path = addDataPrefix("flags/%s.png" % new_country)
                    if not os.path.isfile(path):
                        path = addDataPrefix("flags/unknown.png")
                    item = self.tv.get_selection().get_selected()
                    if item is not None:
                        model, ts_iter = item
                        model[ts_iter][0] = get_pixbuf(path)

                        # Notify playerCombos in NewGameTasker
                        discoverer.emit("all_engines_discovered")
コード例 #27
0
ファイル: enginesDialog.py プロジェクト: scchess/pychess
def run(widgets):
    global firstRun
    if firstRun:
        # Bubble sort for the translated countries
        for i in range(len(ISO3166_LIST) - 1, 1, -1):
            for j in range(1, i - 1):
                if ISO3166_LIST[i].country < ISO3166_LIST[j].country:
                    tmp = ISO3166_LIST[i]
                    ISO3166_LIST[i] = ISO3166_LIST[j]
                    ISO3166_LIST[j] = tmp
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not (iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"],
                            name="engine_country_combo")
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        EnginesDialog(widgets)

        def delete_event(widget, *args):
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", delete_event)
        widgets["engines_close_button"].connect("clicked", delete_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event", lambda w, e: delete_event(w)
            if e.keyval == Gdk.KEY_Escape else None)

        firstRun = False

    widgets["manage_engines_dialog"].show()
コード例 #28
0
def run(widgets):
    global firstRun
    if firstRun:
        # Bubble sort for the translated countries
        for i in range(len(ISO3166_LIST) - 1, 1, - 1):
            for j in range(1, i - 1):
                if ISO3166_LIST[i].country < ISO3166_LIST[j].country:
                    tmp = ISO3166_LIST[i]
                    ISO3166_LIST[i] = ISO3166_LIST[j]
                    ISO3166_LIST[j] = tmp
        # Display of the countries
        items = []
        for iso in ISO3166_LIST:
            path = addDataPrefix("flags/%s.png" % iso.iso2)
            if not(iso.iso2 and os.path.isfile(path)):
                path = addDataPrefix("flags/unknown.png")
            items.append((get_pixbuf(path), iso.country))
        uistuff.createCombo(widgets["engine_country_combo"], name="engine_country_combo",
                            ellipsize_mode=Pango.EllipsizeMode.END)
        data = [(item[0], item[1]) for item in items]
        uistuff.updateCombo(widgets["engine_country_combo"], data)

        EnginesDialog(widgets)

        def delete_event(widget, *args):
            widgets["manage_engines_dialog"].hide()
            return True

        widgets["manage_engines_dialog"].connect("delete-event", delete_event)
        widgets["engines_close_button"].connect("clicked", delete_event)
        widgets["manage_engines_dialog"].connect(
            "key-press-event",
            lambda w, e: delete_event(w) if e.keyval == Gdk.KEY_Escape else None)

        firstRun = False

    widgets["manage_engines_dialog"].show()
コード例 #29
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)
コード例 #30
0
    def initButtons(self, board):
        align = createAlignment(4, 0, 4, 0)
        toolbar = Gtk.Toolbar()

        image1 = get_pixbuf("glade/first.png")
        firstButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image1))
        firstButton.set_tooltip_text(_("Jump to initial position"))
        toolbar.insert(firstButton, -1)

        image2 = get_pixbuf("glade/prev.png")
        prevButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image2))
        prevButton.set_tooltip_text(_("Step back one move"))
        toolbar.insert(prevButton, -1)

        image3 = get_pixbuf("glade/mainline.png")
        mainButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image3))
        mainButton.set_tooltip_text(_("Go back to the main line"))
        toolbar.insert(mainButton, -1)

        image4 = get_pixbuf("glade/parent.png")
        upButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image4))
        upButton.set_tooltip_text(_("Go back to the parent line"))
        toolbar.insert(upButton, -1)

        image5 = get_pixbuf("glade/next.png")
        nextButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image5))
        nextButton.set_tooltip_text(_("Step forward one move"))
        toolbar.insert(nextButton, -1)

        image6 = get_pixbuf("glade/last.png")
        lastButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image6))
        lastButton.set_tooltip_text(_("Jump to latest position"))
        toolbar.insert(lastButton, -1)

        image7 = get_pixbuf("glade/find.png")
        filterButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image7))
        filterButton.set_tooltip_text(_("Find position in current database"))
        toolbar.insert(filterButton, -1)

        image8 = get_pixbuf("glade/save.png")
        self.saveButton = Gtk.ToolButton.new(Gtk.Image.new_from_pixbuf(image8))
        self.saveButton.set_tooltip_text(_("Save arrows/circles"))
        toolbar.insert(self.saveButton, -1)

        def on_clicked(button, func):
            # Prevent moving in game while lesson not finished
            if self.gamemodel.lesson_game and not self.gamemodel.solved:
                return
            else:
                func()

        self.cids[firstButton] = firstButton.connect("clicked", on_clicked,
                                                     self.board.view.showFirst)
        self.cids[prevButton] = prevButton.connect("clicked", on_clicked,
                                                   self.board.view.showPrev)
        self.cids[mainButton] = mainButton.connect(
            "clicked", on_clicked, self.board.view.backToMainLine)
        self.cids[upButton] = upButton.connect(
            "clicked", on_clicked, self.board.view.backToParentLine)
        self.cids[nextButton] = nextButton.connect("clicked", on_clicked,
                                                   self.board.view.showNext)
        self.cids[lastButton] = lastButton.connect("clicked", on_clicked,
                                                   self.board.view.showLast)
        self.cids[filterButton] = filterButton.connect("clicked", on_clicked,
                                                       self.find_in_database)
        self.cids[self.saveButton] = self.saveButton.connect(
            "clicked", on_clicked, self.save_shapes_to_pgn)

        self.on_shapes_changed(self.board)
        self.board.connect("shapes_changed", self.on_shapes_changed)

        tool_box = Gtk.Box()
        tool_box.pack_start(toolbar, True, True, 0)

        align.add(tool_box)
        return align
コード例 #31
0
ファイル: newGameDialog.py プロジェクト: jcoffee/pychess
from pychess.Players.engineNest import discoverer
from pychess.Players.Human import Human
from pychess.widgets import BoardPreview
from pychess.widgets import ionest
from pychess.widgets import ImageMenu
from pychess.widgets.BoardControl import BoardControl
from pychess.Savers import fen, pgn
from pychess.Savers.ChessFile import LoadingError
from pychess.Variants import variants
from pychess.Variants.normal import NormalBoard

#===============================================================================
# We init most dialog icons global to make them accessibly to the
# Background.Taskers so they have a similar look.
#===============================================================================
big_time = get_pixbuf("glade/stock_alarm.svg")
big_people = load_icon(48, "stock_people", "system-users")
iwheels = load_icon(24, "gtk-execute", "system-run")
ipeople = load_icon(24, "stock_people", "system-users")
inotebook = load_icon(24, "stock_notebook", "computer")
speople = load_icon(16, "stock_people", "system-users")
snotebook = load_icon(16, "stock_notebook", "computer")

weather_icons = ("clear", "clear-night", "few-clouds", "few-clouds-night", "fog", "overcast", "severe-alert", "showers-scattered", "showers", "storm")
skillToIcon = {}
# Used by TaskerManager. Put here to help synchronization
skillToIconLarge = {}
for i, icon in enumerate(weather_icons, start=1):
    skillToIcon[2*i-1] = load_icon(16, "weather-%s" % icon)
    skillToIcon[2*i] = load_icon(16, "weather-%s" % icon)
    skillToIconLarge[2*i-1] = load_icon(48, "weather-%s" % icon)
コード例 #32
0
    def __init__(self, widgets):

        #################
        # Board Colours
        #################

        def on_colour_set_light(color_btn):
            conf.set('lightcolour',
                     widgets['light_cbtn'].get_color().to_string())

        widgets["light_cbtn"].connect_after("color-set", on_colour_set_light)

        def on_colour_set_dark(color_btn):
            conf.set('darkcolour',
                     widgets['dark_cbtn'].get_color().to_string())

        widgets["dark_cbtn"].connect_after("color-set", on_colour_set_dark)

        def on_reset_colour_clicked(btn):
            conf.set("lightcolour", "#ffffffffffff")
            conf.set("darkcolour", "#aaaaaaaaaaaa")

        widgets["reset_btn"].connect("clicked", on_reset_colour_clicked)

        # Get the current board colours if set, if not set, set them to default
        conf.set("lightcolour", conf.get("lightcolour", "#ffffffffffff"))
        conf.set("darkcolour", conf.get("darkcolour", "#aaaaaaaaaaaa"))

        # Next 2 lines take a #hex str converts them to a color then to a RGBA representation
        lightcolour = Gdk.RGBA()
        lightcolour.parse(conf.get("lightcolour", "#ffffffffffff"))
        darkcolour = Gdk.RGBA()
        darkcolour.parse(conf.get("darkcolour", "#aaaaaaaaaaaa"))

        # Set the color swatches in preference to stored values
        widgets['light_cbtn'].set_rgba(lightcolour)
        widgets['dark_cbtn'].set_rgba(darkcolour)

        #############
        # Chess Sets
        #############
        self.themes = self.discover_themes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run create_theme_preview.sh !"
                )
                break

        iconView = widgets["pieceTheme"]
        iconView.set_model(store)
        iconView.set_pixbuf_column(0)
        iconView.set_text_column(1)

        #############################################
        # Hack to fix spacing problem in iconview
        # http://stackoverflow.com/questions/14090094/what-causes-the-different-display-behaviour-for-a-gtkiconview-between-different
        def keep_size(crt, *args):
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt, crp = iconView.get_cells()
        crt_notify = crt.connect('notify', keep_size)

        #############################################

        def _get_active(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                idx = indices[0]
                theme = model[idx][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _set_active(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _get_active,
                     _set_active, "Chessicons")
コード例 #33
0
    def load(self, widgets, connection, lounge):
        self.widgets = widgets
        self.connection = connection
        self.lounge = lounge
        self.infobar = lounge.infobar

        __widget__ = lounge.seek_list

        self.messages = {}
        self.seeks = {}
        self.challenges = {}
        self.seekPix = get_pixbuf("glade/seek.png")
        self.chaPix = get_pixbuf("glade/challenge.png")
        self.manSeekPix = get_pixbuf("glade/manseek.png")

        self.widgets["seekExpander"].set_vexpand(False)

        self.tv = self.widgets["seektreeview"]
        self.store = Gtk.ListStore(FICSSoughtMatch, GdkPixbuf.Pixbuf,
                                   GdkPixbuf.Pixbuf, str, int, str, str, str,
                                   int, Gdk.RGBA, str)

        self.seek_filter = self.store.filter_new()
        self.seek_filter.set_visible_func(self.seek_filter_func)

        self.filter_toggles = {}
        self.filter_buttons = ("standard_toggle1", "blitz_toggle1", "lightning_toggle1", "variant_toggle1", "computer_toggle1")
        for widget in self.filter_buttons:
            uistuff.keep(self.widgets[widget], widget)
            self.widgets[widget].connect("toggled", self.on_filter_button_toggled)
            initial = conf.get(widget, True)
            self.filter_toggles[widget] = initial
            self.widgets[widget].set_active(initial)

        self.model = self.seek_filter.sort_new_with_model()
        self.tv.set_model(self.model)

        self.tv.set_model(self.model)
        self.addColumns(self.tv,
                        "FICSSoughtMatch",
                        "",
                        "",
                        _("Name"),
                        _("Rating"),
                        _("Rated"),
                        _("Type"),
                        _("Clock"),
                        "gametime",
                        "textcolor",
                        "tooltip",
                        hide=[0, 8, 9, 10],
                        pix=[1, 2])
        self.tv.set_search_column(3)
        self.tv.set_tooltip_column(10, )
        for i in range(0, 2):
            self.tv.get_model().set_sort_func(i, self.pixCompareFunction,
                                              i + 1)
        for i in range(2, 8):
            self.tv.get_model().set_sort_func(i, self.compareFunction, i)
        try:
            self.tv.set_search_position_func(self.lowLeftSearchPosFunc, None)
        except AttributeError:
            # Unknow signal name is raised by gtk < 2.10
            pass
        for num in range(2, 7):
            column = self.tv.get_column(num)
            for cellrenderer in column.get_cells():
                column.add_attribute(cellrenderer, "foreground_rgba", 9)
        self.selection = self.tv.get_selection()
        self.lastSeekSelected = None
        self.selection.set_select_function(self.selectFunction, True)
        self.selection.connect("changed", self.onSelectionChanged)
        self.widgets["clearSeeksButton"].connect("clicked",
                                                 self.onClearSeeksClicked)
        self.widgets["acceptButton"].connect("clicked", self.on_accept)
        self.widgets["declineButton"].connect("clicked", self.onDeclineClicked)
        self.tv.connect("row-activated", self.row_activated)
        self.tv.connect('button-press-event', self.button_press_event)

        self.connection.seeks.connect("FICSSeekCreated", self.onAddSeek)
        self.connection.seeks.connect("FICSSeekRemoved", self.onRemoveSeek)
        self.connection.challenges.connect("FICSChallengeIssued",
                                           self.onChallengeAdd)
        self.connection.challenges.connect("FICSChallengeRemoved",
                                           self.onChallengeRemove)
        self.connection.glm.connect("our-seeks-removed",
                                    self.our_seeks_removed)
        self.connection.glm.connect("assessReceived", self.onAssessReceived)
        self.connection.bm.connect("playGameCreated", self.onPlayingGame)
        self.connection.bm.connect("curGameEnded", self.onCurGameEnded)

        def get_sort_order(modelsort):
            identity, order = modelsort.get_sort_column_id()
            if identity is None or identity < 0:
                identity = 0
            else:
                identity += 1
            if order == Gtk.SortType.DESCENDING:
                identity = -1 * identity
            return identity

        def set_sort_order(modelsort, value):
            if value != 0:
                order = Gtk.SortType.ASCENDING if value > 0 else Gtk.SortType.DESCENDING
                modelsort.set_sort_column_id(abs(value) - 1, order)

        uistuff.keep(self.model, "seektreeview_sort_order_col", get_sort_order,
                     lambda modelsort, value: set_sort_order(modelsort, value))

        self.createLocalMenu((ACCEPT, ASSESS, CHALLENGE, CHAT, FOLLOW, SEPARATOR, FINGER, ARCHIVED))
        self.assess_sent = False

        return __widget__
コード例 #34
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Background image
        path = conf.get("welcome_image", addDataPrefix("glade/clear.png"))
        conf.set("welcome_image", path)

        image_chooser_dialog = Gtk.FileChooserDialog(
            _("Select background image file"), mainwindow(),
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        image_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            image_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Images"))
        filter.add_pattern("*.bmp")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.png")
        filter.add_pattern("*.svg")
        image_chooser_dialog.add_filter(filter)
        image_chooser_button.set_filename(path)

        self.widgets["imageChooserDock"].add(image_chooser_button)
        image_chooser_button.show()

        def select_new_image(button):
            new_image = image_chooser_dialog.get_filename()
            if new_image:
                conf.set("welcome_image", new_image)
                from pychess.widgets.TaskerManager import tasker
                newTheme(tasker, background=new_image)
                tasker.queue_draw()
            else:
                # restore the original
                image_chooser_dialog.set_filename(path)

        image_chooser_button.connect("file-set", select_new_image)

        # Board Colours

        style_ctxt = widgets["main_window"].get_style_context()
        LIGHT = hexcol(style_ctxt.lookup_color("p_light_color")[1])
        DARK = hexcol(style_ctxt.lookup_color("p_dark_color")[1])

        def onColourSetLight(_):
            """ :Description: Sets the light squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('lightcolour',
                     widgets['light_cbtn'].get_color().to_string())

        widgets["light_cbtn"].connect_after("color-set", onColourSetLight)

        def onColourSetDark(_):
            """ :Description: Sets the dark squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('darkcolour',
                     widgets['dark_cbtn'].get_color().to_string())

        widgets["dark_cbtn"].connect_after("color-set", onColourSetDark)

        def onResetColourClicked(_):
            """ :Description: Resets the chess board squares to factory default
            """
            conf.set("lightcolour", LIGHT)
            conf.set("darkcolour", DARK)

        widgets["reset_btn"].connect("clicked", onResetColourClicked)

        # Get the current board colours if set, if not set, set them to default
        conf.set("lightcolour", conf.get("lightcolour", LIGHT))
        conf.set("darkcolour", conf.get("darkcolour", DARK))

        # Next 2 lines take a #hex str converts them to a color then to a RGBA representation
        self.lightcolour = Gdk.RGBA()
        self.lightcolour.parse(conf.get("lightcolour", LIGHT))
        self.darkcolour = Gdk.RGBA()
        self.darkcolour.parse(conf.get("darkcolour", DARK))

        # Set the color swatches in preference to stored values
        widgets['light_cbtn'].set_rgba(self.lightcolour)
        widgets['dark_cbtn'].set_rgba(self.darkcolour)

        # Chess Sets

        self.themes = self.discoverThemes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run \
                    create_theme_preview.sh !")
                break

        self.icon_view = widgets["pieceTheme"]
        self.icon_view.set_model(store)
        self.icon_view.set_pixbuf_column(0)
        self.icon_view.set_text_column(1)

        def keepSize(crt, _):
            """ :Description: Hack to fix spacing problem in iconview
                http://stackoverflow.com/questions/14090094/what-causes-the-different-\
                    display-behaviour-for-a-gtkiconview-between-different
            """
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt = self.icon_view.get_cells()[0]
        crt_notify = crt.connect('notify', keepSize)

        def _getActive(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                idx = indices[0]
                theme = model[idx][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _setActive(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _getActive,
                     _setActive, "Chessicons")
コード例 #35
0
ファイル: preferencesDialog.py プロジェクト: bboutkov/pychess
    def __init__(self, widgets):
        self.widgets = widgets

        # Background image
        path = conf.get("welcome_image", addDataPrefix("glade/clear.png"))
        conf.set("welcome_image", path)

        image_chooser_dialog = Gtk.FileChooserDialog(
            _("Select background image file"), None, Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        image_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            image_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Images"))
        filter.add_pattern("*.bmp")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.png")
        filter.add_pattern("*.svg")
        image_chooser_dialog.add_filter(filter)
        image_chooser_button.set_filename(path)

        self.widgets["imageChooserDock"].add(image_chooser_button)
        image_chooser_button.show()

        def select_new_image(button):
            new_image = image_chooser_dialog.get_filename()
            if new_image:
                conf.set("welcome_image", new_image)
                from pychess.widgets.TaskerManager import tasker
                newTheme(tasker, background=new_image)
                tasker.queue_draw()
            else:
                # restore the original
                image_chooser_dialog.set_filename(path)

        image_chooser_button.connect("file-set", select_new_image)

        # Board Colours

        style_ctxt = widgets["main_window"].get_style_context()
        LIGHT = hexcol(style_ctxt.lookup_color("p_light_color")[1])
        DARK = hexcol(style_ctxt.lookup_color("p_dark_color")[1])

        def onColourSetLight(_):
            """ :Description: Sets the light squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('lightcolour',
                     widgets['light_cbtn'].get_color().to_string())

        widgets["light_cbtn"].connect_after("color-set", onColourSetLight)

        def onColourSetDark(_):
            """ :Description: Sets the dark squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('darkcolour',
                     widgets['dark_cbtn'].get_color().to_string())

        widgets["dark_cbtn"].connect_after("color-set", onColourSetDark)

        def onResetColourClicked(_):
            """ :Description: Resets the chess board squares to factory default
            """
            conf.set("lightcolour", LIGHT)
            conf.set("darkcolour", DARK)

        widgets["reset_btn"].connect("clicked", onResetColourClicked)

        # Get the current board colours if set, if not set, set them to default
        conf.set("lightcolour", conf.get("lightcolour", LIGHT))
        conf.set("darkcolour", conf.get("darkcolour", DARK))

        # Next 2 lines take a #hex str converts them to a color then to a RGBA representation
        self.lightcolour = Gdk.RGBA()
        self.lightcolour.parse(conf.get("lightcolour", LIGHT))
        self.darkcolour = Gdk.RGBA()
        self.darkcolour.parse(conf.get("darkcolour", DARK))

        # Set the color swatches in preference to stored values
        widgets['light_cbtn'].set_rgba(self.lightcolour)
        widgets['dark_cbtn'].set_rgba(self.darkcolour)

        # Chess Sets

        self.themes = self.discoverThemes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run \
                    create_theme_preview.sh !")
                break

        self.icon_view = widgets["pieceTheme"]
        self.icon_view.set_model(store)
        self.icon_view.set_pixbuf_column(0)
        self.icon_view.set_text_column(1)

        def keepSize(crt, _):
            """ :Description: Hack to fix spacing problem in iconview
                http://stackoverflow.com/questions/14090094/what-causes-the-different-\
                    display-behaviour-for-a-gtkiconview-between-different
            """
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt = self.icon_view.get_cells()[0]
        crt_notify = crt.connect('notify', keepSize)

        def _getActive(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                idx = indices[0]
                theme = model[idx][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _setActive(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _getActive,
                     _setActive, "Chessicons")
コード例 #36
0
    def load(self, gmwidg):
        self.gmwidg = gmwidg
        self.boardcontrol = gmwidg.board
        self.boardview = gmwidg.board.view

        self.figuresInNotation = conf.get("figuresInNotation")

        self.sw = Gtk.ScrolledWindow()
        self.tv = Gtk.TreeView()
        self.tv.set_property("headers_visible", False)
        self.sw.add(self.tv)
        self.sw.show_all()

        self.store = Gtk.TreeStore(GObject.TYPE_PYOBJECT,
                                   GObject.TYPE_PYOBJECT, int, bool, str, bool,
                                   bool)
        self.tv.set_model(self.store)

        # ## move suggested
        moveRenderer = Gtk.CellRendererText()
        moveRenderer.set_property("xalign", 1.0)
        moveRenderer.set_property("yalign", 0)
        c0 = Gtk.TreeViewColumn("Move", moveRenderer)

        def getMoveText(column, cell, store, iter, data):
            board, move, pv = store[iter][0]
            if not move:
                cell.set_property("text", "")
            else:
                if self.figuresInNotation:
                    cell.set_property("text", toFAN(board, move))
                else:
                    cell.set_property("text", toSAN(board, move, True))

        c0.set_cell_data_func(moveRenderer, getMoveText)

        # ## strength of the move
        c1 = Gtk.TreeViewColumn("Strength", StrengthCellRenderer(), data=1)

        # ## multipv (number of analysis lines)
        self.multipvRenderer = Gtk.CellRendererSpin()
        adjustment = Gtk.Adjustment(value=1,
                                    lower=1,
                                    upper=9,
                                    step_increment=1)
        self.multipvRenderer.set_property("adjustment", adjustment)
        self.multipvRenderer.set_property("editable", True)
        self.multipvRenderer.set_property("width_chars", 1)
        c2 = Gtk.TreeViewColumn("PV", self.multipvRenderer, editable=3)
        c2.set_property("min_width", 80)

        def spin_visible(column, cell, store, iter, data):
            if store[iter][2] == 0:
                cell.set_property('visible', False)
            else:
                cell.set_property("text", str(store[iter][2]))
                cell.set_property('visible', True)

        c2.set_cell_data_func(self.multipvRenderer, spin_visible)

        def multipv_edited(renderer, path, text):
            iter = self.store.get_iter(path)
            self.store.set_value(
                iter, 2, self.advisors[int(
                    path[0])].multipv_edited(1 if text == "" else int(text)))

        self.multipv_cid = self.multipvRenderer.connect(
            'edited', multipv_edited)

        # ## start/stop button for analysis engines
        self.toggleRenderer = CellRendererPixbufXt()
        self.toggleRenderer.set_property("stock-id", "gtk-add")
        c4 = Gtk.TreeViewColumn("StartStop", self.toggleRenderer)

        self.play_image = get_pixbuf("glade/play.png")
        self.pause_image = get_pixbuf("glade/pause.png")

        def cb_visible(column, cell, store, iter, data):
            if not store[iter][6]:
                cell.set_property('visible', False)
            else:
                cell.set_property('visible', True)

            if store[iter][5]:
                cell.set_property("pixbuf", self.play_image)
            else:
                cell.set_property("pixbuf", self.pause_image)

        c4.set_cell_data_func(self.toggleRenderer, cb_visible)

        def toggled_cb(cell, path):
            self.store[path][5] = not self.store[path][5]
            self.advisors[int(path[0])].start_stop(self.store[path][5])

        self.toggle_cid = self.toggleRenderer.connect('clicked', toggled_cb)

        self.tv.append_column(c4)
        self.tv.append_column(c0)
        self.tv.append_column(c1)
        self.tv.append_column(c2)
        # ## header text, or analysis line
        uistuff.appendAutowrapColumn(self.tv, "Details", text=4)

        self.cid = self.boardview.connect("shownChanged", self.shownChanged)
        self.tv_cids = [
            self.tv.connect("cursor_changed", self.selection_changed),
            self.tv.connect("select_cursor_row", self.selection_changed),
            self.tv.connect("row-activated", self.row_activated),
            self.tv.connect("query-tooltip", self.query_tooltip),
        ]
        self.tv.props.has_tooltip = True
        self.tv.set_property("show-expanders", False)

        self.advisors = []
        self.conf_conids = []

        if conf.get("opening_check"):
            advisor = OpeningAdvisor(self.store, self.tv, self.boardcontrol)
            self.advisors.append(advisor)
        if conf.get("endgame_check"):
            advisor = EndgameAdvisor(self.store, self.tv, self.boardcontrol)
            self.advisors.append(advisor)

        self.model_cids = [
            gmwidg.gamemodel.connect("analyzer_added", self.on_analyzer_added),
            gmwidg.gamemodel.connect("analyzer_removed",
                                     self.on_analyzer_removed),
            gmwidg.gamemodel.connect_after("game_terminated",
                                           self.on_game_terminated),
        ]

        def on_opening_check(none):
            if conf.get("opening_check") and self.boardview is not None:
                advisor = OpeningAdvisor(self.store, self.tv,
                                         self.boardcontrol)
                self.advisors.append(advisor)
                advisor.shownChanged(self.boardview, self.boardview.shown)
            else:
                for advisor in self.advisors:
                    if advisor.mode == OPENING:
                        parent = advisor.empty_parent()
                        self.store.remove(parent)
                        self.advisors.remove(advisor)

        self.conf_conids.append(
            conf.notify_add("opening_check", on_opening_check))

        def on_opening_file_entry_changed(none):
            path = conf.get("opening_file_entry")
            if os.path.isfile(path):
                for advisor in self.advisors:
                    if advisor.mode == OPENING and self.boardview is not None:
                        advisor.shownChanged(self.boardview,
                                             self.boardview.shown)

        self.conf_conids.append(
            conf.notify_add("opening_file_entry",
                            on_opening_file_entry_changed))

        def on_endgame_check(none):
            if conf.get("endgame_check"):
                advisor = EndgameAdvisor(self.store, self.tv,
                                         self.boardcontrol)
                self.advisors.append(advisor)
                advisor.shownChanged(self.boardview, self.boardview.shown)
            else:
                for advisor in self.advisors:
                    if advisor.mode == ENDGAME:
                        advisor._del()
                        parent = advisor.empty_parent()
                        self.store.remove(parent)
                        self.advisors.remove(advisor)

        self.conf_conids.append(
            conf.notify_add("endgame_check", on_endgame_check))

        def on_figures_in_notation(none):
            self.figuresInNotation = conf.get("figuresInNotation")

        self.conf_conids.append(
            conf.notify_add("figuresInNotation", on_figures_in_notation))

        return self.sw
コード例 #37
0
ファイル: gamewidget.py プロジェクト: CarbonFixer/pychess
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)
コード例 #38
0
    def __init__(self, widgets):

        # Board Colours

        style_ctxt = widgets["window1"].get_style_context()
        LIGHT = hexcol(style_ctxt.lookup_color("p_light_color")[1])
        DARK = hexcol(style_ctxt.lookup_color("p_dark_color")[1])

        def onColourSetLight(_):
            """ :Description: Sets the light squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('lightcolour',
                     widgets['light_cbtn'].get_color().to_string())

        widgets["light_cbtn"].connect_after("color-set", onColourSetLight)

        def onColourSetDark(_):
            """ :Description: Sets the dark squares of the chess board
                to the value selected in the colour picker
            """
            conf.set('darkcolour',
                     widgets['dark_cbtn'].get_color().to_string())

        widgets["dark_cbtn"].connect_after("color-set", onColourSetDark)

        def onResetColourClicked(_):
            """ :Description: Resets the chess board squares to factory default
            """
            conf.set("lightcolour", LIGHT)
            conf.set("darkcolour", DARK)

        widgets["reset_btn"].connect("clicked", onResetColourClicked)

        # Get the current board colours if set, if not set, set them to default
        conf.set("lightcolour", conf.get("lightcolour", LIGHT))
        conf.set("darkcolour", conf.get("darkcolour", DARK))

        # Next 2 lines take a #hex str converts them to a color then to a RGBA representation
        self.lightcolour = Gdk.RGBA()
        self.lightcolour.parse(conf.get("lightcolour", LIGHT))
        self.darkcolour = Gdk.RGBA()
        self.darkcolour.parse(conf.get("darkcolour", DARK))

        # Set the color swatches in preference to stored values
        widgets['light_cbtn'].set_rgba(self.lightcolour)
        widgets['dark_cbtn'].set_rgba(self.darkcolour)

        # Chess Sets

        self.themes = self.discoverThemes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print(
                    "WARNING: No piece theme preview icons found. Please run \
                    create_theme_preview.sh !")
                break

        self.icon_view = widgets["pieceTheme"]
        self.icon_view.set_model(store)
        self.icon_view.set_pixbuf_column(0)
        self.icon_view.set_text_column(1)

        def keepSize(crt, _):
            """ :Description: Hack to fix spacing problem in iconview
                http://stackoverflow.com/questions/14090094/what-causes-the-different-\
                    display-behaviour-for-a-gtkiconview-between-different
            """
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt = self.icon_view.get_cells()[0]
        crt_notify = crt.connect('notify', keepSize)

        def _getActive(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                idx = indices[0]
                theme = model[idx][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _setActive(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index, ))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _getActive,
                     _setActive, "Chessicons")
コード例 #39
0
    def load(self, widgets, connection, lounge):
        self.widgets = widgets
        self.connection = connection
        self.lounge = lounge

        __widget__ = lounge.games_list

        self.games = {}
        self.recpix = load_icon(16, "media-record")
        self.clearpix = get_pixbuf("glade/board.png")
        self.tv = self.widgets["gametreeview"]
        self.store = Gtk.ListStore(FICSGame, GdkPixbuf.Pixbuf, str, int, str,
                                   int, str, str)

        self.game_filter = self.store.filter_new()
        self.game_filter.set_visible_func(self.game_filter_func)

        self.filter_toggles = {}
        self.filter_buttons = ("standard_toggle", "blitz_toggle", "lightning_toggle", "variant_toggle")
        for widget in self.filter_buttons:
            uistuff.keep(self.widgets[widget], widget)
            self.widgets[widget].connect("toggled", self.on_filter_button_toggled)
            initial = conf.get(widget, True)
            self.filter_toggles[widget] = initial
            self.widgets[widget].set_active(initial)

        self.model = self.game_filter.sort_new_with_model()
        self.tv.set_model(self.model)
        self.tv.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
        self.addColumns(self.tv,
                        "FICSGame",
                        "",
                        _("White"),
                        _("Rating"),
                        _("Black"),
                        _("Rating"),
                        _("Type"),
                        _("Rated"),
                        hide=[0],
                        pix=[1])

        self.tv.get_model().set_sort_func(0, self.pixCompareFunction, 1)
        for i in range(1, 7):
            self.tv.get_model().set_sort_func(i, self.compareFunction, i)
        self.prev_sort_column_id = []
        self.model.connect("sort-column-changed", self.on_sort_column_change)

        self.tv.set_has_tooltip(True)
        self.tv.connect("query-tooltip", self.on_query_tooltip)
        self.selection = self.tv.get_selection()
        self.selection.connect("changed", self.onSelectionChanged)
        self.onSelectionChanged(self.selection)

        try:
            self.tv.set_search_position_func(self.lowLeftSearchPosFunc, None)
        except AttributeError:
            # Unknow signal name is raised by gtk < 2.10
            pass

        def searchCallback(model, column, key, sel_iter, user_data):
            if model.get_value(sel_iter, 2).lower().startswith(key) or \
                    model.get_value(sel_iter, 4).lower().startswith(key):
                return False
            return True

        self.tv.set_search_equal_func(searchCallback, None)

        self.connection.games.connect("FICSGameCreated", self.onGameAdd)
        self.connection.games.connect("FICSGameEnded", self.onGameRemove)
        self.widgets["observeButton"].connect("clicked", self.on_observe)
        self.tv.connect("row-activated", self.on_observe)
        self.connection.bm.connect("obsGameCreated", self.onGameObserved)
        self.connection.bm.connect("obsGameUnobserved", self.onGameUnobserved)

        self.tv.connect('button-press-event', self.button_press_event)
        self.createLocalMenu((OBSERVE, FOLLOW, SEPARATOR, FINGER, ARCHIVED))

        return __widget__
コード例 #40
0
ファイル: newGameDialog.py プロジェクト: ypeng22/pychess
from pychess.widgets import ImageMenu, mainwindow
from pychess.widgets.prompttext import getUserTextDialog
from pychess.widgets.BoardControl import BoardControl
from pychess.Savers import fen, pgn
from pychess.Savers.ChessFile import LoadingError
from pychess.Variants import variants
from pychess.Variants.normal import NormalBoard
from pychess.perspectives import perspective_manager
from pychess.perspectives.games import enddir
from pychess.Utils.eco import find_opening_fen

# ===============================================================================
# We init most dialog icons global to make them accessibly to the
# Background.Taskers so they have a similar look.
# ===============================================================================
big_time = get_pixbuf("glade/stock_alarm.svg")
big_people = get_pixbuf("glade/people48.png")
iwheels = get_pixbuf("glade/wheel.png")
ipeople = get_pixbuf("glade/people24.png")
inotebook = load_icon(24, "stock_notebook", "computer")

weather_icons = ("clear", "clear-night", "few-clouds", "few-clouds-night",
                 "fog", "overcast", "severe-alert", "showers-scattered",
                 "showers", "storm")
skillToIcon = {}
# Used by TaskerManager. Put here to help synchronization
skillToIconLarge = {}
for i, icon in enumerate(weather_icons, start=1):
    skillToIcon[2 * i - 1] = get_pixbuf("glade/16x16/weather-%s.png" % icon)
    skillToIcon[2 * i] = get_pixbuf("glade/16x16/weather-%s.png" % icon)
    skillToIconLarge[2 * i - 1] = get_pixbuf("glade/48x48/weather-%s.png" % icon)
コード例 #41
0
ファイル: newGameDialog.py プロジェクト: leogregianin/pychess
from pychess.Players.Human import Human
from pychess.widgets import ImageMenu
from pychess.widgets import mainwindow
from pychess.widgets.BoardControl import BoardControl
from pychess.Savers import fen, pgn
from pychess.Savers.ChessFile import LoadingError
from pychess.Variants import variants
from pychess.Variants.normal import NormalBoard
from pychess.perspectives import perspective_manager
from pychess.perspectives.games import enddir

# ===============================================================================
# We init most dialog icons global to make them accessibly to the
# Background.Taskers so they have a similar look.
# ===============================================================================
big_time = get_pixbuf("glade/stock_alarm.svg")
big_people = load_icon(48, "stock_people", "system-users")
iwheels = load_icon(24, "gtk-execute", "system-run")
ipeople = load_icon(24, "stock_people", "system-users")
inotebook = load_icon(24, "stock_notebook", "computer")

weather_icons = ("clear", "clear-night", "few-clouds", "few-clouds-night",
                 "fog", "overcast", "severe-alert", "showers-scattered",
                 "showers", "storm")
skillToIcon = {}
# Used by TaskerManager. Put here to help synchronization
skillToIconLarge = {}
for i, icon in enumerate(weather_icons, start=1):
    skillToIcon[2 * i - 1] = get_pixbuf("glade/16x16/weather-%s.png" % icon)
    skillToIcon[2 * i] = get_pixbuf("glade/16x16/weather-%s.png" % icon)
    skillToIconLarge[2 * i - 1] = get_pixbuf("glade/48x48/weather-%s.png" % icon)
コード例 #42
0
ファイル: newGameDialog.py プロジェクト: judoaseeta/pychess
from pychess.Players.Human import Human
from pychess.widgets import ImageMenu
from pychess.widgets import mainwindow
from pychess.widgets.BoardControl import BoardControl
from pychess.Savers import fen, pgn
from pychess.Savers.ChessFile import LoadingError
from pychess.Variants import variants
from pychess.Variants.normal import NormalBoard
from pychess.perspectives import perspective_manager
from pychess.perspectives.games import enddir

# ===============================================================================
# We init most dialog icons global to make them accessibly to the
# Background.Taskers so they have a similar look.
# ===============================================================================
big_time = get_pixbuf("glade/stock_alarm.svg")
big_people = load_icon(48, "stock_people", "system-users")
iwheels = load_icon(24, "gtk-execute", "system-run")
ipeople = load_icon(24, "stock_people", "system-users")
inotebook = load_icon(24, "stock_notebook", "computer")

weather_icons = ("clear", "clear-night", "few-clouds", "few-clouds-night",
                 "fog", "overcast", "severe-alert", "showers-scattered",
                 "showers", "storm")
skillToIcon = {}
# Used by TaskerManager. Put here to help synchronization
skillToIconLarge = {}
for i, icon in enumerate(weather_icons, start=1):
    skillToIcon[2 * i - 1] = get_pixbuf("glade/16x16/weather-%s.png" % icon)
    skillToIcon[2 * i] = get_pixbuf("glade/16x16/weather-%s.png" % icon)
    skillToIconLarge[2 * i - 1] = get_pixbuf("glade/48x48/weather-%s.png" %
コード例 #43
0
ファイル: newGameDialog.py プロジェクト: jcoffee/pychess
from pychess.Players.engineNest import discoverer
from pychess.Players.Human import Human
from pychess.widgets import BoardPreview
from pychess.widgets import ionest
from pychess.widgets import ImageMenu
from pychess.widgets.BoardControl import BoardControl
from pychess.Savers import fen, pgn
from pychess.Savers.ChessFile import LoadingError
from pychess.Variants import variants
from pychess.Variants.normal import NormalBoard

#===============================================================================
# We init most dialog icons global to make them accessibly to the
# Background.Taskers so they have a similar look.
#===============================================================================
big_time = get_pixbuf("glade/stock_alarm.svg")
big_people = load_icon(48, "stock_people", "system-users")
iwheels = load_icon(24, "gtk-execute", "system-run")
ipeople = load_icon(24, "stock_people", "system-users")
inotebook = load_icon(24, "stock_notebook", "computer")
speople = load_icon(16, "stock_people", "system-users")
snotebook = load_icon(16, "stock_notebook", "computer")

weather_icons = ("clear", "clear-night", "few-clouds", "few-clouds-night",
                 "fog", "overcast", "severe-alert", "showers-scattered",
                 "showers", "storm")
skillToIcon = {}
# Used by TaskerManager. Put here to help synchronization
skillToIconLarge = {}
for i, icon in enumerate(weather_icons, start=1):
    skillToIcon[2 * i - 1] = load_icon(16, "weather-%s" % icon)
コード例 #44
0
ファイル: newGameDialog.py プロジェクト: judoaseeta/pychess
    def _init(cls):
        cls.white = get_pixbuf("glade/white.png")
        cls.black = get_pixbuf("glade/black.png")

        cls.widgets = uistuff.GladeWidgets("newInOut.glade")
        cls.widgets["newgamedialog"].set_transient_for(mainwindow())

        def on_exchange_players(widget, button_event):
            white = cls.widgets["whitePlayerCombobox"].get_active()
            black = cls.widgets["blackPlayerCombobox"].get_active()
            whiteLevel = cls.widgets["skillSlider1"].get_value()
            blackLevel = cls.widgets["skillSlider2"].get_value()
            cls.widgets["whitePlayerCombobox"].set_active(black)
            cls.widgets["blackPlayerCombobox"].set_active(white)
            cls.widgets["skillSlider1"].set_value(blackLevel)
            cls.widgets["skillSlider2"].set_value(whiteLevel)

        cls.widgets["whitePlayerButton"].set_image(
            Gtk.Image.new_from_pixbuf(cls.white))
        cls.widgets["whitePlayerButton"].connect("button-press-event",
                                                 on_exchange_players)
        cls.widgets["blackPlayerButton"].set_image(
            Gtk.Image.new_from_pixbuf(cls.black))
        cls.widgets["blackPlayerButton"].connect("button-press-event",
                                                 on_exchange_players)

        uistuff.createCombo(cls.widgets["whitePlayerCombobox"],
                            name="whitePlayerCombobox")
        uistuff.createCombo(cls.widgets["blackPlayerCombobox"],
                            name="blackPlayerCombobox")

        cls.widgets["playersIcon"].set_from_pixbuf(big_people)
        cls.widgets["timeIcon"].set_from_pixbuf(big_time)

        def on_playerCombobox_changed(widget, skill_hbox):
            skill_hbox.props.visible = widget.get_active() > 0

        cls.widgets["whitePlayerCombobox"].connect("changed",
                                                   on_playerCombobox_changed,
                                                   cls.widgets["skillHbox1"])
        cls.widgets["blackPlayerCombobox"].connect("changed",
                                                   on_playerCombobox_changed,
                                                   cls.widgets["skillHbox2"])
        cls.widgets["whitePlayerCombobox"].set_active(0)
        cls.widgets["blackPlayerCombobox"].set_active(1)

        def on_skill_changed(scale, image):
            image.set_from_pixbuf(skillToIcon[int(scale.get_value())])

        cls.widgets["skillSlider1"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon1"])
        cls.widgets["skillSlider2"].connect("value-changed", on_skill_changed,
                                            cls.widgets["skillIcon2"])
        cls.widgets["skillSlider1"].set_value(3)
        cls.widgets["skillSlider2"].set_value(3)

        cls.__initTimeRadio(_("Blitz"), "ngblitz", cls.widgets["blitzRadio"],
                            cls.widgets["configImageBlitz"], 5, 0, 0)
        cls.__initTimeRadio(_("Rapid"), "ngrapid", cls.widgets["rapidRadio"],
                            cls.widgets["configImageRapid"], 15, 5, 0)
        cls.__initTimeRadio(_("Normal"), "ngnormal",
                            cls.widgets["normalRadio"],
                            cls.widgets["configImageNormal"], 40, 15, 0)
        cls.__initTimeRadio(_("Classical"), "ngclassical",
                            cls.widgets["classicalRadio"],
                            cls.widgets["configImageClassical"], 3, 0, 40)

        cls.__initVariantRadio("ngvariant1", cls.widgets["playVariant1Radio"],
                               cls.widgets["configImageVariant1"],
                               FISCHERRANDOMCHESS)
        cls.__initVariantRadio("ngvariant2", cls.widgets["playVariant2Radio"],
                               cls.widgets["configImageVariant2"], LOSERSCHESS)

        def updateCombos(*args):
            if cls.widgets["playNormalRadio"].get_active():
                variant = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            else:
                variant = conf.get("ngvariant2", LOSERSCHESS)
            variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            cls.widgets["playVariant1Radio"].set_tooltip_text(
                variants[variant1].__desc__)
            variant2 = conf.get("ngvariant2", LOSERSCHESS)
            cls.widgets["playVariant2Radio"].set_tooltip_text(
                variants[variant2].__desc__)
            data = [(item[0], item[1]) for item in playerItems[variant]]
            uistuff.updateCombo(cls.widgets["blackPlayerCombobox"], data)
            uistuff.updateCombo(cls.widgets["whitePlayerCombobox"], data)

        discoverer.connect_after("all_engines_discovered", updateCombos)
        updateCombos(discoverer)

        conf.notify_add("ngvariant1", updateCombos)
        conf.notify_add("ngvariant2", updateCombos)
        cls.widgets["playNormalRadio"].connect("toggled", updateCombos)
        cls.widgets["playNormalRadio"].set_tooltip_text(
            variants[NORMALCHESS].__desc__)
        cls.widgets["playVariant1Radio"].connect("toggled", updateCombos)
        variant1 = conf.get("ngvariant1", FISCHERRANDOMCHESS)
        cls.widgets["playVariant1Radio"].set_tooltip_text(
            variants[variant1].__desc__)
        cls.widgets["playVariant2Radio"].connect("toggled", updateCombos)
        variant2 = conf.get("ngvariant2", LOSERSCHESS)
        cls.widgets["playVariant2Radio"].set_tooltip_text(
            variants[variant2].__desc__)

        # The "variant" has to come before players, because the engine positions
        # in the user comboboxes can be different in different variants
        for key in ("whitePlayerCombobox", "blackPlayerCombobox",
                    "skillSlider1", "skillSlider2", "notimeRadio",
                    "blitzRadio", "rapidRadio", "normalRadio",
                    "classicalRadio", "playNormalRadio", "playVariant1Radio",
                    "playVariant2Radio"):
            uistuff.keep(cls.widgets[key], key)

        # We don't want the dialog to deallocate when closed. Rather we hide
        # it on respond
        cls.widgets["newgamedialog"].connect("delete_event", lambda *a: True)
コード例 #45
0
    def __on_show_window(self, widget):
        notebook = self.widgets['preferences_notebook']
        page_num = notebook.get_current_page()
        if notebook.get_nth_page(page_num) == self.widgets['sidepanels']:
            self.showit()

    def __on_hide_window(self, widget):
        self.hideit()


# Theme initing

board_items = [(None, "colors only")]
boards_path = addDataPrefix("boards")
board_items += [(get_pixbuf(os.path.join(boards_path, b), 24), b[:-6])
                for b in listdir(boards_path) if b.endswith("_d.png")]


class ThemeTab:
    """ :Description: Allows the setting of various user specific chess
        sets and board colours
    """
    def __init__(self, widgets):
        self.widgets = widgets

        # Background image
        path = conf.get("welcome_image", addDataPrefix("glade/clear.png"))
        conf.set("welcome_image", path)

        image_chooser_dialog = Gtk.FileChooserDialog(
コード例 #46
0
    def __on_show_window(self, widget):
        notebook = self.widgets['preferences_notebook']
        page_num = notebook.get_current_page()
        if notebook.get_nth_page(page_num) == self.widgets['sidepanels']:
            self.showit()

    def __on_hide_window(self, widget):
        self.hideit()


# Theme initing

board_items = [(None, "colors only")]
boards_path = addDataPrefix("boards")
board_items += [(get_pixbuf(os.path.join(boards_path, b), 24), b[:-6]) for b in listdir(boards_path) if b.endswith("_d.png")]


class ThemeTab:
    """ :Description: Allows the setting of various user specific chess
        sets and board colours
    """
    def __init__(self, widgets):
        self.widgets = widgets

        # Font chooser
        font = conf.get("movetextFont", "FreeSerif Regular 12")
        font_button = Gtk.FontButton.new_with_font(font)
        demo_text = "♔a1 ♕f8 ♖h8 ♗g7 ♘g2 Ka1 Qf8 Rh8 Bg7 Ng2"
        font_button.set_preview_text(demo_text)
        self.widgets["fontChooserDock"].add(font_button)
コード例 #47
0
from pychess.Utils.const import REMOTE, UNFINISHED_STATES, PAUSED, RUNNING, LOCAL, \
    WHITE, BLACK, ACTION_MENU_ITEMS, DRAW, UNDOABLE_STATES, HINT, SPY, WHITEWON, \
    MENU_ITEMS, BLACKWON, DROP, FAN_PIECES, TOOL_CHESSDB, TOOL_SCOUTFISH
from pychess.Utils.GameModel import GameModel
from pychess.Utils.Move import listToMoves
from pychess.Utils.lutils import lmove
from pychess.Utils.lutils.lmove import ParsingError
from pychess.Utils.logic import playerHasMatingMaterial, isClaimableDraw
from pychess.ic import get_infobarmessage_content, get_infobarmessage_content2
from pychess.ic.FICSObjects import get_player_tooltip_text
from pychess.ic.ICGameModel import ICGameModel
from pychess.widgets import createImage, createAlignment, gtk_close
from pychess.widgets.InfoBar import InfoBarNotebook, InfoBarMessage, InfoBarMessageButton
from pychess.perspectives import perspective_manager

light_on = get_pixbuf("glade/16x16/weather-clear.png")
light_off = get_pixbuf("glade/16x16/weather-clear-night.png")

widgets = None


def setWidgets(w):
    global widgets
    widgets = w
    pychess.widgets.main_window = widgets["main_window"]


def getWidgets():
    return widgets

コード例 #48
0
ファイル: newGameDialog.py プロジェクト: leogregianin/pychess
    def _init(cls):
        cls.white = get_pixbuf("glade/white.png")
        cls.black = get_pixbuf("glade/black.png")

        cls.widgets = uistuff.GladeWidgets("newInOut.glade")
        cls.widgets["newgamedialog"].set_transient_for(mainwindow())

        def on_exchange_players(widget, button_event):
            white = cls.widgets["whitePlayerCombobox"].get_active()
            black = cls.widgets["blackPlayerCombobox"].get_active()
            whiteLevel = cls.widgets["skillSlider1"].get_value()
            blackLevel = cls.widgets["skillSlider2"].get_value()
            cls.widgets["whitePlayerCombobox"].set_active(black)
            cls.widgets["blackPlayerCombobox"].set_active(white)
            cls.widgets["skillSlider1"].set_value(blackLevel)
            cls.widgets["skillSlider2"].set_value(whiteLevel)

        cls.widgets["whitePlayerButton"].set_image(Gtk.Image.new_from_pixbuf(cls.white))
        cls.widgets["whitePlayerButton"].connect("button-press-event", on_exchange_players)
        cls.widgets["blackPlayerButton"].set_image(Gtk.Image.new_from_pixbuf(cls.black))
        cls.widgets["blackPlayerButton"].connect("button-press-event", on_exchange_players)

        uistuff.createCombo(cls.widgets["whitePlayerCombobox"], name="whitePlayerCombobox")
        uistuff.createCombo(cls.widgets["blackPlayerCombobox"], name="blackPlayerCombobox")

        cls.widgets["playersIcon"].set_from_pixbuf(big_people)
        cls.widgets["timeIcon"].set_from_pixbuf(big_time)

        def on_playerCombobox_changed(widget, skill_hbox, skill_level):
            position = widget.get_active()
            skill_hbox.props.visible = position > 0
            if position > 0:
                tree_iter = widget.get_active_iter()
                if tree_iter is not None:
                    engine_name = widget.get_model()[tree_iter][1]
                    engine = discoverer.getEngineByName(engine_name)
                    if engine:
                        pref_level = engine.get("level")
                        if pref_level:
                            skill_level.set_value(pref_level)

        cls.widgets["whitePlayerCombobox"].connect("changed", on_playerCombobox_changed, cls.widgets["skillHbox1"], cls.widgets["skillSlider1"])
        cls.widgets["blackPlayerCombobox"].connect("changed", on_playerCombobox_changed, cls.widgets["skillHbox2"], cls.widgets["skillSlider2"])
        cls.widgets["whitePlayerCombobox"].set_active(0)
        cls.widgets["blackPlayerCombobox"].set_active(1)

        def on_skill_changed(scale, image):
            image.set_from_pixbuf(skillToIcon[int(scale.get_value())])

        cls.widgets["skillSlider1"].connect("value-changed", on_skill_changed, cls.widgets["skillIcon1"])
        cls.widgets["skillSlider2"].connect("value-changed", on_skill_changed, cls.widgets["skillIcon2"])
        cls.widgets["skillSlider1"].set_value(3)
        cls.widgets["skillSlider2"].set_value(3)

        cls.__initTimeRadio("ngblitz", cls.widgets["blitzRadio"], cls.widgets["configImageBlitz"], 5, 0, 0)
        cls.__initTimeRadio("ngrapid", cls.widgets["rapidRadio"], cls.widgets["configImageRapid"], 15, 5, 0)
        cls.__initTimeRadio("ngnormal", cls.widgets["normalRadio"], cls.widgets["configImageNormal"], 45, 15, 0)
        cls.__initTimeRadio("ngclassical", cls.widgets["classicalRadio"], cls.widgets["configImageClassical"], 3, 0, 40)

        cls.__initVariantRadio("ngvariant1", cls.widgets["playVariant1Radio"], cls.widgets["configImageVariant1"])
        cls.__initVariantRadio("ngvariant2", cls.widgets["playVariant2Radio"], cls.widgets["configImageVariant2"])

        def updateCombos(*args):
            if cls.widgets["playNormalRadio"].get_active():
                variant = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant = conf.get("ngvariant1")
            else:
                variant = conf.get("ngvariant2")
            variant1 = conf.get("ngvariant1")
            cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)
            variant2 = conf.get("ngvariant2")
            cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)
            data = [(item[0], item[1]) for item in playerItems[variant]]
            uistuff.updateCombo(cls.widgets["blackPlayerCombobox"], data)
            uistuff.updateCombo(cls.widgets["whitePlayerCombobox"], data)

        discoverer.connect_after("all_engines_discovered", updateCombos)
        updateCombos(discoverer)

        conf.notify_add("ngvariant1", updateCombos)
        conf.notify_add("ngvariant2", updateCombos)
        cls.widgets["playNormalRadio"].connect("toggled", updateCombos)
        cls.widgets["playNormalRadio"].set_tooltip_text(variants[NORMALCHESS].__desc__)
        cls.widgets["playVariant1Radio"].connect("toggled", updateCombos)
        variant1 = conf.get("ngvariant1")
        cls.widgets["playVariant1Radio"].set_tooltip_text(variants[variant1].__desc__)
        cls.widgets["playVariant2Radio"].connect("toggled", updateCombos)
        variant2 = conf.get("ngvariant2")
        cls.widgets["playVariant2Radio"].set_tooltip_text(variants[variant2].__desc__)

        # The "variant" has to come before players, because the engine positions
        # in the user comboboxes can be different in different variants
        for key in ("whitePlayerCombobox", "blackPlayerCombobox",
                    "skillSlider1", "skillSlider2", "notimeRadio",
                    "blitzRadio", "rapidRadio", "normalRadio", "classicalRadio",
                    "playNormalRadio", "playVariant1Radio", "playVariant2Radio"):
            uistuff.keep(cls.widgets[key], key)

        # We don't want the dialog to deallocate when closed. Rather we hide
        # it on respond
        cls.widgets["newgamedialog"].connect("delete_event", lambda *a: True)
コード例 #49
0
    def __init__ (self, widgets):

        #################
        # Board Colours
        #################

        def on_colour_set_light(color_btn):
            conf.set('lightcolour',widgets['light_cbtn'].get_color().to_string())

        widgets["light_cbtn"].connect_after("color-set",
                                                on_colour_set_light)

        def on_colour_set_dark(color_btn):
            conf.set('darkcolour',widgets['dark_cbtn'].get_color().to_string())

        widgets["dark_cbtn"].connect_after("color-set",
                                                on_colour_set_dark)

        def on_reset_colour_clicked(btn):
            conf.set("lightcolour", "#ffffffffffff")
            conf.set("darkcolour", "#aaaaaaaaaaaa")

        widgets["reset_btn"].connect("clicked", on_reset_colour_clicked)


        # Get the current board colours if set, if not set, set them to default
        conf.set("lightcolour", conf.get("lightcolour", "#ffffffffffff"))
        conf.set("darkcolour", conf.get("darkcolour", "#aaaaaaaaaaaa"))

        # Next 2 lines take a #hex str converts them to a color then to a RGBA representation
        lightcolour =  Gdk.RGBA()
        lightcolour.parse(conf.get("lightcolour", "#ffffffffffff"))
        darkcolour =  Gdk.RGBA()
        darkcolour.parse(conf.get("darkcolour", "#aaaaaaaaaaaa"))

        # Set the color swatches in preference to stored values
        widgets['light_cbtn'].set_rgba(lightcolour)
        widgets['dark_cbtn'].set_rgba(darkcolour)


        #############
        # Chess Sets
        #############
        self.themes = self.discover_themes()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for theme in self.themes:
            pngfile = "%s/%s.png" % (addDataPrefix("pieces"), theme)

            if isfile(pngfile):
                pixbuf = get_pixbuf(pngfile)
                store.append((pixbuf, theme))
            else:
                print("WARNING: No piece theme preview icons found. Please run create_theme_preview.sh !")
                break

        iconView = widgets["pieceTheme"]
        iconView.set_model(store)
        iconView.set_pixbuf_column(0)
        iconView.set_text_column(1)

        #############################################
        # Hack to fix spacing problem in iconview
        # http://stackoverflow.com/questions/14090094/what-causes-the-different-display-behaviour-for-a-gtkiconview-between-different
        def keep_size(crt, *args):
            crt.handler_block(crt_notify)
            crt.set_property('width', 40)
            crt.handler_unblock(crt_notify)

        crt, crp = iconView.get_cells()
        crt_notify = crt.connect('notify', keep_size)
        #############################################

        def _get_active(iconview):
            model = iconview.get_model()
            selected = iconview.get_selected_items()

            if len(selected) == 0:
                return conf.get("pieceTheme", "Chessicons")

            indices = selected[0].get_indices()
            if indices:
                i = indices[0]
                theme = model[i][1]
                Pieces.set_piece_theme(theme)
                return theme

        def _set_active(iconview, value):
            try:
                index = self.themes.index(value)
            except ValueError:
                index = 0
            iconview.select_path(Gtk.TreePath(index,))

        uistuff.keep(widgets["pieceTheme"], "pieceTheme", _get_active,
                     _set_active, "Chessicons")
コード例 #50
0
    def load(self, widgets, connection, lounge):
        self.widgets = widgets
        self.connection = connection
        self.lounge = lounge

        __widget__ = lounge.games_list

        self.games = {}
        self.recpix = load_icon(16, "media-record")
        self.clearpix = get_pixbuf("glade/board.png")
        self.tv = self.widgets["gametreeview"]
        self.store = Gtk.ListStore(FICSGame, GdkPixbuf.Pixbuf, str, int, str,
                                   int, str, str)

        self.game_filter = self.store.filter_new()
        self.game_filter.set_visible_func(self.game_filter_func)

        self.filter_toggles = {}
        self.filter_buttons = ("standard_toggle", "blitz_toggle",
                               "lightning_toggle", "variant_toggle")
        for widget in self.filter_buttons:
            uistuff.keep(self.widgets[widget], widget)
            self.widgets[widget].connect("toggled",
                                         self.on_filter_button_toggled)
            initial = conf.get(widget, True)
            self.filter_toggles[widget] = initial
            self.widgets[widget].set_active(initial)

        self.model = self.game_filter.sort_new_with_model()
        self.tv.set_model(self.model)
        self.tv.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
        self.addColumns(self.tv,
                        "FICSGame",
                        "",
                        _("White"),
                        _("Rating"),
                        _("Black"),
                        _("Rating"),
                        _("Type"),
                        _("Rated"),
                        hide=[0],
                        pix=[1])

        self.tv.get_model().set_sort_func(0, self.pixCompareFunction, 1)
        for i in range(1, 7):
            self.tv.get_model().set_sort_func(i, self.compareFunction, i)
        self.prev_sort_column_id = []
        self.model.connect("sort-column-changed", self.on_sort_column_change)

        self.tv.set_has_tooltip(True)
        self.tv.connect("query-tooltip", self.on_query_tooltip)
        self.selection = self.tv.get_selection()
        self.selection.connect("changed", self.onSelectionChanged)
        self.onSelectionChanged(self.selection)

        try:
            self.tv.set_search_position_func(self.lowLeftSearchPosFunc, None)
        except AttributeError:
            # Unknow signal name is raised by gtk < 2.10
            pass

        def searchCallback(model, column, key, sel_iter, user_data):
            if model.get_value(sel_iter, 2).lower().startswith(key) or \
                    model.get_value(sel_iter, 4).lower().startswith(key):
                return False
            return True

        self.tv.set_search_equal_func(searchCallback, None)

        self.connection.games.connect("FICSGameCreated", self.onGameAdd)
        self.connection.games.connect("FICSGameEnded", self.onGameRemove)
        self.widgets["observeButton"].connect("clicked", self.on_observe)
        self.tv.connect("row-activated", self.on_observe)
        self.connection.bm.connect("obsGameCreated", self.onGameObserved)
        self.connection.bm.connect("obsGameUnobserved", self.onGameUnobserved)

        self.tv.connect('button-press-event', self.button_press_event)
        self.createLocalMenu((OBSERVE, FOLLOW, SEPARATOR, FINGER, ARCHIVED))

        return __widget__
コード例 #51
0
ファイル: preferencesDialog.py プロジェクト: ypeng22/pychess
    def __on_show_window(self, widget):
        notebook = self.widgets['preferences_notebook']
        page_num = notebook.get_current_page()
        if notebook.get_nth_page(page_num) == self.widgets['sidepanels']:
            self.showit()

    def __on_hide_window(self, widget):
        self.hideit()


# Theme initing

board_items = [(None, "colors only")]
boards_path = addDataPrefix("boards")
board_items += [(get_pixbuf(os.path.join(boards_path, b), 24), b[:-6]) for b in listdir(boards_path) if b.endswith("_d.png")]
board_items.append((None, "transparent"))


class ThemeTab:
    """ :Description: Allows the setting of various user specific chess
        sets and board colours
    """
    def __init__(self, widgets):
        self.widgets = widgets

        # Font chooser
        font = conf.get("movetextFont")
        font_button = Gtk.FontButton.new_with_font(font)
        demo_text = "♔a1 ♕f8 ♖h8 ♗g7 ♘g2 Ka1 Qf8 Rh8 Bg7 Ng2"
        font_button.set_preview_text(demo_text)